From 10aa1829f58578704ed821a84eec63d302161150 Mon Sep 17 00:00:00 2001 From: "rick.liu" <842001597@qq.com> Date: Mon, 16 Nov 2026 17:28:23 +0800 Subject: [PATCH] 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 --- .gitignore | 7 + DECOMPILATION_AUDIT.md | 268 ++++ README.md | 65 +- docs/CODE_WALKTHROUGH.md | 456 ++++++ pom.xml | 19 + src/main/java/com/midm/MainApplication.java | 2 +- src/main/java/com/midm/app/AppConfig.java | 29 + src/main/java/com/midm/app/AsyncConfig.java | 55 + .../com/midm/app/BasicAuthInterceptor.java | 49 + src/main/java/com/midm/app/DbConfig.java | 97 ++ src/main/java/com/midm/app/DbInitialize.java | 122 +- .../java/com/midm/app/GlobalController.java | 124 ++ .../java/com/midm/app/InterceptorConfig.java | 30 + src/main/java/com/midm/app/LocaleConfig.java | 58 + .../java/com/midm/app/PropertiesConfig.java | 29 + .../java/com/midm/app/SecurityConfig.java | 12 +- src/main/java/com/midm/app/StartupKeeper.java | 81 + .../com/midm/app/converter/DateConverter.java | 20 +- .../app/converter/DirectionConverter.java | 18 +- .../app/converter/JsonElementConverter.java | 19 + .../app/converter/JsonObjectConverter.java | 19 + .../app/converter/UserAgentConverter.java | 20 +- .../com/midm/app/converter/package-info.java | 16 + src/main/java/com/midm/app/package-info.java | 23 + .../java/com/midm/constant/GeneralConst.java | 147 ++ .../java/com/midm/constant/LocaleConst.java | 29 + .../java/com/midm/constant/LocationConst.java | 31 + .../java/com/midm/constant/MidmConst.java | 582 +++++++ .../java/com/midm/constant/PropertyConst.java | 288 ++++ .../java/com/midm/constant/package-info.java | 16 + .../com/midm/controller/BaseController.java | 97 ++ .../com/midm/controller/DeviceController.java | 12 +- .../midm/controller/ExceptionController.java | 111 ++ .../midm/controller/FragmentController.java | 90 +- .../com/midm/controller/HomeController.java | 135 ++ .../com/midm/controller/UserController.java | 38 + .../controller/lib/BarcodeController.java | 21 + .../midm/controller/lib/FilesController.java | 413 ++++- .../controller/lib/ResourceController.java | 77 +- .../midm/controller/lib/StoreController.java | 258 +++ .../com/midm/controller/lib/package-info.java | 15 + .../com/midm/controller/package-info.java | 17 + src/main/java/com/midm/dpc/DpcController.java | 36 + src/main/java/com/midm/dpc/DpcModel.java | 331 ++++ src/main/java/com/midm/dpc/DpcUtils.java | 34 + src/main/java/com/midm/dpc/package-info.java | 14 + .../java/com/midm/model/GeneralProfile.java | 321 +++- .../java/com/midm/model/GroupByResult.java | 47 + .../java/com/midm/model/IF_EXISTS_OPTION.java | 38 + .../java/com/midm/model/battery/Battery.java | 144 ++ .../com/midm/model/battery/BatteryLog.java | 77 + .../com/midm/model/battery/ValueWithTime.java | 47 + .../com/midm/model/battery/package-info.java | 14 + .../java/com/midm/model/device/AppInfo.java | 133 ++ .../midm/model/device/DEVICE_PROPERTY.java | 23 + .../java/com/midm/model/device/DataUsage.java | 150 ++ .../java/com/midm/model/device/Device.java | 347 +++- .../com/midm/model/device/DeviceApps.java | 149 +- .../com/midm/model/device/DeviceGroup.java | 122 +- .../java/com/midm/model/device/DeviceKey.java | 71 + .../com/midm/model/device/DeviceLicense.java | 406 ++++- .../com/midm/model/device/DeviceNote.java | 106 ++ .../com/midm/model/device/DeviceProfile.java | 352 ++++- .../midm/model/device/DeviceProfileGroup.java | 90 +- .../midm/model/device/DeviceProfileState.java | 211 +++ .../com/midm/model/device/DeviceReport.java | 90 ++ .../com/midm/model/device/ProfileApps.java | 391 ++++- .../com/midm/model/device/ProfileScope.java | 104 +- .../midm/model/device/ReconnectMonitor.java | 168 +- .../com/midm/model/device/package-info.java | 27 + .../java/com/midm/model/file/AppFile.java | 226 ++- .../java/com/midm/model/file/BaseFile.java | 288 +++- .../com/midm/model/file/DeployOption.java | 132 ++ .../java/com/midm/model/file/FILE_TYPE.java | 15 + .../java/com/midm/model/file/OtaFile.java | 438 +++++- .../com/midm/model/file/REPORT_ERROR.java | 42 +- .../com/midm/model/file/package-info.java | 17 + src/main/java/com/midm/model/log/MidmLog.java | 161 ++ .../java/com/midm/model/log/package-info.java | 12 + .../com/midm/model/message/MIDM_REQUEST.java | 53 + .../com/midm/model/message/MidmPacket.java | 185 +++ .../com/midm/model/message/MidmQuery.java | 144 ++ .../com/midm/model/message/MidmResponse.java | 532 ++++++- .../com/midm/model/message/package-info.java | 15 + .../java/com/midm/model/news/MessageLog.java | 173 ++ .../java/com/midm/model/news/NewsMessage.java | 353 ++++- .../com/midm/model/news/package-info.java | 13 + src/main/java/com/midm/model/org/Site.java | 375 ++++- .../java/com/midm/model/org/SiteFile.java | 110 ++ .../java/com/midm/model/org/SiteInfo.java | 197 ++- .../java/com/midm/model/org/SiteLicense.java | 308 +++- .../java/com/midm/model/org/SitePlan.java | 73 + .../java/com/midm/model/org/SiteRequest.java | 141 ++ .../com/midm/model/org/USER_PROPERTY.java | 23 + src/main/java/com/midm/model/org/User.java | 631 +++++++- .../java/com/midm/model/org/UserAccess.java | 39 + .../java/com/midm/model/org/UserGroup.java | 82 + .../java/com/midm/model/org/UserRole.java | 106 +- .../java/com/midm/model/org/UserToken.java | 208 ++- .../java/com/midm/model/org/package-info.java | 23 + .../java/com/midm/model/package-info.java | 14 + .../com/midm/model/store/AppReleaseNote.java | 144 +- .../java/com/midm/model/store/KeyStore.java | 104 ++ .../com/midm/model/store/OtaReleaseNote.java | 106 ++ .../com/midm/model/store/ReleaseNote.java | 77 + .../java/com/midm/model/store/StoreApp.java | 106 +- .../com/midm/model/store/StoreAppFile.java | 24 + .../java/com/midm/model/store/StoreBase.java | 116 ++ .../java/com/midm/model/store/StoreOta.java | 106 ++ .../com/midm/model/store/StoreOtaFile.java | 43 + .../com/midm/model/store/StoreOtherFile.java | 41 + .../com/midm/model/store/StoreWebApp.java | 170 +- .../com/midm/model/store/package-info.java | 22 + .../java/com/midm/model/system/AltLocale.java | 49 + .../java/com/midm/model/system/Category.java | 134 +- .../com/midm/model/system/CategoryId.java | 57 + .../com/midm/model/system/DbTemplate.java | 82 + .../com/midm/model/system/HelpMessage.java | 143 ++ .../com/midm/model/system/HostLicense.java | 321 ++++ .../com/midm/model/system/LicenseFeature.java | 77 + .../com/midm/model/system/LicenseModel.java | 332 +++- .../midm/model/system/PolicyAgreement.java | 130 ++ .../com/midm/model/system/ResourceLocale.java | 99 ++ .../midm/model/system/ResourceMessage.java | 97 ++ .../midm/model/system/StandaloneLicense.java | 313 +++- .../com/midm/model/system/SystemSetting.java | 67 + .../com/midm/model/system/package-info.java | 24 + .../com/midm/model/template/MailTemplate.java | 116 ++ .../com/midm/model/template/package-info.java | 12 + src/main/java/com/midm/package-info.java | 12 + .../device/DeviceLicenseRepository.java | 14 +- .../midm/repository/device/package-info.java | 12 + .../com/midm/resolver/DbResourceResolver.java | 10 + .../com/midm/resolver/DbTemplateResolver.java | 23 + .../java/com/midm/resolver/package-info.java | 13 + .../java/com/midm/security/UserPrincipal.java | 61 + .../java/com/midm/security/package-info.java | 12 + .../java/com/midm/service/Aggregations.java | 99 +- .../java/com/midm/service/BaseService.java | 373 ++++- .../java/com/midm/service/EmailService.java | 282 +++- .../midm/service/EmailTemplateResolver.java | 10 + .../com/midm/service/ExternalApiService.java | 81 +- .../java/com/midm/service/GeneralService.java | 45 + .../midm/service/ScheduledTaskService.java | 133 +- .../midm/service/battery/BatteryService.java | 32 +- .../midm/service/battery/package-info.java | 12 + .../com/midm/service/cloudStorage/AwsS3.java | 125 +- .../midm/service/cloudStorage/AzureBlob.java | 147 +- .../service/cloudStorage/CloudStorage.java | 2 +- .../cloudStorage/CloudStorageService.java | 11 +- .../cloudStorage/GoogleCloudStorage.java | 117 +- .../service/cloudStorage/package-info.java | 16 + .../service/device/DeviceAppsService.java | 126 +- .../midm/service/device/DeviceKeyService.java | 14 +- .../service/device/DeviceReportService.java | 448 +++++- .../midm/service/device/DeviceService.java | 1391 ++++++++++++++++- .../midm/service/device/DevicesParser.java | 184 ++- .../service/device/MustProfileService.java | 59 + .../midm/service/device/ProfileAdvisor.java | 93 +- .../midm/service/device/ProfileService.java | 704 ++++++++- .../com/midm/service/device/package-info.java | 19 + .../midm/service/file/DeviceFilesService.java | 83 +- .../com/midm/service/file/FileService.java | 747 ++++++++- .../com/midm/service/file/ReportService.java | 343 +++- .../com/midm/service/file/package-info.java | 14 + .../java/com/midm/service/log/LogService.java | 10 +- .../com/midm/service/log/package-info.java | 12 + .../service/message/MidmWebSocketSession.java | 360 ++++- .../service/message/UserSocketSessions.java | 60 +- .../message/WebSocketSessionManager.java | 407 ++++- .../midm/service/message/package-info.java | 14 + .../midm/service/news/MessageLogService.java | 95 +- .../midm/service/news/NewsMessageService.java | 599 ++++++- .../com/midm/service/news/package-info.java | 13 + .../midm/service/org/SiteLicenseService.java | 363 ++++- .../com/midm/service/org/SiteService.java | 511 +++++- .../midm/service/org/UserSecurityService.java | 30 + .../com/midm/service/org/UserService.java | 717 ++++++++- .../com/midm/service/org/package-info.java | 15 + .../java/com/midm/service/package-info.java | 18 + .../midm/service/store/KeyStoreService.java | 70 +- .../midm/service/store/StoreAppService.java | 322 +++- .../midm/service/store/StoreOtaService.java | 166 +- .../midm/service/store/StoreOtherService.java | 144 +- .../service/store/StoreWebAppService.java | 148 +- .../com/midm/service/store/package-info.java | 16 + .../service/system/HelpMessageService.java | 168 +- .../service/system/HostLicenseService.java | 299 +++- .../midm/service/system/LicenseService.java | 159 +- .../midm/service/system/LocaleService.java | 199 ++- .../system/PolicyAgreementService.java | 58 +- .../midm/service/system/RestoreService.java | 78 + .../midm/service/system/SettingsService.java | 361 ++++- .../com/midm/service/system/package-info.java | 18 + .../service/template/TemplateService.java | 47 + .../midm/service/template/package-info.java | 12 + .../midm/webservice/battery/BatteryApi.java | 120 +- .../midm/webservice/battery/package-info.java | 12 + .../webservice/cloud/CloudStorageApi.java | 84 +- .../midm/webservice/cloud/package-info.java | 12 + .../com/midm/webservice/device/DeviceApi.java | 705 ++++++++- .../midm/webservice/device/DeviceAppApi.java | 130 ++ .../webservice/device/DeviceFilesApi.java | 100 ++ .../webservice/device/DeviceGroupApi.java | 73 + .../webservice/device/DeviceLicenseApi.java | 75 + .../midm/webservice/device/DeviceNoteApi.java | 69 + .../webservice/device/DeviceProfileApi.java | 491 +++++- .../device/DeviceProfileGroupApi.java | 72 + .../midm/webservice/device/package-info.java | 19 + .../com/midm/webservice/files/AppsApi.java | 260 ++- .../com/midm/webservice/files/FilesApi.java | 233 ++- .../midm/webservice/files/GooglePlayApi.java | 49 + .../com/midm/webservice/files/OtasApi.java | 246 ++- .../com/midm/webservice/files/ReportApi.java | 127 +- .../midm/webservice/files/package-info.java | 16 + .../java/com/midm/webservice/log/LogsApi.java | 90 +- .../com/midm/webservice/log/package-info.java | 12 + .../midm/webservice/news/NewsMessageApi.java | 228 +++ .../midm/webservice/news/package-info.java | 12 + .../java/com/midm/webservice/org/SiteApi.java | 373 ++++- .../java/com/midm/webservice/org/UserApi.java | 798 +++++++++- .../com/midm/webservice/org/UserGroupApi.java | 75 + .../com/midm/webservice/org/package-info.java | 14 + .../com/midm/webservice/ota/OtaService.java | 62 + .../com/midm/webservice/ota/package-info.java | 12 + .../com/midm/webservice/stat/StatApi.java | 187 ++- .../midm/webservice/stat/package-info.java | 12 + .../midm/webservice/store/KeyStoreApi.java | 122 +- .../midm/webservice/store/StoreAppsApi.java | 231 ++- .../midm/webservice/store/StoreOtasApi.java | 224 ++- .../midm/webservice/store/StoreOtherApi.java | 108 ++ .../midm/webservice/store/StoreWebAppApi.java | 157 +- .../midm/webservice/store/package-info.java | 16 + .../midm/webservice/system/AltLocaleApi.java | 68 + .../webservice/system/HelpMessageApi.java | 149 ++ .../webservice/system/HostLicenseApi.java | 297 ++++ .../midm/webservice/system/LicenseApi.java | 299 ++++ .../com/midm/webservice/system/LocaleApi.java | 88 ++ .../webservice/system/PolicyAgreementApi.java | 87 ++ .../webservice/system/ResourceMessageApi.java | 154 ++ .../webservice/system/SystemSettingsApi.java | 98 ++ .../midm/webservice/system/package-info.java | 19 + .../midm/websocket/message/QueryHandler.java | 48 +- .../midm/websocket/message/package-info.java | 12 + .../java/com/mitac/cell/barcode/QrCode.java | 118 ++ .../com/mitac/cell/barcode/package-info.java | 12 + .../mitac/cell/constant/DateTimeConst.java | 48 + .../com/mitac/cell/constant/GeneralConst.java | 48 + .../com/mitac/cell/constant/LocaleConst.java | 21 + .../mitac/cell/constant/LocationConst.java | 31 + .../com/mitac/cell/constant/MessageConst.java | 72 + .../mitac/cell/constant/PropertyConst.java | 198 +++ .../com/mitac/cell/constant/SizeConst.java | 31 + .../com/mitac/cell/constant/package-info.java | 18 + .../java/com/mitac/cell/data/McCompress.java | 74 + .../com/mitac/cell/data/McDecompress.java | 91 ++ src/main/java/com/mitac/cell/data/McXml.java | 58 + .../com/mitac/cell/data/package-info.java | 14 + src/main/java/com/mitac/cell/db/DbObject.java | 169 +- .../java/com/mitac/cell/db/package-info.java | 12 + .../java/com/mitac/cell/db/util/JpaQuery.java | 80 + .../com/mitac/cell/db/util/McDbUtils.java | 25 + .../com/mitac/cell/db/util/McMongoUtils.java | 125 ++ .../com/mitac/cell/db/util/McPipeLine.java | 10 + .../com/mitac/cell/db/util/package-info.java | 15 + src/main/java/com/mitac/cell/doc/Csv.java | 209 ++- .../java/com/mitac/cell/doc/CsvReader.java | 57 + .../java/com/mitac/cell/doc/ExcelCell.java | 79 + .../java/com/mitac/cell/doc/ExcelReader.java | 175 ++- .../java/com/mitac/cell/doc/ExcelRow.java | 59 +- .../java/com/mitac/cell/doc/ExcelWriter.java | 604 ++++++- .../java/com/mitac/cell/doc/HtmlToPdf.java | 26 + .../java/com/mitac/cell/doc/McHtmlDoc.java | 166 ++ .../java/com/mitac/cell/doc/McHtmlUtils.java | 34 + .../java/com/mitac/cell/doc/WordTemplate.java | 135 +- .../java/com/mitac/cell/doc/package-info.java | 21 + .../gson/typeAdapter/CipherTypeAdapter.java | 31 +- .../CompatibleTimeZoneTypeAdapter.java | 31 +- .../cell/gson/typeAdapter/package-info.java | 13 + .../mitac/cell/internet/app/McPlayMarket.java | 69 +- .../com/mitac/cell/internet/app/PlayApp.java | 100 ++ .../mitac/cell/internet/app/package-info.java | 13 + .../internet/html/McHtmlTemplateEngine.java | 73 +- .../cell/internet/html/package-info.java | 12 + .../cell/internet/http/McHttpClient.java | 127 ++ .../mitac/cell/internet/http/McRequest.java | 25 + .../mitac/cell/internet/http/McResponse.java | 73 +- .../cell/internet/http/McResponseEntity.java | 32 +- .../mitac/cell/internet/http/UserAgent.java | 74 +- .../cell/internet/http/package-info.java | 16 + .../cell/internet/mail/McMailSender.java | 317 +++- .../cell/internet/mail/package-info.java | 12 + .../internet/websocket/SocketCloseStatus.java | 40 + .../cell/internet/websocket/package-info.java | 12 + src/main/java/com/mitac/cell/io/ApkSign.java | 87 ++ .../java/com/mitac/cell/io/McApkFile.java | 94 ++ .../mitac/cell/io/McEncryptedFileDrive.java | 388 ++++- src/main/java/com/mitac/cell/io/McFile.java | 227 +++ .../java/com/mitac/cell/io/McFileTable.java | 157 +- .../java/com/mitac/cell/io/McInputStream.java | 24 + .../java/com/mitac/cell/io/McJsonFile.java | 175 +++ .../java/com/mitac/cell/io/McResource.java | 78 + src/main/java/com/mitac/cell/io/McUrl.java | 76 + .../java/com/mitac/cell/io/McZipFile.java | 187 +++ .../java/com/mitac/cell/io/Vector2Svg.java | 180 +++ .../java/com/mitac/cell/io/package-info.java | 22 + src/main/java/com/mitac/cell/map/GeoCode.java | 20 + .../java/com/mitac/cell/map/package-info.java | 12 + .../java/com/mitac/cell/must/MustBuilder.java | 136 ++ .../com/mitac/cell/must/package-info.java | 12 + .../java/com/mitac/cell/net/McNetUtils.java | 136 +- src/main/java/com/mitac/cell/net/Uri.java | 46 +- .../java/com/mitac/cell/net/package-info.java | 13 + .../com/mitac/cell/security/McBase64.java | 36 + .../com/mitac/cell/security/McCrypto.java | 290 ++++ .../com/mitac/cell/security/McOtaCert.java | 83 + .../mitac/cell/security/McTextEncryptor.java | 87 +- .../McUserAuthenticationProvider.java | 31 +- .../security/McUserAuthenticationToken.java | 44 +- .../com/mitac/cell/security/cipher/McRc4.java | 85 +- .../cell/security/cipher/package-info.java | 12 + .../com/mitac/cell/security/package-info.java | 17 + .../java/com/mitac/cell/shell/McRuntime.java | 87 +- .../com/mitac/cell/shell/package-info.java | 12 + .../java/com/mitac/cell/system/HwInfo.java | 111 ++ .../com/mitac/cell/system/McSystemInfo.java | 63 +- .../java/com/mitac/cell/system/MsWindows.java | 45 +- .../java/com/mitac/cell/system/OsInfo.java | 90 ++ .../com/mitac/cell/system/package-info.java | 15 + .../com/mitac/cell/utils/McBooleanUtils.java | 29 +- .../java/com/mitac/cell/utils/McChar.java | 23 + .../com/mitac/cell/utils/McCipherUtils.java | 40 + .../java/com/mitac/cell/utils/McConvert.java | 221 ++- .../com/mitac/cell/utils/McDateTimeUtils.java | 245 +++ .../com/mitac/cell/utils/McEmailUtils.java | 50 +- .../com/mitac/cell/utils/McJsonUtils.java | 314 +++- .../com/mitac/cell/utils/McNumberUtils.java | 85 + .../com/mitac/cell/utils/McStringUtils.java | 168 +- .../java/com/mitac/cell/utils/McUrlUtils.java | 40 + .../com/mitac/cell/utils/McUuidUtils.java | 106 ++ .../com/mitac/cell/utils/package-info.java | 22 + src/main/resources/apksigner/apksigner.jar | Bin 181132 -> 440912 bytes src/main/resources/device_apps_service.txt | Bin 0 -> 8 bytes src/main/resources/device_service.txt | Bin 0 -> 8 bytes .../module/angular-filter/angular-filter.zip | Bin 0 -> 81020 bytes src/main/resources/store_ota_service.txt | Bin 0 -> 8 bytes 346 files changed, 42404 insertions(+), 622 deletions(-) create mode 100644 DECOMPILATION_AUDIT.md create mode 100644 docs/CODE_WALKTHROUGH.md create mode 100644 src/main/java/com/midm/app/converter/package-info.java create mode 100644 src/main/java/com/midm/app/package-info.java create mode 100644 src/main/java/com/midm/constant/package-info.java create mode 100644 src/main/java/com/midm/controller/lib/package-info.java create mode 100644 src/main/java/com/midm/controller/package-info.java create mode 100644 src/main/java/com/midm/dpc/package-info.java create mode 100644 src/main/java/com/midm/model/battery/package-info.java create mode 100644 src/main/java/com/midm/model/device/package-info.java create mode 100644 src/main/java/com/midm/model/file/package-info.java create mode 100644 src/main/java/com/midm/model/log/package-info.java create mode 100644 src/main/java/com/midm/model/message/package-info.java create mode 100644 src/main/java/com/midm/model/news/package-info.java create mode 100644 src/main/java/com/midm/model/org/package-info.java create mode 100644 src/main/java/com/midm/model/package-info.java create mode 100644 src/main/java/com/midm/model/store/package-info.java create mode 100644 src/main/java/com/midm/model/system/package-info.java create mode 100644 src/main/java/com/midm/model/template/package-info.java create mode 100644 src/main/java/com/midm/package-info.java create mode 100644 src/main/java/com/midm/repository/device/package-info.java create mode 100644 src/main/java/com/midm/resolver/package-info.java create mode 100644 src/main/java/com/midm/security/package-info.java create mode 100644 src/main/java/com/midm/service/battery/package-info.java create mode 100644 src/main/java/com/midm/service/cloudStorage/package-info.java create mode 100644 src/main/java/com/midm/service/device/package-info.java create mode 100644 src/main/java/com/midm/service/file/package-info.java create mode 100644 src/main/java/com/midm/service/log/package-info.java create mode 100644 src/main/java/com/midm/service/message/package-info.java create mode 100644 src/main/java/com/midm/service/news/package-info.java create mode 100644 src/main/java/com/midm/service/org/package-info.java create mode 100644 src/main/java/com/midm/service/package-info.java create mode 100644 src/main/java/com/midm/service/store/package-info.java create mode 100644 src/main/java/com/midm/service/system/package-info.java create mode 100644 src/main/java/com/midm/service/template/package-info.java create mode 100644 src/main/java/com/midm/webservice/battery/package-info.java create mode 100644 src/main/java/com/midm/webservice/cloud/package-info.java create mode 100644 src/main/java/com/midm/webservice/device/package-info.java create mode 100644 src/main/java/com/midm/webservice/files/package-info.java create mode 100644 src/main/java/com/midm/webservice/log/package-info.java create mode 100644 src/main/java/com/midm/webservice/news/package-info.java create mode 100644 src/main/java/com/midm/webservice/org/package-info.java create mode 100644 src/main/java/com/midm/webservice/ota/package-info.java create mode 100644 src/main/java/com/midm/webservice/stat/package-info.java create mode 100644 src/main/java/com/midm/webservice/store/package-info.java create mode 100644 src/main/java/com/midm/webservice/system/package-info.java create mode 100644 src/main/java/com/midm/websocket/message/package-info.java create mode 100644 src/main/java/com/mitac/cell/barcode/package-info.java create mode 100644 src/main/java/com/mitac/cell/constant/package-info.java create mode 100644 src/main/java/com/mitac/cell/data/package-info.java create mode 100644 src/main/java/com/mitac/cell/db/package-info.java create mode 100644 src/main/java/com/mitac/cell/db/util/package-info.java create mode 100644 src/main/java/com/mitac/cell/doc/package-info.java create mode 100644 src/main/java/com/mitac/cell/gson/typeAdapter/package-info.java create mode 100644 src/main/java/com/mitac/cell/internet/app/package-info.java create mode 100644 src/main/java/com/mitac/cell/internet/html/package-info.java create mode 100644 src/main/java/com/mitac/cell/internet/http/package-info.java create mode 100644 src/main/java/com/mitac/cell/internet/mail/package-info.java create mode 100644 src/main/java/com/mitac/cell/internet/websocket/package-info.java create mode 100644 src/main/java/com/mitac/cell/io/package-info.java create mode 100644 src/main/java/com/mitac/cell/map/package-info.java create mode 100644 src/main/java/com/mitac/cell/must/package-info.java create mode 100644 src/main/java/com/mitac/cell/net/package-info.java create mode 100644 src/main/java/com/mitac/cell/security/cipher/package-info.java create mode 100644 src/main/java/com/mitac/cell/security/package-info.java create mode 100644 src/main/java/com/mitac/cell/shell/package-info.java create mode 100644 src/main/java/com/mitac/cell/system/package-info.java create mode 100644 src/main/java/com/mitac/cell/utils/package-info.java create mode 100644 src/main/resources/device_apps_service.txt create mode 100644 src/main/resources/device_service.txt create mode 100644 src/main/resources/static/module/angular-filter/angular-filter.zip create mode 100644 src/main/resources/store_ota_service.txt diff --git a/.gitignore b/.gitignore index 7decc11..a48a914 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,10 @@ WEB-INF/ .DS_Store Thumbs.db 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/ diff --git a/DECOMPILATION_AUDIT.md b/DECOMPILATION_AUDIT.md new file mode 100644 index 0000000..0d35981 --- /dev/null +++ b/DECOMPILATION_AUDIT.md @@ -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 的代码生成差异**(枚举 ``、字符串拼接、装箱、`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`(方法级 `` 丢失) +- `DeviceService.java:229: Object cannot be converted to Device`(`List` 变成裸 `List`) +- `FileService.java:169: Object cannot be converted to UUID` +- `DateConverter.java: 不是抽象类,未覆盖 convert`(`implements Converter` 变成裸 `Converter`) +- `ProfileApps.java: List cannot be converted to List`(通配符捕获) +- `DbObject.java: Map cannot be converted to Map` + +**修复方式**:对每个类用 `javap -p -s` 读出原始 `Signature`,按“方法名 + 参数个数 + 参数类型”对齐,恢复: + +- 类/方法类型参数,如 `public T findById(Class, Object)`; +- 返回值与参数泛型,如 `List`、`PageImpl`、`Converter`; +- 字段泛型,如 `List sites`; +- 必要处补回 `Class`、`Collection` 等。 + +共修改 **114 个 Java 文件、约 560 处签名**,并补回 4 个文件缺失的 import。 + +--- + +## 二、变量作用域 / 重名 / 丢失(17 errors) + +Fernflower 在 switch、try/catch、lambda 等场景把不同作用域的变量重名,或直接漏掉声明。已逐处对照 `LocalVariableTable` 和字节码修复: + +| 文件 | 问题 | 修复 | +| --- | --- | --- | +| `SettingsService.java:257` | `settingsMap.put(key, (Object)null)` 与 `Map` 不兼容 | `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` 未定义、`Map` 构造器通配符不兼容 | 裸 `List` + `super((Map)map)` | +| `GeneralProfile.java` | ` T getProfile(...)` 返回 `Object`/`(Object)null` | 补 `(T)` 转换 | +| `NewsMessage.java:94` | 原始 `LinkedTreeMap` 的 `entrySet()` 迭代元素为 `Object` | 先取 `Object`,再显式转 `Map.Entry` | +| `StoreApp.java:67` | `Set.addAll(List)` 捕获失败 | 显式 `(Collection)` 转换 | +| `UserApi.java:1516` | `List` 传给 `saveUsers(List)` | 显式 `(List)` 转换 | +| `McJsonUtils.java:221` | ` 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 个枚举类的 ``: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`:`` 方法签名、`PageImpl` +- `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` 等资源 \ No newline at end of file diff --git a/README.md b/README.md index f4c9a8f..7aef2a7 100644 --- a/README.md +++ b/README.md @@ -130,23 +130,72 @@ iot_m/ ## 🚀 本地快速启动 -### 1. 环境准备 -- **JDK**:OpenJDK 11 或更高 -- **构建工具**:Apache Maven 3.6+ -- **数据库**:MongoDB 4.x+(本地启动或使用 Docker 容器) +### 1. 环境准备(Windows,本机已配置) + +| 组件 | 版本 | 本机路径 | +| :--- | :--- | :--- | +| 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 + +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 docker run -d --name midm-mongo -p 27017:27017 -e MONGO_INITDB_DATABASE=db_midm mongo:5.0 ``` -### 3. 配置与启动 -检查 `src/main/resources/application.properties`,确认 MongoDB 连接配置后执行: -```bash +### 3. 运行时配置 + +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 -java -jar target/midm-1.1.1.12.war +java -jar target\midm-1.1.1.12.war ``` 系统启动后默认监听 `8080` 端口: + +- 登录页:`http://localhost:8080/` - WebSocket 网关端点:`ws://localhost:8080/query` - 零接触 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)。 diff --git a/docs/CODE_WALKTHROUGH.md b/docs/CODE_WALKTHROUGH.md new file mode 100644 index 0000000..fb58fbb --- /dev/null +++ b/docs/CODE_WALKTHROUGH.md @@ -0,0 +1,456 @@ +# MiDM 源码学习指南(CODE WALKTHROUGH) + +> 目标:把反编译出来的 Java 代码变成一套可以按图索骥学习的工程。 +> 本文件讲**架构与调用链**;每个类/方法/字段的细节看源码里的 Javadoc +>(本次已补全 286 个类型、3,989 个方法、1,733 个字段的注释)。 + +--- + +## 0. 推荐阅读顺序 + +1. 先读本文件第 1~4 节,建立“端 → 云 → Mongo → 管理后台”的整体地图。 +2. 读 com.midm.model:先看 GeneralProfile、Device、DeviceProfile、Site、User。 +3. 读 com.midm.service.BaseService 与一个具体 Service(推荐 DeviceService)。 +4. 读 com.midm.websocket.message.QueryHandler:这是设备协议的总入口。 +5. 读 com.midm.webservice.device.DeviceApi / DeviceProfileApi:管理端 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. 目录地图 + +| 包 | 作用 | 先看谁 | +| --- | --- | --- | +| com.midm | 启动入口 | MainApplication | +| com.midm.app | Mongo/Security/WebSocket/Locale/启动初始化 | DbConfig、SecurityConfig、DbInitialize、StartupKeeper | +| com.midm.app.converter | 请求参数 → 对象转换 | DateConverter、JsonObjectConverter | +| com.midm.constant | 常量、集合名、协议码 | MidmConst、PropertyConst | +| com.midm.controller | 页面路由(Thymeleaf) | HomeController、DeviceController | +| com.midm.controller.lib | 图片/文件下载 | FilesController、StoreController | +| com.midm.dpc | Android Enterprise 零接触 | DpcController、DpcModel | +| com.midm.model | 领域模型 / Mongo 文档 | GeneralProfile、Device、DeviceProfile | +| com.midm.repository | Spring Data Repository | DeviceLicenseRepository | +| com.midm.security | 认证主体 | UserPrincipal | +| com.midm.service | 业务服务 | BaseService、DeviceService、ProfileService | +| com.midm.webservice | 管理端/设备端 REST API | DeviceApi、DeviceProfileApi、UserApi | +| com.midm.websocket | WebSocket 网关与协议处理 | QueryHandler | +| com.mitac.cell | 通用基础库 | DbObject、McJsonUtils、McFile、McTextEncryptor | + +--- + +## 3. 启动与配置链路 + +### 3.1 启动入口 + +MainApplication: + +- @SpringBootApplication(scanBasePackages = "com.midm"); +- 继承 SpringBootServletInitializer,既支持 java -jar 也支持外置 Tomcat; +- @EnableScheduling 打开定时任务; +- restart() 在非守护线程中关闭并重建 Spring 上下文,用于运行期热重启。 + +### 3.2 外部配置 + +PropertiesConfig 会强制读取: + +~~~text +C:\ProgramData\MiDM\midm.properties +~~~ + +目录或文件不存在时,PropertySourcesPlaceholderConfigurer 会抛 +FileNotFoundException,应用直接启动失败。本地开发建议内容: + +~~~properties +mongo.uri= +mongo.host=127.0.0.1 +mongo.port=27017 +mongo.dbname=db_midm +mongo.replica_set= +~~~ + +application.properties 负责日志级别、Session Cookie、Tomcat access log、 +Thymeleaf 缓存、静态资源缓存等 Spring Boot 配置;Mongo 连接参数集中在 +DbConfig 的 @Value 字段。 + +### 3.3 Mongo 连接池 + +DbConfig.getConnectiontString() 根据 mongo.uri / mongo.host +动态拼装 ConnectionString: + +- 多节点时拆分逗号分隔的 host,补齐默认端口; +- 强制 w=majority、retryWrites=true、uuidRepresentation=javaLegacy; +- 按配置补齐 maxPoolSize、connectTimeoutMS、maxIdleTimeMS、 + waitqueuetimeoutms、ssl、replicaSet; +- fixDb() 在启动时做索引自愈(删除低效单字段索引,确保复合索引生效)。 + +> 注意:单机 MongoDB 要把 mongo.replica_set 置空;副本集才填 rs0 并执行 +> rs.initiate()。 + +### 3.4 初始化与启动钩子 + +- DbInitialize:首次启动时建集合/索引、修复历史数据、补默认设置。 +- StartupKeeper:监听 ContextRefreshedEvent,加载系统设置、恢复同步、 + 校验 License、加载语言与帮助消息、初始化设备状态、清理孤儿数据、安排通知任务。 + +--- + +## 4. 领域模型与 MongoDB + +### 4.1 公共基类 GeneralProfile + +大部分业务对象继承 com.midm.model.GeneralProfile: + +| 字段 | 作用 | +| --- | --- | +| uuid | 业务主键(@Id),全系统统一用 UUID | +| created / updated | 创建/更新时间 | +| profile | DbObject 扩展属性包,承载厂商/硬件/软件等可变字段 | +| enabled | 通用启用状态 | + +DbObject 继承 org.bson.Document,提供 getString/getBoolean/getList/getDbObject +等便捷方法,避免到处强转。 + +### 4.2 常用注解 + +| 注解 | 含义 | +| --- | --- | +| @Document | 映射为 MongoDB 集合 | +| @Id | 文档主键 | +| @Indexed | 建索引,常用于查询条件 | +| @Field("x") | 指定 Mongo 字段名 | +| @Transient | 不持久化,仅运行时 | +| @DBRef | 引用其他文档(慎用,查询成本高) | +| @Expose(serialize=false) | Gson 序列化时排除(如密码) | + +### 4.3 核心集合(按业务) + +| 领域 | 主要类 | 说明 | +| --- | --- | --- | +| 设备 | Device、DeviceApps、DeviceGroup、DeviceNote | 设备档案、已装应用、分组树、备注 | +| 策略 | DeviceProfile、ProfileApps、ProfileScope | 配置档案、应用/文件/OTA 项、作用域 | +| 组织 | Site、User、SiteInfo、UserGroup | 多租户站点、账号、站点成员、用户组 | +| 授权 | DeviceLicense、SiteLicense、LicenseModel、HostLicense | 设备/站点/主机 License | +| 文件 | BaseFile、AppFile、OtaFile、StoreAppFile | APK/OTA/普通文件/商店文件 | +| 遥测 | Battery、BatteryLog、DataUsage、DeviceReport | 电池健康、流量、设备报表 | +| 审计 | MidmLog、DeviceLog | 操作/设备日志 | +| 系统 | SystemSetting、Locale、HelpMessage、NewsMessage | 设置、语言、帮助、通知 | +| 商店 | StoreApp、StoreWebApp、AppReleaseNote | 应用商店/WebApp/发布说明 | + +阅读实体时先看字段注释和注解,再看对应 Service 如何构造 Criteria。 + +--- + +## 5. Web 层与安全 + +### 5.1 两类入口 + +- com.midm.controller:返回 Thymeleaf 视图名,服务管理后台页面; +- com.midm.webservice:@RestController/JSON,服务前端 AJAX 与设备/第三方 API。 + +统一响应封装是 MidmResponse(code/message/data),异常由 +ExceptionController 收敛。 + +### 5.2 认证与授权 + +- SecurityConfig 定义过滤器链、登录页、静态资源放行、CSRF/Headers; +- BasicAuthInterceptor 处理 Basic/Token 头; +- UserPrincipal 把 User 包装成 Spring Security 主体; +- UserRole 定义角色常量(SUPERVISOR、DEVICE_MANAGER、PROFILE_MANAGER 等); +- UserService.authorizedUser(authentication, accessToken) 是各 API 的统一鉴权入口; +- user.canHandle(siteUuid, roles) 做站点级权限判断。 + +### 5.3 典型 REST 调用链 + +DeviceApi.findDevices() → UserService.authorizedUser() → 站点校验 → +DeviceService.findDevices() → BaseService.findByPage() → MongoTemplate。 + +--- + +## 6. WebSocket 设备通道(重点) + +### 6.1 端点与握手 + +WebSocketConfig 把 /query 注册到 QueryHandler,允许跨域。 +握手完成后 afterConnectionEstablished: + +1. WebSocketSessionManager.toMidmSocketSession(session, true) 从 Header/Query + 解析设备序列号或用户 Token,包装成 MidmWebSocketSession; +2. 按配置设置文本/二进制最大缓冲; +3. 设备连接走 onConnected,管理端用户连接走 register。 + +### 6.2 报文模型 + +MidmPacket 是统一报文: + +- query:请求(MidmQuery,含 code/request/params); +- feedback:响应(MidmResponse,含 code/message/data); +- uuid / queryUuid / recieverUuid:路由与幂等; +- 支持 toTextMessage() / toBinaryMessage(),二进制路径用 McCompress 压缩。 + +MIDM_REQUEST 定义协议码,例如: + +| code | 枚举 | 含义 | +| --- | --- | --- | +| 99 | PING | 心跳 | +| 100 | CONNECT | 建连 | +| 104 | ENROLL | 设备注册 | +| 105 | DEVICE_INFO | 设备信息/遥测上报 | +| 131/132 | UPDATE_PROFILE / UPDATE_ALL_PROFILES | 策略下发/全量同步 | +| 136 | REMOVE_PROFILE | 移除策略 | +| 200 | COMMAND | 远程指令 | +| 210 | QUERY | 查询设备信息 | +| 400 | RTC | 远程协助/WebRTC 信令 | + +### 6.3 消息分发 + +QueryHandler.handleMessage: + +1. 刷新 pong 时间戳; +2. 若租户开启流量采集,按阈值触发 updateDataUsage; +3. 按帧类型分派: + - PongMessage → onPong; + - TextMessage → handleTextMessage("ping" 或 JSON MidmPacket); + - BinaryMessage → McDecompress 解压后按 feedback/ping 处理。 + +onFeedback 是业务总路由:ENROLL 注册、DEVICE_INFO 更新设备、 +UPDATE_PROFILE/命令回执、RTC 信令等。 + +### 6.4 会话管理 + +WebSocketSessionManager 维护: + +- deviceSessions:设备 UUID → MidmWebSocketSession; +- userSessions:用户 UUID → UserSocketSessions; +- 心跳 ping/pong、在线状态广播、断线清理; +- ReconnectMonitor:滑动窗口统计重连频率,异常时 block,防止弱网重连风暴。 + +### 6.5 设备注册(ENROLL)链路 + +QueryHandler.onFeedback 的 ENROLL 分支: + +1. 校验序列号;找不到站点/白名单不允许则回 451/463/461 并关闭; +2. DeviceService.register():初始化设备、绑定分组、所有者、站点; +3. License 激活/试用; +4. 审计日志 LogService.saveDeviceLog; +5. 注册全局 Session,下发 111 + 精简设备配置; +6. License 过期则回 115 并关闭。 + +--- + +## 7. 设备生命周期与策略 + +### 7.1 设备 + +DeviceService 是设备中枢: + +- 注册/保存/批量导入:register、save、saveDevices; +- 查询:findBySerialNo、findDeviceByUuid、findDevices(分页/过滤); +- 分组:findGroupFamily、findChildGroups、findAllDevicesInGroup; +- 删除/退役:delete、retire、deleteBySite; +- License:setTrialLicense、activateLicense、renewLicense; +- OTA 回调:systemImageUpdated、regionImageUpdated。 + +### 7.2 策略(Profile) + +ProfileService 负责配置档案: + +- CRUD:save、find、delete、findProfiles; +- 作用域:updateScope、unscope、isDeviceScoped、isGroupScoped; +- 下发:notifyToSync 给设备发 WebSocket 通知; +- 应用状态:isProfileApplied、profileStatesByDevice; +- 冲突解决:ProfileAdvisor 计算应用/设置/OTA 冲突,决定最终下发项。 + +### 7.3 License + +- DeviceLicense:设备级,含 licenseModel、expiry、activationCount; +- SiteLicense:站点级采购/续费; +- LicenseModel:型号/周期/最大激活数; +- HostLicenseService:主机级 License 校验(单机/多租户模式)。 + +--- + +## 8. 文件与云存储 + +### 8.1 文件模型 + +- BaseFile:文件名、大小、校验和、站点、分类; +- AppFile:APK 包名、版本号、minSdk、签名证书; +- OtaFile:固件 build date、SKU、区域、系统/区域镜像标记。 + +### 8.2 路径规则 + +FileService 统一生成路径:getFilePath、getDeviceFilePath、 +getSiteFilePath、getMustFolderFilePath。上传/下载/删除都走这里, +避免路径拼接散落各处。 + +### 8.3 多云策略 + +CloudStorageService 根据 cloud.storage 设置选择: + +- AwsS3 +- AzureBlob +- GoogleCloudStorage + +统一接口:upload、download/getUrl、exists、delete、list、 +updateMetaInfo、refreshClient。大文件用预签名 URL 让设备直连云存储, +服务端只负责签发和元数据。 + +### 8.4 APK 签名 + +StoreAppService.sign() 调用资源里的 apksigner/apksigner.jar, +用 keystore 对 APK 重签名,并记录证书 MD5/版本信息。 + +--- + +## 9. 报表、邮件与模板 + +### 9.1 报表 + +ReportService 基于 POI 的 ExcelWriter 生成三类报表: + +- generateDeviceReport:设备清单/状态/流量/电池; +- generateProfileReport:策略应用情况; +- generateSiteReport:站点/License/设备分布。 + +模板在 src/main/resources/report/*.xlsx,生成后保存为 SiteFile, +可下载或邮件发送。 + +### 9.2 PDF + +com.mitac.cell.doc.HtmlToPdf 用 Flying Saucer + iText 把 HTML 转 PDF。 + +### 9.3 邮件与模板 + +- EmailService:发送密码重置、License、报表等邮件; +- TemplateService:从 Mongo/资源加载模板; +- McMailSender:封装 JavaMail,支持抄送/密送/附件; +- EmailTemplateResolver:Thymeleaf 模板解析。 + +--- + +## 10. 异步、定时与并发 + +- AsyncConfig:配置 ThreadPoolTaskExecutor; +- @Async:报表生成、邮件发送、日志等不阻塞请求; +- @Scheduled / ScheduledTaskService:设备离线检查、报表过期、通知; +- ReconnectMonitor:滑动窗口 + 定时 unblock; +- synchronized / ConcurrentHashMap:会话表、缓存等共享状态。 + +读并发代码时先找“共享字段”,再看锁粒度和任务调度器。 + +--- + +## 11. 安全细节 + +- 设备密钥:DeviceKeyService 生成/保存 RSA 公私钥; +- 请求验签:ExternalApiService.doRequestRsaIsValid 用 RSA-OAEP 解密设备密文; +- 密码:BCrypt(PasswordEncoder); +- API Token:UserToken / accessToken,一次性令牌用后删除; +- 文件下载:FilesController 校验用户站点归属,防越权下载; +- 安全头/CSRF/Session Cookie:SecurityConfig + application.properties。 + +--- + +## 12. 构建、运行与排错 + +### 12.1 本机环境 + +- JDK 18(编译目标 11); +- Maven 3.9.9; +- MongoDB 7.0.14(单机); +- C:\ProgramData\MiDM\midm.properties 必须存在。 + +### 12.2 命令 + +~~~powershell +mvn clean package -DskipTests +java -jar target\midm-1.1.1.12.war +~~~ + +### 12.3 常见错误 + +| 现象 | 原因 | 处理 | +| --- | --- | --- | +| FileNotFoundException: c:\ProgramData\MiDM\midm.properties | 运行配置缺失 | 创建目录和文件 | +| replicaSet=rs0 连接失败 | 单机 Mongo 却配了副本集 | mongo.replica_set= 置空 | +| 端口占用 | 8080 被占用 | --server.port=18081 | +| 登录页 404 | 访问了错误路径 | 用 /,不是 /login | +| 生成报表/邮件失败 | 模板/邮箱配置缺失 | 看 SettingsService 与运行日志 | + +--- + +## 13. 建议的学习路线 + +| 天 | 目标 | 代码 | +| --- | --- | --- | +| Day 1 | 跑起来 + 模型 | MainApplication → GeneralProfile → Device → Site → User | +| Day 2 | 通用 CRUD/分页 | BaseService → DeviceService 的 find/save/delete | +| Day 3 | 设备协议 | WebSocketConfig → QueryHandler → WebSocketSessionManager | +| Day 4 | 策略与 License | ProfileService → ProfileAdvisor → DeviceLicense | +| Day 5 | 文件/报表/云存储 | FileService → CloudStorageService → ReportService | +| Day 6 | 安全/定时任务 | SecurityConfig → UserPrincipal → ScheduledTaskService | + +练习建议: + +1. 新增一个只读 API:GET /api/device/count,走 DeviceService.count; +2. 给 Device 增加一个 @Indexed 字段,观察 DbInitialize 索引; +3. 在 MIDM_REQUEST 增加一个协议码,在 onFeedback 加分支; +4. 给 ProfileService 增加一个“按名称模糊查询”的方法并写 Javadoc。 + +--- + +## 14. 代码索引(功能 → 类) + +| 功能 | 入口 | 核心实现 | +| --- | --- | --- | +| 启动 | MainApplication | DbConfig、DbInitialize、StartupKeeper | +| 登录/鉴权 | UserApi | UserService、SecurityConfig、UserPrincipal | +| 设备列表/详情 | DeviceApi | DeviceService、BaseService | +| 设备注册 | QueryHandler.ENROLL | DeviceService.register、WebSocketSessionManager | +| 策略管理 | DeviceProfileApi | ProfileService、ProfileAdvisor | +| 策略下发 | ProfileService.notifyToSync | WebSocketSessionManager | +| 设备分组 | DeviceApi | DeviceService.findGroupFamily/findChildGroups | +| License | LicenseApi、HostLicenseApi | LicenseService、HostLicenseService | +| APK/OTA | StoreAppsApi、OtasApi | StoreAppService、FileService、OtaFile | +| 文件下载 | FilesController、DeviceFilesApi | FileService、CloudStorageService | +| 报表 | ReportApi | ReportService、ExcelWriter | +| 电池 | BatteryApi | BatteryService | +| 审计日志 | LogsApi | LogService | +| WebSocket | /query | QueryHandler、WebSocketSessionManager、ReconnectMonitor | +| 零接触 | DpcController | DpcModel、StoreAppService | +| 云存储 | CloudStorageService | AwsS3、AzureBlob、GoogleCloudStorage | + +--- + +## 15. 读代码时最值得问的三个问题 + +1. **数据从哪里来?** 看 @Document 字段、BaseService 的查询条件、Mongo 索引。 +2. **状态在哪里改?** 看 Service 的 save/update 与 @Async/定时任务。 +3. **失败会怎样?** 看 MidmResponse 错误码、throw、catch 与 WebSocket sendFeedback。 + +把这三问套到每个方法上,Javadoc 里的“实现要点/主要调用”就是索引。 diff --git a/pom.xml b/pom.xml index 6ceb3b0..fb2b02e 100644 --- a/pom.xml +++ b/pom.xml @@ -156,6 +156,25 @@ 9.1.22 + + + org.apache.xmlgraphics + batik-transcoder + ${batik.version} + + + org.apache.xmlgraphics + batik-codec + ${batik.version} + + + + + org.bouncycastle + bcprov-jdk14 + 1.64 + + com.google.zxing diff --git a/src/main/java/com/midm/MainApplication.java b/src/main/java/com/midm/MainApplication.java index 27f3545..be130d3 100644 --- a/src/main/java/com/midm/MainApplication.java +++ b/src/main/java/com/midm/MainApplication.java @@ -50,7 +50,7 @@ public class MainApplication extends SpringBootServletInitializer { * @return 绑定当前引导类的构建器实例 */ protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { - return builder.sources(new Class[]{MainApplication.class}); + return builder.sources(MainApplication.class); } /** diff --git a/src/main/java/com/midm/app/AppConfig.java b/src/main/java/com/midm/app/AppConfig.java index 8ab7a86..f012ef8 100644 --- a/src/main/java/com/midm/app/AppConfig.java +++ b/src/main/java/com/midm/app/AppConfig.java @@ -12,11 +12,40 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.util.unit.DataSize; +/** + * 【Spring 配置类】{@code AppConfig} + * + * 类职责: + *
    + *
  • 向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mongoTemplate}(MongoTemplate):MongoDB模板
  • + *
+ * + * 协作对象:{@code MongoTemplate}。 + * + * 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。 + */ @Configuration public class AppConfig { + /** + * MongoDB模板;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MongoTemplate mongoTemplate; + /** + * 处理multipart配置Element。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne、new MultipartConfigFactory。 + * @return 处理结果 + */ @Bean public MultipartConfigElement multipartConfigElement() { SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is("files.maxUploadSize")), SystemSetting.class); diff --git a/src/main/java/com/midm/app/AsyncConfig.java b/src/main/java/com/midm/app/AsyncConfig.java index 8ea96cc..c8928eb 100644 --- a/src/main/java/com/midm/app/AsyncConfig.java +++ b/src/main/java/com/midm/app/AsyncConfig.java @@ -11,17 +11,56 @@ import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; +/** + * 【Spring 配置类】{@code AsyncConfig} + * + * 类职责: + *
    + *
  • 向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code TASK_CORE_POOL_SIZE}(int):字段 TASK_CORE_POOL_SIZE
  • + *
  • {@code TASK_MAX_POOL_SIZE}(int):字段 TASK_MAX_POOL_SIZE
  • + *
  • {@code TASK_QUEUE_CAPACITY}(int):字段 TASK_QUEUE_CAPACITY
  • + *
  • {@code asyncExceptionHandler}(AsyncUncaughtExceptionHandler):异步异常Handler
  • + *
+ * + * 协作对象:{@code AsyncUncaughtExceptionHandler}。 + * + * 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。 + */ @Configuration @EnableAsync public class AsyncConfig implements AsyncConfigurer { + /** + * 字段 TASK_CORE_POOL_SIZE。 + */ private static final int TASK_CORE_POOL_SIZE = 10; + /** + * 字段 TASK_MAX_POOL_SIZE。 + */ private static final int TASK_MAX_POOL_SIZE = 20; + /** + * 字段 TASK_QUEUE_CAPACITY。 + */ private static final int TASK_QUEUE_CAPACITY = 100; + /** + * 异步异常Handler。 + */ private AsyncUncaughtExceptionHandler asyncExceptionHandler = new AsyncUncaughtExceptionHandler() { public void handleUncaughtException(Throwable ex, Method method, Object... params) { } }; + /** + * 获取 {@code asyncExecutor}。 + * + * 实现要点:主要调用:new ThreadPoolTaskExecutor。 + * @return 字段/派生属性 {@code asyncExecutor} 的值 + */ @Bean @Primary public Executor getAsyncExecutor() { @@ -34,10 +73,20 @@ public class AsyncConfig implements AsyncConfigurer { return executor; } + /** + * 获取 {@code asyncUncaughtExceptionHandler}。 + * @return 字段/派生属性 {@code asyncUncaughtExceptionHandler} 的值 + */ public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return this.asyncExceptionHandler; } + /** + * 获取 {@code taskScheduler}。 + * + * 实现要点:主要调用:new ThreadPoolTaskScheduler。 + * @return 字段/派生属性 {@code taskScheduler} 的值 + */ @Bean @Primary public ThreadPoolTaskScheduler getTaskScheduler() { @@ -46,6 +95,12 @@ public class AsyncConfig implements AsyncConfigurer { return taskScheduler; } + /** + * 获取 {@code taskExcutor}。 + * + * 实现要点:主要调用:new ThreadPoolTaskExecutor。 + * @return 字段/派生属性 {@code taskExcutor} 的值 + */ @Bean public ThreadPoolTaskExecutor getTaskExcutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); diff --git a/src/main/java/com/midm/app/BasicAuthInterceptor.java b/src/main/java/com/midm/app/BasicAuthInterceptor.java index f09fce5..cdae019 100644 --- a/src/main/java/com/midm/app/BasicAuthInterceptor.java +++ b/src/main/java/com/midm/app/BasicAuthInterceptor.java @@ -11,13 +11,53 @@ import org.springframework.data.util.Pair; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; +/** + * 【Spring 组件】{@code BasicAuthInterceptor} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceKeyService}(DeviceKeyService):设备密钥服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
+ * + * 协作对象:{@code DeviceKeyService、SettingsService}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component public class BasicAuthInterceptor implements HandlerInterceptor { + /** + * 设备密钥服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired DeviceKeyService deviceKeyService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired 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 { String serialNo = request.getHeader("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) { response.setStatus(code); response.setContentType("application/json"); diff --git a/src/main/java/com/midm/app/DbConfig.java b/src/main/java/com/midm/app/DbConfig.java index 584b729..a2531f5 100644 --- a/src/main/java/com/midm/app/DbConfig.java +++ b/src/main/java/com/midm/app/DbConfig.java @@ -47,33 +47,83 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie @EnableMongoRepositories({"com.midm.repository"}) public class DbConfig extends AbstractMongoClientConfiguration { + /** + * 数据库Servers;从配置注入。 + * + * 注解:{@code @Value("${mongo.servers:}")}。 + */ @Value("${mongo.servers:}") private String dbServers; + /** + * 数据库URI;从配置注入。 + * + * 注解:{@code @Value("${mongo.uri:}")}。 + */ @Value("${mongo.uri:}") private String dbUri; + /** + * 数据库Scheme;从配置注入。 + * + * 注解:{@code @Value("${mongo.scheme:mongodb}")}。 + */ @Value("${mongo.scheme:mongodb}") private String dbScheme; + /** + * 数据库Host;从配置注入。 + * + * 注解:{@code @Value("${mongo.host:127.0.0.1}")}。 + */ @Value("${mongo.host:127.0.0.1}") private String dbHost; + /** + * 数据库Port;从配置注入。 + * + * 注解:{@code @Value("${mongo.port:27017}")}。 + */ @Value("${mongo.port:27017}") private Integer dbPort; + /** + * 数据库名称;从配置注入。 + * + * 注解:{@code @Value("${mongo.dbname:db_midm}")}。 + */ @Value("${mongo.dbname:db_midm}") private String dbName; + /** + * 数据库用户;从配置注入。 + * + * 注解:{@code @Value("${mongo.username:}")}。 + */ @Value("${mongo.username:}") private String dbUser; + /** + * 数据库Password;从配置注入。 + * + * 注解:{@code @Value("${mongo.password:}")}。 + */ @Value("${mongo.password:}") private String dbPassword; + /** + * SSLEnabled;从配置注入。 + * + * 注解:{@code @Value("${mongo.ssl:false}")}。 + */ @Value("${mongo.ssl:false}") private boolean sslEnabled; + /** + * 是否keepAlive;从配置注入。 + * + * 注解:{@code @Value("${mongo.keep_alive:true}")}。 + */ @Value("${mongo.keep_alive:true}") private boolean keepAlive; @@ -81,24 +131,59 @@ public class DbConfig extends AbstractMongoClientConfiguration { @Value("${mongo.maxPoolSize:1000}") private int maxPoolSize; + /** + * 字段 connectionsPerHost;从配置注入。 + * + * 注解:{@code @Value("${mongo.connectionsPerHost: 1000}")}。 + */ @Value("${mongo.connectionsPerHost: 1000}") private int connectionsPerHost; + /** + * 字段 connectionMultiplier;从配置注入。 + * + * 注解:{@code @Value("${mongo.connection_multiplier:200}")}。 + */ @Value("${mongo.connection_multiplier:200}") private int connectionMultiplier; + /** + * 字段 connectTimeout;从配置注入。 + * + * 注解:{@code @Value("${mongo.connect_timeout:5000}")}。 + */ @Value("${mongo.connect_timeout:5000}") private int connectTimeout; + /** + * 字段 waitTimeout;从配置注入。 + * + * 注解:{@code @Value("${mongo.wait_timeout:5000}")}。 + */ @Value("${mongo.wait_timeout:5000}") private int waitTimeout; + /** + * 字段 socketTimeout;从配置注入。 + * + * 注解:{@code @Value("${mongo.socket_timeout:0}")}。 + */ @Value("${mongo.socket_timeout:0}") private int socketTimeout; + /** + * 字段 idleTimeout;从配置注入。 + * + * 注解:{@code @Value("${mongo.idle_timeout:30000}")}。 + */ @Value("${mongo.idle_timeout:30000}") private int idleTimeout; + /** + * 数据库Replica设置;从配置注入。 + * + * 注解:{@code @Value("${mongo.replica_set:rs0}")}。 + */ @Value("${mongo.replica_set:rs0}") private String dbReplicaSet; @@ -188,11 +273,17 @@ public class DbConfig extends AbstractMongoClientConfiguration { if (!params.contains("waitqueuetimeoutms")) { uriBuilder.setParameter("waitqueuetimeoutms", String.valueOf(this.waitTimeout)); } + if (!params.contains("connectTimeoutMS")) { + uriBuilder.setParameter("connectTimeoutMS", String.valueOf(this.connectTimeout)); + } boolean isSrv = uriBuilder.getScheme().endsWith("+srv"); if (!isSrv && !params.contains("ssl")) { uriBuilder.setParameter("ssl", String.valueOf(this.sslEnabled)); } + if (this.socketTimeout > 0 && !params.contains("socketTimeoutMS")) { + uriBuilder.setParameter("", ""); + } if (!Strings.isNullOrEmpty(this.dbReplicaSet) && !params.contains("replicaSet")) { uriBuilder.setParameter("replicaSet", this.dbReplicaSet); @@ -220,6 +311,12 @@ public class DbConfig extends AbstractMongoClientConfiguration { return client; } + /** + * 获取 {@code databaseName}。 + * + * 框架注解:{@code @Override}。 + * @return 字符串结果 + */ @Override protected String getDatabaseName() { return this.dbName; diff --git a/src/main/java/com/midm/app/DbInitialize.java b/src/main/java/com/midm/app/DbInitialize.java index 90f470c..5342069 100644 --- a/src/main/java/com/midm/app/DbInitialize.java +++ b/src/main/java/com/midm/app/DbInitialize.java @@ -57,25 +57,84 @@ import org.springframework.data.mongodb.core.schema.JsonSchemaObject; import org.springframework.data.mongodb.core.schema.JsonSchemaObject.Type; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code DbInitialize} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DB_SCHEME_VER_2}(long):字段 DB_SCHEME_VER_2
  • + *
  • {@code DB_SCHEME_VER_3}(long):字段 DB_SCHEME_VER_3
  • + *
  • {@code DB_SCHEME_VER_4}(long):字段 DB_SCHEME_VER_4
  • + *
  • {@code DB_SCHEME_VER_5}(long):字段 DB_SCHEME_VER_5
  • + *
  • {@code DB_SCHEME_VER_6}(long):字段 DB_SCHEME_VER_6
  • + *
  • {@code KEY_DB_SCHEME}(String):字段 KEY_DB_SCHEME
  • + *
+ * + * 协作对象:{@code MongoTemplate、RestoreService}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component public class DbInitialize { + /** + * 字段 DB_SCHEME_VER_2。 + */ private static final long DB_SCHEME_VER_2 = 20092901L; + /** + * 字段 DB_SCHEME_VER_3。 + */ private static final long DB_SCHEME_VER_3 = 22111002L; + /** + * 字段 DB_SCHEME_VER_4。 + */ private static final long DB_SCHEME_VER_4 = 23072101L; + /** + * 字段 DB_SCHEME_VER_5。 + */ private static final long DB_SCHEME_VER_5 = 23082501L; + /** + * 字段 DB_SCHEME_VER_6。 + */ private static final long DB_SCHEME_VER_6 = 24022701L; + /** + * 字段 KEY_DB_SCHEME。 + */ private String KEY_DB_SCHEME = "db.scheme"; + /** + * MongoDB模板;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MongoTemplate mongoTemplate; + /** + * restore服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private RestoreService restoreService; + /** + * 处理contextRefreshed事件。 + */ @EventListener({ContextRefreshedEvent.class}) public void contextRefreshedEvent() { this.initializeDb(); this.updateScheme(); } + /** + * 处理initialize数据库。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 7 个条件分支、1 个循环;主要调用:findOne、save、new SystemSetting、new Update、updateMulti、new Document。 + */ private void initializeDb() { MongoCollection resourceMessageCollection = this.mongoTemplate.getCollection("resourceMessage"); if (resourceMessageCollection == null || resourceMessageCollection.countDocuments() == 0L) { @@ -147,7 +206,16 @@ public class DbInitialize { 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 { if (keys.length > 0) { 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)) { MongoCollection collection = this.getCollection(entityClass); ListIndexesIterable indexes = collection.listIndexes(); @@ -187,14 +263,16 @@ public class DbInitialize { } } + /** + * 处理ensure设备序列Index。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、2 个循环;主要调用:dropIndex、new Document、new CompoundIndexDefinition。 + */ private void ensureDeviceSerialIndex() { MongoCollection collection = this.getCollection(Device.class); - ListIndexesIterable indexes = collection.listIndexes(); boolean isConfigured = false; - MongoCursor indexDefinition = indexes.iterator(); - while(indexDefinition.hasNext()) { - Document index = (Document)indexDefinition.next(); + for(Document index : collection.listIndexes()) { Document keys = (Document)index.get("key", Document.class); if (keys.containsKey("profile.hardware_info.serial_no") && keys.containsKey("siteUuid")) { if (!index.containsKey("collation")) { @@ -214,11 +292,8 @@ public class DbInitialize { } collection = this.getCollection(DeviceLicense.class); - indexes = collection.listIndexes(); - indexDefinition = indexes.iterator(); - while(indexDefinition.hasNext()) { - Document index = (Document)indexDefinition.next(); + for(Document index : collection.listIndexes()) { Document keys = (Document)index.get("key", Document.class); if (keys.size() == 1 && keys.containsKey("plan")) { 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() { if (this.mongoTemplate.collectionExists("siteReport")) { MongoCollection 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 getCollection(Class entityClass) { return this.mongoTemplate.getCollection(this.mongoTemplate.getCollectionName(entityClass)); } + /** + * 获取 {@code dbScheme}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * @return 数量/长度 + */ private long getDbScheme() { SystemSetting setting = (SystemSetting)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(this.KEY_DB_SCHEME)), SystemSetting.class); return setting != null ? setting.getAsLong() : -1L; } + /** + * 判断 {@code standalone}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * @return 字段/派生属性 {@code standalone} 的值 + */ private boolean isStandalone() { HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class); return license != null && license.isStandalone(); diff --git a/src/main/java/com/midm/app/GlobalController.java b/src/main/java/com/midm/app/GlobalController.java index b5ab458..68f3b7d 100644 --- a/src/main/java/com/midm/app/GlobalController.java +++ b/src/main/java/com/midm/app/GlobalController.java @@ -19,34 +19,113 @@ import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestParam; +/** + * 【Web 控制器】{@code GlobalController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code excludeBindingPrefixes}(String[]):字段 excludeBindingPrefixes
  • + *
  • {@code buildProperties}(BuildProperties):构建Properties
  • + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code licenseService}(HostLicenseService):许可证服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
+ * + * 协作对象:{@code String[]、BuildProperties、LocaleService、SettingsService、HostLicenseService、SiteService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @ControllerAdvice 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/"}; + /** + * 构建Properties;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private BuildProperties buildProperties; + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected LocaleService localeService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService licenseService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected SiteService siteService; + /** + * 帮助消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HelpMessageService helpMessageService; + /** + * servletContext路径;从配置注入。 + * + * 注解:{@code @Value("#{servletContext.contextPath}")}。 + */ @Value("#{servletContext.contextPath}") private String servletContextPath; + /** + * 构建版本。 + * @return 字符串结果 + */ @ModelAttribute("buildVersion") public String buildVersion() { return this.buildProperties.getVersion(); } + /** + * 构建时间。 + * @return 字符串结果 + */ @ModelAttribute("buildTime") public String buildTime() { 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") public Object user(HttpServletRequest request, Authentication authentication, @RequestParam(required = false) String language) { if (this.bindModel(request)) { @@ -61,41 +140,78 @@ public final class GlobalController { } } + /** + * 处理设置列表。 + * @return 结果集合,可能为空 + */ @ModelAttribute("settings") public SettingsService settings() { return this.settingsService; } + /** + * 处理locales。 + * @return 处理结果 + */ @ModelAttribute("locales") public LocaleService locales() { return this.localeService; } + /** + * 处理帮助服务。 + * @return 处理结果 + */ @ModelAttribute("helpService") public HelpMessageService helpService() { return this.helpMessageService; } + /** + * 判断 {@code hostValid}。 + * @return 字段/派生属性 {@code hostValid} 的值 + */ @ModelAttribute("isHostValid") public boolean isHostValid() { return this.licenseService.isValid(); } + /** + * 处理设备Limit。 + * @return 数量/长度 + */ @ModelAttribute("deviceLimit") public int deviceLimit() { return this.licenseService.getDeviceLimit(); } + /** + * 处理站点服务。 + * @return 处理结果 + */ @ModelAttribute("siteService") public SiteService siteService() { return this.siteService; } + /** + * 处理context路径。 + * @return 字符串结果 + */ @ModelAttribute("contextPath") public String contextPath() { 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) { User user = new User(); user.setName("Guest"); @@ -113,6 +229,14 @@ public final class GlobalController { return user; } + /** + * 处理bind模型。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean bindModel(HttpServletRequest request) { String uri = request.getRequestURI(); diff --git a/src/main/java/com/midm/app/InterceptorConfig.java b/src/main/java/com/midm/app/InterceptorConfig.java index 6ae4a3a..84a3a2e 100644 --- a/src/main/java/com/midm/app/InterceptorConfig.java +++ b/src/main/java/com/midm/app/InterceptorConfig.java @@ -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.WebMvcConfigurer; +/** + * 【Spring 配置类】{@code InterceptorConfig} + * + * 类职责: + *
    + *
  • 向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code basicAuthInterceptor}(BasicAuthInterceptor):basicAuth拦截器
  • + *
+ * + * 协作对象:{@code BasicAuthInterceptor}。 + * + * 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。 + */ @Configuration public class InterceptorConfig implements WebMvcConfigurer { + /** + * basicAuth拦截器;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private BasicAuthInterceptor basicAuthInterceptor; + /** + * 添加Interceptors。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param registry 参数 {@code registry}({@code InterceptorRegistry}) + */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.basicAuthInterceptor).addPathPatterns(new String[]{"/api/**"}); } diff --git a/src/main/java/com/midm/app/LocaleConfig.java b/src/main/java/com/midm/app/LocaleConfig.java index c5c0921..d2e0c6f 100644 --- a/src/main/java/com/midm/app/LocaleConfig.java +++ b/src/main/java/com/midm/app/LocaleConfig.java @@ -13,8 +13,24 @@ import org.springframework.web.servlet.i18n.SessionLocaleResolver; import org.thymeleaf.TemplateEngine; import org.thymeleaf.templateresolver.StringTemplateResolver; +/** + * 【Spring 配置类】{@code LocaleConfig} + * + * 类职责: + *
    + *
  • 向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。
  • + *
+ * + * 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。 + */ @Configuration public class LocaleConfig { + /** + * 处理string模板Engine。 + * + * 实现要点:主要调用:new TemplateEngine、new StringTemplateResolver。 + * @return 处理结果 + */ @Bean({"stringTemplateEngine"}) public TemplateEngine stringTemplateEngine() { TemplateEngine templateEngine = new TemplateEngine(); @@ -22,6 +38,12 @@ public class LocaleConfig { return templateEngine; } + /** + * 处理语言区域解析器。 + * + * 实现要点:主要调用:new SessionLocaleResolver。 + * @return 处理结果 + */ @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); @@ -29,15 +51,51 @@ public class LocaleConfig { return localeResolver; } + /** + * 处理消息Source。 + * + * 实现要点:主要调用:new ResourceMessageSource。 + * @return 处理结果 + */ @Bean public MessageSource messageSource() { return new ResourceMessageSource(); } + /** + * 【基础设施】{@code ResourceMessageSource} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
+ * + * 协作对象:{@code LocaleService}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ private class ResourceMessageSource extends AbstractMessageSource { + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 解析代码。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code Locale}) + * @return 处理结果 + */ protected MessageFormat resolveCode(String code, Locale locale) { String msg = this.localeService.getMessage(locale, code); return this.createMessageFormat(msg, locale); diff --git a/src/main/java/com/midm/app/PropertiesConfig.java b/src/main/java/com/midm/app/PropertiesConfig.java index 4a26bed..d8c2a80 100644 --- a/src/main/java/com/midm/app/PropertiesConfig.java +++ b/src/main/java/com/midm/app/PropertiesConfig.java @@ -15,8 +15,24 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; +/** + * 【Spring 配置类】{@code PropertiesConfig} + * + * 类职责: + *
    + *
  • 向 Spring 容器装配 Bean、读取外部配置并控制初始化顺序。
  • + *
+ * + * 学习提示:先看 @Bean 方法与 @Value 配置项,再对照 application.properties 和启动日志。 + */ @Configuration public class PropertiesConfig { + /** + * 处理properties。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new PropertySourcesPlaceholderConfigurer、new ArrayList、new File、exists、new FileSystemResource。 + * @return 处理结果 + */ @Bean public static PropertySourcesPlaceholderConfigurer properties() { PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer(); @@ -31,6 +47,13 @@ public class PropertiesConfig { return ppc; } + /** + * 初始化Properties。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new Properties、new FileOutputStream、close。 + * + * @param file 文件({@code File}) + */ private static void initProperties(File file) { Properties properties = new Properties(); 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() { return (new OsInfo()).getConfigFolder("MiDM"); } diff --git a/src/main/java/com/midm/app/SecurityConfig.java b/src/main/java/com/midm/app/SecurityConfig.java index 2ea75e1..53aa0a2 100644 --- a/src/main/java/com/midm/app/SecurityConfig.java +++ b/src/main/java/com/midm/app/SecurityConfig.java @@ -44,9 +44,19 @@ import org.springframework.web.filter.ForwardedHeaderFilter; @Configuration public class SecurityConfig { + /** + * 构建Properties;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private BuildProperties buildProperties; + /** + * 判断是否Debug;从配置注入。 + * + * 注解:{@code @Value("${spring.thymeleaf.cache: true}")}。 + */ @Value("${spring.thymeleaf.cache: true}") private boolean isDebug; @@ -91,7 +101,7 @@ public class SecurityConfig { * 反向代理转发头过滤器(保障真实 IP 提取) */ @Bean - public FilterRegistrationBean forwardedHeaderFilter() { + public FilterRegistrationBean forwardedHeaderFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new ForwardedHeaderFilter()); filterRegistrationBean.setOrder(Integer.MIN_VALUE); diff --git a/src/main/java/com/midm/app/StartupKeeper.java b/src/main/java/com/midm/app/StartupKeeper.java index e236cb5..0da5ee8 100644 --- a/src/main/java/com/midm/app/StartupKeeper.java +++ b/src/main/java/com/midm/app/StartupKeeper.java @@ -16,29 +16,107 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code StartupKeeper} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code hostLicenseService}(HostLicenseService):host许可证服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code helpMessageService}(HelpMessageService):帮助消息服务
  • + *
+ * + * 协作对象:{@code HostLicenseService、DeviceService、SettingsService、LocaleService、UserService、HelpMessageService}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component public class StartupKeeper { + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 帮助消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HelpMessageService helpMessageService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * 报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ReportService reportService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * restore服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private RestoreService restoreService; + /** + * 处理contextRefreshed事件。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + */ @EventListener({ContextRefreshedEvent.class}) private void contextRefreshedEvent() { this.setDefaultTimeZone(); @@ -63,6 +141,9 @@ public class StartupKeeper { } + /** + * 设置Default时间Zone。 + */ private void setDefaultTimeZone() { TimeZone defaultTimeZone = TimeZone.getTimeZone("UTC"); System.setProperty("user.timezone", defaultTimeZone.getID()); diff --git a/src/main/java/com/midm/app/converter/DateConverter.java b/src/main/java/com/midm/app/converter/DateConverter.java index c0a63b3..3c84153 100644 --- a/src/main/java/com/midm/app/converter/DateConverter.java +++ b/src/main/java/com/midm/app/converter/DateConverter.java @@ -6,8 +6,26 @@ import org.joda.time.DateTime; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code DateConverter} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component -public class DateConverter implements Converter { +public class DateConverter implements Converter { + /** + * 处理转换。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new DateTime、new Date、parse。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + */ public Date convert(String source) { DateTime date = null; diff --git a/src/main/java/com/midm/app/converter/DirectionConverter.java b/src/main/java/com/midm/app/converter/DirectionConverter.java index 3caec26..4fbf312 100644 --- a/src/main/java/com/midm/app/converter/DirectionConverter.java +++ b/src/main/java/com/midm/app/converter/DirectionConverter.java @@ -5,8 +5,24 @@ import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code DirectionConverter} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component -public class DirectionConverter implements Converter { +public class DirectionConverter implements Converter { + /** + * 处理转换。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + */ public Sort.Direction convert(String source) { return Direction.valueOf(source.toUpperCase()); } diff --git a/src/main/java/com/midm/app/converter/JsonElementConverter.java b/src/main/java/com/midm/app/converter/JsonElementConverter.java index 31f0254..5751b62 100644 --- a/src/main/java/com/midm/app/converter/JsonElementConverter.java +++ b/src/main/java/com/midm/app/converter/JsonElementConverter.java @@ -7,8 +7,27 @@ import java.nio.charset.Charset; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code JsonElementConverter} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component public class JsonElementConverter implements Converter { + /** + * 处理转换。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new RuntimeException。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + * @throws RuntimeException 当 RuntimeException 条件不满足或底层调用失败时抛出。 + */ public JsonElement convert(String source) { try { source = URLDecoder.decode(source, Charset.defaultCharset()); diff --git a/src/main/java/com/midm/app/converter/JsonObjectConverter.java b/src/main/java/com/midm/app/converter/JsonObjectConverter.java index 11185aa..56309d9 100644 --- a/src/main/java/com/midm/app/converter/JsonObjectConverter.java +++ b/src/main/java/com/midm/app/converter/JsonObjectConverter.java @@ -7,8 +7,27 @@ import java.nio.charset.Charset; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code JsonObjectConverter} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component public class JsonObjectConverter implements Converter { + /** + * 处理转换。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new RuntimeException。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + * @throws RuntimeException 当 RuntimeException 条件不满足或底层调用失败时抛出。 + */ public JsonObject convert(String source) { try { source = URLDecoder.decode(source, Charset.defaultCharset()); diff --git a/src/main/java/com/midm/app/converter/UserAgentConverter.java b/src/main/java/com/midm/app/converter/UserAgentConverter.java index e59b1ae..3ae2f2e 100644 --- a/src/main/java/com/midm/app/converter/UserAgentConverter.java +++ b/src/main/java/com/midm/app/converter/UserAgentConverter.java @@ -4,8 +4,26 @@ import com.mitac.cell.internet.http.UserAgent; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; +/** + * 【Spring 组件】{@code UserAgentConverter} + * + * 类职责: + *
    + *
  • 作为 Spring 组件参与依赖注入或生命周期回调。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Component -public class UserAgentConverter implements Converter { +public class UserAgentConverter implements Converter { + /** + * 处理转换。 + * + * 实现要点:主要调用:new UserAgent。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + */ public UserAgent convert(String source) { return new UserAgent(source); } diff --git a/src/main/java/com/midm/app/converter/package-info.java b/src/main/java/com/midm/app/converter/package-info.java new file mode 100644 index 0000000..e57b76f --- /dev/null +++ b/src/main/java/com/midm/app/converter/package-info.java @@ -0,0 +1,16 @@ +/** + * Spring MVC 参数类型转换器:把请求中的字符串转换为日期、方向、JSON、User-Agent 等对象。 + * + *

本包主要类型: + *

    + *
  • {@link DateConverter}
  • + *
  • {@link DirectionConverter}
  • + *
  • {@link JsonElementConverter}
  • + *
  • {@link JsonObjectConverter}
  • + *
  • {@link UserAgentConverter}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.app.converter; diff --git a/src/main/java/com/midm/app/package-info.java b/src/main/java/com/midm/app/package-info.java new file mode 100644 index 0000000..081d994 --- /dev/null +++ b/src/main/java/com/midm/app/package-info.java @@ -0,0 +1,23 @@ +/** + * 应用启动与基础设施配置包:Mongo、Security、WebSocket、Locale、启动初始化等。 + * + *

本包主要类型: + *

    + *
  • {@link AppConfig}
  • + *
  • {@link AsyncConfig}
  • + *
  • {@link BasicAuthInterceptor}
  • + *
  • {@link DbConfig}
  • + *
  • {@link DbInitialize}
  • + *
  • {@link GlobalController}
  • + *
  • {@link InterceptorConfig}
  • + *
  • {@link LocaleConfig}
  • + *
  • {@link PropertiesConfig}
  • + *
  • {@link SecurityConfig}
  • + *
  • {@link StartupKeeper}
  • + *
  • {@link WebSocketConfig}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.app; diff --git a/src/main/java/com/midm/constant/GeneralConst.java b/src/main/java/com/midm/constant/GeneralConst.java index f57053a..f3c398a 100644 --- a/src/main/java/com/midm/constant/GeneralConst.java +++ b/src/main/java/com/midm/constant/GeneralConst.java @@ -1,46 +1,193 @@ package com.midm.constant; +/** + * 【常量定义】{@code GeneralConst} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_KEY}(String):字段 KEY_KEY
  • + *
  • {@code KEY_VALUE}(String):字段 KEY_VALUE
  • + *
  • {@code KEY_AUTH_KEY}(String):字段 KEY_AUTH_KEY
  • + *
  • {@code KEY_ID}(String):字段 KEY_ID
  • + *
  • {@code KEY_NAME}(String):字段 KEY_NAME
  • + *
  • {@code KEY_TITLE}(String):字段 KEY_TITLE
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class GeneralConst { + /** + * 字段 KEY_KEY。 + */ public static final String KEY_KEY = "key"; + /** + * 字段 KEY_VALUE。 + */ public static final String KEY_VALUE = "value"; + /** + * 字段 KEY_AUTH_KEY。 + */ public static final String KEY_AUTH_KEY = "auth_key"; + /** + * 字段 KEY_ID。 + */ public static final String KEY_ID = "id"; + /** + * 字段 KEY_NAME。 + */ public static final String KEY_NAME = "name"; + /** + * 字段 KEY_TITLE。 + */ public static final String KEY_TITLE = "title"; + /** + * 字段 KEY_PHONE。 + */ public static final String KEY_PHONE = "phone"; + /** + * 字段 KEY_MOBILE。 + */ public static final String KEY_MOBILE = "mobile"; + /** + * 字段 KEY_THEME。 + */ public static final String KEY_THEME = "theme"; + /** + * 字段 KEY_CONTENT。 + */ public static final String KEY_CONTENT = "content"; + /** + * 字段 KEY_SUMMARY。 + */ public static final String KEY_SUMMARY = "summary"; + /** + * 字段 KEY_USER。 + */ public static final String KEY_USER = "user"; + /** + * 字段 KEY_OWNER。 + */ public static final String KEY_OWNER = "owner"; + /** + * 字段 DEFAULT。 + */ public static final String DEFAULT = "default"; + /** + * 字段 HTML。 + */ public static final String HTML = ".html"; + /** + * 字段 CATEGORY_APP。 + */ public static final String CATEGORY_APP = "app"; + /** + * 字段 CATEGORY_GENERAL。 + */ public static final String CATEGORY_GENERAL = "general"; + /** + * 字段 CATEGORY_OTA。 + */ public static final String CATEGORY_OTA = "ota"; + /** + * 字段 CATEGORY_WEBAPP。 + */ public static final String CATEGORY_WEBAPP = "webapp"; + /** + * 字段 CATEGORY_OTHER。 + */ public static final String CATEGORY_OTHER = "other"; + /** + * 字段 CATEGORY_REPORT。 + */ public static final String CATEGORY_REPORT = "report"; + /** + * 字段 CATEGORY_FILE。 + */ public static final String CATEGORY_FILE = "file"; + /** + * 字段 CATEGORY_DEVICE。 + */ public static final String CATEGORY_DEVICE = "device"; + /** + * 字段 CATEGORY_SCREEN。 + */ public static final String CATEGORY_SCREEN = "screen"; + /** + * 字段 CATEGORY_INSTALLED。 + */ public static final String CATEGORY_INSTALLED = "installed"; + /** + * 字段 CATEGORY_STORAGE。 + */ public static final String CATEGORY_STORAGE = "storage"; + /** + * 字段 PROFILE。 + */ public static final String PROFILE = "profile"; + /** + * 字段 LOGO_LIGHT。 + */ public static final String LOGO_LIGHT = "light"; + /** + * 字段 LOGO_DARK。 + */ public static final String LOGO_DARK = "dark"; + /** + * 字段 FAVICON。 + */ public static final String FAVICON = "favicon"; + /** + * 字段 PROFILE_USERGROUP。 + */ public static final String PROFILE_USERGROUP = "usergroup"; + /** + * 字段 PROFILE_ORGANIZATION。 + */ public static final String PROFILE_ORGANIZATION = "org"; + /** + * 字段 PROFILE_SITE。 + */ public static final String PROFILE_SITE = "site"; + /** + * 字段 PROFILE_DEVICE_GROUP。 + */ public static final String PROFILE_DEVICE_GROUP = "deviceGroup"; + /** + * 字段 DEFAULT_TOKEN_LIFE_CYCLE。 + */ public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L; + /** + * 字段 KEY_LANGUAGE。 + */ public static final String KEY_LANGUAGE = "language"; + /** + * 字段 KEY_DESC。 + */ public static final String KEY_DESC = "desc"; + /** + * 字段 KEY_DEVICE。 + */ public static final String KEY_DEVICE = "device"; + /** + * 字段 KEY_GROUP。 + */ public static final String KEY_GROUP = "group"; + /** + * 字段 KEY_GROUPS。 + */ public static final String KEY_GROUPS = "groups"; + /** + * 字段 KEY_GROUP_UUID。 + */ public static final String KEY_GROUP_UUID = "groupUuid"; + /** + * 字段 KEY_APP_FILE。 + */ public static final String KEY_APP_FILE = "appFile"; } diff --git a/src/main/java/com/midm/constant/LocaleConst.java b/src/main/java/com/midm/constant/LocaleConst.java index 7300036..af91a8c 100644 --- a/src/main/java/com/midm/constant/LocaleConst.java +++ b/src/main/java/com/midm/constant/LocaleConst.java @@ -3,9 +3,38 @@ package com.midm.constant; import java.util.Locale; import org.springframework.data.mongodb.core.query.Collation; +/** + * 【常量定义】{@code LocaleConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DEFAULT_LOCALE}(Locale):字段 DEFAULT_LOCALE
  • + *
  • {@code EN_US}(String):字段 EN_US
  • + *
  • {@code COLLATION_DEFAULT}(Collation):字段 COLLATION_DEFAULT
  • + *
+ * + * 协作对象:{@code Locale、Collation}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class LocaleConst { + /** + * 字段 DEFAULT_LOCALE。 + */ public static final Locale DEFAULT_LOCALE; + /** + * 字段 EN_US。 + */ public static final String EN_US = "en-US"; + /** + * 字段 COLLATION_DEFAULT。 + */ public static final Collation COLLATION_DEFAULT; static { diff --git a/src/main/java/com/midm/constant/LocationConst.java b/src/main/java/com/midm/constant/LocationConst.java index e74c499..053ccfb 100644 --- a/src/main/java/com/midm/constant/LocationConst.java +++ b/src/main/java/com/midm/constant/LocationConst.java @@ -1,8 +1,39 @@ package com.midm.constant; +/** + * 【常量定义】{@code LocationConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_LAT}(String):字段 KEY_LAT
  • + *
  • {@code KEY_LATITUDE}(String):字段 KEY_LATITUDE
  • + *
  • {@code KEY_LON}(String):字段 KEY_LON
  • + *
  • {@code KEY_LONGITUDE}(String):字段 KEY_LONGITUDE
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class LocationConst { + /** + * 字段 KEY_LAT。 + */ public static String KEY_LAT = "lat"; + /** + * 字段 KEY_LATITUDE。 + */ public static String KEY_LATITUDE = "latitude"; + /** + * 字段 KEY_LON。 + */ public static String KEY_LON = "lon"; + /** + * 字段 KEY_LONGITUDE。 + */ public static String KEY_LONGITUDE = "longitude"; } diff --git a/src/main/java/com/midm/constant/MidmConst.java b/src/main/java/com/midm/constant/MidmConst.java index 2f926e9..6f8fa34 100644 --- a/src/main/java/com/midm/constant/MidmConst.java +++ b/src/main/java/com/midm/constant/MidmConst.java @@ -1,191 +1,773 @@ package com.midm.constant; +/** + * 【常量定义】{@code MidmConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code MIDM}(String):字段 MIDM
  • + *
  • {@code KEY_REQUEST}(String):字段 KEY_REQUEST
  • + *
  • {@code KEY_PARAMS}(String):字段 KEY_PARAMS
  • + *
  • {@code KEY_ID}(String):字段 KEY_ID
  • + *
  • {@code KEY_UUID}(String):字段 KEY_UUID
  • + *
  • {@code KEY_EULA}(String):字段 KEY_EULA
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class MidmConst { + /** + * 字段 MIDM。 + */ public static final String MIDM = "midm"; + /** + * 字段 KEY_REQUEST。 + */ public static final String KEY_REQUEST = "request"; + /** + * 字段 KEY_PARAMS。 + */ public static final String KEY_PARAMS = "params"; + /** + * 字段 KEY_ID。 + */ public static final String KEY_ID = "_id"; + /** + * 字段 KEY_UUID。 + */ public static final String KEY_UUID = "uuid"; + /** + * 字段 KEY_EULA。 + */ public static final String KEY_EULA = "eula"; + /** + * 字段 KEY_SITE。 + */ public static final String KEY_SITE = "site"; + /** + * 字段 KEY_SITES。 + */ public static final String KEY_SITES = "sites"; + /** + * 字段 KEY_SITE_UUID。 + */ public static final String KEY_SITE_UUID = "siteUuid"; + /** + * 字段 KEY_SITE_HAS_BATTERY_PLAN。 + */ public static final String KEY_SITE_HAS_BATTERY_PLAN = "hasBatteryPlan"; + /** + * 字段 KEY_GROUP_UUID。 + */ public static final String KEY_GROUP_UUID = "groupUuid"; + /** + * 字段 KEY_PARENT_UUID。 + */ public static final String KEY_PARENT_UUID = "parentUuid"; + /** + * 字段 KEY_ID_NAME。 + */ public static final String KEY_ID_NAME = "idName"; + /** + * 字段 KEY_SITE_ID_NAME。 + */ public static final String KEY_SITE_ID_NAME = "siteIdName"; + /** + * 字段 KEY_USER_UUID。 + */ public static final String KEY_USER_UUID = "userUuid"; + /** + * 字段 KEY_DEVICE_UUID。 + */ public static final String KEY_DEVICE_UUID = "deviceUuid"; + /** + * 字段 KEY_DEVICE_SERIAL。 + */ public static final String KEY_DEVICE_SERIAL = "deviceSerial"; + /** + * 字段 KEY_DEVICE_PROFILE。 + */ public static final String KEY_DEVICE_PROFILE = "deviceProfile"; + /** + * 字段 KEY_RSA。 + */ public static final String KEY_RSA = "rsa"; + /** + * 字段 KEY_SERIALNO。 + */ public static final String KEY_SERIALNO = "serialNo"; + /** + * 字段 KEY_TIMEZONE。 + */ public static final String KEY_TIMEZONE = "timeZone"; + /** + * 字段 KEY_WIFI_MAC。 + */ public static final String KEY_WIFI_MAC = "wifiMac"; + /** + * 字段 KEY_FROM。 + */ public static final String KEY_FROM = "from"; + /** + * 字段 KEY_TO。 + */ public static final String KEY_TO = "to"; + /** + * 字段 KEY_SELF_ENROLL。 + */ public static final String KEY_SELF_ENROLL = "selfEnroll"; + /** + * 字段 KEY_IF_EXISTS。 + */ public static final String KEY_IF_EXISTS = "ifExists"; + /** + * 字段 KEY_RTC_ENABLED。 + */ public static final String KEY_RTC_ENABLED = "rtcEnabled"; + /** + * 字段 KEY_SOURCES。 + */ public static final String KEY_SOURCES = "sources"; + /** + * 字段 KEY_EMAIL。 + */ public static final String KEY_EMAIL = "email"; + /** + * 字段 KEY_ENABLE。 + */ public static final String KEY_ENABLE = "enable"; + /** + * 字段 KEY_ENABLED。 + */ public static final String KEY_ENABLED = "enabled"; + /** + * 字段 KEY_CLIENT_VERSION。 + */ public static final String KEY_CLIENT_VERSION = "clientVersion"; + /** + * 字段 KEY_BATTERY_SERIAL。 + */ public static final String KEY_BATTERY_SERIAL = "batterySerial"; + /** + * 字段 KEY_BATTERY_CONDITION。 + */ public static final String KEY_BATTERY_CONDITION = "batteryCondition"; + /** + * 字段 KEY_COMMAND。 + */ public static final String KEY_COMMAND = "command"; + /** + * 字段 KEY_CATEGORY。 + */ public static final String KEY_CATEGORY = "category"; + /** + * 字段 KEY_LOG。 + */ public static final String KEY_LOG = "log"; + /** + * 字段 KEY_LOGGED_AT。 + */ public static final String KEY_LOGGED_AT = "loggedAt"; + /** + * 字段 KEY_INCLUDES。 + */ public static final String KEY_INCLUDES = "includes"; + /** + * 字段 KEY_URL。 + */ public static final String KEY_URL = "url"; + /** + * 字段 KEY_PATH。 + */ public static final String KEY_PATH = "path"; + /** + * 字段 KEY_ROOT。 + */ public static final String KEY_ROOT = "root"; + /** + * 字段 KEY_OWNER。 + */ public static final String KEY_OWNER = "owner"; + /** + * 字段 KEY_REGION。 + */ public static final String KEY_REGION = "region"; + /** + * 字段 KEY_MODEM。 + */ public static final String KEY_MODEM = "modem"; + /** + * 字段 KEY_USER。 + */ public static final String KEY_USER = "user"; + /** + * 字段 KEY_DEST。 + */ public static final String KEY_DEST = "dest"; + /** + * 字段 KEY_PUSH。 + */ public static final String KEY_PUSH = "push"; + /** + * 字段 KEY_MOVE。 + */ public static final String KEY_MOVE = "move"; + /** + * 字段 KEY_DELETE。 + */ public static final String KEY_DELETE = "delete"; + /** + * 字段 KEY_EXTRACT。 + */ public static final String KEY_EXTRACT = "extract"; + /** + * 字段 KEY_KEEP_IN_HOST。 + */ public static final String KEY_KEEP_IN_HOST = "keepInHost"; + /** + * 字段 KEY_IS_GLOBAL。 + */ public static final String KEY_IS_GLOBAL = "isGlobal"; + /** + * 字段 KEY_UPDATE_VIA。 + */ public static final String KEY_UPDATE_VIA = "update_via"; + /** + * 字段 KEY_SILENT_UPDATE。 + */ public static final String KEY_SILENT_UPDATE = "silent_update"; + /** + * 字段 KEY_ALLOW_DOWNGRADE。 + */ public static final String KEY_ALLOW_DOWNGRADE = "allow_downgrade"; + /** + * 字段 KEY_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"; + /** + * 字段 KEY_REMOVE_AFTER_INSTALL。 + */ public static final String KEY_REMOVE_AFTER_INSTALL = "remove_after_install"; + /** + * 字段 KEY_CREATED。 + */ public static final String KEY_CREATED = "created"; + /** + * 字段 KEY_UPDATED。 + */ public static final String KEY_UPDATED = "updated"; + /** + * 字段 KEY_APPLIED。 + */ public static final String KEY_APPLIED = "applied"; + /** + * 字段 KEY_REPORTED_AT。 + */ public static final String KEY_REPORTED_AT = "reportedAt"; + /** + * 字段 KEY_RESELLER。 + */ public static final String KEY_RESELLER = "reseller"; + /** + * 字段 KEY_RESELLER_SITE。 + */ public static final String KEY_RESELLER_SITE = "resellerSite"; + /** + * 字段 KEY_IS_RESELLER。 + */ public static final String KEY_IS_RESELLER = "isReseller"; + /** + * 字段 KEY_DEVICE_LIMIT。 + */ public static final String KEY_DEVICE_LIMIT = "deviceLimit"; + /** + * 字段 KEY_LICENSE。 + */ public static final String KEY_LICENSE = "license"; + /** + * 字段 KEY_RENEW。 + */ public static final String KEY_RENEW = "renew"; + /** + * 字段 KEY_AUTO_RENEW。 + */ public static final String KEY_AUTO_RENEW = "autoRenew"; + /** + * 字段 KEY_RENEW_TO_SAME_MODEL。 + */ public static final String KEY_RENEW_TO_SAME_MODEL = "renewToSameModel"; + /** + * 字段 KEY_MODEL。 + */ public static final String KEY_MODEL = "model"; + /** + * 字段 KEY_LICENSE_MODEL。 + */ public static final String KEY_LICENSE_MODEL = "licenseModel"; + /** + * 字段 KEY_LICENSE_FEATURE。 + */ public static final String KEY_LICENSE_FEATURE = "licenseFeature"; + /** + * 字段 KEY_FEATURES。 + */ public static final String KEY_FEATURES = "features"; + /** + * 字段 KEY_PLAN。 + */ public static final String KEY_PLAN = "plan"; + /** + * 字段 KEY_TARGET_PLAN。 + */ public static final String KEY_TARGET_PLAN = "targetPlan"; + /** + * 字段 KEY_SYSTEM。 + */ public static final String KEY_SYSTEM = "system"; + /** + * 字段 KEY_STORE。 + */ public static final String KEY_STORE = "store"; + /** + * 字段 KEY_KEYSTORE。 + */ public static final String KEY_KEYSTORE = "keyStore"; + /** + * 字段 KEY_REPORT。 + */ public static final String KEY_REPORT = "report"; + /** + * 字段 KEY_TEMP。 + */ public static final String KEY_TEMP = "temp"; + /** + * 字段 KEY_DATE_TIME。 + */ public static final String KEY_DATE_TIME = "dateTime"; + /** + * 字段 KEY_HOUR_FORMAT。 + */ public static final String KEY_HOUR_FORMAT = "hourFormat"; + /** + * 字段 KEY_ACTIVITY。 + */ public static final String KEY_ACTIVITY = "activity"; + /** + * 字段 KEY_AMOUNT。 + */ public static final String KEY_AMOUNT = "amount"; + /** + * 字段 KEY_TOTAL。 + */ public static final String KEY_TOTAL = "total"; + /** + * 字段 KEY_FRESH。 + */ public static final String KEY_FRESH = "fresh"; + /** + * 字段 KEY_FRESH_EXPIRING。 + */ public static final String KEY_FRESH_EXPIRING = "freshExpiring"; + /** + * 字段 KEY_USED。 + */ public static final String KEY_USED = "used"; + /** + * 字段 KEY_USED_EXPIRING。 + */ public static final String KEY_USED_EXPIRING = "usedExpiring"; + /** + * 字段 KEY_ACTIVE。 + */ public static final String KEY_ACTIVE = "active"; + /** + * 字段 KEY_INACTIVE。 + */ public static final String KEY_INACTIVE = "inactive"; + /** + * 字段 KEY_EXPIRED。 + */ public static final String KEY_EXPIRED = "expired"; + /** + * 字段 KEY_LICENSED。 + */ public static final String KEY_LICENSED = "licensed"; + /** + * 字段 KEY_MEMORY。 + */ public static final String KEY_MEMORY = "memory"; + /** + * 字段 KEY_BATTERY。 + */ public static final String KEY_BATTERY = "battery"; + /** + * 字段 KEY_LOCATION。 + */ public static final String KEY_LOCATION = "location"; + /** + * 字段 KEY_DATA_USAGE。 + */ public static final String KEY_DATA_USAGE = "dataUsage"; + /** + * 字段 REQUEST_APPS。 + */ public static final String REQUEST_APPS = "apps"; + /** + * 字段 REQUEST_OTAS。 + */ public static final String REQUEST_OTAS = "otas"; + /** + * 字段 REQUEST_FILES。 + */ public static final String REQUEST_FILES = "files"; + /** + * 字段 REQUEST_ENROLL。 + */ public static final String REQUEST_ENROLL = "enroll"; + /** + * 字段 REQUEST_DATA_USAGE。 + */ public static final String REQUEST_DATA_USAGE = "data_usage"; + /** + * 字段 KEY_REPEAT_OPTION。 + */ public static final String KEY_REPEAT_OPTION = "repeatOption"; + /** + * 字段 KEY_REPEAT_PERIOD。 + */ public static final String KEY_REPEAT_PERIOD = "repeatPeriod"; + /** + * 字段 KEY_REPEAT_EVERY。 + */ public static final String KEY_REPEAT_EVERY = "repeatEvery"; + /** + * 字段 VALUE_HOST。 + */ public static final String VALUE_HOST = "host"; + /** + * 字段 VALUE_DEVICE。 + */ public static final String VALUE_DEVICE = "device"; + /** + * 字段 VALUE_WIFI。 + */ public static final String VALUE_WIFI = "wifi"; + /** + * 字段 VALUE_MOBILE。 + */ public static final String VALUE_MOBILE = "mobile"; + /** + * 字段 VALUE_BOTH。 + */ public static final String VALUE_BOTH = "both"; + /** + * 字段 VALUE_ALL。 + */ public static final String VALUE_ALL = "all"; + /** + * 字段 VALUE_SELECTED。 + */ public static final String VALUE_SELECTED = "selected"; + /** + * 字段 TYPE_WIFI。 + */ public static final String TYPE_WIFI = "WIFI"; + /** + * 字段 TYPE_MOBILE。 + */ public static final String TYPE_MOBILE = "MOBILE"; + /** + * 字段 VALUE_LOGO。 + */ public static final String VALUE_LOGO = "logo"; + /** + * 字段 VALUE_PROFILE。 + */ public static final String VALUE_PROFILE = "profile"; + /** + * 字段 VALUE_BACKGROUND。 + */ public static final String VALUE_BACKGROUND = "background"; + /** + * 字段 VALUE_DEFAULT_HEART_BEAT。 + */ public static final int VALUE_DEFAULT_HEART_BEAT = 300; + /** + * 字段 KEY_WEBSOCKET_EXTENSION。 + */ public static final String KEY_WEBSOCKET_EXTENSION = "sec-websocket-extensions"; + /** + * 字段 REQUEST_UPDATE_PROFILE。 + */ public static final String REQUEST_UPDATE_PROFILE = "update_profile"; + /** + * 字段 CODE_UPDATE_PROFILE。 + */ public static final int CODE_UPDATE_PROFILE = 131; + /** + * 字段 REQUEST_UPDATE_ALL_PROFILES。 + */ public static final String REQUEST_UPDATE_ALL_PROFILES = "update_profile_all"; + /** + * 字段 CODE_UPDATE_ALL_PROFILES。 + */ public static final int CODE_UPDATE_ALL_PROFILES = 132; + /** + * 字段 REQUEST_SYNC_PROFILE。 + */ public static final String REQUEST_SYNC_PROFILE = "sync_profile"; + /** + * 字段 CODE_SYNC_PROFILE。 + */ public static final int CODE_SYNC_PROFILE = 136; + /** + * 字段 REQUEST_REMOVE_PROFILE。 + */ public static final String REQUEST_REMOVE_PROFILE = "remove_profile"; + /** + * 字段 CODE_REMOVE_PROFILE。 + */ public static final int CODE_REMOVE_PROFILE = 136; + /** + * 字段 KEY_THEME。 + */ public static final String KEY_THEME = "theme"; + /** + * 字段 KEY_NOTIFICATION。 + */ public static final String KEY_NOTIFICATION = "noti"; + /** + * 字段 KEY_COUNT。 + */ public static final String KEY_COUNT = "count"; + /** + * 字段 KEY_PAGE。 + */ public static final String KEY_PAGE = "page"; + /** + * 字段 KEY_EXPIRY。 + */ public static final String KEY_EXPIRY = "expiry"; + /** + * 字段 KEY_LICENSE_EXPIRY。 + */ public static final String KEY_LICENSE_EXPIRY = "licenseExpiry"; + /** + * 字段 KEY_FINAL_EXPIRY。 + */ public static final String KEY_FINAL_EXPIRY = "finalExpiry"; + /** + * 字段 KEY_ACTIVATED_AT。 + */ public static final String KEY_ACTIVATED_AT = "activatedAt"; + /** + * 字段 KEY_ACTIVATION_COUNT。 + */ public static final String KEY_ACTIVATION_COUNT = "activationCount"; + /** + * 字段 KEY_CHILD_SITE。 + */ public static final String KEY_CHILD_SITE = "childSite"; + /** + * 字段 KEY_URL_EXPIRY。 + */ public static final String KEY_URL_EXPIRY = "urlExpiry"; + /** + * 字段 KEY_ICON_EXPIRY。 + */ public static final String KEY_ICON_EXPIRY = "iconExpiry"; + /** + * 字段 KEY_EXPIRED_IN_10。 + */ public static final String KEY_EXPIRED_IN_10 = "expiredIn10"; + /** + * 字段 KEY_EXPIRED_IN_30。 + */ public static final String KEY_EXPIRED_IN_30 = "expiredIn30"; + /** + * 字段 KEY_EXPIRED_IN_45。 + */ 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"; + /** + * 字段 KEY_FOR_WHAT。 + */ public static final String KEY_FOR_WHAT = "forWhat"; + /** + * 字段 KEY_REFERENCE。 + */ public static final String KEY_REFERENCE = "reference"; + /** + * 字段 KEY_LOGGER。 + */ public static final String KEY_LOGGER = "logger"; + /** + * 字段 KEY_INSTALL。 + */ public static final String KEY_INSTALL = "install"; + /** + * 字段 KEY_INSTALL_APPS。 + */ public static final String KEY_INSTALL_APPS = "installApps"; + /** + * 字段 KEY_SHOW。 + */ public static final String KEY_SHOW = "show"; + /** + * 字段 KEY_MSETTINGS。 + */ public static final String KEY_MSETTINGS = "msettings"; + /** + * 字段 KEY_WALLPAPER。 + */ public static final String KEY_WALLPAPER = "wallpaper"; + /** + * 字段 PLAN_STANDARD_BATTERYPRO。 + */ public static final String PLAN_STANDARD_BATTERYPRO = "standardWithBatteryPro"; + /** + * 字段 PLAN_STANDARD。 + */ public static final String PLAN_STANDARD = "standard"; + /** + * 字段 PLAN_LITE。 + */ public static final String PLAN_LITE = "lite"; + /** + * 字段 KEY_ERROR。 + */ public static final String KEY_ERROR = "error"; + /** + * 字段 KEY_PAGE_FOR。 + */ public static final String KEY_PAGE_FOR = "pageFor"; + /** + * 字段 KEY_HAS_USER。 + */ public static final String KEY_HAS_USER = "hasUser"; + /** + * 字段 KEY_IP。 + */ public static final String KEY_IP = "ip"; + /** + * 字段 KEY_IP_ADDR。 + */ public static final String KEY_IP_ADDR = "ip_addr"; + /** + * 字段 KEY_PUBLIC_IP。 + */ public static final String KEY_PUBLIC_IP = "public_ip"; + /** + * 字段 KEY_ADD。 + */ public static final String KEY_ADD = "add"; + /** + * 字段 KEY_REMOVE。 + */ public static final String KEY_REMOVE = "remove"; + /** + * 字段 KEY_PO。 + */ public static final String KEY_PO = "po"; + /** + * 字段 KEY_NOTE。 + */ public static final String KEY_NOTE = "note"; + /** + * 字段 KEY_NOTES。 + */ public static final String KEY_NOTES = "notes"; + /** + * 字段 KEY_SETTINGS。 + */ public static final String KEY_SETTINGS = "settings"; + /** + * 字段 KEY_PROFILES。 + */ public static final String KEY_PROFILES = "profiles"; + /** + * 字段 KEY_STATUS。 + */ public static final String KEY_STATUS = "status"; + /** + * 字段 STATUS_ADDED。 + */ public static final String STATUS_ADDED = "added"; + /** + * 字段 STATUS_REPLACED。 + */ public static final String STATUS_REPLACED = "replaced"; + /** + * 字段 STATUS_REMOVED。 + */ public static final String STATUS_REMOVED = "removed"; + /** + * 字段 VALUE_UNKNOWN。 + */ public static final String VALUE_UNKNOWN = "unknown"; + /** + * 字段 VALUE_NONE。 + */ public static final String VALUE_NONE = "none"; + /** + * 字段 VALUE_NEVER。 + */ public static final String VALUE_NEVER = "never"; + /** + * 字段 VALUE_DISABLED。 + */ public static final String VALUE_DISABLED = "disabled"; + /** + * 字段 VALUE_ONCE。 + */ public static final String VALUE_ONCE = "once"; + /** + * 字段 VALUE_BLOCKED。 + */ public static final String VALUE_BLOCKED = "blocked"; + /** + * 字段 VALUE_MITAC。 + */ public static final String VALUE_MITAC = "mitac"; + /** + * 字段 PACKAGE_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"; + /** + * 字段 PACKAGE_MILOCK。 + */ public static final String PACKAGE_MILOCK = "com.mitac.milock"; + /** + * 字段 PACKAGE_MIBATTERY。 + */ public static final String PACKAGE_MIBATTERY = "com.mitac.utils.battery"; + /** + * 字段 COLLECTION_MIDM_LOG。 + */ public static final String COLLECTION_MIDM_LOG = "midmLog"; + /** + * 字段 COLLECTION_DEVICE_REPORT。 + */ public static final String COLLECTION_DEVICE_REPORT = "deviceReport"; + /** + * 字段 COLOR_RED。 + */ public static final String COLOR_RED = "red"; } diff --git a/src/main/java/com/midm/constant/PropertyConst.java b/src/main/java/com/midm/constant/PropertyConst.java index a743f27..9b54f47 100644 --- a/src/main/java/com/midm/constant/PropertyConst.java +++ b/src/main/java/com/midm/constant/PropertyConst.java @@ -1,93 +1,381 @@ package com.midm.constant; +/** + * 【常量定义】{@code PropertyConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code CATEGORY_HADRWARE}(String):字段 CATEGORY_HADRWARE
  • + *
  • {@code CATEGORY_SOFTWARE_INFO}(String):字段 CATEGORY_SOFTWARE_INFO
  • + *
  • {@code CATEGORY_NETWORK}(String):字段 CATEGORY_NETWORK
  • + *
  • {@code CATEGORY_SHIPMENT}(String):字段 CATEGORY_SHIPMENT
  • + *
  • {@code CATEGORY_EVENT}(String):字段 CATEGORY_EVENT
  • + *
  • {@code CATEGORY_ACTIVITY}(String):字段 CATEGORY_ACTIVITY
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class PropertyConst { + /** + * 字段 CATEGORY_HADRWARE。 + */ public static final String CATEGORY_HADRWARE = "hardware_info"; + /** + * 字段 CATEGORY_SOFTWARE_INFO。 + */ public static final String CATEGORY_SOFTWARE_INFO = "software_info"; + /** + * 字段 CATEGORY_NETWORK。 + */ public static final String CATEGORY_NETWORK = "network"; + /** + * 字段 CATEGORY_SHIPMENT。 + */ public static final String CATEGORY_SHIPMENT = "shipment"; + /** + * 字段 CATEGORY_EVENT。 + */ public static final String CATEGORY_EVENT = "event"; + /** + * 字段 CATEGORY_ACTIVITY。 + */ public static final String CATEGORY_ACTIVITY = "activity"; + /** + * 字段 CATEGORY_UPDATE。 + */ public static final String CATEGORY_UPDATE = "update"; + /** + * 字段 ROLE。 + */ public static final String ROLE = "role"; + /** + * 字段 ADMIN。 + */ public static final String ADMIN = "admin"; + /** + * 字段 ADMINISTRATOR。 + */ public static final String ADMINISTRATOR = "Administrator"; + /** + * 字段 NAME。 + */ public static final String NAME = "name"; + /** + * 字段 NATIONAL_ID。 + */ public static final String NATIONAL_ID = "nationalId"; + /** + * 字段 GENDER。 + */ public static final String GENDER = "gender"; + /** + * 字段 COMMENT。 + */ public static final String COMMENT = "comment"; + /** + * 字段 MEMO。 + */ public static final String MEMO = "memo"; + /** + * 字段 EMAIL。 + */ public static final String EMAIL = "email"; + /** + * 字段 LOGIN_ID。 + */ public static final String LOGIN_ID = "loginId"; + /** + * 字段 PASSWORD。 + */ public static final String PASSWORD = "password"; + /** + * 字段 PROPERTIES。 + */ public static final String PROPERTIES = "properties"; + /** + * 字段 USER_PROPERTIES。 + */ public static final String USER_PROPERTIES = "userProperties"; + /** + * 字段 REGISTER_PROPERTIES。 + */ public static final String REGISTER_PROPERTIES = "registerProperties"; + /** + * 字段 KEEP_SIGNIN。 + */ public static final String KEEP_SIGNIN = "keepSignIn"; + /** + * 字段 LAST_SITE。 + */ public static final String LAST_SITE = "lastSite"; + /** + * 字段 LAST_PAGE。 + */ public static final String LAST_PAGE = "lastPage"; + /** + * 字段 DEPARTMENT。 + */ public static final String DEPARTMENT = "dept"; + /** + * 字段 PLACE。 + */ public static final String PLACE = "place"; + /** + * 字段 REFERENCE。 + */ public static final String REFERENCE = "reference"; + /** + * 字段 POST_FROM。 + */ public static final String POST_FROM = "postFrom"; + /** + * 字段 POST_TO。 + */ public static final String POST_TO = "postTo"; + /** + * 字段 DOCUMENT_NO。 + */ public static final String DOCUMENT_NO = "doc_no"; + /** + * 字段 UPDATE。 + */ public static final String UPDATE = "update"; + /** + * 字段 SERIAL_NO。 + */ public static final String SERIAL_NO = "serial_no"; + /** + * 字段 PART_NO。 + */ public static final String PART_NO = "part_no"; + /** + * 字段 PALLET_NO。 + */ public static final String PALLET_NO = "pallet_mo"; + /** + * 字段 CARTON_SN。 + */ public static final String CARTON_SN = "carton_no"; + /** + * 字段 ACTIVE。 + */ public static final String ACTIVE = "active"; + /** + * 字段 WIFI。 + */ public static final String WIFI = "wifi"; + /** + * 字段 WIFI_MAC。 + */ public static final String WIFI_MAC = "wifi_mac"; + /** + * 字段 MAC_ADDRESS。 + */ public static final String MAC_ADDRESS = "mac_address"; + /** + * 字段 SKU_ID。 + */ public static final String SKU_ID = "sku_id"; + /** + * 字段 COMPATIBLE_SKUS。 + */ public static final String COMPATIBLE_SKUS = "compatibleSkus"; + /** + * 字段 DEVICE_ID。 + */ public static final String DEVICE_ID = "deviceId"; + /** + * 字段 SSID。 + */ public static final String SSID = "ssid"; + /** + * 字段 TELEPHONY。 + */ public static final String TELEPHONY = "telephony"; + /** + * 字段 PRODUCT_ID。 + */ public static final String PRODUCT_ID = "product_id"; + /** + * 字段 PRODUCT_MODEL。 + */ public static final String PRODUCT_MODEL = "product_model"; + /** + * 字段 BUILD_NO。 + */ public static final String BUILD_NO = "build_no"; + /** + * 字段 DISPLAY_ID。 + */ public static final String DISPLAY_ID = "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"; + /** + * 字段 BUILD_DATE。 + */ public static final String BUILD_DATE = "build_date"; + /** + * 字段 REGION_VERSION。 + */ public static final String REGION_VERSION = "region_version"; + /** + * 字段 REGION_BUILD_DATE。 + */ public static final String REGION_BUILD_DATE = "region_build_date"; + /** + * 字段 CUSTOMER_ID。 + */ public static final String CUSTOMER_ID = "customer_id"; + /** + * 字段 ACTIVE_NETWORK。 + */ public static final String ACTIVE_NETWORK = "active_network"; + /** + * 字段 SDK_VERSION。 + */ public static final String SDK_VERSION = "sdk_version"; + /** + * 字段 SCRIPT_VERSION。 + */ public static final String SCRIPT_VERSION = "script_version"; + /** + * 字段 RELEASE_VERSION。 + */ public static final String RELEASE_VERSION = "release_version"; + /** + * 字段 OS_VERSION。 + */ public static final String OS_VERSION = "os_version"; + /** + * 字段 GMS_AVAILABLE。 + */ public static final String GMS_AVAILABLE = "gms_available"; + /** + * 字段 TYPE。 + */ public static final String TYPE = "type"; + /** + * 字段 PRE_BUILD。 + */ public static final String PRE_BUILD = "preBuild"; + /** + * 字段 POST_BUILD。 + */ public static final String POST_BUILD = "postBuild"; + /** + * 字段 STATE。 + */ public static final String STATE = "state"; + /** + * 字段 IS_ONLINE。 + */ public static final String IS_ONLINE = "isOnline"; + /** + * 字段 STATE_REGISTERED。 + */ public static final String STATE_REGISTERED = "registered"; + /** + * 字段 STATE_ENROLLED。 + */ public static final String STATE_ENROLLED = "enrolled"; + /** + * 字段 STATE_RETIRED。 + */ public static final String STATE_RETIRED = "retired"; + /** + * 字段 FILE_URL。 + */ public static final String FILE_URL = "fileUrl"; + /** + * 字段 ICON_URL。 + */ public static final String ICON_URL = "iconUrl"; + /** + * 字段 SETTINGS_HEARTBEAT_INTERVAL。 + */ public static final String SETTINGS_HEARTBEAT_INTERVAL = "websocket.heartbeat.interval"; + /** + * 字段 MESSAGE。 + */ public static final String MESSAGE = "message"; + /** + * 字段 FILE_NAME。 + */ public static final String FILE_NAME = "fileName"; + /** + * 字段 FILE_LENGTH。 + */ public static final String FILE_LENGTH = "fileLength"; + /** + * 字段 PACKAGE。 + */ public static final String PACKAGE = "package"; + /** + * 字段 PACKAGE_NAME。 + */ public static final String PACKAGE_NAME = "packageName"; + /** + * 字段 LABEL。 + */ public static final String LABEL = "label"; + /** + * 字段 VERSION_CODE。 + */ public static final String VERSION_CODE = "versionCode"; + /** + * 字段 VERSION_NAME。 + */ public static final String VERSION_NAME = "versionName"; + /** + * 字段 CHECKSUM。 + */ public static final String CHECKSUM = "checksum"; + /** + * 字段 CERT_MD5。 + */ public static final String CERT_MD5 = "certMd5"; + /** + * 字段 STORAGES。 + */ public static final String STORAGES = "storages"; + /** + * 字段 MEMORY。 + */ public static final String MEMORY = "memory"; + /** + * 字段 BATTERY。 + */ public static final String BATTERY = "battery"; + /** + * 字段 TEMPERATURE。 + */ public static final String TEMPERATURE = "temperature"; + /** + * 字段 VOLTAGE。 + */ public static final String VOLTAGE = "voltage"; + /** + * 字段 CHARGE_LEVEL。 + */ public static final String CHARGE_LEVEL = "level"; + /** + * 字段 CHARGING_STATUS。 + */ public static final String CHARGING_STATUS = "charginStatus"; + /** + * 字段 PLUGGED。 + */ public static final String PLUGGED = "plugged"; } diff --git a/src/main/java/com/midm/constant/package-info.java b/src/main/java/com/midm/constant/package-info.java new file mode 100644 index 0000000..aba054b --- /dev/null +++ b/src/main/java/com/midm/constant/package-info.java @@ -0,0 +1,16 @@ +/** + * 全局常量包:集合名、协议码、Locale、属性键等。 + * + *

本包主要类型: + *

    + *
  • {@link GeneralConst}
  • + *
  • {@link LocaleConst}
  • + *
  • {@link LocationConst}
  • + *
  • {@link MidmConst}
  • + *
  • {@link PropertyConst}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.constant; diff --git a/src/main/java/com/midm/controller/BaseController.java b/src/main/java/com/midm/controller/BaseController.java index d6a6697..5fe4478 100644 --- a/src/main/java/com/midm/controller/BaseController.java +++ b/src/main/java/com/midm/controller/BaseController.java @@ -14,22 +14,88 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.web.servlet.LocaleResolver; +/** + * 【Java 类型】{@code BaseController} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code localeResolver}(LocaleResolver):语言区域解析器
  • + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code user}(User):用户
  • + *
  • {@code theme}(String):字段 theme
  • + *
+ * + * 协作对象:{@code LocaleResolver、LocaleService、UserService、SiteService、User}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class BaseController { + /** + * 语言区域解析器;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected LocaleResolver localeResolver; + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected LocaleService localeService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected SiteService siteService; + /** + * 用户。 + */ protected User user = null; + /** + * 字段 theme。 + */ 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) { 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) { this.determineUser(request, authentication); 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); } + /** + * 获取View。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param viewName 参数 {@code viewName}({@code String}) + * @return 字符串结果 + */ protected String getView(Authentication authentication, String viewName) { 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) { User user = UserPrincipal.getUser(authentication); String theme = user == null ? "default" : user.getTheme(); return theme + fileName; } + /** + * 获取模板Resource。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ protected String getTemplateResource(Authentication authentication, String fileName) { if (this.user == null) { this.user = UserPrincipal.getUser(authentication); @@ -67,6 +156,14 @@ public class BaseController { 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) { if (authentication != null) { synchronized(authentication) { diff --git a/src/main/java/com/midm/controller/DeviceController.java b/src/main/java/com/midm/controller/DeviceController.java index 8a51611..ac94641 100644 --- a/src/main/java/com/midm/controller/DeviceController.java +++ b/src/main/java/com/midm/controller/DeviceController.java @@ -52,11 +52,21 @@ import org.springframework.web.servlet.view.RedirectView; public class DeviceController extends BaseController { /** 设备详情页支持的功能标签页集合 */ - private static List tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs"); + private static List tabs = Arrays.asList("general", "remoteControl", "apps", "files", "location", "logs"); + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; diff --git a/src/main/java/com/midm/controller/ExceptionController.java b/src/main/java/com/midm/controller/ExceptionController.java index ef31055..46af643 100644 --- a/src/main/java/com/midm/controller/ExceptionController.java +++ b/src/main/java/com/midm/controller/ExceptionController.java @@ -16,8 +16,33 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +/** + * 【Web 控制器】{@code ExceptionController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"error"}, 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"}) public void gen204(HttpServletRequest request, HttpServletResponse response) { 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( value = {"blocked"}, method = {RequestMethod.GET} @@ -87,35 +137,96 @@ public class ExceptionController extends BaseController implements ErrorControll return this.getView(authentication, "/error"); } + /** + * 【Java 类型】{@code Error} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(int):代码
  • + *
  • {@code exception}(Exception):异常
  • + *
  • {@code message}(String):消息
  • + *
+ * + * 协作对象:{@code Exception}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ private class Error { + /** + * 代码。 + */ private int code; + /** + * 异常。 + */ private Exception exception; + /** + * 消息。 + */ private String message; + /** + * 构造 {@code Error} 实例。 + * + * @param code 状态码/业务码({@code int}) + */ public Error(int code) { this.setCode(code); } + /** + * 获取 {@code code}。 + * @return 数量/长度 + */ public int getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code int}) + */ public void setCode(int code) { this.code = code; } + /** + * 获取 {@code exception}。 + * @return 字段/派生属性 {@code exception} 的值 + */ public Exception getException() { return this.exception; } + /** + * 设置 {@code exception}。 + * + * @param exception 参数 {@code exception}({@code Exception}) + */ public void setException(Exception exception) { this.exception = exception; } + /** + * 获取 {@code message}。 + * @return 字符串结果 + */ public String getMessage() { return this.message; } + /** + * 设置 {@code message}。 + * + * @param message 消息内容({@code String}) + */ public void setMessage(String message) { this.message = message; } diff --git a/src/main/java/com/midm/controller/FragmentController.java b/src/main/java/com/midm/controller/FragmentController.java index 72f8abd..e252ce2 100644 --- a/src/main/java/com/midm/controller/FragmentController.java +++ b/src/main/java/com/midm/controller/FragmentController.java @@ -11,8 +11,31 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +/** + * 【Web 控制器】{@code FragmentController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"/view/**"}, method = {RequestMethod.GET} @@ -27,6 +50,19 @@ public class FragmentController extends BaseController { 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( value = {"/view/system/resource"}, method = {RequestMethod.GET} @@ -37,6 +73,21 @@ public class FragmentController extends BaseController { 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( value = {"/fragment/{fragmentName}"}, method = {RequestMethod.GET} @@ -48,20 +99,48 @@ public class FragmentController extends BaseController { model.addAttribute("hasUser", this.userService.hasUser()); } - String var10000 = this.getView(authentication, request.getServletPath()); - return var10000 + " :: fragment"; + return this.getView(authentication, request.getServletPath()) + " :: 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( value = {"/fragment/{fragmentName}/{blockName}"}, method = {RequestMethod.GET} ) public String fragment(HttpServletRequest request, HttpServletResponse response, Authentication authentication, Locale locale, Model model, @PathVariable String fragmentName, @PathVariable String blockName) { super.init(request, response, authentication); - String var10000 = this.getView(authentication, "/fragment/" + fragmentName); - return var10000 + " :: " + blockName; + return this.getView(authentication, "/fragment/" + fragmentName) + " :: " + 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( value = {"/dialog/{dialogName}"}, method = {RequestMethod.GET} @@ -73,7 +152,6 @@ public class FragmentController extends BaseController { model.addAttribute("hasUser", this.userService.hasUser()); } - String var10000 = this.getView(authentication, request.getServletPath()); - return var10000 + " :: dialog"; + return this.getView(authentication, request.getServletPath()) + " :: dialog"; } } diff --git a/src/main/java/com/midm/controller/HomeController.java b/src/main/java/com/midm/controller/HomeController.java index 90c253b..e96c294 100644 --- a/src/main/java/com/midm/controller/HomeController.java +++ b/src/main/java/com/midm/controller/HomeController.java @@ -23,8 +23,37 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.view.RedirectView; +/** + * 【Web 控制器】{@code HomeController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"/", "/index.html"}, 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( value = {"/remoteLogout"}, method = {RequestMethod.GET} @@ -109,6 +150,16 @@ public class HomeController extends BaseController { return this.getView(authentication, "/remoteLogout"); } + /** + * 处理homePost。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * 框架注解:{@code @RequestMapping(value = {"/"}, method = {RequestMethod.POST})}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + */ @RequestMapping( value = {"/"}, 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( value = {"register"}, 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( value = {"{modelSite}/register"}, method = {RequestMethod.GET} @@ -152,6 +231,22 @@ public class HomeController extends BaseController { 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( value = {"/bypass", "/dpc"}, 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( value = {"{modelSite}/bypass", "{modelSite}/dpc"}, 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( value = {"/requestTrial"}, 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( method = {RequestMethod.OPTIONS, RequestMethod.GET}, path = {"/login/{siteId}"} diff --git a/src/main/java/com/midm/controller/UserController.java b/src/main/java/com/midm/controller/UserController.java index 19f3098..4bddbe9 100644 --- a/src/main/java/com/midm/controller/UserController.java +++ b/src/main/java/com/midm/controller/UserController.java @@ -16,8 +16,33 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.server.NotAcceptableStatusException; +/** + * 【Web 控制器】{@code UserController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"/resetPassword"}, 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( value = {"/keepSession"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/controller/lib/BarcodeController.java b/src/main/java/com/midm/controller/lib/BarcodeController.java index 6945f69..6ab2fb7 100644 --- a/src/main/java/com/midm/controller/lib/BarcodeController.java +++ b/src/main/java/com/midm/controller/lib/BarcodeController.java @@ -9,8 +9,29 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +/** + * 【Web 控制器】{@code BarcodeController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"/barcode/qr/{code}"}, method = {RequestMethod.GET} diff --git a/src/main/java/com/midm/controller/lib/FilesController.java b/src/main/java/com/midm/controller/lib/FilesController.java index 5d2120c..a3033f8 100644 --- a/src/main/java/com/midm/controller/lib/FilesController.java +++ b/src/main/java/com/midm/controller/lib/FilesController.java @@ -36,25 +36,103 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.HandlerMapping; +/** + * 【Web 控制器】{@code FilesController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code storeAppService}(StoreAppService):store应用服务
  • + *
  • {@code storeOtaService}(StoreOtaService):storeOTA 固件服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code reportService}(ReportService):报表服务
  • + *
+ * + * 协作对象:{@code ServletContext、FileService、StoreAppService、StoreOtaService、DeviceService、ReportService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller public class FilesController { + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ServletContext servletContext; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * store应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreAppService storeAppService; + /** + * storeOTA 固件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtaService storeOtaService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ReportService reportService; + /** + * storeOther服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtherService storeOtherService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired 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( value = {"userfile/{userUuid}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET} @@ -66,6 +144,20 @@ public class FilesController { 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( value = {"file/device/{deviceUuid}/{fileUuid}/{fileName}"}, 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( value = {"file/{fileType}/{fileUuid}/{fileName}"}, 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( value = {"file/report/template/{fileName}"}, method = {RequestMethod.GET} @@ -117,6 +235,19 @@ public class FilesController { 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( value = {"must/reserved/{fileUuid}/{fileName}"}, 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( value = {"must/download/{isDirectory}/{fileUuid}/{fileName}/**"}, 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( value = {"store/{fileType}/{packageName}/{versionCode}/{fileUuid}/{fileName}"}, 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( value = {"store/ota/{productId}/{fileUuid}/{fileName}"}, 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( value = {"store/other/{fileUuid}/{fileName}"}, 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( value = {"{siteUuid}/file/{fileType}/{fileUuid}/{fileName}"}, 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( value = {"icon/app/{fileUuid}/{fileName}"}, method = {RequestMethod.GET} @@ -283,8 +502,7 @@ public class FilesController { if (iconFile.exists()) { byte[] iconData = iconFile.toBytes(); if (iconData != null) { - String var10000 = Files.getNameWithoutExtension(fileName); - fileName = var10000 + (iconData[0] == 60 ? ".svg" : ".png"); + fileName = Files.getNameWithoutExtension(fileName) + (iconData[0] == 60 ? ".svg" : ".png"); fileName = McUrlUtils.encode(fileName); McResource.copyFileToResponse(this.servletContext, response, iconData, fileName); 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( value = {"icon/must/app/{profileUuid}/{fileName}"}, 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( value = {"icon/store/app/{packageName}"}, 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( value = {"icon/mime/{extension}"}, method = {RequestMethod.GET} @@ -350,6 +605,18 @@ public class FilesController { 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( value = {"icon/folder/{folderType}"}, method = {RequestMethod.GET} @@ -363,6 +630,18 @@ public class FilesController { 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( value = {"profile/user/{userUuid}"}, 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( value = {"favicon"}, 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( value = {"background"}, 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( value = {"background/{siteUuid}"}, method = {RequestMethod.GET} @@ -429,6 +741,15 @@ public class FilesController { 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( value = {"logo/{siteUuid}"}, method = {RequestMethod.GET} @@ -437,6 +758,15 @@ public class FilesController { 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( value = {"profile/site/{siteUuid}"}, method = {RequestMethod.GET} @@ -445,6 +775,16 @@ public class FilesController { 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) { if (this.cloudStorageService.hasCloudStorage()) { 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( value = {"profile/org/{userUuid}"}, method = {RequestMethod.GET} @@ -495,6 +846,18 @@ public class FilesController { 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( value = {"device/screen/{deviceUuid}"}, 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( value = {"device/file/{deviceUuid}/{hostFile}/{fileName}"}, 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( value = {"file/checksum/{fileUuid}"}, 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) { try { 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) { BaseFile file = null; switch (fileType) { diff --git a/src/main/java/com/midm/controller/lib/ResourceController.java b/src/main/java/com/midm/controller/lib/ResourceController.java index bd90720..82012bd 100644 --- a/src/main/java/com/midm/controller/lib/ResourceController.java +++ b/src/main/java/com/midm/controller/lib/ResourceController.java @@ -17,8 +17,27 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code ResourceController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
+ * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller 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( value = {"/js/**", "/css/**"}, method = {RequestMethod.GET} @@ -27,6 +46,19 @@ public class ResourceController extends BaseController { 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( value = {"js/controller/login.js"}, method = {RequestMethod.GET}, @@ -38,6 +70,18 @@ public class ResourceController extends BaseController { 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( value = {"/js/controller/resetPassword.js"}, method = {RequestMethod.GET}, @@ -50,27 +94,54 @@ public class ResourceController extends BaseController { 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( value = {"img/**"}, method = {RequestMethod.GET} ) @ResponseBody - public ResponseEntity getImage(HttpServletRequest request, Authentication authentication) { + public ResponseEntity getImage(HttpServletRequest request, Authentication authentication) { String path = this.getTemplateResource(authentication, request.getServletPath()); 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( value = {"images/**"}, method = {RequestMethod.GET} ) @ResponseBody - public ResponseEntity getImages(HttpServletRequest request, Authentication authentication) { + public ResponseEntity getImages(HttpServletRequest request, Authentication authentication) { String path = this.getTemplateResource(authentication, "/img" + request.getServletPath()); 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); if (Strings.isNullOrEmpty(subType)) { subType = "jpg"; diff --git a/src/main/java/com/midm/controller/lib/StoreController.java b/src/main/java/com/midm/controller/lib/StoreController.java index f61654e..7dea65a 100644 --- a/src/main/java/com/midm/controller/lib/StoreController.java +++ b/src/main/java/com/midm/controller/lib/StoreController.java @@ -39,32 +39,121 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.WebContext; +/** + * 【Web 控制器】{@code StoreController} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code storeAppService}(StoreAppService):store应用服务
  • + *
  • {@code storeOtaService}(StoreOtaService):storeOTA 固件服务
  • + *
  • {@code storeWebAppService}(StoreWebAppService):storeWeb应用服务
  • + *
  • {@code stringTemplateEngine}(TemplateEngine):string模板Engine
  • + *
  • {@code keyStoreService}(KeyStoreService):密钥Store服务
  • + *
+ * + * 协作对象:{@code ServletContext、StoreAppService、StoreOtaService、StoreWebAppService、TemplateEngine、KeyStoreService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"store"}) public class StoreController { + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ServletContext servletContext; + /** + * store应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreAppService storeAppService; + /** + * storeOTA 固件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtaService storeOtaService; + /** + * storeWeb应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreWebAppService storeWebAppService; + /** + * string模板Engine;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。 + */ @Autowired @Qualifier("stringTemplateEngine") private TemplateEngine stringTemplateEngine; + /** + * 密钥Store服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private KeyStoreService keyStoreService; + /** + * storeOther服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtherService storeOtherService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy 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( value = {"apps/download/{packageName}"}, method = {RequestMethod.GET} @@ -82,6 +171,22 @@ public class StoreController { 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( value = {"apps/{packageName}/{version}/{keyStoreId}"}, 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( value = {"app/{fileUuid}"}, 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) { String url = this.cloudStorageService.getUrl("store", "app", appFile.getPackageName(), appFile.getVersionCode(), appFile.getFileUuid()); 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( value = {"apps/{packageName}/releaseNote"}, method = {RequestMethod.GET} @@ -166,6 +307,23 @@ public class StoreController { 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( value = {"apps/{packageName}/{keyStore}/releaseNote", "apps/{packageName}/{keyStore}/releaseNote/{pathSdkVersion}"}, method = {RequestMethod.GET} @@ -196,6 +354,20 @@ public class StoreController { 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( value = {"apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink", "apps/{packageName}/{keyStore}/releaseNote/showAllDownloadLink/{pathSdkVersion}"}, method = {RequestMethod.GET} @@ -205,6 +377,21 @@ public class StoreController { 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( value = {"ota/{fileUuid}"}, 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( value = {"webapp/{fileUuid}"}, method = {RequestMethod.GET} @@ -246,6 +449,20 @@ public class StoreController { 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( value = {"webapp/latest"}, method = {RequestMethod.GET} @@ -255,6 +472,15 @@ public class StoreController { 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) { try { 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( value = {"webapp/releaseNote"}, method = {RequestMethod.GET} @@ -294,6 +537,21 @@ public class StoreController { 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( value = {"other/{fileName}"}, method = {RequestMethod.GET} diff --git a/src/main/java/com/midm/controller/lib/package-info.java b/src/main/java/com/midm/controller/lib/package-info.java new file mode 100644 index 0000000..be82205 --- /dev/null +++ b/src/main/java/com/midm/controller/lib/package-info.java @@ -0,0 +1,15 @@ +/** + * 文件/图片下载与静态资源控制器:处理设备截图、应用图标、报表下载等二进制响应。 + * + *

本包主要类型: + *

    + *
  • {@link BarcodeController}
  • + *
  • {@link FilesController}
  • + *
  • {@link ResourceController}
  • + *
  • {@link StoreController}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.controller.lib; diff --git a/src/main/java/com/midm/controller/package-info.java b/src/main/java/com/midm/controller/package-info.java new file mode 100644 index 0000000..2995595 --- /dev/null +++ b/src/main/java/com/midm/controller/package-info.java @@ -0,0 +1,17 @@ +/** + * 页面路由控制器:负责 Thymeleaf 页面渲染、登录跳转和静态资源入口。 + * + *

本包主要类型: + *

    + *
  • {@link BaseController}
  • + *
  • {@link DeviceController}
  • + *
  • {@link ExceptionController}
  • + *
  • {@link FragmentController}
  • + *
  • {@link HomeController}
  • + *
  • {@link UserController}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.controller; diff --git a/src/main/java/com/midm/dpc/DpcController.java b/src/main/java/com/midm/dpc/DpcController.java index 9a12849..d65dc9a 100644 --- a/src/main/java/com/midm/dpc/DpcController.java +++ b/src/main/java/com/midm/dpc/DpcController.java @@ -47,10 +47,25 @@ import org.springframework.web.util.UriComponentsBuilder; */ @Controller public class DpcController { + /** + * store应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreAppService storeAppService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; @@ -84,6 +99,15 @@ public class DpcController { 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) { String adminPackage = dpc.getDeviceAdmin(); if (!Strings.isNullOrEmpty(adminPackage) && adminPackage.indexOf(47) < 0) { @@ -145,6 +169,18 @@ public class DpcController { 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( value = {"/dpc/checksum"}, method = {RequestMethod.GET} diff --git a/src/main/java/com/midm/dpc/DpcModel.java b/src/main/java/com/midm/dpc/DpcModel.java index e32de03..891d5d0 100644 --- a/src/main/java/com/midm/dpc/DpcModel.java +++ b/src/main/java/com/midm/dpc/DpcModel.java @@ -6,94 +6,217 @@ import com.google.gson.GsonBuilder; import com.google.gson.annotations.SerializedName; import org.springframework.security.crypto.password.PasswordEncoder; +/** + * 【Android Enterprise 配置】{@code DpcModel} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code COMPONENT_MUST_SERVICE}(String):字段 COMPONENT_MUST_SERVICE
  • + *
  • {@code COMPONENT_MIDM_DPC}(String):字段 COMPONENT_MIDM_DPC
  • + *
  • {@code ssid}(String):字段 ssid
  • + *
  • {@code security}(String):字段 security
  • + *
  • {@code password}(String):密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)
  • + *
  • {@code hidden}(Boolean):是否hidden
  • + *
+ * + * 协作对象:{@code MidmConfig}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class DpcModel { + /** + * 字段 COMPONENT_MUST_SERVICE。 + */ 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"; + /** + * 字段 ssid。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_SSID", alternate = {"ssid"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_WIFI_SSID", alternate = {"ssid"} ) private String ssid; + /** + * 字段 security。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", alternate = {"security"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_WIFI_SECURITY_TYPE", alternate = {"security"} ) private String security; + /** + * 密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_PASSWORD", alternate = {"password"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_WIFI_PASSWORD", alternate = {"password"} ) private String password; + /** + * 是否hidden。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_WIFI_HIDDEN", alternate = {"hidden"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_WIFI_HIDDEN", alternate = {"hidden"} ) private Boolean hidden; + /** + * 启用全部系统应用列表。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED", alternate = {"enableAllSystemApps"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED", alternate = {"enableAllSystemApps"} ) private boolean enableAllSystemApps = true; + /** + * 设备Admin。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", alternate = {"deviceAdmin"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME", alternate = {"deviceAdmin"} ) private String deviceAdmin; + /** + * 字段 packageChecksum。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", alternate = {"packageChecksum"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM", alternate = {"packageChecksum"} ) private String packageChecksum; + /** + * 下载URL。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", alternate = {"downloadUrl"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION", alternate = {"downloadUrl"} ) private String downloadUrl; + /** + * 语言区域。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LOCALE", alternate = {"locale"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_LOCALE", alternate = {"locale"} ) private String locale; + /** + * 时间Zone。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_TIME_ZONE", alternate = {"timeZone"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_TIME_ZONE", alternate = {"timeZone"} ) private String timeZone; + /** + * local时间。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_LOCAL_TIME", alternate = {"localTime"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_LOCAL_TIME", alternate = {"localTime"} ) private String localTime; + /** + * midm配置。 + * + * 注解:{@code @SerializedName(value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", alternate = {"midm"})}。 + */ @SerializedName( value = "android.app.extra.PROVISIONING_ADMIN_EXTRAS_BUNDLE", alternate = {"midm"} ) private MidmConfig midmConfig; + /** + * 获取 {@code ssid}。 + * @return 字符串结果 + */ public String getSsid() { return this.ssid; } + /** + * 设置 {@code ssid}。 + * + * @param ssid 参数 {@code ssid}({@code String}) + */ public void setSsid(String ssid) { this.ssid = ssid; } + /** + * 获取 {@code security}。 + * @return 字符串结果 + */ public String getSecurity() { return this.security; } + /** + * 设置 {@code security}。 + * + * @param securityType 参数 {@code securityType}({@code String}) + */ public void setSecurity(String securityType) { this.security = securityType; } + /** + * 获取 {@code password}。 + * @return 字符串结果 + */ public String getPassword() { return this.password; } + /** + * 设置 {@code password}。 + * + * @param password 密码({@code String}) + */ public void setPassword(String password) { this.password = password; } + /** + * 加密Password。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param passwordEncoder 参数 {@code passwordEncoder}({@code PasswordEncoder}) + */ public void encryptPassword(PasswordEncoder passwordEncoder) { if (this.midmConfig != null && !Strings.isNullOrEmpty(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() { return this.hidden; } + /** + * 设置 {@code hidden}。 + * + * @param isHidden 参数 {@code isHidden}({@code boolean}) + */ public void setHidden(boolean isHidden) { this.hidden = isHidden; } + /** + * 判断 {@code enableAllSystemApps}。 + * @return 字段/派生属性 {@code enableAllSystemApps} 的值 + */ public boolean isEnableAllSystemApps() { return this.enableAllSystemApps; } + /** + * 设置 {@code enableAllSystemApps}。 + * + * @param enableAllSystemApps 参数 {@code enableAllSystemApps}({@code boolean}) + */ public void setEnableAllSystemApps(boolean enableAllSystemApps) { this.enableAllSystemApps = enableAllSystemApps; } + /** + * 获取 {@code deviceAdmin}。 + * @return 字符串结果 + */ public String getDeviceAdmin() { return this.deviceAdmin; } + /** + * 设置 {@code deviceAdmin}。 + * + * @param deviceAdmin 参数 {@code deviceAdmin}({@code String}) + */ public void setDeviceAdmin(String deviceAdmin) { this.deviceAdmin = deviceAdmin; } + /** + * 获取 {@code deviceAdminPackageName}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getDeviceAdminPackageName() { if (Strings.isNullOrEmpty(this.deviceAdmin)) { return null; @@ -134,145 +290,320 @@ public class DpcModel { } } + /** + * 获取 {@code packageChecksum}。 + * @return 字符串结果 + */ public String getPackageChecksum() { return this.packageChecksum; } + /** + * 设置 {@code packageChecksum}。 + * + * @param packageChecksum 参数 {@code packageChecksum}({@code String}) + */ public void setPackageChecksum(String packageChecksum) { this.packageChecksum = packageChecksum; } + /** + * 获取 {@code downloadUrl}。 + * @return 字符串结果 + */ public String getDownloadUrl() { return this.downloadUrl; } + /** + * 设置 {@code downloadUrl}。 + * + * @param downloadUrl 参数 {@code downloadUrl}({@code String}) + */ public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } + /** + * 获取 {@code locale}。 + * @return 字符串结果 + */ public String getLocale() { return this.locale; } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code String}) + */ public void setLocale(String locale) { this.locale = locale; } + /** + * 获取 {@code midm}。 + * @return 字段/派生属性 {@code midm} 的值 + */ public MidmConfig getMidm() { return this.midmConfig; } + /** + * 设置 {@code midm}。 + * + * @param midm 参数 {@code midm}({@code MidmConfig}) + */ public void setMidm(MidmConfig midm) { this.midmConfig = midm; } + /** + * 处理转换为Dpc配置。 + * + * 实现要点:主要调用:new GsonBuilder。 + * @return 字符串结果 + */ public String toDpcConfig() { Gson gson = (new GsonBuilder()).disableHtmlEscaping().create(); return gson.toJson(this); } + /** + * 【Android Enterprise 配置】{@code MidmConfig} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code hostUrl}(String):hostURL
  • + *
  • {@code clientAppUrl}(String):client应用URL
  • + *
  • {@code systemAppUrl}(String):系统应用URL
  • + *
  • {@code updateLatest}(Boolean):更新最新
  • + *
  • {@code installSilent}(Boolean):是否installSilent
  • + *
  • {@code siteId}(String):站点ID
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public static class MidmConfig { + /** + * hostURL。 + * + * 注解:{@code @SerializedName(value = "midm.host.url", alternate = {"hostUrl"})}。 + */ @SerializedName( value = "midm.host.url", alternate = {"hostUrl"} ) private String hostUrl; + /** + * client应用URL。 + * + * 注解:{@code @SerializedName(value = "midm.app.client.url", alternate = {"clientAppUrl"})}。 + */ @SerializedName( value = "midm.app.client.url", alternate = {"clientAppUrl"} ) private String clientAppUrl; + /** + * 系统应用URL。 + * + * 注解:{@code @SerializedName(value = "midm.app.system.url", alternate = {"systemAppUrl"})}。 + */ @SerializedName( value = "midm.app.system.url", alternate = {"systemAppUrl"} ) private String systemAppUrl; + /** + * 更新最新。 + * + * 注解:{@code @SerializedName(value = "midm.app.install.latest", alternate = {"updateLatest"})}。 + */ @SerializedName( value = "midm.app.install.latest", alternate = {"updateLatest"} ) private Boolean updateLatest; + /** + * 是否installSilent。 + * + * 注解:{@code @SerializedName(value = "midm.app.install.slient", alternate = {"installSilent"})}。 + */ @SerializedName( value = "midm.app.install.slient", alternate = {"installSilent"} ) private Boolean installSilent; + /** + * 站点ID。 + * + * 注解:{@code @SerializedName(value = "midm.site", alternate = {"siteId"})}。 + */ @SerializedName( value = "midm.site", alternate = {"siteId"} ) private String siteId; + /** + * 用户邮箱(登录名,建立索引)。 + * + * 注解:{@code @SerializedName(value = "midm.email", alternate = {"email"})}。 + */ @SerializedName( value = "midm.email", alternate = {"email"} ) private String email; + /** + * 密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)。 + * + * 注解:{@code @SerializedName(value = "midm.password", alternate = {"password"})}。 + */ @SerializedName( value = "midm.password", alternate = {"password"} ) private String password; + /** + * 获取 {@code hostUrl}。 + * @return 字符串结果 + */ public String getHostUrl() { return this.hostUrl; } + /** + * 设置 {@code hostUrl}。 + * + * @param url 参数 {@code url}({@code String}) + */ public void setHostUrl(String url) { this.hostUrl = url; } + /** + * 获取 {@code clientAppUrl}。 + * @return 字符串结果 + */ public String getClientAppUrl() { return this.clientAppUrl; } + /** + * 设置 {@code clientAppUrl}。 + * + * @param clientAppUrl 参数 {@code clientAppUrl}({@code String}) + */ public void setClientAppUrl(String clientAppUrl) { this.clientAppUrl = clientAppUrl; } + /** + * 获取 {@code systemAppUrl}。 + * @return 字符串结果 + */ public String getSystemAppUrl() { return this.systemAppUrl; } + /** + * 设置 {@code systemAppUrl}。 + * + * @param systemAppUrl 参数 {@code systemAppUrl}({@code String}) + */ public void setSystemAppUrl(String systemAppUrl) { this.systemAppUrl = systemAppUrl; } + /** + * 获取 {@code updateLatest}。 + * @return 字段/派生属性 {@code updateLatest} 的值 + */ public Boolean getUpdateLatest() { return this.updateLatest; } + /** + * 设置 {@code updateLatest}。 + * + * @param updateLatest 参数 {@code updateLatest}({@code Boolean}) + */ public void setUpdateLatest(Boolean updateLatest) { this.updateLatest = updateLatest; } + /** + * 获取 {@code installSilent}。 + * @return 字段/派生属性 {@code installSilent} 的值 + */ public Boolean getInstallSilent() { return this.installSilent; } + /** + * 设置 {@code installSilent}。 + * + * @param installSilent 参数 {@code installSilent}({@code Boolean}) + */ public void setInstallSilent(Boolean installSilent) { this.installSilent = installSilent; } + /** + * 获取 {@code siteId}。 + * @return 字符串结果 + */ public String getSiteId() { return this.siteId; } + /** + * 设置 {@code siteId}。 + * + * @param siteId 参数 {@code siteId}({@code String}) + */ public void setSiteId(String siteId) { this.siteId = siteId; } + /** + * 获取 {@code email}。 + * @return 字符串结果 + */ public String getEmail() { return this.email; } + /** + * 设置 {@code email}。 + * + * @param email 邮箱({@code String}) + */ public void setEmail(String email) { this.email = email; } + /** + * 获取 {@code password}。 + * @return 字符串结果 + */ public String getPassword() { return this.password; } + /** + * 设置 {@code password}。 + * + * @param password 密码({@code String}) + */ public void setPassword(String password) { this.password = password; } diff --git a/src/main/java/com/midm/dpc/DpcUtils.java b/src/main/java/com/midm/dpc/DpcUtils.java index 83f551a..0481c6d 100644 --- a/src/main/java/com/midm/dpc/DpcUtils.java +++ b/src/main/java/com/midm/dpc/DpcUtils.java @@ -9,7 +9,25 @@ import java.security.NoSuchAlgorithmException; import java.util.Base64; import org.apache.commons.io.IOUtils; +/** + * 【Android Enterprise 配置】{@code DpcUtils} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class DpcUtils { + /** + * 获取Checksum。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 字符串结果 + */ public static String getChecksum(URL url) { try { 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) { return !file.exists() ? null : getChecksum((new McFile(file)).toBytes()); } + /** + * 获取Checksum。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @return 字符串结果 + */ public static String getChecksum(byte[] bytes) { try { MessageDigest shaDigest = MessageDigest.getInstance("SHA-256"); diff --git a/src/main/java/com/midm/dpc/package-info.java b/src/main/java/com/midm/dpc/package-info.java new file mode 100644 index 0000000..25e152b --- /dev/null +++ b/src/main/java/com/midm/dpc/package-info.java @@ -0,0 +1,14 @@ +/** + * Android Enterprise 零接触(Zero-Touch)配置:生成 DPC 二维码与 provisioning JSON。 + * + *

本包主要类型: + *

    + *
  • {@link DpcController}
  • + *
  • {@link DpcModel}
  • + *
  • {@link DpcUtils}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.dpc; diff --git a/src/main/java/com/midm/model/GeneralProfile.java b/src/main/java/com/midm/model/GeneralProfile.java index 3658536..e73000c 100644 --- a/src/main/java/com/midm/model/GeneralProfile.java +++ b/src/main/java/com/midm/model/GeneralProfile.java @@ -10,34 +10,102 @@ import org.joda.time.DateTime; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; +/** + * 【Java 类型】{@code GeneralProfile} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code profile}(DbObject):配置档案
  • + *
  • {@code settings}(DbObject):设置列表
  • + *
  • {@code created}(Date):创建时间
  • + *
  • {@code updated}(Date):最后更新时间
  • + *
  • {@code enabled}(Boolean):是否启用
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class GeneralProfile { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id protected UUID uuid; + /** + * 配置档案。 + */ protected DbObject profile; + /** + * 设置列表。 + */ protected DbObject settings; + /** + * 创建时间。 + */ protected Date created; + /** + * 最后更新时间;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed protected Date updated; + /** + * 是否启用。 + */ protected Boolean enabled; + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.generateId(); this.created = new Date(); this.updated = this.created; } + /** + * 生成ID。 + */ public void generateId() { this.uuid = UUID.randomUUID(); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code profile}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile() { if (this.profile == null) { this.profile = new DbObject(); @@ -46,10 +114,21 @@ public class GeneralProfile { return this.profile; } + /** + * 设置 {@code profile}。 + * + * @param profile 设备配置档案({@code DbObject}) + */ public void setProfile(DbObject profile) { this.profile = profile; } + /** + * 获取 {@code settings}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getSettings() { if (this.settings == null) { this.settings = new DbObject(); @@ -58,34 +137,72 @@ public class GeneralProfile { return this.settings; } + /** + * 设置 {@code settings}。 + * + * @param settings 参数 {@code settings}({@code DbObject}) + */ public void setSettings(DbObject settings) { this.settings = settings; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } + /** + * 设置Updated。 + * + * 实现要点:主要调用:new Date。 + */ public void setUpdated() { this.setUpdated(new Date()); } + /** + * 获取 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public boolean getEnabled() { return this.enabled != null && this.enabled; } + /** + * 判断 {@code ended}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字段/派生属性 {@code ended} 的值 + */ public boolean isEnded() { if ("ends".equals(this.getProfile("endsOption"))) { 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) { this.enabled = enabled; } - public Object getProfile(String key) { - return this.getProfile(key, (Object)null); + /** + * 获取配置档案。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code profile} 的值 + */ + public 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 getProfile(String key, T defaultValue) { if (this.getProfile().containsKey(key)) { try { - return this.getProfile().get(key); + return (T)this.getProfile().get(key); } catch (Exception var4) { } } @@ -114,35 +251,96 @@ public class GeneralProfile { 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) { Boolean value = McBooleanUtils.isTrue(this.getProfile(category, key, subCategory, item)); 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) { return this.getProfileCategory(category, key, subCategory).get(item); } + /** + * 获取配置档案Category。 + * + * @param categoryNames 参数 {@code categoryNames}({@code String[]}) + * @return MongoDB 文档扩展对象 + */ public DbObject getProfileCategory(String... 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) { 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) { 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) { 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) { this.getProfileCategory(category, subCategory, item).put(key, value); } + /** + * 移除配置档案。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。 + * + * @param key 键/配置项({@code String}) + */ public void removeProfile(String key) { if (this.profile != null) { this.profile.remove(key); @@ -150,47 +348,121 @@ public class GeneralProfile { } + /** + * 获取设置。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code setting} 的值 + */ public Object getSetting(String key) { return this.getSettings().get(key); } + /** + * 获取设置AsString。 + * + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ public String getSettingAsString(String key) { 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) { 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) { return this.getSettings().getFloat(key, def); } + /** + * 获取设置AsBoolean。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code settingAsBoolean} 的值 + */ public boolean getSettingAsBoolean(String key) { 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) { 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) { Boolean value = McBooleanUtils.isTrue(this.getSetting(category, key)); return value == null ? def : value; } + /** + * 获取设置AsUUID。 + * + * @param key 键/配置项({@code String}) + * @return UUID + */ public UUID getSettingAsUuid(String key) { return this.getSettings().getUuid(key); } + /** + * 获取设置列表Category。 + * + * @param categoryNames 参数 {@code categoryNames}({@code String[]}) + * @return MongoDB 文档扩展对象 + */ public DbObject getSettingsCategory(String... 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) { return this.getSettingsCategory(category).get(key); } + /** + * 设置设置。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code UUID}) + */ public void setSetting(String key, UUID value) { if (value != null) { 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) { 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) { Document dbObject = this.getSettingsCategory(categoryName); if (value != null) { @@ -214,27 +501,53 @@ public class GeneralProfile { } + /** + * 移除选项。 + * + * @param key 键/配置项({@code String}) + */ public void removeOption(String key) { this.getSettings().remove(key); } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { Object value = this.getProfile("name"); return value == null ? null : (String)value; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.setProfile("name", name); } + /** + * 获取 {@code description}。 + * @return 字符串结果 + */ public String getDescription() { return (String)this.getProfile("desc"); } + /** + * 设置 {@code description}。 + * + * @param desc 参数 {@code desc}({@code String}) + */ public void setDescription(String desc) { this.setProfile("desc", desc); } + /** + * 处理minify。 + */ public void minify() { this.created = null; } diff --git a/src/main/java/com/midm/model/GroupByResult.java b/src/main/java/com/midm/model/GroupByResult.java index c6793cb..c576982 100644 --- a/src/main/java/com/midm/model/GroupByResult.java +++ b/src/main/java/com/midm/model/GroupByResult.java @@ -1,25 +1,72 @@ package com.midm.model; +/** + * 【Java 类型】{@code GroupByResult} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code groups}(String[]):分组列表
  • + *
  • {@code count}(int):统计
  • + *
+ * + * 协作对象:{@code String[]}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class GroupByResult { + /** + * 分组列表。 + */ private String[] groups; + /** + * 统计。 + */ private int count; + /** + * 获取 {@code count}。 + * @return 数量/长度 + */ public int getCount() { return this.count; } + /** + * 设置 {@code count}。 + * + * @param count 参数 {@code count}({@code int}) + */ public void setCount(int count) { this.count = count; } + /** + * 获取 {@code group}。 + * @return 字符串结果 + */ public String getGroup() { return this.groups.length > 0 ? this.groups[0] : null; } + /** + * 获取 {@code groups}。 + * @return 字段/派生属性 {@code groups} 的值 + */ public String[] getGroups() { return this.groups; } + /** + * 设置 {@code groups}。 + * + * @param groups 参数 {@code groups}({@code String[]}) + */ public void setGroups(String[] groups) { this.groups = groups; } diff --git a/src/main/java/com/midm/model/IF_EXISTS_OPTION.java b/src/main/java/com/midm/model/IF_EXISTS_OPTION.java index 28b68ce..af407fb 100644 --- a/src/main/java/com/midm/model/IF_EXISTS_OPTION.java +++ b/src/main/java/com/midm/model/IF_EXISTS_OPTION.java @@ -2,6 +2,22 @@ package com.midm.model; import com.google.common.base.CharMatcher; +/** + * 【枚举常量】{@code IF_EXISTS_OPTION} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code option}(int):选项
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum IF_EXISTS_OPTION { ignore(0), skip(0), @@ -11,12 +27,28 @@ public enum IF_EXISTS_OPTION { modify(2), remove(3); + /** + * 选项。 + */ public int option; + /** + * 构造 {@code IF_EXISTS_OPTION} 实例。 + * + * @param option 参数 {@code option}({@code int}) + */ private IF_EXISTS_OPTION(int option) { this.option = option; } + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static IF_EXISTS_OPTION get(String key) { try { 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) { return get(option).option; } diff --git a/src/main/java/com/midm/model/battery/Battery.java b/src/main/java/com/midm/model/battery/Battery.java index 0b4c1c5..55f8f76 100644 --- a/src/main/java/com/midm/model/battery/Battery.java +++ b/src/main/java/com/midm/model/battery/Battery.java @@ -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.mapping.Document; +/** + * 【MongoDB 文档实体】{@code Battery} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code states}(DbObject):字段 states
  • + *
  • {@code deviceGroupPath}(String):设备分组路径
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndexes({@CompoundIndex( def = "{'profile.hardware_info.batterySerial':1}", unique = true )}) public class Battery extends GeneralProfile { + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 字段 states。 + */ private DbObject states; + /** + * 设备分组路径;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private String deviceGroupPath; + /** + * 构造 {@code Battery} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Battery() { this.init(); } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 获取 {@code batterySerial}。 + * @return 字符串结果 + */ public String getBatterySerial() { return (String)this.getCategoryProfile("hardware_info", "batterySerial"); } + /** + * 获取 {@code deviceSerial}。 + * @return 字符串结果 + */ public String getDeviceSerial() { return (String)this.getCategoryProfile("hardware_info", "deviceSerial"); } + /** + * 设置 {@code deviceSerial}。 + * + * @param deviceSerial 参数 {@code deviceSerial}({@code String}) + */ public void setDeviceSerial(String deviceSerial) { this.setProfile("hardware_info", "deviceSerial", deviceSerial.trim()); } + /** + * 获取 {@code model}。 + * @return 字符串结果 + */ public String getModel() { return (String)this.getCategoryProfile("hardware_info", "model"); } + /** + * 获取 {@code deviceId}。 + * @return 字符串结果 + */ public String getDeviceId() { return (String)this.getCategoryProfile("hardware_info", "device_id"); } + /** + * 设置 {@code registerState}。 + * + * @param state 参数 {@code state}({@code String}) + */ public void setRegisterState(String state) { this.getStates().put("state", state); } + /** + * 获取 {@code registerState}。 + * @return 字符串结果 + */ public String getRegisterState() { return this.getStates().getString("state"); } + /** + * 获取 {@code batteryCondition}。 + * @return 数量/长度 + */ public Integer getBatteryCondition() { return this.getStates().getInteger("batteryCondition", -1); } + /** + * 获取 {@code states}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getStates() { if (this.states == null) { this.states = new DbObject(); @@ -75,20 +161,42 @@ public class Battery extends GeneralProfile { return this.states; } + /** + * 获取 {@code deviceGroupPath}。 + * @return 字符串结果 + */ public String getDeviceGroupPath() { return this.deviceGroupPath; } + /** + * 设置 {@code deviceGroupPath}。 + * + * @param deviceGroupPath 参数 {@code deviceGroupPath}({@code String}) + */ public void setDeviceGroupPath(String deviceGroupPath) { this.deviceGroupPath = deviceGroupPath; } + /** + * 获取 {@code lastTemp}。 + * + * 实现要点:主要调用:new TypeToken。 + * @return 字段/派生属性 {@code lastTemp} 的值 + */ public ValueWithTime getLastTemp() { List dbTempList = (List)McJsonUtils.toObject(McJsonUtils.toJson(this.getStates().get("temperature")), (new TypeToken() { }).getType()); 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) { DbObject obj = new DbObject(); obj.append("reportedAt", t.getReportedAt()).append("value", t.getValue()); @@ -97,22 +205,58 @@ public class Battery extends GeneralProfile { this.getStates().put("temperature", list); } + /** + * 【枚举常量】{@code BATTERY_CONDITION} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code value}(int):值
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public static enum BATTERY_CONDITION { UNKNOWN(-1), GOOD(0), AVERAGE(1), SERVICE_SOON(2); + /** + * 值。 + */ private int value; + /** + * 构造 {@code BATTERY_CONDITION} 实例。 + * + * @param value 值({@code int}) + */ private BATTERY_CONDITION(int value) { this.value = value; } + /** + * 获取 {@code value}。 + * @return 数量/长度 + */ public int getValue() { return this.value; } + /** + * 处理用于值。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param value 值({@code int}) + * @return 处理结果 + */ public static BATTERY_CONDITION forValue(int value) { for(BATTERY_CONDITION e : values()) { if (e.value == value) { diff --git a/src/main/java/com/midm/model/battery/BatteryLog.java b/src/main/java/com/midm/model/battery/BatteryLog.java index 3902fb6..9637b12 100644 --- a/src/main/java/com/midm/model/battery/BatteryLog.java +++ b/src/main/java/com/midm/model/battery/BatteryLog.java @@ -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.mapping.Document; +/** + * 【MongoDB 文档实体】{@code BatteryLog} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code batterySerial}(String):电池序列
  • + *
  • {@code category}(String):字段 category
  • + *
  • {@code log}(String):日志
  • + *
  • {@code reportedAt}(Date):时间字段
  • + *
  • {@code states}(DbObject):字段 states
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndex( def = "{batterySerial: 1, reportedAt: 1}" ) public class BatteryLog { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid = UUID.randomUUID(); + /** + * 电池序列;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String batterySerial; + /** + * 字段 category;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String category; + /** + * 日志。 + */ private String log; + /** + * 时间字段;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date reportedAt; + /** + * 字段 states。 + */ private DbObject states; + /** + * 时间字段。 + */ private Date recordedAt = new Date(); + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 获取 {@code batterySerial}。 + * @return 字符串结果 + */ public String getBatterySerial() { return this.batterySerial; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } + /** + * 获取 {@code states}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getStates() { if (this.states == null) { this.states = new DbObject(); @@ -45,6 +118,10 @@ public class BatteryLog { return this.states; } + /** + * 获取 {@code reportedAt}。 + * @return 字段/派生属性 {@code reportedAt} 的值 + */ public Date getReportedAt() { return this.reportedAt; } diff --git a/src/main/java/com/midm/model/battery/ValueWithTime.java b/src/main/java/com/midm/model/battery/ValueWithTime.java index 43ed85e..06838aa 100644 --- a/src/main/java/com/midm/model/battery/ValueWithTime.java +++ b/src/main/java/com/midm/model/battery/ValueWithTime.java @@ -2,27 +2,74 @@ package com.midm.model.battery; import java.util.Date; +/** + * 【领域模型】{@code ValueWithTime} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code reportedAt}(Date):时间字段
  • + *
  • {@code value}(double):值
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ValueWithTime { + /** + * 时间字段。 + */ private Date reportedAt; + /** + * 值。 + */ private double value; + /** + * 构造 {@code ValueWithTime} 实例。 + * + * @param reportedAt 参数 {@code reportedAt}({@code Date}) + * @param value 值({@code double}) + */ public ValueWithTime(Date reportedAt, double value) { this.reportedAt = reportedAt; this.value = value; } + /** + * 获取 {@code reportedAt}。 + * @return 字段/派生属性 {@code reportedAt} 的值 + */ public Date getReportedAt() { return this.reportedAt; } + /** + * 设置 {@code reportedAt}。 + * + * @param reportedAt 参数 {@code reportedAt}({@code Date}) + */ public void setReportedAt(Date reportedAt) { this.reportedAt = reportedAt; } + /** + * 获取 {@code value}。 + * @return 字段/派生属性 {@code value} 的值 + */ public double getValue() { return this.value; } + /** + * 设置 {@code value}。 + * + * @param value 值({@code double}) + */ public void setValue(double value) { this.value = value; } diff --git a/src/main/java/com/midm/model/battery/package-info.java b/src/main/java/com/midm/model/battery/package-info.java new file mode 100644 index 0000000..9c35a05 --- /dev/null +++ b/src/main/java/com/midm/model/battery/package-info.java @@ -0,0 +1,14 @@ +/** + * 电池健康度(BMS)模型:电压、温度、循环次数、SOH 状态等遥测数据。 + * + *

本包主要类型: + *

    + *
  • {@link Battery}
  • + *
  • {@link BatteryLog}
  • + *
  • {@link ValueWithTime}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.battery; diff --git a/src/main/java/com/midm/model/device/AppInfo.java b/src/main/java/com/midm/model/device/AppInfo.java index 92a83f6..4e87fa9 100644 --- a/src/main/java/com/midm/model/device/AppInfo.java +++ b/src/main/java/com/midm/model/device/AppInfo.java @@ -2,89 +2,222 @@ package com.midm.model.device; import com.google.common.base.Strings; +/** + * 【领域模型】{@code AppInfo} + * + * 类职责: + *

    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code packageName}(String):package名称
  • + *
  • {@code label}(String):字段 label
  • + *
  • {@code versionName}(String):版本名称
  • + *
  • {@code versionCode}(Integer):版本代码
  • + *
  • {@code minSdkVersion}(Integer):minSDK版本
  • + *
  • {@code appSize}(Long):应用数量
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class AppInfo { + /** + * package名称。 + */ private String packageName; + /** + * 字段 label。 + */ private String label; + /** + * 版本名称。 + */ private String versionName; + /** + * 版本代码。 + */ private Integer versionCode; + /** + * minSDK版本。 + */ private Integer minSdkVersion; + /** + * 应用数量。 + */ private Long appSize; + /** + * 数据数量。 + */ private Long dataSize; + /** + * 第一Installed。 + */ private Long firstInstalled; + /** + * 最后Updated。 + */ private Long lastUpdated; + /** + * 获取 {@code packageName}。 + * @return 字符串结果 + */ public String getPackageName() { return this.packageName; } + /** + * 设置 {@code packageName}。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public void setPackageName(String packageName) { this.packageName = packageName; } + /** + * 获取 {@code label}。 + * @return 字符串结果 + */ public String getLabel() { return Strings.isNullOrEmpty(this.label) ? this.packageName : this.label; } + /** + * 设置 {@code label}。 + * + * @param label 参数 {@code label}({@code String}) + */ public void setLabel(String label) { this.label = label; } + /** + * 获取 {@code versionName}。 + * @return 字符串结果 + */ public String getVersionName() { return this.versionName; } + /** + * 设置 {@code versionName}。 + * + * @param versionName 参数 {@code versionName}({@code String}) + */ public void setVersionName(String versionName) { this.versionName = versionName; } + /** + * 获取 {@code versionCode}。 + * @return 数量/长度 + */ public int getVersionCode() { return this.versionCode; } + /** + * 设置 {@code versionCode}。 + * + * @param versionCode 参数 {@code versionCode}({@code int}) + */ public void setVersionCode(int versionCode) { this.versionCode = versionCode; } + /** + * 处理minSDK版本。 + * @return 数量/长度 + */ public int minSdkVersion() { return this.minSdkVersion; } + /** + * 设置 {@code minSdkVersion}。 + * + * @param version 参数 {@code version}({@code int}) + */ public void setMinSdkVersion(int version) { this.minSdkVersion = version; } + /** + * 获取 {@code appSize}。 + * @return 数量/长度 + */ public long getAppSize() { return this.appSize; } + /** + * 设置 {@code appSize}。 + * + * @param appSize 参数 {@code appSize}({@code long}) + */ public void setAppSize(long appSize) { this.appSize = appSize; } + /** + * 获取 {@code dataSize}。 + * @return 数量/长度 + */ public long getDataSize() { return this.dataSize; } + /** + * 设置 {@code dataSize}。 + * + * @param dataSize 参数 {@code dataSize}({@code long}) + */ public void setDataSize(long dataSize) { this.dataSize = dataSize; } + /** + * 获取 {@code firstInstalled}。 + * @return 数量/长度 + */ public long getFirstInstalled() { return this.firstInstalled; } + /** + * 设置 {@code firstInstalled}。 + * + * @param firstInstalled 参数 {@code firstInstalled}({@code long}) + */ public void setFirstInstalled(long firstInstalled) { this.firstInstalled = firstInstalled; } + /** + * 获取 {@code lastUpdated}。 + * @return 数量/长度 + */ public long getLastUpdated() { return this.lastUpdated; } + /** + * 设置 {@code lastUpdated}。 + * + * @param lastUpdated 参数 {@code lastUpdated}({@code long}) + */ public void setLastUpdated(long lastUpdated) { this.lastUpdated = lastUpdated; } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return String.format("%s %s(%s)", this.label, this.versionName, this.packageName); } diff --git a/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java b/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java index b8ad864..9fe5aa6 100644 --- a/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java +++ b/src/main/java/com/midm/model/device/DEVICE_PROPERTY.java @@ -2,6 +2,21 @@ package com.midm.model.device; import com.google.common.base.CharMatcher; +/** + * 【枚举常量】{@code DEVICE_PROPERTY} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum DEVICE_PROPERTY { serialno, serial_no, @@ -41,6 +56,14 @@ public enum DEVICE_PROPERTY { rsa, unknown; + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static DEVICE_PROPERTY get(String key) { try { return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); diff --git a/src/main/java/com/midm/model/device/DataUsage.java b/src/main/java/com/midm/model/device/DataUsage.java index b09fe90..85cf71e 100644 --- a/src/main/java/com/midm/model/device/DataUsage.java +++ b/src/main/java/com/midm/model/device/DataUsage.java @@ -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.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DataUsage} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code from}(Date):从
  • + *
  • {@code to}(Date):转换为
  • + *
  • {@code usage}(DbObject):用量
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndex( def = "{deviceUuid: 1, siteUuid: 1}" ) public class DataUsage { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 设备UUID。 + */ private UUID deviceUuid; + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 从;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date from; + /** + * 转换为;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date to; + /** + * 用量。 + */ private DbObject usage; + /** + * 时间字段;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed(expireAfterSeconds = 15552000)}。 + */ @Indexed( expireAfterSeconds = 15552000 ) private Date recordedAt; + /** + * 构造 {@code DataUsage} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new Date。 + */ public DataUsage() { this.uuid = UUID.randomUUID(); 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) { this(); this.setSiteUuid(device.getSiteUuid()); @@ -67,70 +135,152 @@ public class DataUsage { } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code from}。 + * @return 字段/派生属性 {@code from} 的值 + */ public Date getFrom() { return this.from; } + /** + * 设置 {@code from}。 + * + * @param from 起始时间({@code Date}) + */ public void setFrom(Date from) { this.from = from; } + /** + * 获取 {@code to}。 + * @return 字段/派生属性 {@code to} 的值 + */ public Date getTo() { return this.to; } + /** + * 设置 {@code to}。 + * + * @param to 结束时间({@code Date}) + */ public void setTo(Date to) { this.to = to; } + /** + * 获取 {@code usage}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getUsage() { return this.usage; } + /** + * 获取用量。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @return 数量/长度 + */ public long getUsage(String category, String key) { return this.getUsage().getDbObject(new String[]{category}).getLong(key, 0L); } + /** + * 设置 {@code usage}。 + * + * @param usage 参数 {@code usage}({@code DbObject}) + */ public void setUsage(DbObject usage) { this.usage = usage; } + /** + * 获取 {@code recordedAt}。 + * @return 字段/派生属性 {@code recordedAt} 的值 + */ public Date getRecordedAt() { return this.recordedAt; } + /** + * 设置 {@code recordedAt}。 + * + * @param recordedAt 参数 {@code recordedAt}({@code Date}) + */ public void setRecordedAt(Date recordedAt) { this.recordedAt = recordedAt; } + /** + * 判断是否LaterThan。 + * + * @param usage 参数 {@code usage}({@code DataUsage}) + * @return 字段/派生属性 {@code laterThan} 的值 + */ public boolean isLaterThan(DataUsage usage) { return usage.getTo().getTime() < this.getFrom().getTime(); } + /** + * 判断是否Overlapped。 + * + * @param usage 参数 {@code usage}({@code DataUsage}) + * @return 字段/派生属性 {@code overlapped} 的值 + */ public boolean isOverlapped(DataUsage usage) { return usage.getFrom().getTime() >= this.getTo().getTime() && usage.getTo().getTime() <= this.getTo().getTime(); } diff --git a/src/main/java/com/midm/model/device/Device.java b/src/main/java/com/midm/model/device/Device.java index 20c57d1..228cf78 100644 --- a/src/main/java/com/midm/model/device/Device.java +++ b/src/main/java/com/midm/model/device/Device.java @@ -80,7 +80,7 @@ public class Device extends GeneralProfile { /** 临时字段:设备当前生效的策略清单缓存 */ @Transient - private List deviceProfiles; + private List deviceProfiles; /** 许可激活时间点索引 */ @Indexed @@ -107,40 +107,82 @@ public class Device extends GeneralProfile { private Date lastDisconnected; /** 终端已安装的应用程序包信息清单快照 */ - private List installedApps; + private List installedApps; + /** + * 获取 {@code rsa}。 + * @return 字符串结果 + */ public String getRsa() { return this.rsa; } + /** + * 设置 {@code rsa}。 + * + * @param rsa 参数 {@code rsa}({@code String}) + */ public void setRsa(String rsa) { this.rsa = rsa; } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code groupUuid}。 + * @return UUID + */ public UUID getGroupUuid() { return this.groupUuid; } + /** + * 获取 {@code groupPath}。 + * @return 字符串结果 + */ public String getGroupPath() { return this.groupPath; } + /** + * 设置 {@code groupPath}。 + * + * @param groupPath 参数 {@code groupPath}({@code String}) + */ public void setGroupPath(String groupPath) { this.groupPath = groupPath; } + /** + * 获取 {@code owner}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getOwner() { return this.owner; } + /** + * 设置 {@code owner}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param owner 参数 {@code owner}({@code User}) + */ public void setOwner(User owner) { this.owner = owner; if (owner != null) { @@ -149,18 +191,40 @@ public class Device extends GeneralProfile { } + /** + * 获取 {@code ownerUuid}。 + * @return UUID + */ public UUID getOwnerUuid() { return this.ownerUuid; } + /** + * 设置 {@code ownerUuid}。 + * + * @param ownerUuid 所有者用户 UUID({@code UUID}) + */ public void setOwnerUuid(UUID ownerUuid) { this.ownerUuid = ownerUuid; } + /** + * 判断 {@code owner}。 + * @return 字段/派生属性 {@code owner} 的值 + */ public boolean hasOwner() { return this.getOwner() != null; } + /** + * 获取所有者信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code String}) + * @return 字符串结果 + */ public String getOwnerInfo(String key, String defaultValue) { if (this.owner == null) { DbObject owner = this.getProfileCategory(new String[]{"owner"}); @@ -170,18 +234,37 @@ public class Device extends GeneralProfile { } } + /** + * 判断 {@code associated}。 + * @return 字段/派生属性 {@code associated} 的值 + */ public boolean isAssociated() { return this.getDeviceGroup() != null; } + /** + * 判断 {@code register}。 + * @return 字段/派生属性 {@code register} 的值 + */ public boolean canRegister() { return !Strings.isNullOrEmpty(this.getSerialNo()); } + /** + * 获取 {@code deviceGroup}。 + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup getDeviceGroup() { return this.deviceGroup; } + /** + * 设置 {@code deviceGroup}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param deviceGroup 设备分组对象({@code DeviceGroup}) + */ public void setDeviceGroup(DeviceGroup deviceGroup) { if (deviceGroup != null && deviceGroup.getSiteUuid().equals(this.getSiteUuid())) { this.deviceGroup = deviceGroup; @@ -192,6 +275,12 @@ public class Device extends GeneralProfile { } + /** + * 获取 {@code states}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getStates() { if (this.states == null) { this.states = new DbObject(); @@ -200,132 +289,276 @@ public class Device extends GeneralProfile { return this.states; } + /** + * 设置 {@code states}。 + * + * @param states 参数 {@code states}({@code DbObject}) + */ public void setStates(DbObject states) { this.states = states; } + /** + * 获取 {@code state}。 + * @return 字符串结果 + */ public String getState() { return this.getStates().getString("state", "unknown"); } + /** + * 设置 {@code state}。 + * + * @param state 参数 {@code state}({@code String}) + */ public void setState(String state) { this.setState("state", state); } + /** + * 判断 {@code online}。 + * @return 字段/派生属性 {@code online} 的值 + */ public boolean isOnline() { return this.getStates().getBoolean("isOnline", false); } + /** + * 设置 {@code online}。 + * + * @param online 参数 {@code online}({@code boolean}) + */ public void setOnline(boolean online) { this.setState("isOnline", online); } + /** + * 判断 {@code blocked}。 + * @return 字段/派生属性 {@code blocked} 的值 + */ public boolean isBlocked() { return this.getStates().containsKey("blocked"); } + /** + * 设置状态。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setState(String key, Object value) { this.getStates().append(key, value); } + /** + * 设置 {@code clientVersion}。 + * + * @param version 参数 {@code version}({@code int}) + */ public void setClientVersion(int version) { this.getStates().put("clientVersion", version); } + /** + * 获取 {@code clientVersion}。 + * @return 数量/长度 + */ public int getClientVersion() { return this.getStates().getInteger("clientVersion", -1); } + /** + * 获取 {@code batteryCondition}。 + * @return 字段/派生属性 {@code batteryCondition} 的值 + */ public Battery.BATTERY_CONDITION getBatteryCondition() { return Battery.BATTERY_CONDITION.forValue(this.getStates().getInteger("batteryCondition", -1)); } + /** + * 判断 {@code oldClient}。 + * @return 字段/派生属性 {@code oldClient} 的值 + */ public boolean hasOldClient() { return this.getClientVersion() < 0; } + /** + * 获取 {@code enrolled}。 + * @return 字段/派生属性 {@code enrolled} 的值 + */ public Date getEnrolled() { return this.enrolled; } + /** + * 判断 {@code enrolled}。 + * @return 字段/派生属性 {@code enrolled} 的值 + */ public boolean isEnrolled() { return this.enrolled != null; } + /** + * 设置 {@code enrolled}。 + * + * @param enrolled 参数 {@code enrolled}({@code Date}) + */ public void setEnrolled(Date enrolled) { this.enrolled = enrolled; this.setState("enrolled"); this.setLicenseExpiry(); } + /** + * 判断 {@code retired}。 + * @return 字段/派生属性 {@code retired} 的值 + */ public boolean isRetired() { return this.getState().equals("retired"); } + /** + * 获取 {@code lastCheckedIn}。 + * @return 字段/派生属性 {@code lastCheckedIn} 的值 + */ public Date getLastCheckedIn() { return this.lastCheckedIn; } + /** + * 设置最后Checked在。 + * + * 实现要点:主要调用:new Date。 + */ public void setLastCheckedIn() { this.setLastCheckedIn(new Date()); } + /** + * 设置 {@code lastCheckedIn}。 + * + * @param lastCheckedIn 参数 {@code lastCheckedIn}({@code Date}) + */ public void setLastCheckedIn(Date lastCheckedIn) { this.lastCheckedIn = lastCheckedIn; } + /** + * 获取 {@code lastDisconnected}。 + * @return 字段/派生属性 {@code lastDisconnected} 的值 + */ public Date getLastDisconnected() { return this.lastDisconnected; } + /** + * 设置最后Disconnected。 + * + * 实现要点:主要调用:new Date。 + */ public void setLastDisconnected() { this.lastDisconnected = new Date(); } + /** + * 设置 {@code lastDisconnected}。 + * + * @param disconnected 参数 {@code disconnected}({@code Date}) + */ public void setLastDisconnected(Date disconnected) { this.lastDisconnected = disconnected; } - public List getInstalledApps() { + /** + * 获取 {@code installedApps}。 + * @return 应用信息列表,可能为空 + */ + public List getInstalledApps() { return this.installedApps; } - public void setInstalledApps(List installedApps) { + /** + * 设置 {@code installedApps}。 + * + * @param installedApps 参数 {@code installedApps}({@code List}) + */ + public void setInstalledApps(List installedApps) { this.installedApps = installedApps; } - public void setDeviceProfiles(List deviceProfiles) { + /** + * 设置 {@code deviceProfiles}。 + * + * @param deviceProfiles 参数 {@code deviceProfiles}({@code List}) + */ + public void setDeviceProfiles(List deviceProfiles) { this.deviceProfiles = deviceProfiles; } + /** + * 获取 {@code serialNo}。 + * @return 字符串结果 + */ public String getSerialNo() { return (String)this.getCategoryProfile("hardware_info", "serial_no"); } + /** + * 设置 {@code serialNo}。 + * + * @param serialNo 设备序列号({@code String}) + */ public void setSerialNo(String serialNo) { this.setProfile("hardware_info", "serial_no", serialNo.trim()); } + /** + * 获取 {@code modelId}。 + * @return 字符串结果 + */ public String getModelId() { return (String)this.getCategoryProfile("hardware_info", "product_id"); } + /** + * 获取 {@code buildNo}。 + * @return 字符串结果 + */ public String getBuildNo() { return this.getProfileCategory(new String[]{"software_info"}).getString("build_no"); } + /** + * 获取 {@code displayId}。 + * @return 字符串结果 + */ public String getDisplayId() { return this.getProfileCategory(new String[]{"software_info"}).getString("display_id"); } + /** + * 获取 {@code productDisplayId}。 + * @return 字符串结果 + */ public String getProductDisplayId() { return this.getProfileCategory(new String[]{"software_info"}).getString("product_display_id"); } + /** + * 获取 {@code buildDate}。 + * @return 数量/长度 + */ public long getBuildDate() { return this.getProfileCategory(new String[]{"software_info"}).getLong("build_date", -1L); } + /** + * 获取 {@code sdkVersion}。 + * + * 实现要点:包含 8 个条件分支、0 个循环。 + * @return 数量/长度 + */ public int getSdkVersion() { if (this.isEnrolled()) { 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() { return (String)this.getCategoryProfile("software_info", "customer_id"); } + /** + * 获取 {@code regionImgVersion}。 + * @return 字符串结果 + */ public String getRegionImgVersion() { return this.getProfile().getDbObject(new String[]{"software_info"}).getString("region_version"); } + /** + * 获取 {@code scriptVersion}。 + * @return 字符串结果 + */ public String getScriptVersion() { return (String)this.getCategoryProfile("software_info", "script_version"); } + /** + * 获取 {@code regionBuildDate}。 + * @return 数量/长度 + */ public long getRegionBuildDate() { return this.getProfile().getDbObject(new String[]{"software_info"}).getLong("region_build_date"); } + /** + * 判断 {@code gmsAvailable}。 + * @return 字段/派生属性 {@code gmsAvailable} 的值 + */ public boolean isGmsAvailable() { return this.getProfile().getDbObject(new String[]{"software_info"}).getBoolean("gms_available"); } + /** + * 获取 {@code skuId}。 + * + * 实现要点:包含 7 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getSkuId() { String skuId = (String)this.getCategoryProfile("hardware_info", "sku_id"); if (skuId == null) { @@ -404,27 +663,54 @@ public class Device extends GeneralProfile { return skuId; } + /** + * 获取 {@code deviceId}。 + * @return 字符串结果 + */ public String getDeviceId() { return (String)this.getCategoryProfile("hardware_info", "device_id"); } + /** + * 获取 {@code buildFingerPrint}。 + * @return 字符串结果 + */ public String getBuildFingerPrint() { return (String)this.getCategoryProfile("software_info", "build_fingerprint"); } + /** + * 判断 {@code mobileConnected}。 + * @return 字段/派生属性 {@code mobileConnected} 的值 + */ public boolean isMobileConnected() { String type = this.getProfileCategory(new String[]{"network", "active"}).getString("type"); return "MOBILE".equalsIgnoreCase(type); } + /** + * 获取 {@code wifiMacAddr}。 + * @return 字符串结果 + */ public String getWifiMacAddr() { return this.getProfileCategory(new String[]{"network", "wifi"}).getString("mac_address"); } + /** + * 获取 {@code license}。 + * @return 字段/派生属性 {@code license} 的值 + */ public DeviceLicense getLicense() { return this.license; } + /** + * 设置 {@code license}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + */ public void setLicense(DeviceLicense license) { this.license = license; if (license != null) { @@ -434,14 +720,28 @@ public class Device extends GeneralProfile { } + /** + * 获取 {@code licensed}。 + * @return 字段/派生属性 {@code licensed} 的值 + */ public Date getLicensed() { return this.licensed; } + /** + * 设置 {@code licensed}。 + * + * @param licensed 参数 {@code licensed}({@code Date}) + */ public void setLicensed(Date licensed) { this.licensed = licensed; } + /** + * 设置许可证Expiry。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + */ private void setLicenseExpiry() { if (this.hasLicense()) { 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() { if (this.licenseExpiry == null && this.hasLicense()) { this.licenseExpiry = this.license.getExpiry(); @@ -460,35 +766,66 @@ public class Device extends GeneralProfile { return this.licenseExpiry; } + /** + * 判断 {@code licenseExpired}。 + * @return 字段/派生属性 {@code licenseExpired} 的值 + */ public boolean isLicenseExpired() { return this.license != null && !this.license.isPerpetual() && this.license.isExpired(); } + /** + * 设置 {@code licenseExpiry}。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + */ public void setLicenseExpiry(Date expiry) { this.licenseExpiry = expiry; } + /** + * 判断 {@code license}。 + * @return 字段/派生属性 {@code license} 的值 + */ public boolean hasLicense() { return this.license != null; } + /** + * 判断 {@code trial}。 + * @return 字段/派生属性 {@code trial} 的值 + */ public boolean isTrial() { return !this.hasLicense() || this.license.isTrial(); } + /** + * 移除许可证。 + */ public void removeLicense() { this.setLicense((DeviceLicense)null); } + /** + * 获取 {@code plan}。 + * @return 字符串结果 + */ public String getPlan() { return this.license.getPlan(); } + /** + * 处理重置。 + */ public void reset() { this.setEnrolled((Date)null); this.getStates().clear(); } + /** + * 处理clone。 + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device clone() { return (Device)McJsonUtils.clone(this); } diff --git a/src/main/java/com/midm/model/device/DeviceApps.java b/src/main/java/com/midm/model/device/DeviceApps.java index 9b781a6..e0c7a5f 100644 --- a/src/main/java/com/midm/model/device/DeviceApps.java +++ b/src/main/java/com/midm/model/device/DeviceApps.java @@ -10,64 +10,167 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceApps} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
  • {@code serialNo}(String):序列号
  • + *
  • {@code category}(String):字段 category
  • + *
  • {@code apps}(List):应用列表
  • + *
  • {@code reported}(Date):时间字段
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class DeviceApps { + /** + * 设备UUID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID deviceUuid; + /** + * 序列号;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private String serialNo; + /** + * 字段 category。 + */ private String category = "installed"; - private List apps; + /** + * 应用列表。 + */ + private List apps; + /** + * 时间字段。 + */ private Date reported = new Date(); + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 获取 {@code serialNo}。 + * @return 字符串结果 + */ public String getSerialNo() { return this.serialNo; } + /** + * 设置 {@code serialNo}。 + * + * @param serialNo 设备序列号({@code String}) + */ public void setSerialNo(String serialNo) { this.serialNo = serialNo; } + /** + * 获取 {@code category}。 + * @return 字符串结果 + */ public String getCategory() { return this.category; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } - public List getApps() { + /** + * 获取 {@code apps}。 + * @return 应用信息列表,可能为空 + */ + public List getApps() { return this.apps; } - public void setApps(List apps) { + /** + * 设置 {@code apps}。 + * + * @param apps 参数 {@code apps}({@code List}) + */ + public void setApps(List apps) { this.apps = apps; } + /** + * 获取 {@code clientService}。 + * @return 字段/派生属性 {@code clientService} 的值 + */ public AppInfo getClientService() { return this.getApp("com.mitac.midm.client"); } + /** + * 设置 {@code clientService}。 + * + * @param appInfo 参数 {@code appInfo}({@code AppInfo}) + */ public void setClientService(AppInfo appInfo) { this.setApp(appInfo); } + /** + * 获取 {@code systemService}。 + * @return 字段/派生属性 {@code systemService} 的值 + */ public AppInfo getSystemService() { return this.getApp("com.mitac.midm.system"); } + /** + * 设置 {@code systemService}。 + * + * @param appInfo 参数 {@code appInfo}({@code AppInfo}) + */ public void setSystemService(AppInfo appInfo) { this.setApp(appInfo); } + /** + * 获取应用。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字段/派生属性 {@code app} 的值 + */ public AppInfo getApp(String packageName) { if (this.apps != null) { for(AppInfo app : this.apps) { @@ -81,6 +184,13 @@ public class DeviceApps { return null; } + /** + * 设置 {@code app}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param newApp 参数 {@code newApp}({@code AppInfo}) + */ public void setApp(AppInfo newApp) { if (newApp != null && !Strings.isNullOrEmpty(newApp.getPackageName())) { if (this.apps == null) { @@ -91,6 +201,11 @@ public class DeviceApps { } } + /** + * 修复Abnormal。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:remove。 + */ public void fixAbnormal() { Iterator it = this.apps.iterator(); @@ -107,14 +222,34 @@ public class DeviceApps { } + /** + * 获取 {@code reported}。 + * @return 字段/派生属性 {@code reported} 的值 + */ public Date getReported() { return this.reported; } + /** + * 设置 {@code reported}。 + * + * @param reported 参数 {@code reported}({@code Date}) + */ public void setReported(Date 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) { if (minSdk != -1 && deviceSdk < minSdk) { 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) { List newApps = null; if (obj instanceof DeviceApps) { diff --git a/src/main/java/com/midm/model/device/DeviceGroup.java b/src/main/java/com/midm/model/device/DeviceGroup.java index 05c57c3..fc5d526 100644 --- a/src/main/java/com/midm/model/device/DeviceGroup.java +++ b/src/main/java/com/midm/model/device/DeviceGroup.java @@ -6,23 +6,78 @@ import java.util.UUID; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceGroup} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code parentUuid}(UUID):父级UUID
  • + *
  • {@code order}(Integer):字段 order
  • + *
  • {@code deviceNumbers}(Integer):设备Numbers
  • + *
  • {@code children}(List):子级
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document -public class DeviceGroup extends GeneralProfile implements Comparable { +public class DeviceGroup extends GeneralProfile implements Comparable { + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 父级UUID。 + */ private UUID parentUuid; + /** + * 字段 order。 + */ private Integer order; + /** + * 设备Numbers;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Integer deviceNumbers; - private List children; + /** + * 子级。 + */ + private List children; + /** + * 构造 {@code DeviceGroup} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DeviceGroup() { this.deviceNumbers = 0; } + /** + * 构造 {@code DeviceGroup} 实例。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public DeviceGroup(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) { this.init(); this.siteUuid = siteUuid; @@ -30,50 +85,109 @@ public class DeviceGroup extends GeneralProfile implements Comparable { this.setName(name); } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code parentUuid}。 + * @return UUID + */ public UUID getParentUuid() { return this.parentUuid; } + /** + * 设置 {@code parentUuid}。 + * + * @param parentUuid 参数 {@code parentUuid}({@code UUID}) + */ public void setParentUuid(UUID parentUuid) { this.parentUuid = parentUuid; } + /** + * 获取 {@code order}。 + * @return 数量/长度 + */ public Integer getOrder() { return this.order; } + /** + * 设置 {@code order}。 + * + * @param order 参数 {@code order}({@code Integer}) + */ public void setOrder(Integer order) { this.order = order; } + /** + * 获取 {@code deviceNumbers}。 + * @return 数量/长度 + */ public Integer getDeviceNumbers() { return this.deviceNumbers; } + /** + * 设置 {@code deviceNumbers}。 + * + * @param numbers 参数 {@code numbers}({@code Integer}) + */ public void setDeviceNumbers(Integer numbers) { this.deviceNumbers = numbers == null ? 0 : numbers; } - public List getChildren() { + /** + * 获取 {@code children}。 + * @return 设备分组列表,可能为空 + */ + public List getChildren() { return this.children; } - public void setChildren(List children) { + /** + * 设置 {@code children}。 + * + * @param children 参数 {@code children}({@code List}) + */ + public void setChildren(List children) { this.children = children; } + /** + * 比较当前对象与另一个对象是否相等。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean equals(UUID uuid) { return this.uuid != null && this.uuid.equals(uuid); } + /** + * 按业务字段比较两个对象的顺序。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param target 参数 {@code target}({@code Object}) + * @return 数量/长度 + */ public int compareTo(Object target) { UUID targetUuid = null; if (target instanceof UUID) { diff --git a/src/main/java/com/midm/model/device/DeviceKey.java b/src/main/java/com/midm/model/device/DeviceKey.java index 9bf5d38..ce17333 100644 --- a/src/main/java/com/midm/model/device/DeviceKey.java +++ b/src/main/java/com/midm/model/device/DeviceKey.java @@ -6,19 +6,68 @@ import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceKey} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code deviceSerial}(String):设备序列
  • + *
  • {@code rsa}(String):RSA
  • + *
  • {@code created}(Date):创建时间
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class DeviceKey { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 设备序列;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String deviceSerial; + /** + * RSA。 + */ private String rsa; + /** + * 创建时间。 + */ private Date created; + /** + * 构造 {@code DeviceKey} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DeviceKey() { 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) { this.uuid = UUID.randomUUID(); this.created = new Date(); @@ -26,22 +75,44 @@ public class DeviceKey { this.rsa = rsa; } + /** + * 获取 {@code deviceSerial}。 + * @return 字符串结果 + */ public String getDeviceSerial() { return this.deviceSerial; } + /** + * 设置 {@code deviceSerial}。 + * + * @param deviceSerial 参数 {@code deviceSerial}({@code String}) + */ public void setDeviceSerial(String deviceSerial) { this.deviceSerial = deviceSerial; } + /** + * 获取 {@code rsa}。 + * @return 字符串结果 + */ public String getRsa() { return this.rsa; } + /** + * 设置 {@code rsa}。 + * + * @param rsa 参数 {@code rsa}({@code String}) + */ public void setRsa(String rsa) { this.rsa = rsa; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } diff --git a/src/main/java/com/midm/model/device/DeviceLicense.java b/src/main/java/com/midm/model/device/DeviceLicense.java index 0e903b4..eb41e21 100644 --- a/src/main/java/com/midm/model/device/DeviceLicense.java +++ b/src/main/java/com/midm/model/device/DeviceLicense.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code DeviceLicense} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
  • {@code deviceSerial}(String):设备序列
  • + *
  • {@code siteLicense}(SiteLicense):站点许可证
  • + *
  • {@code childSiteLicense}(SiteLicense):子站点许可证
  • + *
  • {@code site}(Site):站点
  • + *
+ * + * 协作对象:{@code SiteLicense、Site、LicenseModel}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndexes({@CompoundIndex( 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}" )}) public class DeviceLicense { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 设备UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private UUID deviceUuid; + /** + * 设备序列;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String deviceSerial; + /** + * 站点许可证;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private SiteLicense siteLicense; + /** + * 子站点许可证;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private SiteLicense childSiteLicense; + /** + * 站点;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site site; + /** + * 子站点;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site childSite; + /** + * 许可证模型;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private LicenseModel licenseModel; + /** + * 计划。 + */ private String plan; + /** + * 是否autoRenew。 + */ private boolean autoRenew; + /** + * renew转换为Same模型。 + */ private boolean renewToSameModel; + /** + * activation统计。 + */ private int activationCount; + /** + * 时间字段;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date activatedAt; + /** + * 时间字段;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date expiry; - private List reactivated; + /** + * 日期集合。 + */ + private List reactivated; + /** + * 创建时间。 + */ private Date created; + /** + * 构造 {@code DeviceLicense} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new Date。 + */ public DeviceLicense() { this.plan = "standard"; this.autoRenew = false; @@ -71,44 +170,92 @@ public class DeviceLicense { this.created = new Date(); } + /** + * 构造 {@code DeviceLicense} 实例。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + */ public DeviceLicense(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) { this((Device)null, (SiteLicense)license); this.setPlan(plan); } + /** + * 构造 {@code DeviceLicense} 实例。 + * + * @param device 设备({@code Device}) + */ public DeviceLicense(Device device) { this(); this.setDevice(device); } + /** + * 构造 {@code DeviceLicense} 实例。 + * + * @param device 设备({@code Device}) + * @param license 参数 {@code license}({@code SiteLicense}) + */ public DeviceLicense(Device device, SiteLicense license) { this(); this.setSiteLicense(license); this.setDevice(device); } + /** + * 构造 {@code DeviceLicense} 实例。 + * + * @param device 设备({@code Device}) + * @param licenseModel 参数 {@code licenseModel}({@code LicenseModel}) + */ public DeviceLicense(Device device, LicenseModel licenseModel) { this(); this.setLicenseModel(licenseModel); this.setDevice(device); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code siteLicense}。 + * @return 字段/派生属性 {@code siteLicense} 的值 + */ public SiteLicense getSiteLicense() { return this.siteLicense; } + /** + * 设置 {@code siteLicense}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + */ public void setSiteLicense(SiteLicense license) { this.siteLicense = license; if (license != null) { @@ -120,22 +267,46 @@ public class DeviceLicense { } + /** + * 获取 {@code childSiteLicense}。 + * @return 字段/派生属性 {@code childSiteLicense} 的值 + */ public SiteLicense getChildSiteLicense() { return this.childSiteLicense; } + /** + * 设置 {@code childSiteLicense}。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + */ public void setChildSiteLicense(SiteLicense license) { this.childSiteLicense = license; } + /** + * 判断 {@code lite}。 + * @return 字段/派生属性 {@code lite} 的值 + */ public boolean isLite() { return this.site.isLite() || this.plan.equals("lite"); } + /** + * 获取 {@code site}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getSite() { return this.site; } + /** + * 设置 {@code site}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + */ public void setSite(Site site) { if (site == null) { this.site = this.childSite = null; @@ -148,26 +319,56 @@ public class DeviceLicense { } + /** + * 获取 {@code childSite}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getChildSite() { return this.childSite; } + /** + * 设置 {@code childSite}。 + * + * @param child 参数 {@code child}({@code Site}) + */ public void setChildSite(Site child) { this.childSite = child; } + /** + * 判断 {@code licenseModel}。 + * @return 字段/派生属性 {@code licenseModel} 的值 + */ public boolean hasLicenseModel() { return this.getLicenseModel() != null; } + /** + * 获取 {@code licenseModel}。 + * @return 字段/派生属性 {@code licenseModel} 的值 + */ public LicenseModel getLicenseModel() { return this.licenseModel; } + /** + * 设置 {@code licenseModel}。 + * + * @param licenseModel 参数 {@code licenseModel}({@code LicenseModel}) + */ public void setLicenseModel(LicenseModel licenseModel) { 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) { this.licenseModel = licenseModel; if (licenseModel != null && setExpiry) { @@ -176,14 +377,31 @@ public class DeviceLicense { } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 设置 {@code device}。 + * + * 实现要点:包含 8 个条件分支、0 个循环;主要调用:new Date。 + * + * @param device 设备({@code Device}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setDevice(Device device) { if (this.isExceedActivationCount() && this.beforeExpiry()) { return false; @@ -222,42 +440,89 @@ public class DeviceLicense { } } + /** + * 获取 {@code deviceSerial}。 + * @return 字符串结果 + */ public String getDeviceSerial() { return this.deviceSerial; } + /** + * 设置 {@code deviceSerial}。 + * + * @param serialNo 设备序列号({@code String}) + */ public void setDeviceSerial(String serialNo) { this.deviceSerial = serialNo; } + /** + * 获取 {@code plan}。 + * @return 字符串结果 + */ public String getPlan() { return this.plan; } + /** + * 设置 {@code plan}。 + * + * @param plan 参数 {@code plan}({@code String}) + */ public void setPlan(String plan) { this.plan = plan; } + /** + * 判断 {@code autoRenew}。 + * @return 字段/派生属性 {@code autoRenew} 的值 + */ public boolean isAutoRenew() { return this.autoRenew; } + /** + * 设置 {@code autoRenew}。 + * + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + */ public void setAutoRenew(boolean autoRenew) { this.autoRenew = autoRenew; } + /** + * 判断 {@code renewToSameModel}。 + * @return 字段/派生属性 {@code renewToSameModel} 的值 + */ public boolean isRenewToSameModel() { return this.renewToSameModel; } + /** + * 设置 {@code renewToSameModel}。 + * + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + */ public void setRenewToSameModel(boolean renewToSameModel) { this.renewToSameModel = renewToSameModel; } + /** + * 获取 {@code activationCount}。 + * @return 数量/长度 + */ public int getActivationCount() { return this.activationCount; } + /** + * 设置 {@code activationCount}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param count 参数 {@code count}({@code int}) + */ public void setActivationCount(int count) { if (count < 0) { count = 0; @@ -270,6 +535,11 @@ public class DeviceLicense { } + /** + * 重置Activation统计。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ public void resetActivationCount() { if (this.isTrial()) { 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) { return this.activationCount > maxActivationCount; } + /** + * 判断 {@code active}。 + * @return 字段/派生属性 {@code active} 的值 + */ public boolean isActive() { return this.activatedAt == null; } + /** + * 判断 {@code activated}。 + * @return 字段/派生属性 {@code activated} 的值 + */ public boolean isActivated() { return this.activatedAt != null; } + /** + * 判断 {@code expired}。 + * @return 字段/派生属性 {@code expired} 的值 + */ public boolean isExpired() { return !this.beforeExpiry(); } + /** + * 判断 {@code extend}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new DateTime。 + * @return 字段/派生属性 {@code extend} 的值 + */ public boolean canExtend() { if (!this.isPerpetual()) { return false; @@ -311,14 +605,32 @@ public class DeviceLicense { } } + /** + * 获取 {@code activatedAt}。 + * @return 字段/派生属性 {@code activatedAt} 的值 + */ public Date getActivatedAt() { return this.activatedAt; } + /** + * 处理激活。 + * + * 实现要点:主要调用:new Date。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public Boolean activate() { 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) { if (!this.isActivated()) { this.activatedAt = activatedAt; @@ -339,71 +651,155 @@ public class DeviceLicense { } } + /** + * 处理重置。 + */ public void reset() { this.setDevice((Device)null); } + /** + * 获取 {@code expiry}。 + * @return 字段/派生属性 {@code expiry} 的值 + */ public Date getExpiry() { return this.expiry; } + /** + * 处理beforeExpiry。 + * + * 实现要点:主要调用:new Date。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean beforeExpiry() { return this.expiry != null && this.expiry.after(new Date()); } + /** + * 设置 {@code expiry}。 + * + * @param expiryDate 参数 {@code expiryDate}({@code Date}) + */ public void setExpiry(Date expiryDate) { this.expiry = expiryDate; } + /** + * 处理extendExpiryDays。 + * + * 实现要点:主要调用:new DateTime。 + * + * @param days 参数 {@code days}({@code int}) + */ public void extendExpiryDays(int days) { this.setExpiry((new DateTime()).plusDays(days).toDate()); } + /** + * 处理过期。 + * + * 实现要点:主要调用:new Date。 + */ public void expire() { this.setExpiry(new Date()); } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 判断 {@code perpetual}。 + * @return 字段/派生属性 {@code perpetual} 的值 + */ public boolean isPerpetual() { return this.licenseModel != null && this.licenseModel.isPerpetual(); } + /** + * 判断 {@code trial}。 + * @return 字段/派生属性 {@code trial} 的值 + */ public boolean isTrial() { return this.siteLicense == null || this.licenseModel == null || this.licenseModel.isTrial(); } + /** + * 判断 {@code exceedActivationCount}。 + * @return 字段/派生属性 {@code exceedActivationCount} 的值 + */ public boolean isExceedActivationCount() { int maxCount = this.licenseModel == null ? 2 : this.licenseModel.getMaxActivation(); return maxCount > 0 && maxCount <= this.activationCount; } + /** + * 判断 {@code valid}。 + * + * 实现要点:主要调用:new Date。 + * @return 字段/派生属性 {@code valid} 的值 + */ public boolean isValid() { return this.isPerpetual() ? true : (new Date()).before(this.expiry); } + /** + * 判断是否Same许可证模型。 + * + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @return 字段/派生属性 {@code sameLicenseModel} 的值 + */ public boolean isSameLicenseModel(UUID licenseModelUuid) { return this.licenseModel != null && this.licenseModel.getUuid().equals(licenseModelUuid); } + /** + * 获取 {@code remainingDays}。 + * + * 实现要点:主要调用:new Date、new DateTime。 + * @return 数量/长度 + */ public int getRemainingDays() { return this.expiry.before(new Date()) ? 0 : McDateTimeUtils.daysBetween(new DateTime(this.expiry), DateTime.now()); } - public List getReactivated() { + /** + * 获取 {@code reactivated}。 + * @return 日期列表,可能为空 + */ + public List getReactivated() { return this.reactivated; } - public void setReactivated(List reactivated) { + /** + * 设置 {@code reactivated}。 + * + * @param reactivated 参数 {@code reactivated}({@code List}) + */ + public void setReactivated(List reactivated) { this.reactivated = reactivated; } + /** + * 处理reactivate。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ArrayList、new DateTime。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean reactivate() { if (this.isPerpetual()) { if (this.reactivated == null) { @@ -421,6 +817,10 @@ public class DeviceLicense { return false; } + /** + * 获取 {@code po}。 + * @return 字符串结果 + */ public String getPo() { return this.childSiteLicense != null ? this.childSiteLicense.getPo() : (this.siteLicense != null ? this.siteLicense.getPo() : null); } diff --git a/src/main/java/com/midm/model/device/DeviceNote.java b/src/main/java/com/midm/model/device/DeviceNote.java index a242a95..cd940d9 100644 --- a/src/main/java/com/midm/model/device/DeviceNote.java +++ b/src/main/java/com/midm/model/device/DeviceNote.java @@ -7,66 +7,172 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceNote} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
  • {@code writerUuid}(UUID):writerUUID
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code note}(String):备注
  • + *
  • {@code registeredAt}(Date):时间字段
  • + *
+ * + * 协作对象:{@code User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class DeviceNote { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 设备UUID。 + */ private UUID deviceUuid; + /** + * writerUUID。 + */ private UUID writerUuid; + /** + * 字段 writer;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private User writer; + /** + * 备注。 + */ private String note; + /** + * 时间字段。 + */ private Date registeredAt; + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.setUuid(UUID.randomUUID()); this.setRegisteredAt(new Date()); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 获取 {@code writerUuid}。 + * @return UUID + */ public UUID getWriterUuid() { return this.writerUuid; } + /** + * 设置 {@code writerUuid}。 + * + * @param writerUuid 参数 {@code writerUuid}({@code UUID}) + */ public void setWriterUuid(UUID writerUuid) { this.writerUuid = writerUuid; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param writer 参数 {@code writer}({@code User}) + */ public void setWriter(User writer) { this.writer = writer; } + /** + * 获取 {@code note}。 + * @return 字符串结果 + */ public String getNote() { return this.note; } + /** + * 设置 {@code note}。 + * + * @param note 参数 {@code note}({@code String}) + */ public void setNote(String note) { this.note = note; } + /** + * 获取 {@code registeredAt}。 + * @return 字段/派生属性 {@code registeredAt} 的值 + */ public Date getRegisteredAt() { return this.registeredAt; } + /** + * 设置 {@code registeredAt}。 + * + * @param registeredAt 参数 {@code registeredAt}({@code Date}) + */ public void setRegisteredAt(Date registeredAt) { this.registeredAt = registeredAt; } diff --git a/src/main/java/com/midm/model/device/DeviceProfile.java b/src/main/java/com/midm/model/device/DeviceProfile.java index 17c8571..7263a5f 100644 --- a/src/main/java/com/midm/model/device/DeviceProfile.java +++ b/src/main/java/com/midm/model/device/DeviceProfile.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code DeviceProfile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code deviceProfileGroup}(DeviceProfileGroup):设备配置档案分组
  • + *
  • {@code writerUuid}(UUID):writerUUID
  • + *
  • {@code isGlobal}(boolean):判断是否Global
  • + *
  • {@code status}(DbObject):状态
  • + *
  • {@code apps}(ProfileApps):应用列表
  • + *
+ * + * 协作对象:{@code DeviceProfileGroup、DbObject、ProfileApps、ProfileScope、User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndex( def = "{'deviceProfileGroup.uuid': 1}" ) public class DeviceProfile extends GeneralProfile { + /** + * 用户所属站点 UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private UUID siteUuid; + /** + * 设备配置档案分组;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private DeviceProfileGroup deviceProfileGroup; + /** + * writerUUID。 + */ private UUID writerUuid; + /** + * 判断是否Global。 + */ private boolean isGlobal; + /** + * 状态。 + */ private DbObject status; + /** + * 应用列表。 + */ private ProfileApps apps; - private List otas; + /** + * UUID集合。 + */ + private List otas; + /** + * 文件列表。 + */ private DbObject files; + /** + * 范围。 + */ private ProfileScope scope; - private List sequence; + /** + * UUID集合。 + */ + private List sequence; + /** + * 字段 progress;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DbObject progress; + /** + * 字段 reference;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DbObject reference; + /** + * 分组UUID;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private UUID groupUuid; + /** + * 字段 writer;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private User writer; + /** + * need旧格式化;Gson 序列化控制;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Expose(serialize = false) @Transient}。 + */ @Expose( serialize = false ) @Transient private boolean needOldFormat = false; + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 判断 {@code global}。 + * @return 字段/派生属性 {@code global} 的值 + */ public boolean isGlobal() { return this.isGlobal; } + /** + * 设置 {@code isGlobal}。 + * + * @param isGlobal 参数 {@code isGlobal}({@code boolean}) + */ public void setIsGlobal(boolean isGlobal) { this.isGlobal = isGlobal; } + /** + * 获取 {@code groupUuid}。 + * @return UUID + */ public UUID getGroupUuid() { return this.groupUuid; } + /** + * 设置 {@code groupUuid}。 + * + * @param groupUuid 分组 UUID({@code UUID}) + */ public void setGroupUuid(UUID groupUuid) { this.groupUuid = groupUuid; } + /** + * 获取 {@code deviceProfileGroup}。 + * @return 字段/派生属性 {@code deviceProfileGroup} 的值 + */ public DeviceProfileGroup getDeviceProfileGroup() { return this.deviceProfileGroup; } + /** + * 设置 {@code deviceProfileGroup}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param deviceProfileGroup 参数 {@code deviceProfileGroup}({@code DeviceProfileGroup}) + */ public void setDeviceProfileGroup(DeviceProfileGroup deviceProfileGroup) { this.deviceProfileGroup = deviceProfileGroup; 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 getFileUUids() { Set pushUuids = new HashSet(); if (this.files != null && !this.files.isEmpty() && this.files.containsKey("push")) { List pushes = this.files.getList("push", DbObject.class); @@ -99,74 +222,153 @@ public class DeviceProfile extends GeneralProfile { return pushUuids; } + /** + * 应用Order。 + * @return 字符串结果 + */ public String applyOrder() { return this.getProfile().getString("applyOrder", "none"); } - public List getSequence() { + /** + * 获取 {@code sequence}。 + * @return UUID列表,可能为空 + */ + public List getSequence() { return this.sequence; } + /** + * 判断 {@code sequence}。 + * @return 字段/派生属性 {@code sequence} 的值 + */ public boolean hasSequence() { return this.sequence != null && !this.sequence.isEmpty(); } - public void setSequence(List sequence) { + /** + * 设置 {@code sequence}。 + * + * @param sequence 参数 {@code sequence}({@code List}) + */ + public void setSequence(List sequence) { this.sequence = sequence; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code writerUuid}。 + * @return UUID + */ public UUID getWriterUuid() { return this.writerUuid; } + /** + * 设置 {@code writerUuid}。 + * + * @param writerUuid 参数 {@code writerUuid}({@code UUID}) + */ public void setWriterUuid(UUID writerUuid) { this.writerUuid = writerUuid; } + /** + * 获取 {@code status}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getStatus() { return this.status; } + /** + * 设置 {@code status}。 + * + * @param status 状态({@code DbObject}) + */ public void setStatus(DbObject status) { this.status = status; } + /** + * 获取 {@code scope}。 + * @return 字段/派生属性 {@code scope} 的值 + */ public ProfileScope getScope() { return this.scope; } + /** + * 判断 {@code scope}。 + * @return 字段/派生属性 {@code scope} 的值 + */ public boolean hasScope() { return this.scope != null && this.scope.hasScoped(); } + /** + * 判断 {@code scopeDeviceGroups}。 + * @return 字段/派生属性 {@code scopeDeviceGroups} 的值 + */ public boolean hasScopeDeviceGroups() { return this.scope != null && this.scope.getGroup() != null && !this.scope.getGroup().isEmpty(); } - public Set getScopedDeviceGroups() { + /** + * 获取 {@code scopedDeviceGroups}。 + * @return UUID列表,可能为空 + */ + public Set getScopedDeviceGroups() { return this.scope == null ? null : this.scope.getGroup(); } - public Set getScopedDevice() { + /** + * 获取 {@code scopedDevice}。 + * @return String列表,可能为空 + */ + public Set getScopedDevice() { return this.scope == null ? null : this.scope.getDevice(); } + /** + * 设置 {@code scope}。 + * + * @param scope 参数 {@code scope}({@code ProfileScope}) + */ public void setScope(ProfileScope scope) { this.scope = scope; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param writer 参数 {@code writer}({@code User}) + */ public void setWriter(User writer) { this.writer = writer; } + /** + * 初始化应用列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ public void initApps() { if (this.apps != null) { this.apps.initInstallApp(); @@ -175,11 +377,21 @@ public class DeviceProfile extends GeneralProfile { } + /** + * 获取 {@code apps}。 + * @return 字段/派生属性 {@code apps} 的值 + */ public ProfileApps getApps() { return this.apps; } - public List getInstallApps() { + /** + * 获取 {@code installApps}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 配置档案Apps.Install应用列表,可能为空 + */ + public List getInstallApps() { if (this.apps == null) { this.initApps(); } @@ -187,7 +399,13 @@ public class DeviceProfile extends GeneralProfile { return this.apps == null ? null : this.apps.getInstallApp(); } - public List getInstallUuids() { + /** + * 获取 {@code installUuids}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return UUID列表,可能为空 + */ + public List getInstallUuids() { if (this.apps == null) { this.initApps(); } @@ -195,6 +413,14 @@ public class DeviceProfile extends GeneralProfile { 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) { if (this.apps == null) { this.initApps(); @@ -203,18 +429,37 @@ public class DeviceProfile extends GeneralProfile { return this.apps != null ? this.apps.getInstallApp(packageName) : null; } + /** + * 设置 {@code apps}。 + * + * @param apps 参数 {@code apps}({@code ProfileApps}) + */ public void setApps(ProfileApps apps) { this.apps = apps; } + /** + * 处理need旧格式化。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean needOldFormat() { return this.needOldFormat; } + /** + * 设置 {@code needOldFormat}。 + * + * @param need 参数 {@code need}({@code boolean}) + */ public void setNeedOldFormat(boolean need) { this.needOldFormat = need; } + /** + * 设置转换为旧格式化。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ public void setToOldFormat() { if (this.apps != null) { this.apps.setToOldFormat(); @@ -222,50 +467,106 @@ public class DeviceProfile extends GeneralProfile { } - public List getWhiteListPackages() { + /** + * 获取 {@code whiteListPackages}。 + * @return String列表,可能为空 + */ + public List getWhiteListPackages() { return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; } - public List getBlackListPackages() { + /** + * 获取 {@code blackListPackages}。 + * @return String列表,可能为空 + */ + public List getBlackListPackages() { return this.apps != null ? this.apps.getPackageList(this.apps.getWhiteList()) : null; } - public List getOtas() { + /** + * 获取 {@code otas}。 + * @return UUID列表,可能为空 + */ + public List getOtas() { return this.otas; } - public void setOtas(List otas) { + /** + * 设置 {@code otas}。 + * + * @param otas 参数 {@code otas}({@code List}) + */ + public void setOtas(List otas) { this.otas = otas; } + /** + * 检查构建日期。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean checkBuildDate() { return this.getSettingAsBoolean("otas", "checkBuildDate", false); } + /** + * 获取 {@code files}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getFiles() { return this.files; } + /** + * 设置 {@code files}。 + * + * @param files 参数 {@code files}({@code DbObject}) + */ public void setFiles(DbObject files) { this.files = files; } + /** + * 获取 {@code progress}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProgress() { return this.progress; } + /** + * 设置 {@code progress}。 + * + * @param progress 参数 {@code progress}({@code DbObject}) + */ public void setProgress(DbObject progress) { this.progress = progress; } + /** + * 获取 {@code reference}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReference() { return this.reference; } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code DbObject}) + */ public void setReference(DbObject 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) { if (data == null) { if (this.reference != null) { @@ -279,6 +580,11 @@ public class DeviceProfile extends GeneralProfile { } + /** + * 处理unset日期时间设置列表。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:remove。 + */ public void unsetDateTimeSettings() { DbObject settings = this.getSettingsCategory(new String[]{"system", "dateTime"}); if (settings != null) { @@ -295,6 +601,11 @@ public class DeviceProfile extends GeneralProfile { } + /** + * 转换Custom设置列表用于设备。 + * + * 实现要点:包含 6 个条件分支、1 个循环;主要调用:new DbObject、remove。 + */ public void convertCustomSettingsForDevice() { 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() { return this.getProfile().getBoolean("removeIfNoScope", false); } + /** + * 处理unscopeIfApplied。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean unscopeIfApplied() { return this.getProfile().getBoolean("unscopeIfApplied", false); } + /** + * 处理minify。 + */ public void minify() { super.minify(); this.deviceProfileGroup = null; @@ -343,6 +665,10 @@ public class DeviceProfile extends GeneralProfile { this.writer = null; } + /** + * 处理clone。 + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile clone() { return (DeviceProfile)McJsonUtils.clone(this); } diff --git a/src/main/java/com/midm/model/device/DeviceProfileGroup.java b/src/main/java/com/midm/model/device/DeviceProfileGroup.java index 724b45b..da3dfc0 100644 --- a/src/main/java/com/midm/model/device/DeviceProfileGroup.java +++ b/src/main/java/com/midm/model/device/DeviceProfileGroup.java @@ -6,52 +6,136 @@ import java.util.UUID; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceProfileGroup} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code parentUuid}(UUID):父级UUID
  • + *
  • {@code order}(Integer):字段 order
  • + *
  • {@code deviceProfileNumbers}(Long):设备配置档案Numbers
  • + *
  • {@code children}(List):子级
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class DeviceProfileGroup extends GeneralProfile { + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 父级UUID。 + */ private UUID parentUuid; + /** + * 字段 order。 + */ private Integer order; + /** + * 设备配置档案Numbers;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Long deviceProfileNumbers; - private List children; + /** + * 子级。 + */ + private List children; + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code parentUuid}。 + * @return UUID + */ public UUID getParentUuid() { return this.parentUuid; } + /** + * 设置 {@code parentUuid}。 + * + * @param parentUuid 参数 {@code parentUuid}({@code UUID}) + */ public void setParentUuid(UUID parentUuid) { this.parentUuid = parentUuid; } + /** + * 获取 {@code order}。 + * @return 数量/长度 + */ public Integer getOrder() { return this.order; } + /** + * 设置 {@code order}。 + * + * @param order 参数 {@code order}({@code Integer}) + */ public void setOrder(Integer order) { this.order = order; } + /** + * 获取 {@code deviceProfileNumbers}。 + * @return 数量/长度 + */ public Long getDeviceProfileNumbers() { return this.deviceProfileNumbers; } + /** + * 设置 {@code deviceProfileNumbers}。 + * + * @param numbers 参数 {@code numbers}({@code Long}) + */ public void setDeviceProfileNumbers(Long numbers) { this.deviceProfileNumbers = numbers; } - public List getChildren() { + /** + * 获取 {@code children}。 + * @return 设备配置档案分组列表,可能为空 + */ + public List getChildren() { return this.children; } - public void setChildren(List children) { + /** + * 设置 {@code children}。 + * + * @param children 参数 {@code children}({@code List}) + */ + public void setChildren(List children) { this.children = children; } } diff --git a/src/main/java/com/midm/model/device/DeviceProfileState.java b/src/main/java/com/midm/model/device/DeviceProfileState.java index 0fcab1f..bdf6e68 100644 --- a/src/main/java/com/midm/model/device/DeviceProfileState.java +++ b/src/main/java/com/midm/model/device/DeviceProfileState.java @@ -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.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DeviceProfileState} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code STATE_IN_PROGRESS}(String):字段 STATE_IN_PROGRESS
  • + *
  • {@code STATE_DONE}(String):字段 STATE_DONE
  • + *
  • {@code STATE_UNKNWON}(String):字段 STATE_UNKNWON
  • + *
  • {@code scoped}(Scoped):字段 scoped
  • + *
  • {@code updated}(long):最后更新时间
  • + *
  • {@code state}(String):状态
  • + *
+ * + * 协作对象:{@code Scoped、DeviceReport}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndexes({@CompoundIndex( def = "{'_id.deviceUuid': 1}" @@ -18,103 +43,238 @@ import org.springframework.data.mongodb.core.mapping.Document; def = "{'_id.profileUuid': 1}" )}) public class DeviceProfileState { + /** + * 字段 STATE_IN_PROGRESS。 + */ public static final String STATE_IN_PROGRESS = "in_progress"; + /** + * 字段 STATE_DONE。 + */ public static final String STATE_DONE = "done"; + /** + * 字段 STATE_UNKNWON。 + */ public static final String STATE_UNKNWON = "unknown"; + /** + * 字段 scoped;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private Scoped scoped; + /** + * 最后更新时间。 + */ private long updated = -1L; + /** + * 状态;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String state = "unknown"; + /** + * 应用第一状态。 + */ private String applyFirstState = "unknown"; + /** + * 字段 applied;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private long applied; + /** + * 报表;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DeviceReport report; + /** + * 构造 {@code DeviceProfileState} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DeviceProfileState() { } + /** + * 构造 {@code DeviceProfileState} 实例。 + * + * 实现要点:主要调用:new Scoped、new Date。 + * + * @param device 设备({@code Device}) + * @param profile 设备配置档案({@code DeviceProfile}) + */ public DeviceProfileState(Device device, DeviceProfile profile) { this.scoped = new Scoped(profile.getUuid(), device.getUuid()); this.updated = profile.getUpdated().getTime(); this.applied = (new Date()).getTime(); } + /** + * 构造 {@code DeviceProfileState} 实例。 + * + * @param report 参数 {@code report}({@code DeviceReport}) + */ public DeviceProfileState(DeviceReport report) { this.setReport(report); } + /** + * 获取 {@code scoped}。 + * @return 字段/派生属性 {@code scoped} 的值 + */ public Scoped getScoped() { return this.scoped; } + /** + * 设置 {@code scoped}。 + * + * @param scoped 参数 {@code scoped}({@code Scoped}) + */ public void setScoped(Scoped scoped) { this.scoped = scoped; } + /** + * 获取 {@code profileUuid}。 + * @return UUID + */ public UUID getProfileUuid() { return this.getScoped().getProfileUuid(); } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.getScoped().getDeviceUuid(); } + /** + * 获取 {@code updated}。 + * @return 数量/长度 + */ public long getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code long}) + */ public void setUpdated(long updated) { this.updated = updated; } + /** + * 获取 {@code state}。 + * @return 字符串结果 + */ public String getState() { return this.state; } + /** + * 判断 {@code done}。 + * @return 字段/派生属性 {@code done} 的值 + */ public boolean isDone() { return this.state == null || this.state.equals("done"); } + /** + * 设置 {@code state}。 + * + * @param state 参数 {@code state}({@code String}) + */ public void setState(String state) { this.state = state; } + /** + * 获取 {@code applyFirstState}。 + * @return 字符串结果 + */ public String getApplyFirstState() { return this.applyFirstState; } + /** + * 判断 {@code applyFirstDone}。 + * @return 字段/派生属性 {@code applyFirstDone} 的值 + */ public boolean isApplyFirstDone() { return this.applyFirstState != null && this.applyFirstState.equals("done"); } + /** + * 设置 {@code applyFirstState}。 + * + * @param applyFirstState 参数 {@code applyFirstState}({@code String}) + */ public void setApplyFirstState(String applyFirstState) { this.applyFirstState = applyFirstState; } + /** + * 获取 {@code applied}。 + * @return 数量/长度 + */ public long getApplied() { return this.applied; } + /** + * 设置 {@code applied}。 + * + * @param applied 参数 {@code applied}({@code long}) + */ public void setApplied(long applied) { this.applied = applied; this.setState("done"); } + /** + * 设置Applied。 + * + * @param applied 参数 {@code applied}({@code long}) + * @param state 参数 {@code state}({@code String}) + */ public void setApplied(long applied, String state) { this.state = state; this.applied = applied; } + /** + * 设置Applied。 + * + * 实现要点:主要调用:new Date。 + */ public void setApplied() { this.applied = (new Date()).getTime(); } + /** + * 获取 {@code report}。 + * @return 字段/派生属性 {@code report} 的值 + */ public DeviceReport getReport() { return this.report; } + /** + * 设置 {@code report}。 + * + * 实现要点:主要调用:new Scoped。 + * + * @param report 参数 {@code report}({@code DeviceReport}) + */ public void setReport(DeviceReport report) { this.report = report; DbObject profile = report.getProperties().getDbObject(new String[]{"deviceProfile"}); @@ -124,30 +284,81 @@ public class DeviceProfileState { this.setState("done"); } + /** + * 【领域模型】{@code Scoped} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profileUuid}(UUID):配置档案UUID
  • + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public static class Scoped implements Serializable { + /** + * 配置档案UUID。 + */ private UUID profileUuid; + /** + * 设备UUID。 + */ private UUID deviceUuid; + /** + * 构造 {@code Scoped} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Scoped() { } + /** + * 构造 {@code Scoped} 实例。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + */ public Scoped(UUID profileUuid, UUID deviceUuid) { this.profileUuid = profileUuid; this.deviceUuid = deviceUuid; } + /** + * 获取 {@code profileUuid}。 + * @return UUID + */ public UUID getProfileUuid() { return this.profileUuid; } + /** + * 设置 {@code profileUuid}。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + */ public void setProfileUuid(UUID profileUuid) { this.profileUuid = profileUuid; } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } diff --git a/src/main/java/com/midm/model/device/DeviceReport.java b/src/main/java/com/midm/model/device/DeviceReport.java index 4e6c483..70053e6 100644 --- a/src/main/java/com/midm/model/device/DeviceReport.java +++ b/src/main/java/com/midm/model/device/DeviceReport.java @@ -53,43 +53,89 @@ public class DeviceReport { /** 云端服务端持久化写入数据库的系统时间戳 */ private Date recordedAt; + /** + * 构造 {@code DeviceReport} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DeviceReport() { this.setRecordedAt(); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.setUuid(UUID.randomUUID()); this.setReportedAt(new Date()); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.deviceUuid; } + /** + * 设置 {@code deviceUuid}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void setDeviceUuid(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 获取 {@code serialNo}。 + * @return 字符串结果 + */ public String getSerialNo() { return this.serialNo; } + /** + * 设置 {@code serialNo}。 + * + * @param serialNo 设备序列号({@code String}) + */ public void setSerialNo(String serialNo) { this.serialNo = serialNo; } + /** + * 判断 {@code properties}。 + * @return 字段/派生属性 {@code properties} 的值 + */ public boolean hasProperties() { return this.properties != null && !this.properties.isEmpty(); } + /** + * 获取 {@code properties}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProperties() { if (this.properties == null) { this.properties = new DbObject(); @@ -98,38 +144,82 @@ public class DeviceReport { return this.properties; } + /** + * 设置 {@code properties}。 + * + * @param properties 参数 {@code properties}({@code DbObject}) + */ public void setProperties(DbObject properties) { this.properties = properties; } + /** + * 获取 {@code reportedAt}。 + * @return 字段/派生属性 {@code reportedAt} 的值 + */ public Date getReportedAt() { return this.reportedAt; } + /** + * 设置 {@code reportedAt}。 + * + * @param reportedAt 参数 {@code reportedAt}({@code Date}) + */ public void setReportedAt(Date reportedAt) { this.reportedAt = reportedAt; } + /** + * 获取 {@code recordedAt}。 + * @return 字段/派生属性 {@code recordedAt} 的值 + */ public Date getRecordedAt() { return this.recordedAt; } + /** + * 设置 {@code recordedAt}。 + * + * @param recordedAt 参数 {@code recordedAt}({@code Date}) + */ public void setRecordedAt(Date recordedAt) { this.recordedAt = recordedAt; } + /** + * 设置RecordedAt。 + * + * 实现要点:主要调用:new Date。 + */ public void setRecordedAt() { this.recordedAt = new Date(); } + /** + * 设置Property。 + * + * @param key 键/配置项({@code String}) + * @param val 参数 {@code val}({@code Object}) + */ public void setProperty(String key, Object val) { this.getProperties().append(key, val); } + /** + * 获取Property。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code property} 的值 + */ public Object getProperty(String key) { return this.getProperties().get(key); } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return McJsonUtils.toJson(this); } diff --git a/src/main/java/com/midm/model/device/ProfileApps.java b/src/main/java/com/midm/model/device/ProfileApps.java index 4baf3b3..3d6c225 100644 --- a/src/main/java/com/midm/model/device/ProfileApps.java +++ b/src/main/java/com/midm/model/device/ProfileApps.java @@ -15,45 +15,126 @@ import java.util.stream.Collectors; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Field; +/** + * 【领域模型】{@code ProfileApps} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code install}(List):?集合
  • + *
  • {@code installApp}(List):install应用
  • + *
  • {@code uninstall}(List):数据库Object集合
  • + *
  • {@code appWidget}(List):应用Widget
  • + *
  • {@code widget}(List):数据库Object集合
  • + *
  • {@code grantAll}(List):grant全部
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ProfileApps { - private List install; + /** + * ?集合。 + */ + private List install; + /** + * install应用;不持久化到 MongoDB,仅运行时使用;Gson 序列化控制。 + * + * 注解:{@code @Transient @Expose(serialize = false)}。 + */ @Transient @Expose( serialize = false ) - private List installApp; - private List uninstall; + private List installApp; + /** + * 数据库Object集合。 + */ + private List uninstall; + /** + * 应用Widget;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("add_appwidget") @Field("add_appwidget")}。 + */ @SerializedName("add_appwidget") @Field("add_appwidget") - private List appWidget; - private List widget; + private List appWidget; + /** + * 数据库Object集合。 + */ + private List widget; + /** + * grant全部;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("grant_all") @Field("grant_all")}。 + */ @SerializedName("grant_all") @Field("grant_all") - private List grantAll; - private List disabled; + private List grantAll; + /** + * 数据库Object集合。 + */ + private List disabled; + /** + * Wi-FiOnly;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("wifi_only") @Field("wifi_only")}。 + */ @SerializedName("wifi_only") @Field("wifi_only") - private List wifiOnly; + private List wifiOnly; + /** + * white列出;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("white_list") @Field("white_list")}。 + */ @SerializedName("white_list") @Field("white_list") - private List whiteList; + private List whiteList; + /** + * black列出;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("black_list") @Field("black_list")}。 + */ @SerializedName("black_list") @Field("black_list") - private List blackList; + private List blackList; - public List getInstall() { + /** + * 获取 {@code install}。 + * @return ?列表,可能为空 + */ + public List getInstall() { return this.install; } - public void setInstall(List install) { + /** + * 设置 {@code install}。 + * + * @param install 参数 {@code install}({@code List}) + */ + public void setInstall(List install) { this.install = install; } + /** + * 设置转换为旧格式化。 + */ public void setToOldFormat() { this.install = this.getInstallUuids(); } - public List getInstallApp() { + /** + * 获取 {@code installApp}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return Install应用列表,可能为空 + */ + public List getInstallApp() { if (this.installApp == null && this.install != null) { this.initInstallApp(); } @@ -61,10 +142,15 @@ public class ProfileApps { return this.installApp; } + /** + * 初始化Install应用。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new TypeToken。 + */ public void initInstallApp() { if (this.install != null && !this.install.isEmpty()) { if (this.install.get(0) instanceof InstallApp) { - this.installApp = this.install; + this.installApp = (List)this.install; } else { this.installApp = (List)McJsonUtils.toObject(McJsonUtils.toJsonElement(this.install), (new TypeToken() { }).getType()); @@ -74,15 +160,32 @@ public class ProfileApps { } - public void setInstallApp(List installApp) { + /** + * 设置 {@code installApp}。 + * + * @param installApp 参数 {@code installApp}({@code List}) + */ + public void setInstallApp(List installApp) { this.installApp = installApp; } + /** + * 判断 {@code installApps}。 + * @return 字段/派生属性 {@code installApps} 的值 + */ public boolean hasInstallApps() { this.getInstallApp(); return this.installApp != null && !this.installApp.isEmpty(); } + /** + * 获取Install应用。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字段/派生属性 {@code installApp} 的值 + */ public InstallApp getInstallApp(String packageName) { if (!this.hasInstallApps()) { 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) { if (this.hasInstallApps()) { Iterator it = this.installApp.iterator(); @@ -112,83 +223,177 @@ public class ProfileApps { return false; } - public List getInstallUuids() { + /** + * 获取 {@code installUuids}。 + * @return UUID列表,可能为空 + */ + public List getInstallUuids() { 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 getUninstall() { return this.toDbList(this.uninstall); } - public void setUninstall(List uninstall) { + /** + * 设置 {@code uninstall}。 + * + * @param uninstall 参数 {@code uninstall}({@code List}) + */ + public void setUninstall(List uninstall) { this.uninstall = uninstall; } - public List getAppWidget() { + /** + * 获取 {@code appWidget}。 + * @return 数据库Object列表,可能为空 + */ + public List getAppWidget() { return this.appWidget; } - public void setAppWidget(List addAppWidget) { + /** + * 设置 {@code appWidget}。 + * + * @param addAppWidget 参数 {@code addAppWidget}({@code List}) + */ + public void setAppWidget(List addAppWidget) { this.appWidget = addAppWidget; } - public List getWidget() { + /** + * 获取 {@code widget}。 + * @return 数据库Object列表,可能为空 + */ + public List getWidget() { return this.widget; } - public void setWidget(List widget) { + /** + * 设置 {@code widget}。 + * + * @param widget 参数 {@code widget}({@code List}) + */ + public void setWidget(List widget) { this.widget = widget; } - public List getGrantAll() { + /** + * 获取 {@code grantAll}。 + * @return 数据库Object列表,可能为空 + */ + public List getGrantAll() { return this.toDbList(this.grantAll); } - public void setGrantAll(List grantAll) { + /** + * 设置 {@code grantAll}。 + * + * @param grantAll 参数 {@code grantAll}({@code List}) + */ + public void setGrantAll(List grantAll) { this.grantAll = grantAll; } - public List getDisabled() { + /** + * 获取 {@code disabled}。 + * @return 数据库Object列表,可能为空 + */ + public List getDisabled() { return this.toDbList(this.disabled); } - public void setDisabled(List disabled) { + /** + * 设置 {@code disabled}。 + * + * @param disabled 参数 {@code disabled}({@code List}) + */ + public void setDisabled(List disabled) { this.disabled = disabled; } - public List getWifiOnly() { + /** + * 获取 {@code wifiOnly}。 + * @return 数据库Object列表,可能为空 + */ + public List getWifiOnly() { return this.toDbList(this.wifiOnly); } - public void setWifiOnly(List wifiOnly) { + /** + * 设置 {@code wifiOnly}。 + * + * @param wifiOnly 参数 {@code wifiOnly}({@code List}) + */ + public void setWifiOnly(List wifiOnly) { this.wifiOnly = wifiOnly; } - public List getWhiteList() { + /** + * 获取 {@code whiteList}。 + * @return 数据库Object列表,可能为空 + */ + public List getWhiteList() { return this.toDbList(this.whiteList); } - public void setWhiteList(List whiteList) { + /** + * 设置 {@code whiteList}。 + * + * @param whiteList 参数 {@code whiteList}({@code List}) + */ + public void setWhiteList(List whiteList) { this.whiteList = whiteList; } - public List getBlackList() { + /** + * 获取 {@code blackList}。 + * @return 数据库Object列表,可能为空 + */ + public List getBlackList() { return this.toDbList(this.blackList); } - public void setBlackList(List blackList) { + /** + * 设置 {@code blackList}。 + * + * @param blackList 参数 {@code blackList}({@code List}) + */ + public void setBlackList(List blackList) { this.blackList = blackList; } - public List getPackageList(List apps) { + /** + * 获取Package列出。 + * + * @param apps 参数 {@code apps}({@code List}) + * @return String列表,可能为空 + */ + public List getPackageList(List apps) { return apps != null ? (List)apps.stream().map((app) -> app.getString("package")).collect(Collectors.toList()) : null; } + /** + * 判断 {@code empty}。 + * @return 字段/派生属性 {@code empty} 的值 + */ 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()); } - private List toDbList(List list) { + /** + * 处理转换为数据库列出。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ArrayList、new DbObject。 + * + * @param list 参数 {@code list}({@code List}) + * @return 数据库Object列表,可能为空 + */ + private List toDbList(List list) { if (list != null && !list.isEmpty()) { List dbList = new ArrayList(); list.forEach((item) -> { @@ -205,78 +410,196 @@ public class ProfileApps { } } + /** + * 【领域模型】{@code InstallApp} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code packageName}(String):package名称
  • + *
  • {@code silentInstall}(Boolean):是否silentInstall
  • + *
  • {@code grantAll}(Boolean):grant全部
  • + *
  • {@code startsOnUpdate}(Boolean):starts处理更新
  • + *
  • {@code rebootsOnUpdate}(Boolean):reboots处理更新
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public static class InstallApp { + /** + * 对象唯一标识(MongoDB 主键)。 + */ private UUID uuid; + /** + * package名称。 + */ private String packageName; + /** + * 是否silentInstall;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("silent_install") @Field("silent_install")}。 + */ @SerializedName("silent_install") @Field("silent_install") private Boolean silentInstall = true; + /** + * grant全部;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("grant_all") @Field("grant_all")}。 + */ @SerializedName("grant_all") @Field("grant_all") private Boolean grantAll = false; + /** + * starts处理更新;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("starts_on_update") @Field("starts_on_update")}。 + */ @SerializedName("starts_on_update") @Field("starts_on_update") private Boolean startsOnUpdate = false; + /** + * reboots处理更新;通过 @Field 映射到 MongoDB 字段。 + * + * 注解:{@code @SerializedName("reboots_on_update") @Field("reboots_on_update")}。 + */ @SerializedName("reboots_on_update") @Field("reboots_on_update") private Boolean rebootsOnUpdate = false; + /** + * 构造 {@code InstallApp} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public InstallApp() { } + /** + * 构造 {@code InstallApp} 实例。 + * + * @param appFile 参数 {@code appFile}({@code AppFile}) + */ public InstallApp(AppFile appFile) { this.uuid = appFile.getFileUuid(); this.packageName = appFile.getPackageName(); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code packageName}。 + * @return 字符串结果 + */ public String getPackageName() { return this.packageName; } + /** + * 设置 {@code packageName}。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public void setPackageName(String packageName) { this.packageName = packageName; } + /** + * 获取 {@code silentInstall}。 + * @return 字段/派生属性 {@code silentInstall} 的值 + */ public Boolean getSilentInstall() { return this.silentInstall; } + /** + * 设置 {@code silentInstall}。 + * + * @param silentInstall 参数 {@code silentInstall}({@code Boolean}) + */ public void setSilentInstall(Boolean silentInstall) { this.silentInstall = silentInstall; } + /** + * 获取 {@code grantAll}。 + * @return 字段/派生属性 {@code grantAll} 的值 + */ public Boolean getGrantAll() { return this.grantAll; } + /** + * 设置 {@code grantAll}。 + * + * @param grantAll 参数 {@code grantAll}({@code Boolean}) + */ public void setGrantAll(Boolean grantAll) { this.grantAll = grantAll; } + /** + * 获取 {@code startsOnUpdate}。 + * @return 字段/派生属性 {@code startsOnUpdate} 的值 + */ public Boolean getStartsOnUpdate() { return this.startsOnUpdate; } + /** + * 设置 {@code startsOnUpdate}。 + * + * @param startsOnUpdate 参数 {@code startsOnUpdate}({@code Boolean}) + */ public void setStartsOnUpdate(Boolean startsOnUpdate) { this.startsOnUpdate = startsOnUpdate; } + /** + * 获取 {@code rebootsOnUpdate}。 + * @return 字段/派生属性 {@code rebootsOnUpdate} 的值 + */ public Boolean getRebootsOnUpdate() { return this.rebootsOnUpdate; } + /** + * 设置 {@code rebootsOnUpdate}。 + * + * @param rebootsOnUpdate 参数 {@code rebootsOnUpdate}({@code Boolean}) + */ public void setRebootsOnUpdate(Boolean rebootsOnUpdate) { this.rebootsOnUpdate = rebootsOnUpdate; } + /** + * 比较当前对象与另一个对象是否相等。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param obj 参数 {@code obj}({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean equals(Object obj) { if (!(obj instanceof InstallApp)) { return false; diff --git a/src/main/java/com/midm/model/device/ProfileScope.java b/src/main/java/com/midm/model/device/ProfileScope.java index d13eefa..24ae967 100644 --- a/src/main/java/com/midm/model/device/ProfileScope.java +++ b/src/main/java/com/midm/model/device/ProfileScope.java @@ -4,19 +4,62 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; +/** + * 【领域模型】{@code ProfileScope} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code group}(Set):分组
  • + *
  • {@code device}(Set):设备
  • + *
  • {@code userGroup}(Set):用户分组
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ProfileScope { - Set group; - Set device; - Set userGroup; + /** + * 分组。 + */ + Set group; + /** + * 设备。 + */ + Set device; + /** + * 用户分组。 + */ + Set userGroup; - public Set getGroup() { + /** + * 获取 {@code group}。 + * @return UUID列表,可能为空 + */ + public Set getGroup() { return this.group; } - public void setGroup(Set group) { + /** + * 设置 {@code group}。 + * + * @param group 分组对象({@code Set}) + */ + public void setGroup(Set group) { this.group = group; } + /** + * 添加分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。 + * + * @param groupUuid 分组 UUID({@code UUID}) + */ public void addGroup(UUID groupUuid) { if (this.group == null) { this.group = new HashSet(); @@ -25,6 +68,13 @@ public class ProfileScope { } + /** + * 移除分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。 + * + * @param groupUuid 分组 UUID({@code UUID}) + */ public void removeGroup(UUID groupUuid) { if (this.group != null) { this.group.remove(groupUuid); @@ -32,14 +82,30 @@ public class ProfileScope { } - public Set getDevice() { + /** + * 获取 {@code device}。 + * @return String列表,可能为空 + */ + public Set getDevice() { return this.device; } - public void setDevice(Set device) { + /** + * 设置 {@code device}。 + * + * @param device 设备({@code Set}) + */ + public void setDevice(Set device) { this.device = device; } + /** + * 添加设备。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。 + * + * @param serialNo 设备序列号({@code String}) + */ public void addDevice(String serialNo) { if (this.device == null) { this.device = new HashSet(); @@ -48,6 +114,13 @@ public class ProfileScope { } + /** + * 移除设备。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。 + * + * @param serialNo 设备序列号({@code String}) + */ public void removeDevice(String serialNo) { if (this.device != null) { this.device.remove(serialNo); @@ -55,14 +128,27 @@ public class ProfileScope { } - public Set getUserGroup() { + /** + * 获取 {@code userGroup}。 + * @return String列表,可能为空 + */ + public Set getUserGroup() { return this.userGroup; } - public void setUserGroup(Set userGroup) { + /** + * 设置 {@code userGroup}。 + * + * @param userGroup 参数 {@code userGroup}({@code Set}) + */ + public void setUserGroup(Set userGroup) { this.userGroup = userGroup; } + /** + * 判断 {@code scoped}。 + * @return 字段/派生属性 {@code scoped} 的值 + */ public boolean hasScoped() { return this.group != null && !this.group.isEmpty() || this.device != null && !this.device.isEmpty() || this.userGroup != null && !this.userGroup.isEmpty(); } diff --git a/src/main/java/com/midm/model/device/ReconnectMonitor.java b/src/main/java/com/midm/model/device/ReconnectMonitor.java index e248fd2..a9bb85c 100644 --- a/src/main/java/com/midm/model/device/ReconnectMonitor.java +++ b/src/main/java/com/midm/model/device/ReconnectMonitor.java @@ -8,25 +8,92 @@ import java.util.TimerTask; import java.util.UUID; import org.joda.time.LocalDateTime; +/** + * 【领域模型】{@code ReconnectMonitor} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code BLOCKING_HOURS}(int):字段 BLOCKING_HOURS
  • + *
  • {@code RECONNECT_FOR}(int):字段 RECONNECT_FOR
  • + *
  • {@code device}(Device):设备
  • + *
  • {@code startedAt}(Date):时间字段
  • + *
  • {@code prevMins}(long):字段 prevMins
  • + *
  • {@code count}(int):统计
  • + *
+ * + * 协作对象:{@code Device、Timer、OnAbusedListener}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ReconnectMonitor { + /** + * 字段 BLOCKING_HOURS。 + */ private static final int BLOCKING_HOURS = 12; + /** + * 字段 RECONNECT_FOR。 + */ private static final int RECONNECT_FOR = 10; + /** + * 设备。 + */ private Device device; + /** + * 时间字段。 + */ private Date startedAt; + /** + * 字段 prevMins。 + */ private long prevMins; + /** + * 统计。 + */ private int count; + /** + * 总数。 + */ private int total; + /** + * 时间字段。 + */ private Date blockedAt; + /** + * 时间字段。 + */ private Date unblockAt; + /** + * unblock定时器。 + */ private Timer unblockTimer; + /** + * 监听器。 + */ private OnAbusedListener listener; + /** + * 构造 {@code ReconnectMonitor} 实例。 + * + * @param device 设备({@code Device}) + * @param listener 参数 {@code listener}({@code OnAbusedListener}) + */ public ReconnectMonitor(Device device, OnAbusedListener listener) { this.device = device; this.listener = listener; this.init(); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ private void init() { this.startedAt = new Date(); this.blockedAt = null; @@ -35,34 +102,67 @@ public class ReconnectMonitor { this.total = this.count = 1; } + /** + * 获取 {@code device}。 + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device getDevice() { return this.device; } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.device.getUuid(); } + /** + * 获取 {@code startedAt}。 + * @return 字段/派生属性 {@code startedAt} 的值 + */ public Date getStartedAt() { return this.startedAt; } + /** + * 获取 {@code blockedAt}。 + * @return 字段/派生属性 {@code blockedAt} 的值 + */ public Date getBlockedAt() { return this.blockedAt; } + /** + * 获取 {@code unblockAt}。 + * @return 字段/派生属性 {@code unblockAt} 的值 + */ public Date getUnblockAt() { return this.unblockAt; } + /** + * 获取 {@code count}。 + * @return 数量/长度 + */ public int getCount() { return this.count; } + /** + * 获取 {@code total}。 + * @return 数量/长度 + */ public int getTotal() { return this.total; } + /** + * 处理connected。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new Date。 + */ public void connected() { long curMins = this.getCurMins(); long gap = curMins - this.prevMins; @@ -82,16 +182,32 @@ public class ReconnectMonitor { } + /** + * 判断 {@code blocked}。 + * @return 字段/派生属性 {@code blocked} 的值 + */ public boolean isBlocked() { return this.blockedAt != null; } + /** + * 处理block。 + * + * 实现要点:主要调用:new Date、new LocalDateTime。 + */ public void block() { this.blockedAt = new Date(); this.unblockAt = (new LocalDateTime(this.blockedAt)).plusHours(12).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).toDate(); this.startUnblockTimer(); } + /** + * 处理block。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。 + * + * @param device 设备({@code Device}) + */ public void block(Device device) { if (device.isBlocked()) { 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() { this.stopUnblockTimer(); - String var10003 = this.device.getUuid().toString(); - this.unblockTimer = new Timer(var10003 + (new Date()).getTime()); + this.unblockTimer = new Timer(this.device.getUuid().toString() + (new Date()).getTime()); this.unblockTimer.schedule(new TimerTask() { public void run() { ReconnectMonitor.this.unblock((User)null); @@ -119,6 +239,11 @@ public class ReconnectMonitor { }, this.unblockAt); } + /** + * 停止Unblock定时器。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:cancel。 + */ private void stopUnblockTimer() { if (this.unblockTimer != null) { try { @@ -131,6 +256,13 @@ public class ReconnectMonitor { } + /** + * 处理unblock。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + */ public void unblock(User user) { this.stopUnblockTimer(); this.startedAt = null; @@ -144,6 +276,11 @@ public class ReconnectMonitor { } + /** + * 处理处理Abused。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ private void onAbused() { this.block(); if (this.listener != null) { @@ -152,13 +289,40 @@ public class ReconnectMonitor { } + /** + * 获取 {@code curMins}。 + * + * 实现要点:主要调用:new Date。 + * @return 数量/长度 + */ private long getCurMins() { return (new Date()).getTime() / 60000L; } + /** + * 【接口契约】{@code OnAbusedListener} + * + * 类职责: + *
    + *
  • 定义调用方与实现方之间的契约,屏蔽具体实现。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public interface OnAbusedListener { + /** + * 处理处理Abused。 + * + * @param monitor 参数 {@code monitor}({@code ReconnectMonitor}) + */ void onAbused(ReconnectMonitor monitor); + /** + * 处理处理Unblocked。 + * + * @param monitor 参数 {@code monitor}({@code ReconnectMonitor}) + * @param user 当前用户({@code User}) + */ void onUnblocked(ReconnectMonitor monitor, User user); } } diff --git a/src/main/java/com/midm/model/device/package-info.java b/src/main/java/com/midm/model/device/package-info.java new file mode 100644 index 0000000..8d7b7cd --- /dev/null +++ b/src/main/java/com/midm/model/device/package-info.java @@ -0,0 +1,27 @@ +/** + * 设备领域模型:设备档案、分组、策略、应用、License、遥测状态。 + * + *

本包主要类型: + *

    + *
  • {@link AppInfo}
  • + *
  • {@link DEVICE_PROPERTY}
  • + *
  • {@link DataUsage}
  • + *
  • {@link Device}
  • + *
  • {@link DeviceApps}
  • + *
  • {@link DeviceGroup}
  • + *
  • {@link DeviceKey}
  • + *
  • {@link DeviceLicense}
  • + *
  • {@link DeviceNote}
  • + *
  • {@link DeviceProfile}
  • + *
  • {@link DeviceProfileGroup}
  • + *
  • {@link DeviceProfileState}
  • + *
  • {@link DeviceReport}
  • + *
  • {@link ProfileApps}
  • + *
  • {@link ProfileScope}
  • + *
  • {@link ReconnectMonitor}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.device; diff --git a/src/main/java/com/midm/model/file/AppFile.java b/src/main/java/com/midm/model/file/AppFile.java index 45c9e0a..40738c2 100644 --- a/src/main/java/com/midm/model/file/AppFile.java +++ b/src/main/java/com/midm/model/file/AppFile.java @@ -12,24 +12,76 @@ import net.dongliu.apk.parser.bean.ApkMeta; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code AppFile} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code appInfo}(DbObject):应用信息
  • + *
  • {@code updateOptions}(DbObject):更新选项列表
  • + *
  • {@code generateIcon}(boolean):生成Icon
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class AppFile extends BaseFile { + /** + * 应用信息。 + */ private DbObject appInfo; + /** + * 更新选项列表。 + */ private DbObject updateOptions; + /** + * 生成Icon;不持久化到 MongoDB,仅运行时使用;Gson 序列化控制。 + * + * 注解:{@code @Transient @Expose(serialize = false)}。 + */ @Transient @Expose( serialize = false ) private boolean generateIcon; + /** + * 构造 {@code AppFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public AppFile() { 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) { 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) { super(user, fileUuid, file); this.generateIcon = true; @@ -37,14 +89,28 @@ public class AppFile extends BaseFile { this.setAppInfo(file); } + /** + * 判断 {@code apk}。 + * @return 字段/派生属性 {@code apk} 的值 + */ public boolean isApk() { return !Strings.isNullOrEmpty(this.getPackageName()); } + /** + * 判断 {@code systemPermission}。 + * @return 字段/派生属性 {@code systemPermission} 的值 + */ public boolean hasSystemPermission() { return "android.uid.system".equals(this.getSharedUserId()); } + /** + * 获取 {@code appInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getAppInfo() { if (this.appInfo == null) { this.appInfo = new DbObject(); @@ -53,14 +119,31 @@ public class AppFile extends BaseFile { return this.appInfo; } + /** + * 设置 {@code appInfo}。 + * + * @param appInfo 参数 {@code appInfo}({@code DbObject}) + */ public void setAppInfo(DbObject appInfo) { this.appInfo = appInfo; } + /** + * 设置应用信息。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setAppInfo(String key, Object value) { this.getAppInfo().append(key, value); } + /** + * 获取 {@code updateOptions}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getUpdateOptions() { if (this.updateOptions == null) { this.updateOptions = new DbObject(); @@ -69,30 +152,65 @@ public class AppFile extends BaseFile { return this.updateOptions; } + /** + * 设置 {@code updateOptions}。 + * + * @param updateOptions 参数 {@code updateOptions}({@code DbObject}) + */ public void setUpdateOptions(DbObject updateOptions) { this.updateOptions = updateOptions; } + /** + * 设置更新选项列表。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setUpdateOptions(String key, Object value) { this.getUpdateOptions().append(key, value); } + /** + * 判断 {@code mitacApp}。 + * @return 字段/派生属性 {@code mitacApp} 的值 + */ public boolean isMitacApp() { return this.getPackageName().toLowerCase().contains("mitac"); } + /** + * 获取 {@code packageName}。 + * @return 字符串结果 + */ public String getPackageName() { return this.getAppInfo().getString("packageName"); } + /** + * 设置 {@code packageName}。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public void setPackageName(String packageName) { this.setAppInfo("packageName", packageName); } + /** + * 获取 {@code sharedUserId}。 + * @return 字符串结果 + */ public String getSharedUserId() { return this.getAppInfo().getString("sharedUid"); } + /** + * 设置 {@code sharedUserId}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param sharedUid 参数 {@code sharedUid}({@code String}) + */ public void setSharedUserId(String sharedUid) { if (!Strings.isNullOrEmpty(sharedUid)) { this.setAppInfo("sharedUid", sharedUid); @@ -100,42 +218,89 @@ public class AppFile extends BaseFile { } + /** + * 获取 {@code label}。 + * @return 字符串结果 + */ public String getLabel() { return this.getAppInfo().getString("label"); } + /** + * 设置 {@code label}。 + * + * @param label 参数 {@code label}({@code String}) + */ public void setLabel(String label) { this.setAppInfo("label", label); } + /** + * 获取 {@code iconName}。 + * @return 字符串结果 + */ public String getIconName() { return this.getAppInfo().getString("iconName"); } + /** + * 设置 {@code iconName}。 + * + * @param iconName 参数 {@code iconName}({@code String}) + */ public void setIconName(String iconName) { this.setAppInfo("iconName", iconName); } + /** + * 获取 {@code versionCode}。 + * @return 数量/长度 + */ public long getVersionCode() { return this.getAppInfo().getLong("versionCode"); } + /** + * 设置 {@code versionCode}。 + * + * @param versionCode 参数 {@code versionCode}({@code long}) + */ public void setVersionCode(long versionCode) { this.setAppInfo("versionCode", versionCode); } + /** + * 获取 {@code versionName}。 + * @return 字符串结果 + */ public String getVersionName() { return this.getAppInfo().getString("versionName"); } + /** + * 设置 {@code versionName}。 + * + * @param versionName 参数 {@code versionName}({@code String}) + */ public void setVersionName(String versionName) { this.setAppInfo("versionName", versionName); } + /** + * 获取 {@code minSdkVersion}。 + * @return 数量/长度 + */ public int getMinSdkVersion() { return this.getAppInfo().getInteger("minSdkVersion", -1); } + /** + * 设置 {@code minSdkVersion}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param minSdkVersion 参数 {@code minSdkVersion}({@code String}) + */ public void setMinSdkVersion(String minSdkVersion) { if (!Strings.isNullOrEmpty(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) { this.setAppInfo("minSdkVersion", minSdkVersion); } + /** + * 获取 {@code maxSdkVersion}。 + * @return 数量/长度 + */ public int getMaxSdkVersion() { return this.getAppInfo().getInteger("maxSdkVersion", -1); } + /** + * 设置 {@code maxSdkVersion}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param maxSdkVersion 参数 {@code maxSdkVersion}({@code String}) + */ public void setMaxSdkVersion(String maxSdkVersion) { if (!Strings.isNullOrEmpty(maxSdkVersion)) { this.setAppInfo("maxSdkVersion", Integer.parseInt(maxSdkVersion)); @@ -158,10 +339,21 @@ public class AppFile extends BaseFile { } + /** + * 获取 {@code targetSdkVersion}。 + * @return 数量/长度 + */ public int getTargetSdkVersion() { return this.getAppInfo().getInteger("targetSdkVersion", -1); } + /** + * 设置 {@code targetSdkVersion}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param targetSdkVersion 参数 {@code targetSdkVersion}({@code String}) + */ public void setTargetSdkVersion(String targetSdkVersion) { if (Strings.isNullOrEmpty(targetSdkVersion)) { this.getAppInfo().remove("targetSdkVersion"); @@ -171,18 +363,38 @@ public class AppFile extends BaseFile { } - public List getUserPermission() { + /** + * 获取 {@code userPermission}。 + * @return String列表,可能为空 + */ + public List getUserPermission() { return this.getAppInfo().getList("userPermission", String.class); } - public void setUserPermission(List userPermission) { + /** + * 设置 {@code userPermission}。 + * + * @param userPermission 参数 {@code userPermission}({@code List}) + */ + public void setUserPermission(List userPermission) { this.setAppInfo("userPermission", userPermission); } + /** + * 获取 {@code certMd5}。 + * @return 字符串结果 + */ public String getCertMd5() { return this.getAppInfo().getString("certMd5"); } + /** + * 设置 {@code certMd5}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param certMd5 参数 {@code certMd5}({@code String}) + */ public void setCertMd5(String certMd5) { if (!Strings.isNullOrEmpty(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) { try { McApkFile apkFile = new McApkFile(file); @@ -220,6 +439,9 @@ public class AppFile extends BaseFile { } + /** + * 处理minify。 + */ public void minify() { super.minify(); this.setUserPermission((List)null); diff --git a/src/main/java/com/midm/model/file/BaseFile.java b/src/main/java/com/midm/model/file/BaseFile.java index 0953ff7..6e6f614 100644 --- a/src/main/java/com/midm/model/file/BaseFile.java +++ b/src/main/java/com/midm/model/file/BaseFile.java @@ -14,23 +14,90 @@ import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code BaseFile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileUuid}(UUID):文件UUID
  • + *
  • {@code userUuid}(UUID):用户UUID
  • + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code fileInfo}(DbObject):文件信息
  • + *
  • {@code extra}(DbObject):字段 extra
  • + *
  • {@code name}(String):名称
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class BaseFile { + /** + * 文件UUID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id protected UUID fileUuid; + /** + * 用户UUID。 + */ protected UUID userUuid; + /** + * 用户所属站点 UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed protected UUID siteUuid; + /** + * 文件信息。 + */ protected DbObject fileInfo; + /** + * 字段 extra。 + */ protected DbObject extra; + /** + * 名称。 + */ protected String name; + /** + * 是否启用。 + */ protected boolean enabled = true; + /** + * 最后Updated。 + */ protected Date lastUpdated; + /** + * 时间字段。 + */ protected Date registeredAt; + /** + * 构造 {@code BaseFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { this.setUserUuid(user); this.setFileUuid(fileUuid); @@ -38,30 +105,64 @@ public class BaseFile { this.initRegisteredAt(); } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code fileUuid}。 + * @return UUID + */ public UUID getFileUuid() { return this.fileUuid; } + /** + * 设置 {@code fileUuid}。 + * + * @param uid 参数 {@code uid}({@code UUID}) + */ public void setFileUuid(UUID uid) { this.fileUuid = uid; } + /** + * 获取 {@code userUuid}。 + * @return UUID + */ public UUID getUserUuid() { return this.userUuid; } + /** + * 设置 {@code userUuid}。 + * + * @param uid 参数 {@code uid}({@code UUID}) + */ public void setUserUuid(UUID uid) { this.userUuid = uid; } + /** + * 设置 {@code userUuid}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + */ public void setUserUuid(User user) { if (user != null) { this.userUuid = user.getUuid(); @@ -69,6 +170,12 @@ public class BaseFile { } + /** + * 获取 {@code fileInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getFileInfo() { if (this.fileInfo == null) { this.fileInfo = new DbObject(); @@ -77,6 +184,14 @@ public class BaseFile { return this.fileInfo; } + /** + * 获取文件信息AsString。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ public String getFileInfoAsString(String key) { if (this.fileInfo == null) { this.fileInfo = new DbObject(); @@ -85,14 +200,29 @@ public class BaseFile { return this.fileInfo.getString(key); } + /** + * 移除文件信息。 + */ public void removeFileInfo() { this.fileInfo = null; } + /** + * 设置 {@code fileInfo}。 + * + * @param fileInfo 参数 {@code fileInfo}({@code DbObject}) + */ public void setFileInfo(DbObject fileInfo) { this.fileInfo = fileInfo; } + /** + * 设置 {@code fileInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param file 文件({@code McFile}) + */ public void setFileInfo(McFile file) { if (file.exists()) { this.setLength(file.length()); @@ -102,15 +232,31 @@ public class BaseFile { } + /** + * 获取 {@code extra}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getExtra() { return this.extra; } + /** + * 设置 {@code extra}。 + * + * @param extra 参数 {@code extra}({@code DbObject}) + */ public void setExtra(DbObject extra) { this.extra = extra; } - public void setExtra(Map parameters) { + /** + * 设置 {@code extra}。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new DbObject。 + * + * @param parameters 参数 {@code parameters}({@code Map}) + */ + public void setExtra(Map parameters) { if (parameters != null) { if (this.extra == null) { this.extra = new DbObject(); @@ -119,7 +265,7 @@ public class BaseFile { parameters.forEach((k, v) -> { String key = (String) k; 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)); } @@ -128,30 +274,63 @@ public class BaseFile { } + /** + * 获取 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public boolean getEnabled() { return this.enabled; } + /** + * 设置 {@code enabled}。 + * + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void setEnabled(boolean enabled) { this.enabled = enabled; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code fileName}。 + * @return 字符串结果 + */ public String getFileName() { return this.getFileInfo().getString("fileName"); } + /** + * 设置 {@code fileName}。 + * + * @param fileName 文件名({@code String}) + */ public void setFileName(String fileName) { this.setFileInfo("fileName", fileName); } + /** + * 获取 {@code contentType}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Tika。 + * @return 字符串结果 + */ public String getContentType() { String contentType = this.getFileInfo().getString("contentType"); if (Strings.isNullOrEmpty(contentType)) { @@ -162,30 +341,64 @@ public class BaseFile { return contentType; } + /** + * 设置 {@code type}。 + * + * @param contentType Content-Type({@code String}) + */ public void setType(String contentType) { this.setFileInfo("contentType", contentType); } + /** + * 获取 {@code length}。 + * @return 数量/长度 + */ public long getLength() { return this.getFileInfo().getLong("length"); } + /** + * 设置 {@code length}。 + * + * @param length 参数 {@code length}({@code long}) + */ public void setLength(long length) { this.setFileInfo("length", length); } + /** + * 获取 {@code checksum}。 + * @return 数量/长度 + */ public long getChecksum() { return this.getFileInfo().getLong("checksum"); } + /** + * 设置 {@code checksum}。 + * + * @param checksum 参数 {@code checksum}({@code long}) + */ public void setChecksum(long checksum) { this.setFileInfo("checksum", checksum); } + /** + * 获取 {@code lastModified}。 + * @return 数量/长度 + */ public long getLastModified() { return this.getFileInfo().getLong("lastModified"); } + /** + * 设置 {@code lastModified}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。 + * + * @param lastModified 参数 {@code lastModified}({@code long}) + */ public void setLastModified(long lastModified) { if (lastModified <= 0L) { lastModified = (new Date()).getTime(); @@ -194,25 +407,51 @@ public class BaseFile { this.setFileInfo("lastModified", lastModified); } + /** + * 设置文件信息。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setFileInfo(String key, Object value) { this.getFileInfo().append(key, value); } + /** + * 设置 {@code fileUrl}。 + * + * @param url 参数 {@code url}({@code String}) + */ public void setFileUrl(String url) { this.setFileInfo("fileUrl", url); } + /** + * 获取 {@code urlExpiry}。 + * @return 数量/长度 + */ public long getUrlExpiry() { Date expiry = this.getFileInfo().getDate("urlExpiry"); return expiry == null ? -1L : expiry.getTime(); } + /** + * 设置 {@code cloudUrl}。 + * + * @param url 参数 {@code url}({@code String}) + */ public void setCloudUrl(String url) { this.setFileInfo("fileUrl", url); Date expiry = LocalDateTime.now().plusDays(6).toDate(); this.setFileInfo("urlExpiry", expiry); } + /** + * 判断 {@code fileUrl}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。 + * @return 字段/派生属性 {@code fileUrl} 的值 + */ public boolean hasFileUrl() { boolean hasUrl = this.getFileInfo().containsKey("fileUrl"); if (hasUrl && this.getFileInfo().containsKey("urlExpiry")) { @@ -226,10 +465,20 @@ public class BaseFile { return hasUrl; } + /** + * 获取 {@code fileUrl}。 + * @return 字符串结果 + */ public String getFileUrl() { return this.getFileInfoAsString("fileUrl"); } + /** + * 判断 {@code iconUrl}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Date。 + * @return 字段/派生属性 {@code iconUrl} 的值 + */ public boolean hasIconUrl() { boolean hasUrl = this.getFileInfo().containsKey("iconUrl"); if (hasUrl && this.getFileInfo().containsKey("iconExpiry")) { @@ -243,37 +492,72 @@ public class BaseFile { return hasUrl; } + /** + * 设置 {@code iconUrl}。 + * + * @param url 参数 {@code url}({@code String}) + */ public void setIconUrl(String url) { this.setFileInfo("iconUrl", url); Date expiry = LocalDateTime.now().plusDays(6).toDate(); this.setFileInfo("iconExpiry", expiry); } + /** + * 获取 {@code iconUrl}。 + * @return 字符串结果 + */ public String getIconUrl() { return this.getFileInfoAsString("iconUrl"); } + /** + * 获取 {@code lastUpdated}。 + * @return 字段/派生属性 {@code lastUpdated} 的值 + */ public Date getLastUpdated() { return this.lastUpdated; } + /** + * 设置 {@code lastUpdated}。 + * + * @param lastUpdated 参数 {@code lastUpdated}({@code Date}) + */ public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } + /** + * 获取 {@code registeredAt}。 + * @return 字段/派生属性 {@code registeredAt} 的值 + */ public Date getRegisteredAt() { return this.registeredAt; } + /** + * 设置 {@code registeredAt}。 + * + * @param registeredAt 参数 {@code registeredAt}({@code Date}) + */ public void setRegisteredAt(Date registeredAt) { this.registeredAt = registeredAt; } + /** + * 初始化RegisteredAt。 + * + * 实现要点:主要调用:new Date。 + */ public void initRegisteredAt() { this.setRegisteredAt(new Date()); this.setLastUpdated(this.getRegisteredAt()); } + /** + * 处理minify。 + */ public void minify() { this.userUuid = null; this.registeredAt = null; diff --git a/src/main/java/com/midm/model/file/DeployOption.java b/src/main/java/com/midm/model/file/DeployOption.java index bc7455a..81518e0 100644 --- a/src/main/java/com/midm/model/file/DeployOption.java +++ b/src/main/java/com/midm/model/file/DeployOption.java @@ -1,80 +1,212 @@ package com.midm.model.file; +/** + * 【领域模型】{@code DeployOption} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code PROPERTY_DEFAULT}(String):字段 PROPERTY_DEFAULT
  • + *
  • {@code PROPERTY_FORCE_TO_DOWNLOAD}(String):字段 PROPERTY_FORCE_TO_DOWNLOAD
  • + *
  • {@code PROPERTY_FORCE_TO_INSTALL}(String):字段 PROPERTY_FORCE_TO_INSTALL
  • + *
  • {@code PROPERTY_SAVE_AS}(String):字段 PROPERTY_SAVE_AS
  • + *
  • {@code PROPERTY_KEEP_BACKUP}(String):字段 PROPERTY_KEEP_BACKUP
  • + *
  • {@code isDefault}(boolean):判断是否Default
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class DeployOption { + /** + * 字段 PROPERTY_DEFAULT。 + */ public static final String PROPERTY_DEFAULT = "default"; + /** + * 字段 PROPERTY_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"; + /** + * 字段 PROPERTY_SAVE_AS。 + */ public static final String PROPERTY_SAVE_AS = "save_as"; + /** + * 字段 PROPERTY_KEEP_BACKUP。 + */ public static final String PROPERTY_KEEP_BACKUP = "keep_backgup"; + /** + * 判断是否Default。 + */ private boolean isDefault; + /** + * uninstall第一。 + */ private boolean uninstallFirst; + /** + * keep数据。 + */ private boolean keepData; + /** + * force转换为下载。 + */ private boolean forceToDownload; + /** + * forece转换为Install。 + */ private boolean foreceToInstall; + /** + * 保存转换为。 + */ private String saveTo; + /** + * 是否keepBackup。 + */ private boolean keepBackup; + /** + * 判断是否用户Mode。 + */ private boolean isUserMode; + /** + * 获取 {@code isDefault}。 + * @return 字段/派生属性 {@code isDefault} 的值 + */ public boolean getIsDefault() { return this.isDefault; } + /** + * 设置 {@code isDefault}。 + * + * @param isDefault 参数 {@code isDefault}({@code boolean}) + */ public void setIsDefault(boolean isDefault) { this.isDefault = isDefault; } + /** + * 获取 {@code uninstallFirst}。 + * @return 字段/派生属性 {@code uninstallFirst} 的值 + */ public boolean getUninstallFirst() { return this.uninstallFirst; } + /** + * 设置 {@code uninstallFirst}。 + * + * @param uninstallFirst 参数 {@code uninstallFirst}({@code boolean}) + */ public void setUninstallFirst(boolean uninstallFirst) { this.uninstallFirst = uninstallFirst; } + /** + * 获取 {@code keepData}。 + * @return 字段/派生属性 {@code keepData} 的值 + */ public boolean getKeepData() { return this.keepData; } + /** + * 设置 {@code keepData}。 + * + * @param keepData 参数 {@code keepData}({@code boolean}) + */ public void setKeepData(boolean keepData) { this.keepData = keepData; } + /** + * 获取 {@code forceToDownload}。 + * @return 字段/派生属性 {@code forceToDownload} 的值 + */ public boolean getForceToDownload() { return this.forceToDownload; } + /** + * 设置 {@code forceToDownload}。 + * + * @param forceToDownload 参数 {@code forceToDownload}({@code boolean}) + */ public void setForceToDownload(boolean forceToDownload) { this.forceToDownload = forceToDownload; } + /** + * 获取 {@code foreceToInstall}。 + * @return 字段/派生属性 {@code foreceToInstall} 的值 + */ public boolean getForeceToInstall() { return this.foreceToInstall; } + /** + * 设置 {@code foreceToInstall}。 + * + * @param foreceToInstall 参数 {@code foreceToInstall}({@code boolean}) + */ public void setForeceToInstall(boolean foreceToInstall) { this.foreceToInstall = foreceToInstall; } + /** + * 获取 {@code saveTo}。 + * @return 字符串结果 + */ public String getSaveTo() { return this.saveTo; } + /** + * 设置 {@code saveTo}。 + * + * @param saveTo 参数 {@code saveTo}({@code String}) + */ public void setSaveTo(String saveTo) { this.saveTo = saveTo; } + /** + * 获取 {@code keepBackup}。 + * @return 字段/派生属性 {@code keepBackup} 的值 + */ public boolean getKeepBackup() { return this.keepBackup; } + /** + * 设置 {@code keepBackup}。 + * + * @param keepBackup 参数 {@code keepBackup}({@code boolean}) + */ public void setKeepBackup(boolean keepBackup) { this.keepBackup = keepBackup; } + /** + * 获取 {@code isUserMode}。 + * @return 字段/派生属性 {@code isUserMode} 的值 + */ public boolean getIsUserMode() { return this.isUserMode; } + /** + * 设置 {@code isUserMode}。 + * + * @param isUserMode 参数 {@code isUserMode}({@code boolean}) + */ public void setIsUserMode(boolean isUserMode) { this.isUserMode = isUserMode; } diff --git a/src/main/java/com/midm/model/file/FILE_TYPE.java b/src/main/java/com/midm/model/file/FILE_TYPE.java index 3e6efb0..3f2e8ff 100644 --- a/src/main/java/com/midm/model/file/FILE_TYPE.java +++ b/src/main/java/com/midm/model/file/FILE_TYPE.java @@ -1,5 +1,20 @@ package com.midm.model.file; +/** + * 【枚举常量】{@code FILE_TYPE} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum FILE_TYPE { OTA, REGION, diff --git a/src/main/java/com/midm/model/file/OtaFile.java b/src/main/java/com/midm/model/file/OtaFile.java index 645e7ae..2e69a73 100644 --- a/src/main/java/com/midm/model/file/OtaFile.java +++ b/src/main/java/com/midm/model/file/OtaFile.java @@ -45,6 +45,9 @@ import org.springframework.data.mongodb.core.mapping.Document; public class OtaFile extends BaseFile implements Comparable { /** Android Recovery 固件升级脚本入口 */ 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"; /** Android 操作系统属性字典路径(包含型号、Build版本、指纹等关键参数) */ @@ -55,19 +58,39 @@ public class OtaFile extends BaseFile implements Comparable { /** OTA 元数据配置文件(版本区间、差分基线版本等) */ 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 DbObject otaInfo; + /** + * 构造 {@code OtaFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { super(user, fileUuid, file); this.setOtaInfo(file); } + /** + * 判断 {@code otaImage}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字段/派生属性 {@code otaImage} 的值 + */ public boolean isOtaImage() { if (Strings.isNullOrEmpty(this.getProductId()) && Strings.isNullOrEmpty(this.getDeviceId())) { return false; @@ -76,6 +99,12 @@ public class OtaFile extends BaseFile implements Comparable { } } + /** + * 获取 {@code otaInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getOtaInfo() { if (this.otaInfo == null) { this.otaInfo = new DbObject(); @@ -84,14 +113,32 @@ public class OtaFile extends BaseFile implements Comparable { return this.otaInfo; } + /** + * 设置 {@code otaInfo}。 + * + * @param otaInfo 参数 {@code otaInfo}({@code DbObject}) + */ public void setOtaInfo(DbObject otaInfo) { this.otaInfo = otaInfo; } + /** + * 设置OTA 固件信息。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setOtaInfo(String key, Object value) { this.getOtaInfo().append(key, value); } + /** + * 设置 {@code otaInfo}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ZipFile。 + * + * @param file 文件({@code McFile}) + */ public void setOtaInfo(McFile file) { try { this.retrieveBuildInfo(new ZipFile(file)); @@ -100,30 +147,61 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 获取 {@code type}。 + * @return 字符串结果 + */ public String getType() { return this.getOtaInfo().getString("type", "system"); } + /** + * 判断 {@code systemImage}。 + * @return 字段/派生属性 {@code systemImage} 的值 + */ public boolean isSystemImage() { return this.getType().equals("system"); } + /** + * 判断 {@code regionImage}。 + * @return 字段/派生属性 {@code regionImage} 的值 + */ public boolean isRegionImage() { return this.getType().equals("region"); } + /** + * 判断 {@code modemImage}。 + * @return 字段/派生属性 {@code modemImage} 的值 + */ public boolean isModemImage() { return this.getType().equals("modem"); } + /** + * 判断 {@code abUpdate}。 + * @return 字段/派生属性 {@code abUpdate} 的值 + */ public boolean isAbUpdate() { return this.getOtaInfo().getBoolean("abUpdate", false); } + /** + * 判断 {@code partial}。 + * @return 字段/派生属性 {@code partial} 的值 + */ public boolean isPartial() { return this.getOtaInfo().containsKey("preBuild"); } + /** + * 设置 {@code type}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param type 类型({@code String}) + */ public void setType(String type) { if (type.toLowerCase().equals("base")) { type = "system"; @@ -132,67 +210,142 @@ public class OtaFile extends BaseFile implements Comparable { this.getOtaInfo().put("type", type); } + /** + * 设置 {@code abUpdate}。 + * + * @param abUpdate 参数 {@code abUpdate}({@code boolean}) + */ public void setAbUpdate(boolean abUpdate) { this.getOtaInfo().put("abUpdate", abUpdate); } + /** + * 获取 {@code buildDate}。 + * @return 数量/长度 + */ public long getBuildDate() { return this.getOtaInfo().getLong("buildDate", -1L); } + /** + * 设置 {@code buildDate}。 + * + * @param date 参数 {@code date}({@code long}) + */ public void setBuildDate(long date) { this.setOtaInfo("buildDate", date); } + /** + * 获取 {@code sdkLevel}。 + * @return 数量/长度 + */ public int getSdkLevel() { return this.getOtaInfo().getInteger("sdk", -1); } + /** + * 设置 {@code sdkLevel}。 + * + * @param level 参数 {@code level}({@code int}) + */ public void setSdkLevel(int level) { this.setOtaInfo("sdk", level); } + /** + * 获取 {@code postBuildDate}。 + * @return 数量/长度 + */ public long getPostBuildDate() { return this.getOtaInfo().getLong("postBuildDate", -1L); } + /** + * 设置 {@code postBuildDate}。 + * + * @param date 参数 {@code date}({@code long}) + */ public void setPostBuildDate(long date) { this.setOtaInfo("postBuildDate", date); } + /** + * 获取 {@code productId}。 + * @return 字符串结果 + */ public String getProductId() { return this.getOtaInfo().getString("productId"); } + /** + * 设置 {@code productId}。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void setProductId(String productId) { this.setOtaInfo("productId", productId); } + /** + * 获取 {@code targetProduct}。 + * @return 字符串结果 + */ public String getTargetProduct() { return this.getOtaInfo().getString("targetProduct"); } + /** + * 设置 {@code targetProduct}。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void setTargetProduct(String productId) { this.setOtaInfo("targetProduct", productId); } + /** + * 获取 {@code skuId}。 + * @return 字符串结果 + */ public String getSkuId() { return this.getOtaInfo().getString("skuId"); } + /** + * 设置 {@code skuId}。 + * + * @param skuId 参数 {@code skuId}({@code String}) + */ public void setSkuId(String skuId) { this.setOtaInfo("skuId", skuId); } + /** + * 判断 {@code compatibleSkuIds}。 + * @return 字段/派生属性 {@code compatibleSkuIds} 的值 + */ public boolean hasCompatibleSkuIds() { List ids = this.getOtaInfo().getList("compatibleSkuIds", String.class); return ids != null && ids.size() > 0; } - public List getCompatibleSkuIds() { + /** + * 获取 {@code compatibleSkuIds}。 + * @return String列表,可能为空 + */ + public List getCompatibleSkuIds() { return this.getOtaInfo().getList("compatibleSkuIds", String.class); } + /** + * 判断是否CompatibleSkuID。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param skuId 参数 {@code skuId}({@code String}) + * @return 字段/派生属性 {@code compatibleSkuId} 的值 + */ public boolean isCompatibleSkuId(String skuId) { if (Strings.isNullOrEmpty(skuId)) { return false; @@ -207,6 +360,13 @@ public class OtaFile extends BaseFile implements Comparable { } } + /** + * 设置 {@code compatibleSkuIds}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param skuIds 参数 {@code skuIds}({@code String}) + */ public void setCompatibleSkuIds(String skuIds) { if (!Strings.isNullOrEmpty(skuIds)) { String[] ids = skuIds.split("\\s*,\\s*"); @@ -217,34 +377,74 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 获取 {@code deviceId}。 + * @return 字符串结果 + */ public String getDeviceId() { return this.getOtaInfo().getString("deviceId"); } + /** + * 设置 {@code deviceId}。 + * + * @param deviceId 参数 {@code deviceId}({@code String}) + */ public void setDeviceId(String deviceId) { this.setOtaInfo("deviceId", deviceId); } + /** + * 获取 {@code displayId}。 + * @return 字符串结果 + */ public String getDisplayId() { return this.getOtaInfo().getString("displayId"); } + /** + * 设置 {@code displayId}。 + * + * @param displayId 参数 {@code displayId}({@code String}) + */ public void setDisplayId(String displayId) { this.setOtaInfo("displayId", displayId); } + /** + * 设置 {@code productDisplayId}。 + * + * @param displayId 参数 {@code displayId}({@code String}) + */ public void setProductDisplayId(String displayId) { this.setOtaInfo("productDisplayId", displayId); } + /** + * 获取 {@code preDisplayId}。 + * @return 字符串结果 + */ public String getPreDisplayId() { return this.getOtaInfo().getString("preDisplayId"); } + /** + * 设置 {@code preDisplayId}。 + * + * @param displayId 参数 {@code displayId}({@code String}) + */ public void setPreDisplayId(String displayId) { this.setOtaInfo("preDisplayId", displayId); } + /** + * 解析SkuID。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param displayId 参数 {@code displayId}({@code String}) + * @return 字符串结果 + */ public static String parseSkuId(String displayId) { if (displayId != null) { int startIndex = displayId.indexOf(46); @@ -262,142 +462,302 @@ public class OtaFile extends BaseFile implements Comparable { return null; } + /** + * 获取 {@code brand}。 + * @return 字符串结果 + */ public String getBrand() { return this.getOtaInfo().getString("brand"); } + /** + * 设置 {@code brand}。 + * + * @param brand 参数 {@code brand}({@code String}) + */ public void setBrand(String brand) { this.setOtaInfo("brand", brand); } + /** + * 获取 {@code customer}。 + * @return 字符串结果 + */ public String getCustomer() { return this.getOtaInfo().getString("customer"); } + /** + * 设置 {@code customer}。 + * + * @param customer 参数 {@code customer}({@code String}) + */ public void setCustomer(String customer) { this.setOtaInfo("customer", customer); } + /** + * 获取 {@code customerId}。 + * @return 字符串结果 + */ public String getCustomerId() { return this.getOtaInfo().getString("customerId"); } + /** + * 设置 {@code customerId}。 + * + * @param customerId 参数 {@code customerId}({@code String}) + */ public void setCustomerId(String customerId) { this.setOtaInfo("customerId", customerId); } + /** + * 获取 {@code partNo}。 + * @return 字符串结果 + */ public String getPartNo() { return this.getOtaInfo().getString("partNo"); } + /** + * 设置 {@code partNo}。 + * + * @param partNo 参数 {@code partNo}({@code String}) + */ public void setPartNo(String partNo) { this.setOtaInfo("partNo", partNo); } + /** + * 获取 {@code osVersion}。 + * @return 字符串结果 + */ public String getOsVersion() { return this.getOtaInfo().getString("osVersion"); } + /** + * 设置 {@code osVersion}。 + * + * @param version 参数 {@code version}({@code String}) + */ public void setOsVersion(String version) { this.setOtaInfo("osVersion", version); } + /** + * 获取 {@code scriptVersion}。 + * @return 字符串结果 + */ public String getScriptVersion() { return this.getOtaInfo().getString("scriptVersion"); } + /** + * 设置 {@code scriptVersion}。 + * + * @param partNo 参数 {@code partNo}({@code String}) + */ public void setScriptVersion(String partNo) { this.setOtaInfo("scriptVersion", partNo); } + /** + * 获取 {@code releaseVersion}。 + * @return 字符串结果 + */ public String getReleaseVersion() { return this.getOtaInfo().getString("releaseVersion"); } + /** + * 设置 {@code releaseVersion}。 + * + * @param partNo 参数 {@code partNo}({@code String}) + */ public void setReleaseVersion(String partNo) { this.setOtaInfo("releaseVersion", partNo); } + /** + * 获取 {@code marketName1}。 + * @return 字符串结果 + */ public String getMarketName1() { return this.getOtaInfo().getString("marketName1"); } + /** + * 设置 {@code marketName1}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setMarketName1(String name) { this.setOtaInfo("marketName1", name); } + /** + * 获取 {@code marketName2}。 + * @return 字符串结果 + */ public String getMarketName2() { return this.getOtaInfo().getString("marketName2"); } + /** + * 设置 {@code marketName2}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setMarketName2(String name) { this.setOtaInfo("marketName2", name); } + /** + * 获取 {@code securityPatchLevel}。 + * @return 字符串结果 + */ public String getSecurityPatchLevel() { return this.getOtaInfo().getString("securityPatch"); } + /** + * 设置 {@code securityPatchLevel}。 + * + * @param level 参数 {@code level}({@code String}) + */ public void setSecurityPatchLevel(String level) { this.setOtaInfo("securityPatch", level); } + /** + * 获取 {@code buildType}。 + * @return 字符串结果 + */ public String getBuildType() { return this.getOtaInfo().getString("buildType"); } + /** + * 设置 {@code buildType}。 + * + * @param buildType 参数 {@code buildType}({@code String}) + */ public void setBuildType(String buildType) { this.setOtaInfo("buildType", buildType); } + /** + * 获取 {@code buildTags}。 + * @return 字符串结果 + */ public String getBuildTags() { return this.getOtaInfo().getString("buildTags"); } + /** + * 设置 {@code buildTags}。 + * + * @param buildTags 参数 {@code buildTags}({@code String}) + */ public void setBuildTags(String buildTags) { this.setOtaInfo("buildTags", buildTags); } + /** + * 获取 {@code preBuild}。 + * @return 字符串结果 + */ public String getPreBuild() { return this.getOtaInfo().getString("preBuild"); } + /** + * 设置 {@code preBuild}。 + * + * @param value 值({@code String}) + */ public void setPreBuild(String value) { this.setOtaInfo("preBuild", value); } + /** + * 获取 {@code otaCertHash}。 + * @return 字符串结果 + */ public String getOtaCertHash() { return this.getOtaInfo().getString("otaCert"); } + /** + * 设置 {@code otaCertHash}。 + * + * @param hash 参数 {@code hash}({@code String}) + */ public void setOtaCertHash(String hash) { this.setOtaInfo("otaCert", hash); } + /** + * 获取 {@code modemSku}。 + * @return 字符串结果 + */ public String getModemSku() { return this.getOtaInfo().getString("modemSku"); } + /** + * 设置 {@code modemSku}。 + * + * @param hash 参数 {@code hash}({@code String}) + */ public void setModemSku(String hash) { this.setOtaInfo("modemSku", hash); } + /** + * 获取 {@code modemFirmwareVersion}。 + * @return 字符串结果 + */ public String getModemFirmwareVersion() { return this.getOtaInfo().getString("modemFirmwareVersion"); } + /** + * 设置 {@code modemFirmwareVersion}。 + * + * @param hash 参数 {@code hash}({@code String}) + */ public void setModemFirmwareVersion(String hash) { this.setOtaInfo("modemFirmwareVersion", hash); } + /** + * 获取 {@code modemFirmwareLongVersion}。 + * @return 字符串结果 + */ public String getModemFirmwareLongVersion() { return this.getOtaInfo().getString("modemFirmwareLongVersion"); } + /** + * 设置 {@code modemFirmwareLongVersion}。 + * + * @param hash 参数 {@code hash}({@code String}) + */ public void setModemFirmwareLongVersion(String hash) { this.setOtaInfo("modemFirmwareLongVersion", hash); } + /** + * 处理retrieve构建信息。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 13 个条件分支、2 个循环;主要调用:new ZipInputStream、close。 + * + * @param zipFile 参数 {@code zipFile}({@code ZipFile}) + */ private void retrieveBuildInfo(ZipFile zipFile) { try { Enumeration entries = zipFile.entries(); @@ -475,6 +835,13 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 处理dispatchUpdaterScript。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环。 + * + * @param is 参数 {@code is}({@code InputStream}) + */ private void dispatchUpdaterScript(InputStream is) { try { String script = IOUtils.toString(is, "UTF-8"); @@ -520,6 +887,13 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 处理dispatchProp。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new Properties。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ private void dispatchProp(InputStream input) { try { Properties properties = new Properties(); @@ -534,6 +908,13 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 处理dispatchJSON。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、1 个循环。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ private void dispatchJson(InputStream input) { if (input != null) { JsonElement json = McJsonUtils.toJsonElement(input); @@ -552,11 +933,26 @@ public class OtaFile extends BaseFile implements Comparable { } } + /** + * 处理dispatchOTA 固件证书。 + * + * 实现要点:主要调用:new McOtaCert。 + * + * @param otaCertIs 参数 {@code otaCertIs}({@code InputStream}) + */ private void dispatchOtaCert(InputStream otaCertIs) { McOtaCert otaCert = new McOtaCert(otaCertIs); this.setOtaCertHash(otaCert.getBase64Hash()); } + /** + * 设置OTA 固件Property。 + * + * 实现要点:包含 25 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + */ private void setOtaProperty(String key, String value) { switch (key) { case "ota-type": @@ -660,6 +1056,7 @@ public class OtaFile extends BaseFile implements Comparable { break; case "mitac-package-type": this.setType(value); + break; case "post-build-incremental": default: break; @@ -711,10 +1108,21 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 获取 {@code postBuild}。 + * @return 字符串结果 + */ public String getPostBuild() { return this.getOtaInfo().getString("postBuild"); } + /** + * 处理dispatchPost构建。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * @param text 参数 {@code text}({@code String}) + */ private void dispatchPostBuild(String text) { this.setOtaInfo("postBuild", text); String[] tags = text.split(":"); @@ -736,6 +1144,17 @@ public class OtaFile extends BaseFile implements Comparable { } + /** + * 处理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) { int keyIndex = sb.indexOf(key); if (keyIndex < 0) { @@ -747,6 +1166,15 @@ public class OtaFile extends BaseFile implements Comparable { } } + /** + * 处理最后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) { int keyIndex = sb.indexOf(key); int endIndex = sb.lastIndexOf(",", keyIndex); @@ -754,6 +1182,14 @@ public class OtaFile extends BaseFile implements Comparable { return startIndex < endIndex ? sb.substring(startIndex, endIndex) : ""; } + /** + * 按业务字段比较两个对象的顺序。 + * + * 实现要点:包含 6 个条件分支、0 个循环。 + * + * @param other 参数 {@code other}({@code OtaFile}) + * @return 数量/长度 + */ public int compareTo(OtaFile other) { int result = this.getSkuId().compareTo(other.getSkuId()); if (result == 0) { diff --git a/src/main/java/com/midm/model/file/REPORT_ERROR.java b/src/main/java/com/midm/model/file/REPORT_ERROR.java index 475cb32..a172e79 100644 --- a/src/main/java/com/midm/model/file/REPORT_ERROR.java +++ b/src/main/java/com/midm/model/file/REPORT_ERROR.java @@ -2,6 +2,23 @@ package com.midm.model.file; import java.util.List; +/** + * 【枚举常量】{@code REPORT_ERROR} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code COLLECT_SSN}(List):REPORT_ERROR集合
  • + *
  • {@code value}(int):值
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum REPORT_ERROR { UNKNOWN(1000), FILE_ERROR(1001), @@ -14,17 +31,40 @@ public enum REPORT_ERROR { FILE_ALREADY_EXISTS(1009), 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 COLLECT_SSN = List.of(UNKNOWN, FILE_ERROR, INSUFFICIENT_SPACE, DEVICE_NOT_FOUND, CANNOT_RESUME, FILE_ALREADY_EXISTS); + /** + * 值。 + */ private int value; + /** + * 构造 {@code REPORT_ERROR} 实例。 + * + * @param value 值({@code int}) + */ private REPORT_ERROR(int value) { this.value = value; } + /** + * 获取 {@code value}。 + * @return 数量/长度 + */ public int getValue() { return this.value; } + /** + * 处理从值。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param value 值({@code int}) + * @return 处理结果 + */ public static REPORT_ERROR fromValue(int value) { for(REPORT_ERROR e : values()) { if (e.getValue() == value) { diff --git a/src/main/java/com/midm/model/file/package-info.java b/src/main/java/com/midm/model/file/package-info.java new file mode 100644 index 0000000..9837820 --- /dev/null +++ b/src/main/java/com/midm/model/file/package-info.java @@ -0,0 +1,17 @@ +/** + * 文件领域模型:APK/OTA/报表/图片等文件元数据与上传结果。 + * + *

本包主要类型: + *

    + *
  • {@link AppFile}
  • + *
  • {@link BaseFile}
  • + *
  • {@link DeployOption}
  • + *
  • {@link FILE_TYPE}
  • + *
  • {@link OtaFile}
  • + *
  • {@link REPORT_ERROR}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.file; diff --git a/src/main/java/com/midm/model/log/MidmLog.java b/src/main/java/com/midm/model/log/MidmLog.java index 6b04888..d18ad14 100644 --- a/src/main/java/com/midm/model/log/MidmLog.java +++ b/src/main/java/com/midm/model/log/MidmLog.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code MidmLog} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code forWhat}(UUID):用于What
  • + *
  • {@code category}(String):字段 category
  • + *
  • {@code log}(String):日志
  • + *
  • {@code reference}(DbObject):字段 reference
  • + *
  • {@code loggedAt}(Date):时间字段
  • + *
+ * + * 协作对象:{@code DbObject、User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document @CompoundIndexes({@CompoundIndex( def = "{'category':1, 'loggedAt':1}" @@ -21,21 +46,62 @@ import org.springframework.data.mongodb.core.mapping.Document; def = "{'forWhat':1, 'log': 1}" )}) public class MidmLog { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 用于What。 + */ private UUID forWhat; + /** + * 字段 category。 + */ private String category; + /** + * 日志。 + */ private String log; + /** + * 字段 reference。 + */ private DbObject reference; + /** + * 时间字段。 + */ private Date loggedAt; + /** + * 字段 logger;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private User logger; + /** + * 构造 {@code MidmLog} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new Date。 + */ public MidmLog() { this.setUuid(UUID.randomUUID()); 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) { this(); if (user != null) { @@ -47,38 +113,80 @@ public class MidmLog { this.setLog(log); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code forWhat}。 + * @return UUID + */ public UUID getForWhat() { return this.forWhat; } + /** + * 设置 {@code forWhat}。 + * + * @param forWhat 参数 {@code forWhat}({@code UUID}) + */ public void setForWhat(UUID forWhat) { this.forWhat = forWhat; } + /** + * 获取 {@code category}。 + * @return 字符串结果 + */ public String getCategory() { return this.category; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } + /** + * 获取 {@code log}。 + * @return 字符串结果 + */ public String getLog() { return this.log; } + /** + * 设置 {@code log}。 + * + * @param log 参数 {@code log}({@code String}) + */ public void setLog(String log) { this.log = log; } + /** + * 获取 {@code reference}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReference() { if (this.reference == null) { this.reference = new DbObject(); @@ -87,14 +195,32 @@ public class MidmLog { return this.reference; } + /** + * 判断 {@code reference}。 + * @return 字段/派生属性 {@code reference} 的值 + */ public boolean hasReference() { return this.reference != null && this.reference.size() > 0; } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code DbObject}) + */ public void setReference(DbObject 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) { if (agent != null) { 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) { this.getReference().put(key, value); } + /** + * 获取 {@code loggerUuid}。 + * @return UUID + */ public UUID getLoggerUuid() { return this.logger != null ? this.logger.getUuid() : null; } + /** + * 获取 {@code loggedAt}。 + * @return 字段/派生属性 {@code loggedAt} 的值 + */ public Date getLoggedAt() { return this.loggedAt; } + /** + * 设置 {@code loggedAt}。 + * + * @param loggedAt 参数 {@code loggedAt}({@code Date}) + */ public void setLoggedAt(Date loggedAt) { this.loggedAt = loggedAt; } + /** + * 设置 {@code loggedAt}。 + * + * 实现要点:主要调用:new Date。 + * + * @param loggedAt 参数 {@code loggedAt}({@code long}) + */ public void setLoggedAt(long loggedAt) { this.loggedAt = new Date(loggedAt); } + /** + * 获取 {@code logger}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getLogger() { return this.logger; } + /** + * 设置 {@code logger}。 + * + * @param logger 参数 {@code logger}({@code User}) + */ public void setLogger(User logger) { this.logger = logger; } diff --git a/src/main/java/com/midm/model/log/package-info.java b/src/main/java/com/midm/model/log/package-info.java new file mode 100644 index 0000000..b8a6478 --- /dev/null +++ b/src/main/java/com/midm/model/log/package-info.java @@ -0,0 +1,12 @@ +/** + * 审计与操作日志模型。 + * + *

本包主要类型: + *

    + *
  • {@link MidmLog}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.log; diff --git a/src/main/java/com/midm/model/message/MIDM_REQUEST.java b/src/main/java/com/midm/model/message/MIDM_REQUEST.java index 8ba124c..7845309 100644 --- a/src/main/java/com/midm/model/message/MIDM_REQUEST.java +++ b/src/main/java/com/midm/model/message/MIDM_REQUEST.java @@ -1,5 +1,22 @@ package com.midm.model.message; +/** + * 【枚举常量】{@code MIDM_REQUEST} + * + * 类职责: + *

    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(int):代码
  • + *
  • {@code request}(String):请求
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum MIDM_REQUEST { PING(99, "ping"), CONNECT(100, "connect"), @@ -21,22 +38,50 @@ public enum MIDM_REQUEST { RTC(400, "rtc"), UNKNOWN(-1, ""); + /** + * 代码。 + */ private int code; + /** + * 请求。 + */ private String request; + /** + * 构造 {@code MIDM_REQUEST} 实例。 + * + * @param code 状态码/业务码({@code int}) + * @param request HTTP 请求({@code String}) + */ private MIDM_REQUEST(int code, String request) { this.code = code; this.request = request; } + /** + * 获取 {@code code}。 + * @return 数量/长度 + */ public int getCode() { return this.code; } + /** + * 获取 {@code request}。 + * @return 字符串结果 + */ public String getRequest() { return this.request; } + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param code 状态码/业务码({@code int}) + * @return 处理结果 + */ public static MIDM_REQUEST get(int code) { for(MIDM_REQUEST request : values()) { if (request.code == code) { @@ -47,6 +92,14 @@ public enum MIDM_REQUEST { return UNKNOWN; } + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param requestText 参数 {@code requestText}({@code String}) + * @return 处理结果 + */ public static MIDM_REQUEST get(String requestText) { for(MIDM_REQUEST request : values()) { if (request.getRequest().equalsIgnoreCase(requestText.trim())) { diff --git a/src/main/java/com/midm/model/message/MidmPacket.java b/src/main/java/com/midm/model/message/MidmPacket.java index b462ef1..9e99ff7 100644 --- a/src/main/java/com/midm/model/message/MidmPacket.java +++ b/src/main/java/com/midm/model/message/MidmPacket.java @@ -14,121 +14,306 @@ import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.web.socket.BinaryMessage; import org.springframework.web.socket.TextMessage; +/** + * 【MongoDB 文档实体】{@code MidmPacket} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code recieverUuid}(UUID):recieverUUID
  • + *
  • {@code queryUuid}(UUID):查询UUID
  • + *
  • {@code query}(MidmQuery):查询
  • + *
  • {@code feedback}(MidmResponse):反馈
  • + *
  • {@code readAt}(Date):读取At
  • + *
+ * + * 协作对象:{@code MidmQuery、MidmResponse}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class MidmPacket implements Serializable { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * recieverUUID。 + */ private UUID recieverUuid; + /** + * 查询UUID。 + */ private UUID queryUuid; + /** + * 查询;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private MidmQuery query; + /** + * 反馈。 + */ private MidmResponse feedback; + /** + * 读取At。 + */ private Date readAt; + /** + * 构造 {@code MidmPacket} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public MidmPacket() { this.setUuid(UUID.randomUUID()); } + /** + * 构造 {@code MidmPacket} 实例。 + * + * 实现要点:主要调用:new MidmQuery。 + * + * @param code 状态码/业务码({@code int}) + */ public MidmPacket(int code) { this.init(); this.setQuery(new MidmQuery(code)); } + /** + * 构造 {@code MidmPacket} 实例。 + * + * @param request HTTP 请求({@code MIDM_REQUEST}) + */ public MidmPacket(MIDM_REQUEST request) { this(request.getCode()); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + */ private void init() { this.setUuid(UUID.randomUUID()); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code recieverUuid}。 + * @return UUID + */ public UUID getRecieverUuid() { return this.recieverUuid; } + /** + * 设置 {@code recieverUuid}。 + * + * @param recieverUuid 参数 {@code recieverUuid}({@code UUID}) + */ public void setRecieverUuid(UUID recieverUuid) { this.recieverUuid = recieverUuid; } + /** + * 获取 {@code queryUuid}。 + * @return UUID + */ public UUID getQueryUuid() { return this.queryUuid; } + /** + * 设置 {@code queryUuid}。 + * + * @param queryUuid 参数 {@code queryUuid}({@code UUID}) + */ public void setQueryUuid(UUID queryUuid) { this.queryUuid = queryUuid; } + /** + * 获取 {@code query}。 + * @return 字段/派生属性 {@code query} 的值 + */ public MidmQuery getQuery() { return this.query; } + /** + * 设置 {@code query}。 + * + * @param query 查询对象({@code MidmQuery}) + */ public void setQuery(MidmQuery query) { this.query = query; } + /** + * 获取Param。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code param} 的值 + */ public Object getParam(String key) { return this.getQuery().getParam(key); } + /** + * 设置Param。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setParam(String key, Object value) { this.getQuery().setParam(key, value); } + /** + * 获取 {@code feedback}。 + * @return 字段/派生属性 {@code feedback} 的值 + */ public MidmResponse getFeedback() { return this.feedback; } + /** + * 设置 {@code feedback}。 + * + * @param feedback 参数 {@code feedback}({@code MidmResponse}) + */ public void setFeedback(MidmResponse feedback) { this.feedback = feedback; } + /** + * 设置反馈。 + * + * 实现要点:主要调用:new MidmResponse。 + * + * @param code 状态码/业务码({@code int}) + * @param message 消息内容({@code String}) + */ public void setFeedback(int code, String 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) { this.feedback = new MidmResponse(code, message, data); } + /** + * 获取 {@code readAt}。 + * @return 字段/派生属性 {@code readAt} 的值 + */ public Date getReadAt() { return this.readAt; } + /** + * 设置 {@code readAt}。 + * + * @param readAt 参数 {@code readAt}({@code Date}) + */ public void setReadAt(Date readAt) { this.readAt = readAt; } + /** + * 处理转换为消息。 + * + * 实现要点:主要调用:new TextMessage。 + * @return 处理结果 + */ public TextMessage toMessage() { return new TextMessage(this.toString()); } + /** + * 处理转换为Binary。 + * + * 实现要点:主要调用:new BinaryMessage。 + * @return 处理结果 + */ public BinaryMessage toBinary() { byte[] bytes = McCompress.compress(this.toString()); return new BinaryMessage(bytes); } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return McJsonUtils.toJson(this); } + /** + * 处理转换为报文。 + * + * @param message 消息内容({@code TextMessage}) + * @return 处理结果 + */ public static MidmPacket toPacket(TextMessage message) { return (MidmPacket)McJsonUtils.toObject((String)message.getPayload(), MidmPacket.class); } + /** + * 处理topacket。 + * + * 实现要点:主要调用:new String。 + * + * @param message 消息内容({@code BinaryMessage}) + * @return 处理结果 + */ public static MidmPacket topacket(BinaryMessage message) { ByteBuffer bytes = (ByteBuffer)message.getPayload(); byte[] decompressed = McDecompress.decompress(bytes.array()); return (MidmPacket)McJsonUtils.toObject(new String(decompressed, Charsets.UTF_8), MidmPacket.class); } + /** + * 处理转换为报文。 + * + * @param message 消息内容({@code String}) + * @return 处理结果 + */ public static MidmPacket toPacket(String message) { return (MidmPacket)McJsonUtils.toObject(message, MidmPacket.class); } diff --git a/src/main/java/com/midm/model/message/MidmQuery.java b/src/main/java/com/midm/model/message/MidmQuery.java index db7671b..da6225f 100644 --- a/src/main/java/com/midm/model/message/MidmQuery.java +++ b/src/main/java/com/midm/model/message/MidmQuery.java @@ -5,54 +5,144 @@ import java.util.Date; import java.util.UUID; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code MidmQuery} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code senderUuid}(UUID):senderUUID
  • + *
  • {@code code}(int):代码
  • + *
  • {@code query}(DbObject):查询
  • + *
  • {@code isInstant}(boolean):判断是否Instant
  • + *
  • {@code registeredAt}(Date):时间字段
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class MidmQuery { + /** + * 对象唯一标识(MongoDB 主键)。 + */ private UUID uuid; + /** + * senderUUID。 + */ private UUID senderUuid; + /** + * 代码。 + */ private int code; + /** + * 查询。 + */ private DbObject query; + /** + * 判断是否Instant。 + */ private boolean isInstant; + /** + * 时间字段。 + */ private Date registeredAt; + /** + * 构造 {@code MidmQuery} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public MidmQuery() { this.init(); } + /** + * 构造 {@code MidmQuery} 实例。 + * + * @param code 状态码/业务码({@code int}) + */ public MidmQuery(int code) { this(); this.setCode(code); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.setUuid(UUID.randomUUID()); this.isInstant = true; this.setRegisteredAt(new Date()); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code senderUuid}。 + * @return UUID + */ public UUID getSenderUuid() { return this.senderUuid; } + /** + * 设置 {@code senderUuid}。 + * + * @param senderUuid 参数 {@code senderUuid}({@code UUID}) + */ public void setSenderUuid(UUID senderUuid) { this.senderUuid = senderUuid; } + /** + * 获取 {@code code}。 + * @return 数量/长度 + */ public int getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code int}) + */ public void setCode(int code) { this.code = code; } + /** + * 获取 {@code query}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getQuery() { if (this.query == null) { this.query = new DbObject(); @@ -61,18 +151,38 @@ public class MidmQuery { return this.query; } + /** + * 设置 {@code query}。 + * + * @param query 查询对象({@code DbObject}) + */ public void setQuery(DbObject query) { this.query = query; } + /** + * 获取 {@code request}。 + * @return 字符串结果 + */ public String getRequest() { return (String)this.getQuery().get("request"); } + /** + * 设置 {@code request}。 + * + * @param request HTTP 请求({@code String}) + */ public void setRequest(String request) { this.getQuery().put("request", request); } + /** + * 获取 {@code params}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getParams() { DbObject params = this.getQuery().getDbObject(new String[]{"params"}); if (params == null) { @@ -83,30 +193,64 @@ public class MidmQuery { return params; } + /** + * 获取Param。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code param} 的值 + */ public Object getParam(String key) { return this.getParams().get(key); } + /** + * 获取 {@code command}。 + * @return 字符串结果 + */ public String getCommand() { return this.getParam("command").toString(); } + /** + * 设置Param。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setParam(String key, Object value) { this.getParams().put(key, value); } + /** + * 判断 {@code instant}。 + * @return 字段/派生属性 {@code instant} 的值 + */ public boolean isInstant() { return this.isInstant; } + /** + * 设置 {@code instant}。 + * + * @param isInstant 参数 {@code isInstant}({@code boolean}) + */ public void setInstant(boolean isInstant) { this.isInstant = isInstant; } + /** + * 获取 {@code registeredAt}。 + * @return 字段/派生属性 {@code registeredAt} 的值 + */ public Date getRegisteredAt() { return this.registeredAt; } + /** + * 设置 {@code registeredAt}。 + * + * @param registeredAt 参数 {@code registeredAt}({@code Date}) + */ public void setRegisteredAt(Date registeredAt) { this.registeredAt = registeredAt; } diff --git a/src/main/java/com/midm/model/message/MidmResponse.java b/src/main/java/com/midm/model/message/MidmResponse.java index ad8c5eb..74e4b35 100644 --- a/src/main/java/com/midm/model/message/MidmResponse.java +++ b/src/main/java/com/midm/model/message/MidmResponse.java @@ -8,163 +8,584 @@ import java.util.Map; import org.springframework.data.domain.Page; import org.springframework.web.socket.TextMessage; +/** + * 【领域模型】{@code MidmResponse} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code MESSAGE_SUCCEED}(String):字段 MESSAGE_SUCCEED
  • + *
  • {@code MESSAGE_FAILED}(String):字段 MESSAGE_FAILED
  • + *
  • {@code CODE_SERVICE_CONNECTED}(int):字段 CODE_SERVICE_CONNECTED
  • + *
  • {@code CODE_SUCCEED}(int):字段 CODE_SUCCEED
  • + *
  • {@code CODE_CHECKEDIN}(int):字段 CODE_CHECKEDIN
  • + *
  • {@code CODE_ENROLLED}(int):字段 CODE_ENROLLED
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class MidmResponse { + /** + * 字段 MESSAGE_SUCCEED。 + */ public static final String MESSAGE_SUCCEED = "succeed"; + /** + * 字段 MESSAGE_FAILED。 + */ public static final String MESSAGE_FAILED = "failed"; + /** + * 字段 CODE_SERVICE_CONNECTED。 + */ public static final int CODE_SERVICE_CONNECTED = 100; + /** + * 字段 CODE_SUCCEED。 + */ public static final int CODE_SUCCEED = 200; + /** + * 字段 CODE_CHECKEDIN。 + */ public static final int CODE_CHECKEDIN = 110; + /** + * 字段 CODE_ENROLLED。 + */ public static final int CODE_ENROLLED = 111; + /** + * 字段 CODE_ENROLL_REJECTED。 + */ public static final int CODE_ENROLL_REJECTED = 112; + /** + * 字段 CODE_DEVICE_REGISTERD。 + */ public static final int CODE_DEVICE_REGISTERD = 113; + /** + * 字段 CODE_DEVICE_UPDATED。 + */ public static final int CODE_DEVICE_UPDATED = 114; + /** + * 字段 CODE_LICENSE_EXPIRED。 + */ public static final int CODE_LICENSE_EXPIRED = 115; + /** + * 字段 CODE_MESSAGE_NOTIFY。 + */ public static final int CODE_MESSAGE_NOTIFY = 116; + /** + * 字段 CODE_REPORT_READY。 + */ public static final int CODE_REPORT_READY = 117; + /** + * 字段 CODE_REPORT_GENERATE_FAIL。 + */ public static final int CODE_REPORT_GENERATE_FAIL = 118; + /** + * 字段 CODE_HOST_LICENSE_READY。 + */ public static final int CODE_HOST_LICENSE_READY = 119; + /** + * 字段 CODE_SITE_LICENSE_READY。 + */ public static final int CODE_SITE_LICENSE_READY = 109; + /** + * 字段 CODE_SITE_LICENSE_REQUESTED。 + */ public static final int CODE_SITE_LICENSE_REQUESTED = 108; + /** + * 字段 CODE_SITE_UPGRADE_REQUESTED。 + */ public static final int CODE_SITE_UPGRADE_REQUESTED = 107; + /** + * 字段 CODE_SITE_UPGRADE_SUCCESS。 + */ public static final int CODE_SITE_UPGRADE_SUCCESS = 106; + /** + * 字段 CODE_UPDATE_CIENT_APPS。 + */ public static final int CODE_UPDATE_CIENT_APPS = 121; + /** + * 字段 CODE_ONLINE_STATE_CHANGED。 + */ public static final int CODE_ONLINE_STATE_CHANGED = 211; + /** + * 字段 CODE_DEVICE_STATE_CHANGED。 + */ public static final int CODE_DEVICE_STATE_CHANGED = 300; + /** + * 字段 FEEDBACK_APP_LIST。 + */ public static final int FEEDBACK_APP_LIST = 120; + /** + * 字段 FEEDBACK_APP_INSTALLED。 + */ public static final int FEEDBACK_APP_INSTALLED = 121; + /** + * 字段 FEEDBACK_APP_UNINSTALLED。 + */ public static final int FEEDBACK_APP_UNINSTALLED = 122; + /** + * 字段 FEEDBACK_APP_ENABLE。 + */ public static final int FEEDBACK_APP_ENABLE = 123; + /** + * 字段 FEEDBACK_APP_DISABLE。 + */ public static final int FEEDBACK_APP_DISABLE = 124; + /** + * 字段 FEEDBACK_APP_SHOW。 + */ public static final int FEEDBACK_APP_SHOW = 125; + /** + * 字段 FEEDBACK_APP_HIDE。 + */ public static final int FEEDBACK_APP_HIDE = 126; + /** + * 字段 FEEDBACK_APP_INFO。 + */ public static final int FEEDBACK_APP_INFO = 127; + /** + * 字段 FEEDBACK_FILE_LIST。 + */ public static final int FEEDBACK_FILE_LIST = 130; + /** + * 字段 FEEDBACK_FILE_STORAGE。 + */ public static final int FEEDBACK_FILE_STORAGE = 131; + /** + * 字段 FEEDBACK_FILE_COPY。 + */ public static final int FEEDBACK_FILE_COPY = 132; + /** + * 字段 FEEDBACK_FILE_RENAME。 + */ public static final int FEEDBACK_FILE_RENAME = 133; + /** + * 字段 FEEDBACK_FILE_MOVE。 + */ public static final int FEEDBACK_FILE_MOVE = 134; + /** + * 字段 FEEDBACK_FILE_REMOVE。 + */ public static final int FEEDBACK_FILE_REMOVE = 135; + /** + * 字段 FEEDBACK_FILE_MKDIR。 + */ public static final int FEEDBACK_FILE_MKDIR = 136; + /** + * 字段 FEEDBACK_FILE_PUSH。 + */ public static final int FEEDBACK_FILE_PUSH = 137; + /** + * 字段 FEEDBACK_FILE_PULL。 + */ public static final int FEEDBACK_FILE_PULL = 138; + /** + * 字段 FEEDBACK_FILE_LOGCAT。 + */ public static final int FEEDBACK_FILE_LOGCAT = 139; + /** + * 字段 FEEDBACK_EXEC。 + */ public static final int FEEDBACK_EXEC = 140; + /** + * 字段 FEEDBACK_EXEC_LOGCAT。 + */ public static final int FEEDBACK_EXEC_LOGCAT = 141; + /** + * 字段 FEEDBACK_HARDWARE_INFO。 + */ public static final int FEEDBACK_HARDWARE_INFO = 170; + /** + * 字段 FEEDBACK_SOFTWARE_INFO。 + */ public static final int FEEDBACK_SOFTWARE_INFO = 180; + /** + * 字段 FEEDBACK_MEMORY_USAGE。 + */ public static final int FEEDBACK_MEMORY_USAGE = 190; + /** + * 字段 FEEDBACK_BATTERY_INFO。 + */ public static final int FEEDBACK_BATTERY_INFO = 191; + /** + * 字段 FEEDBACK_DATA_USAGE。 + */ public static final int FEEDBACK_DATA_USAGE = 192; + /** + * 字段 FEEDBACK_ACTIVE_NETWORK。 + */ public static final int FEEDBACK_ACTIVE_NETWORK = 193; + /** + * 字段 FEEDBACK_NETWORK。 + */ public static final int FEEDBACK_NETWORK = 194; + /** + * 字段 FEEDBACK_LOCATION。 + */ public static final int FEEDBACK_LOCATION = 198; + /** + * 字段 FEEDBACK_SCREEN_CAPTURED。 + */ public static final int FEEDBACK_SCREEN_CAPTURED = 199; + /** + * 字段 FEEDBACK_ONLINE_STATE。 + */ public static final int FEEDBACK_ONLINE_STATE = 211; + /** + * 字段 FEEDBACK_CAMERA_STATE。 + */ public static final int FEEDBACK_CAMERA_STATE = 212; + /** + * 字段 FEEDBACK_DEVICE_STATE。 + */ public static final int FEEDBACK_DEVICE_STATE = 300; + /** + * 字段 CODE_FAILED。 + */ public static final int CODE_FAILED = 400; + /** + * 字段 CODE_NOT_FOUND。 + */ public static final int CODE_NOT_FOUND = 404; + /** + * 字段 CODE_FAIL_USER_NOT_FOUND。 + */ public static final int CODE_FAIL_USER_NOT_FOUND = 410; + /** + * 字段 CODE_FAIL_WRONG_PASSWROD。 + */ public static final int CODE_FAIL_WRONG_PASSWROD = 411; + /** + * 字段 CODE_FAIL_USER_NOT_AVAILABLE。 + */ public static final int CODE_FAIL_USER_NOT_AVAILABLE = 412; + /** + * 字段 CODE_FAIL_INSUFFICIENT_INFO。 + */ public static final int CODE_FAIL_INSUFFICIENT_INFO = 413; + /** + * 字段 CODE_FAIL_USER_LOGGED_IN。 + */ 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; + /** + * 字段 CODE_FAIL_REGISTERED_TO_OTHER。 + */ public static final int CODE_FAIL_REGISTERED_TO_OTHER = 416; + /** + * 字段 CODE_FAIL_VERSION_DUPLICATE。 + */ public static final int CODE_FAIL_VERSION_DUPLICATE = 417; + /** + * 字段 CODE_FAIL_USER_NOT_AGREED。 + */ 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; + /** + * 字段 CODE_FAIL_HOST_EXPIRED。 + */ 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; + /** + * 字段 CODE_FAIL_INVALID。 + */ public static final int CODE_FAIL_INVALID = 422; + /** + * 字段 CODE_FAIL_EXISTING_USER。 + */ public static final int CODE_FAIL_EXISTING_USER = 423; + /** + * 字段 CODE_FAIL_EXCEED_LOGIN_FAILURE。 + */ 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; + /** + * 字段 CODE_FAIL_SITE_NOT_FOUND。 + */ 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; + /** + * 字段 CODE_FAIL_SITE_NO_USER。 + */ 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; + /** + * 字段 CODE_FAIL_SITE_SAME。 + */ public static final int CODE_FAIL_SITE_SAME = 455; + /** + * 字段 CODE_FAIL_DEVICE_NO_SERIAL。 + */ 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; + /** + * 字段 CODE_FAIL_NO_DEVICE_EXISTS。 + */ 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; + /** + * 字段 CODE_FAIL_CHILD_EXISTS。 + */ public static final int CODE_FAIL_CHILD_EXISTS = 466; + /** + * 字段 CODE_FAIL_DEVICE_EXISTS。 + */ public static final int CODE_FAIL_DEVICE_EXISTS = 467; + /** + * 字段 CODE_FAIL_LICENSE_EXPIRED。 + */ public static final int CODE_FAIL_LICENSE_EXPIRED = 115; + /** + * 字段 CODE_ERROR_NO_RECORD。 + */ public static final int CODE_ERROR_NO_RECORD = 421; + /** + * 字段 CODE_ERROR_TOKEN_NOT_DEFINED。 + */ public static final int CODE_ERROR_TOKEN_NOT_DEFINED = 461; + /** + * 字段 CODE_ERROR_EXPIRED_TOKEN。 + */ public static final int CODE_ERROR_EXPIRED_TOKEN = 462; + /** + * 字段 CODE_ERROR_INVALID_TOKEN。 + */ public static final int CODE_ERROR_INVALID_TOKEN = 463; + /** + * 字段 CODE_ERROR_URL_FORMAT。 + */ public static final int CODE_ERROR_URL_FORMAT = 431; + /** + * 字段 CODE_ERROR_IO_EXEPTION。 + */ public static final int CODE_ERROR_IO_EXEPTION = 432; + /** + * 字段 CODE_ERROR_NO_PERMISSION。 + */ public static final int CODE_ERROR_NO_PERMISSION = 433; + /** + * 字段 CODE_ERROR_INVALID_SYSTEM_IMAGE。 + */ public static final int CODE_ERROR_INVALID_SYSTEM_IMAGE = 441; + /** + * 字段 CODE_UNKOWN。 + */ public static final int CODE_UNKOWN = -1; + /** + * 字段 MESSAGE_NOT_ALLOWED。 + */ public static final String MESSAGE_NOT_ALLOWED = "Not allowed."; + /** + * 字段 MESSAGE_NOT_AUTHORIZED。 + */ public static final String MESSAGE_NOT_AUTHORIZED = "Not authorized."; + /** + * 字段 MESSAGE_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."; + /** + * 字段 MESSAGE_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."; + /** + * 字段 MESSAGE_NO_SERIAL_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."; + /** + * 字段 MESSAGE_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: "; + /** + * 字段 MESSAGE_NO_RECORDS。 + */ public static final String MESSAGE_NO_RECORDS = "No records."; + /** + * 字段 MESSAGE_NO_REPORTS。 + */ public static final String MESSAGE_NO_REPORTS = "No reports."; + /** + * 字段 MESSAGE_NO_LICENSE。 + */ public static final String MESSAGE_NO_LICENSE = "No license."; + /** + * 字段 MESSAGE_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."; + /** + * 字段 MESSAGE_NO_APP_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."; + /** + * 代码。 + */ private int code; + /** + * 消息。 + */ private String message; + /** + * 数据。 + */ private Object data; + /** + * 字段 reference。 + */ private Object reference; + /** + * 总数分页。 + */ private Integer totalPage; + /** + * 数量。 + */ private Long size; + /** + * 总数数量。 + */ private Long totalSize; + /** + * 构造 {@code MidmResponse} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public MidmResponse() { } + /** + * 构造 {@code MidmResponse} 实例。 + * + * @param code 状态码/业务码({@code int}) + * @param msg 参数 {@code msg}({@code String}) + */ public MidmResponse(int code, String msg) { this.setCode(code); 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) { this.setCode(code); this.setMessage(msg); this.setData(data); } + /** + * 获取 {@code code}。 + * @return 数量/长度 + */ public int getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code int}) + */ public void setCode(int code) { this.code = code; } + /** + * 获取 {@code message}。 + * @return 字符串结果 + */ public String getMessage() { return this.message; } + /** + * 设置 {@code message}。 + * + * @param message 消息内容({@code String}) + */ public void setMessage(String message) { this.message = message; } + /** + * 获取 {@code data}。 + * @return 字段/派生属性 {@code data} 的值 + */ public Object getData() { return this.data; } + /** + * 获取 {@code dataAsDbObject}。 + * + * 实现要点:主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getDataAsDbObject() { Object data = this.getData(); 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) { if (data instanceof UpdateResult) { UpdateResult result = (UpdateResult)data; @@ -175,56 +596,120 @@ public class MidmResponse { } + /** + * 获取 {@code reference}。 + * @return 字段/派生属性 {@code reference} 的值 + */ public Object getReference() { return this.reference; } + /** + * 获取 {@code refereceAsDbObject}。 + * + * 实现要点:主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getRefereceAsDbObject() { Object data = this.getReference(); return data == null ? new DbObject() : new DbObject((Map)data); } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code Object}) + */ public void setReference(Object reference) { this.reference = reference; } + /** + * 获取 {@code totalPage}。 + * @return 数量/长度 + */ public int getTotalPage() { return this.totalPage; } + /** + * 设置 {@code totalPages}。 + * + * @param totalPage 参数 {@code totalPage}({@code int}) + */ public void setTotalPages(int totalPage) { this.totalPage = totalPage; } + /** + * 获取 {@code size}。 + * @return 数量/长度 + */ public long getSize() { return this.size; } + /** + * 设置 {@code size}。 + * + * @param size 每页数量({@code long}) + */ public void setSize(long size) { this.size = size; } + /** + * 获取 {@code totalSize}。 + * @return 数量/长度 + */ public long getTotalSize() { return this.totalSize; } + /** + * 设置 {@code totalSize}。 + * + * @param totalSize 参数 {@code totalSize}({@code long}) + */ public void setTotalSize(long totalSize) { this.totalSize = totalSize; } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return McJsonUtils.toJson(this); } + /** + * 处理转换为Text消息。 + * + * 实现要点:主要调用:new TextMessage。 + * @return 处理结果 + */ public TextMessage toTextMessage() { return new TextMessage(this.toString()); } + /** + * 获取 {@code succeedResponse}。 + * @return 字符串结果 + */ public static String getSucceedResponse() { 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"); if (list != null) { response.setData(list); @@ -234,7 +719,15 @@ public class MidmResponse { 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"); if (page != null) { response.setData(page.getContent()); @@ -246,22 +739,57 @@ public class MidmResponse { return response.toString(); } + /** + * 获取Succeed响应。 + * + * @param data 参数 {@code data}({@code Object}) + * @return 字符串结果 + */ public static String getSucceedResponse(Object data) { return getResponse(200, "succeed", data); } + /** + * 获取 {@code failedResponse}。 + * @return 字符串结果 + */ public static String getFailedResponse() { 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) { 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) { return (new MidmResponse(code, msg, data)).toString(); } + /** + * 获取响应。 + * + * @param object 参数 {@code object}({@code Object}) + * @return 字符串结果 + */ public static String getResponse(Object object) { return McJsonUtils.toJson(object); } diff --git a/src/main/java/com/midm/model/message/package-info.java b/src/main/java/com/midm/model/message/package-info.java new file mode 100644 index 0000000..2d33114 --- /dev/null +++ b/src/main/java/com/midm/model/message/package-info.java @@ -0,0 +1,15 @@ +/** + * WebSocket 报文模型:请求、响应、反馈、参数与错误码。 + * + *

本包主要类型: + *

    + *
  • {@link MIDM_REQUEST}
  • + *
  • {@link MidmPacket}
  • + *
  • {@link MidmQuery}
  • + *
  • {@link MidmResponse}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.message; diff --git a/src/main/java/com/midm/model/news/MessageLog.java b/src/main/java/com/midm/model/news/MessageLog.java index 002c0e0..16ffb70 100644 --- a/src/main/java/com/midm/model/news/MessageLog.java +++ b/src/main/java/com/midm/model/news/MessageLog.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code MessageLog} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code message}(NewsMessage):消息
  • + *
  • {@code reader}(User):字段 reader
  • + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code readDate}(Date):读取日期
  • + *
  • {@code isCheck}(boolean):判断是否检查
  • + *
+ * + * 协作对象:{@code NewsMessage、User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class MessageLog { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 消息;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private NewsMessage message; + /** + * 字段 reader;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private User reader; + /** + * 用户所属站点 UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private UUID siteUuid; + /** + * 读取日期;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date readDate; + /** + * 判断是否检查;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private boolean isCheck; + /** + * 判断是否读取;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private boolean isRead; + /** + * 检查日期;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date checkDate; + /** + * 时间字段;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private Date notified; + /** + * 构造 {@code MessageLog} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { this.uuid = UUID.randomUUID(); this.message = message; @@ -41,6 +124,15 @@ public class MessageLog { 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) { this.uuid = UUID.randomUUID(); this.message = message; @@ -50,74 +142,155 @@ public class MessageLog { this.notified = new Date(); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code message}。 + * @return 字段/派生属性 {@code message} 的值 + */ public NewsMessage getMessage() { return this.message; } + /** + * 设置 {@code message}。 + * + * @param message 消息内容({@code NewsMessage}) + */ public void setMessage(NewsMessage message) { this.message = message; } + /** + * 获取 {@code reader}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getReader() { return this.reader; } + /** + * 设置 {@code reader}。 + * + * @param reader 参数 {@code reader}({@code User}) + */ public void setReader(User reader) { this.reader = reader; } + /** + * 判断 {@code check}。 + * @return 字段/派生属性 {@code check} 的值 + */ public boolean isCheck() { return this.isCheck; } + /** + * 设置 {@code check}。 + * + * @param isCheck 参数 {@code isCheck}({@code boolean}) + */ public void setCheck(boolean isCheck) { this.isCheck = isCheck; } + /** + * 判断 {@code read}。 + * @return 字段/派生属性 {@code read} 的值 + */ public boolean isRead() { return this.isRead; } + /** + * 设置 {@code read}。 + * + * @param isRead 参数 {@code isRead}({@code boolean}) + */ public void setRead(boolean isRead) { this.isRead = isRead; } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code notified}。 + * @return 字段/派生属性 {@code notified} 的值 + */ public Date getNotified() { return this.notified; } + /** + * 设置 {@code notified}。 + * + * @param notified 参数 {@code notified}({@code Date}) + */ public void setNotified(Date notified) { this.notified = notified; } + /** + * 获取 {@code readDate}。 + * @return 字段/派生属性 {@code readDate} 的值 + */ public Date getReadDate() { return this.readDate; } + /** + * 设置 {@code readDate}。 + * + * @param readDate 参数 {@code readDate}({@code Date}) + */ public void setReadDate(Date readDate) { this.readDate = readDate; } + /** + * 获取 {@code checkDate}。 + * @return 字段/派生属性 {@code checkDate} 的值 + */ public Date getCheckDate() { return this.checkDate; } + /** + * 设置 {@code checkDate}。 + * + * @param checkDate 参数 {@code checkDate}({@code Date}) + */ public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } diff --git a/src/main/java/com/midm/model/news/NewsMessage.java b/src/main/java/com/midm/model/news/NewsMessage.java index 4739123..f275ebb 100644 --- a/src/main/java/com/midm/model/news/NewsMessage.java +++ b/src/main/java/com/midm/model/news/NewsMessage.java @@ -18,37 +18,124 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; +import javax.mail.internet.InternetAddress; +/** + * 【MongoDB 文档实体】{@code NewsMessage} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code category}(String):字段 category
  • + *
  • {@code forWhat}(String):用于What
  • + *
  • {@code reference}(DbObject):字段 reference
  • + *
  • {@code message}(DbObject):消息
  • + *
+ * + * 协作对象:{@code User、DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class NewsMessage { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 字段 writer;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private User writer; + /** + * 字段 category。 + */ private String category; + /** + * 用于What。 + */ private String forWhat; + /** + * 字段 reference。 + */ private DbObject reference; + /** + * 消息。 + */ private DbObject message; + /** + * 判断是否Unremovable。 + */ private Boolean isUnremovable; + /** + * 判断是否Enabled。 + */ private Boolean isEnabled; + /** + * 发送调度。 + */ private Date sendSchedule; + /** + * 时间字段。 + */ private Date expiry; + /** + * 发送Now;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private boolean sendNow; + /** + * 创建时间。 + */ private Date created; + /** + * 最后更新时间。 + */ private Date updated; + /** + * 构造 {@code NewsMessage} 实例。 + * + * @param device 设备({@code Device}) + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public NewsMessage(Device device, String category) { this.init(); this.category = "device_" + category; this.reference.put("uuid", device.getUuid()); } + /** + * 构造 {@code NewsMessage} 实例。 + * + * @param device 设备({@code Device}) + */ public NewsMessage(Device device) { this.init(); this.reference.put("uuid", device.getUuid()); } + /** + * 构造 {@code NewsMessage} 实例。 + * + * @param packet WebSocket 报文({@code MidmPacket}) + */ public NewsMessage(MidmPacket packet) { MidmQuery query = packet.getQuery(); this.setUuid(query.getUuid()); @@ -62,16 +149,31 @@ public class NewsMessage { this.getReference().put("query", query.getQuery()); } + /** + * 构造 {@code NewsMessage} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public NewsMessage() { this.init(); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.uuid = UUID.randomUUID(); this.created = new Date(); this.updated = this.created; } + /** + * 获取 {@code message}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage() { if (this.message == null) { this.message = new DbObject(); @@ -80,17 +182,32 @@ public class NewsMessage { return this.message; } + /** + * 获取消息。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage(Locale locale) { return this.getMessage(locale.toLanguageTag()); } + /** + * 获取消息。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、2 个循环;主要调用:new DbObject。 + * + * @param languageTag 参数 {@code languageTag}({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage(String languageTag) { DbObject message = this.getMessage(); DbObject localedMessage = new DbObject(); if (message.get(languageTag) == null) { message.put(languageTag, localedMessage); } 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()); } @@ -109,83 +226,186 @@ public class NewsMessage { return localedMessage; } + /** + * 设置 {@code message}。 + * + * @param message 消息内容({@code DbObject}) + */ public void setMessage(DbObject message) { this.message = message; } + /** + * 设置消息。 + * + * @param title 参数 {@code title}({@code String}) + * @param content 参数 {@code content}({@code String}) + */ public void setMessage(String title, String content) { this.setTitle(title); this.setContent(content); } + /** + * 获取 {@code title}。 + * @return 字符串结果 + */ public String getTitle() { return this.getMessage("en-US").getString("title"); } + /** + * 获取 {@code summary}。 + * @return 字符串结果 + */ public String getSummary() { return this.getMessage().getString("summary"); } + /** + * 判断 {@code content}。 + * @return 字段/派生属性 {@code content} 的值 + */ public boolean hasContent() { return this.getMessage().containsKey("content"); } + /** + * 获取 {@code content}。 + * @return 字符串结果 + */ public String getContent() { return this.getMessage("en-US").getString("content"); } + /** + * 获取Title。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getTitle(String locale) { return this.getMessage(locale).getString("title"); } + /** + * 获取Summary。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getSummary(String locale) { return this.getMessage(locale).getString("summary"); } + /** + * 判断是否Content。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字段/派生属性 {@code content} 的值 + */ public boolean hasContent(String locale) { return this.getMessage(locale).containsKey("content"); } + /** + * 获取Content。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getContent(String locale) { return this.getMessage(locale).getString("content"); } - public List getMailsTo() { + /** + * 获取 {@code mailsTo}。 + * @return InternetAddress列表,可能为空 + */ + public List getMailsTo() { 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) { 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) { this.setTitle(languageTag, title); this.setContent(languageTag, content); this.setSummary(languageTag, summary); } + /** + * 设置 {@code title}。 + * + * @param title 参数 {@code title}({@code String}) + */ public void setTitle(String title) { this.setTitle(Locale.US.toLanguageTag(), title); } + /** + * 设置 {@code content}。 + * + * @param content 参数 {@code content}({@code String}) + */ public void setContent(String content) { this.setContent(Locale.US.toLanguageTag(), content); } + /** + * 设置 {@code summary}。 + * + * @param summary 参数 {@code summary}({@code String}) + */ public void setSummary(String 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) { DbObject message = this.getMessage(languageTag); message.put("title", title); } + /** + * 设置Content。 + * + * @param languageTag 参数 {@code languageTag}({@code String}) + * @param content 参数 {@code content}({@code String}) + */ public void setContent(String languageTag, String content) { DbObject message = this.getMessage(languageTag); message.put("content", content); } + /** + * 获取 {@code reference}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReference() { if (this.reference == null) { this.reference = new DbObject(); @@ -194,111 +414,240 @@ public class NewsMessage { return this.reference; } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code DbObject}) + */ public void setReference(DbObject reference) { this.reference = reference; } + /** + * 设置Summary。 + * + * @param languageTag 参数 {@code languageTag}({@code String}) + * @param summary 参数 {@code summary}({@code String}) + */ public void setSummary(String languageTag, String summary) { DbObject message = this.getMessage(languageTag); message.put("summary", summary); } + /** + * 判断 {@code unremovable}。 + * @return 字段/派生属性 {@code unremovable} 的值 + */ public Boolean isUnremovable() { return this.isUnremovable; } + /** + * 设置 {@code isUnremovable}。 + * + * @param isUnremovable 参数 {@code isUnremovable}({@code Boolean}) + */ public void setIsUnremovable(Boolean isUnremovable) { this.isUnremovable = isUnremovable; } + /** + * 获取 {@code forWhat}。 + * @return 字符串结果 + */ public String getForWhat() { return this.forWhat; } + /** + * 设置 {@code forWhat}。 + * + * @param forWhat 参数 {@code forWhat}({@code String}) + */ public void setForWhat(String forWhat) { this.forWhat = forWhat; } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param writer 参数 {@code writer}({@code User}) + */ public void setWriter(User writer) { this.writer = writer; } + /** + * 获取 {@code category}。 + * @return 字符串结果 + */ public String getCategory() { return this.category; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } + /** + * 获取 {@code sendSchedule}。 + * @return 字段/派生属性 {@code sendSchedule} 的值 + */ public Date getSendSchedule() { return this.sendSchedule; } + /** + * 设置 {@code sendSchedule}。 + * + * @param sendSchedule 参数 {@code sendSchedule}({@code Date}) + */ public void setSendSchedule(Date sendSchedule) { this.sendSchedule = sendSchedule; } + /** + * 发送Now。 + * + * 实现要点:主要调用:new DateTime。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean sendNow() { return this.sendNow || this.sendSchedule == null || McDateTimeUtils.isSameDate(new DateTime(this.sendSchedule), DateTime.now()); } + /** + * 获取 {@code expiry}。 + * @return 字段/派生属性 {@code expiry} 的值 + */ public Date getExpiry() { return this.expiry; } + /** + * 设置 {@code expiry}。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + */ public void setExpiry(Date expiry) { this.expiry = expiry; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } + /** + * 获取 {@code isUnremovable}。 + * @return 字段/派生属性 {@code isUnremovable} 的值 + */ public Boolean getIsUnremovable() { return this.isUnremovable; } + /** + * 判断 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public Boolean isEnabled() { return this.isEnabled; } + /** + * 设置 {@code isEnabled}。 + * + * @param isEnabled 参数 {@code isEnabled}({@code Boolean}) + */ public void setIsEnabled(Boolean isEnabled) { this.isEnabled = isEnabled; } + /** + * 判断 {@code sendNow}。 + * @return 字段/派生属性 {@code sendNow} 的值 + */ public boolean isSendNow() { return this.sendNow; } + /** + * 设置 {@code sendNow}。 + * + * @param sendNow 参数 {@code sendNow}({@code boolean}) + */ public void setSendNow(boolean 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) { DateTime dateTime = new DateTime(dateString); return McDateTimeUtils.toString(dateTime, format); diff --git a/src/main/java/com/midm/model/news/package-info.java b/src/main/java/com/midm/model/news/package-info.java new file mode 100644 index 0000000..ab5f57d --- /dev/null +++ b/src/main/java/com/midm/model/news/package-info.java @@ -0,0 +1,13 @@ +/** + * 新闻/通知消息模型。 + * + *

本包主要类型: + *

    + *
  • {@link MessageLog}
  • + *
  • {@link NewsMessage}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.news; diff --git a/src/main/java/com/midm/model/org/Site.java b/src/main/java/com/midm/model/org/Site.java index 219b352..d2a5798 100644 --- a/src/main/java/com/midm/model/org/Site.java +++ b/src/main/java/com/midm/model/org/Site.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code Site} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code MODEL_MIDM}(String):字段 MODEL_MIDM
  • + *
  • {@code MODEL_MUST}(String):字段 MODEL_MUST
  • + *
  • {@code reseller}(Site):字段 reseller
  • + *
  • {@code idName}(String):ID名称
  • + *
  • {@code latestVisit}(Date):最新Visit
  • + *
  • {@code report}(DbObject):报表
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class Site extends GeneralProfile { + /** + * 字段 MODEL_MIDM。 + */ public static final String MODEL_MIDM = "midm"; + /** + * 字段 MODEL_MUST。 + */ public static final String MODEL_MUST = "must"; + /** + * 字段 reseller;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site reseller; + /** + * ID名称;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed(unique = true)}。 + */ @Indexed( unique = true ) private String idName; + /** + * 最新Visit;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Date latestVisit; + /** + * 报表;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DbObject report; + /** + * 构造 {@code Site} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Site() { this.setEnabled(false); } + /** + * 构造 {@code Site} 实例。 + * + * @param model 参数 {@code model}({@code String}) + */ public Site(String model) { this(); this.setModel(model); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new DbObject、new Date。 + */ public void init() { this.setUuid(UUID.randomUUID()); DbObject notiSettings = new DbObject("sendEmail", true); @@ -49,57 +114,115 @@ public class Site extends GeneralProfile { this.setCreated(new Date()); } + /** + * 获取 {@code reseller}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getReseller() { return this.reseller; } + /** + * 设置 {@code reseller}。 + * + * @param reseller 参数 {@code reseller}({@code Site}) + */ public void setReseller(Site reseller) { this.reseller = reseller; } + /** + * 判断 {@code child}。 + * @return 字段/派生属性 {@code child} 的值 + */ public boolean isChild() { return this.reseller != null; } + /** + * 判断 {@code customize}。 + * @return 字段/派生属性 {@code customize} 的值 + */ public boolean canCustomize() { return true; } + /** + * 获取 {@code domainName}。 + * @return 字段/派生属性 {@code domainName} 的值 + */ public Object getDomainName() { return this.getSetting("domainName"); } + /** + * 获取 {@code idName}。 + * @return 字符串结果 + */ public String getIdName() { return this.idName; } + /** + * 设置 {@code idName}。 + * + * @param idName 参数 {@code idName}({@code String}) + */ public void setIdName(String idName) { this.idName = idName; } + /** + * 获取 {@code title}。 + * @return 字符串结果 + */ public String getTitle() { String siteName = (String)this.getSetting("theme", "siteName"); return Strings.isNullOrEmpty(siteName) ? this.getName() : siteName; } + /** + * 判断 {@code logo}。 + * @return 字段/派生属性 {@code logo} 的值 + */ public boolean hasLogo() { return this.getSettingAsBoolean("theme", "logo", false); } + /** + * 获取 {@code plan}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getPlan() { return this.getProfileCategory(new String[]{"plan"}); } + /** + * 获取 {@code planName}。 + * @return 字符串结果 + */ public String getPlanName() { DbObject plan = this.getPlan(); return plan.getString("plan", "standard"); } + /** + * 获取 {@code showPlanName}。 + * @return 字符串结果 + */ public String getShowPlanName() { String planName = this.getPlanName(); return this.getShowPlanName(planName); } + /** + * 获取Show计划名称。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param planName 参数 {@code planName}({@code String}) + * @return 字符串结果 + */ public String getShowPlanName(String planName) { String name = ""; if (planName.equals("lite")) { @@ -113,10 +236,22 @@ public class Site extends GeneralProfile { return name; } + /** + * 设置 {@code plan}。 + * + * @param plan 参数 {@code plan}({@code DbObject}) + */ public void setPlan(DbObject plan) { this.setProfile("plan", plan); } + /** + * 设置 {@code plan}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:remove。 + * + * @param plan 参数 {@code plan}({@code String}) + */ public void setPlan(String plan) { if (!Strings.isNullOrEmpty(plan)) { this.setProfile("plan", "plan", plan); @@ -129,64 +264,133 @@ public class Site extends GeneralProfile { } } + /** + * 获取 {@code upgradeStatus}。 + * @return 字符串结果 + */ public String getUpgradeStatus() { DbObject plan = this.getPlan(); return plan.getString("upgradeStatus"); } + /** + * 判断 {@code upgradeRequested}。 + * @return 字段/派生属性 {@code upgradeRequested} 的值 + */ public boolean isUpgradeRequested() { return "processing".equals(this.getUpgradeStatus()); } + /** + * 获取 {@code upgradeTargetPlan}。 + * @return 字符串结果 + */ public String getUpgradeTargetPlan() { DbObject plan = this.getPlan(); return plan.getString("targetPlan"); } + /** + * 获取 {@code model}。 + * @return 字符串结果 + */ public String getModel() { return (String)this.getProfile("model", "midm"); } + /** + * 设置 {@code model}。 + * + * @param model 参数 {@code model}({@code String}) + */ public void setModel(String model) { this.setProfile("model", model); } + /** + * 获取 {@code phone}。 + * @return 字符串结果 + */ public String getPhone() { return (String)this.getProfile("phone"); } + /** + * 获取 {@code address}。 + * @return 字符串结果 + */ public String getAddress() { return (String)this.getProfile("address"); } + /** + * 获取 {@code country}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字符串结果 + */ public String getCountry() { return (String)this.getProfile("country"); } + /** + * 判断 {@code reseller}。 + * @return 字段/派生属性 {@code reseller} 的值 + */ public boolean isReseller() { return (Boolean)this.getProfile("isReseller", false); } + /** + * 设置 {@code isReseller}。 + * + * @param isReseller 参数 {@code isReseller}({@code boolean}) + */ public void setIsReseller(boolean isReseller) { this.setProfile("isReseller", isReseller); } + /** + * 处理limitRegistered设备Only。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean limitRegisteredDeviceOnly() { return this.getSettingAsBoolean("enrollment", "registeredOnly", false); } + /** + * 获取 {@code latestVisit}。 + * @return 字段/派生属性 {@code latestVisit} 的值 + */ public Date getLatestVisit() { return this.latestVisit; } + /** + * 设置 {@code latestVisit}。 + * + * @param latestVisit 参数 {@code latestVisit}({@code Date}) + */ public void setLatestVisit(Date latestVisit) { this.latestVisit = latestVisit; } + /** + * 获取 {@code credential}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getCredential() { 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) { if (Strings.isNullOrEmpty(credential)) { 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) { if (!Strings.isNullOrEmpty(credential)) { DbObject value = new DbObject("credential", credential); @@ -213,11 +424,20 @@ public class Site extends GeneralProfile { } + /** + * 处理renewCredential。 + */ public void renewCredential() { String credential = McUuidUtils.toBase64String(UUID.randomUUID(), true); this.setCredential(credential); } + /** + * 获取 {@code settings}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getSettings() { DbObject settings = super.getSettings(); if (settings.get("theme") == null) { @@ -230,6 +450,12 @@ public class Site extends GeneralProfile { return settings; } + /** + * 获取 {@code report}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReport() { if (this.report == null) { this.report = new DbObject(); @@ -238,14 +464,33 @@ public class Site extends GeneralProfile { return this.report; } + /** + * 设置 {@code report}。 + * + * @param report 参数 {@code report}({@code DbObject}) + */ public void setReport(DbObject report) { this.report = report; } + /** + * 添加报表。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void addReport(String key, Object value) { this.getReport().put(key, value); } + /** + * 比较当前对象与另一个对象是否相等。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param obj 参数 {@code obj}({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean equals(Object obj) { if (obj.hashCode() == this.hashCode()) { return true; @@ -260,63 +505,139 @@ public class Site extends GeneralProfile { } } + /** + * 判断 {@code lite}。 + * @return 字段/派生属性 {@code lite} 的值 + */ public boolean isLite() { return this.getPlanName().equals("lite"); } + /** + * 判断 {@code standard}。 + * @return 字段/派生属性 {@code standard} 的值 + */ public boolean isStandard() { return this.getPlanName().equals("standard"); } + /** + * 判断 {@code standardWithBatteryPro}。 + * @return 字段/派生属性 {@code standardWithBatteryPro} 的值 + */ public boolean isStandardWithBatteryPro() { return this.getPlanName().equals("standardWithBatteryPro"); } + /** + * 判断 {@code must}。 + * @return 字段/派生属性 {@code must} 的值 + */ public boolean isMust() { return this.getModel().equals("must"); } + /** + * 设置 {@code must}。 + * + * @param isMust 参数 {@code isMust}({@code boolean}) + */ public void setMust(boolean isMust) { 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) { return !this.isLite() ? true : this.getProfileAsBoolean("plan", "features", subCategory, item, false); } + /** + * 获取 {@code notificationSettings}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getNotificationSettings() { return this.getSettingsCategory(new String[]{"noti"}); } + /** + * 通知Via邮件。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyViaMail() { return this.getNotificationSettings().getBoolean("sendEmail", false); } + /** + * 设置 {@code notifyViaMail}。 + * + * @param viaMail 参数 {@code viaMail}({@code boolean}) + */ public void setNotifyViaMail(boolean viaMail) { this.getNotificationSettings().put("sendEmail", viaMail); } + /** + * 通知设备错误邮件。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyDeviceErrorMail() { return this.getNotificationSettings().getBoolean("sendDeviceErrorEmail", false); } + /** + * 设置 {@code notifyDeviceErrorMail}。 + * + * @param enable 参数 {@code enable}({@code boolean}) + */ public void setNotifyDeviceErrorMail(boolean enable) { this.getNotificationSettings().put("sendDeviceErrorEmail", enable); } + /** + * 通知电池Condition邮件。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyBatteryConditionMail() { return this.getNotificationSettings().getBoolean("sendBatteryConditionEmail", false); } + /** + * 设置 {@code notifyBatteryConditionMail}。 + * + * @param enable 参数 {@code enable}({@code boolean}) + */ public void setNotifyBatteryConditionMail(boolean 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) { 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}) + */ + public void setNotificationSettings(String category, String forWhat, boolean isEnabled, Set roles) { DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); settings.put("isEnabled", isEnabled); 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) { DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); settings.put(key, value); } + /** + * 获取 {@code dataUsage}。 + * @return 字符串结果 + */ public String getDataUsage() { return this.getSettingsCategory(new String[]{"report"}).getString("dataUsage", "none"); } + /** + * 处理collect数据用量。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean collectDataUsage() { 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 getMessageRoles(String category, String forWhat) { DbObject settings = this.getSettingsCategory(new String[]{"noti", category, forWhat}); if (settings.getBoolean("enabled")) { Object value = settings.get("roles"); @@ -355,28 +701,53 @@ public class Site extends GeneralProfile { } } + /** + * 判断 {@code timeZone}。 + * @return 字段/派生属性 {@code timeZone} 的值 + */ public boolean hasTimeZone() { return this.getSetting("general", "timeZone") != null; } + /** + * 设置 {@code timeZone}。 + * + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + */ public void setTimeZone(TimeZone timeZone) { this.setSetting("general", "timeZone", timeZone.getID()); } + /** + * 获取 {@code timeZone}。 + * @return 字段/派生属性 {@code timeZone} 的值 + */ public TimeZone getTimeZone() { Object timeZone = this.getSetting("general", "timeZone"); return timeZone != null ? TimeZone.getTimeZone((String)timeZone) : TimeZone.getDefault(); } + /** + * 获取 {@code includeApps}。 + * @return 字段/派生属性 {@code includeApps} 的值 + */ public String[] getIncludeApps() { String installApps = this.getSettingsCategory(new String[]{"report"}).getString("installApps"); return Strings.isNullOrEmpty(installApps) ? null : installApps.split("[,;\\s]+"); } + /** + * 获取 {@code callbackSetting}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getCallbackSetting() { return this.getSettingsCategory(new String[]{"callback"}); } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return String.format("%s(%s):%s", this.getName(), this.getIdName(), this.getUuid()); } diff --git a/src/main/java/com/midm/model/org/SiteFile.java b/src/main/java/com/midm/model/org/SiteFile.java index d864d4f..d2e289c 100644 --- a/src/main/java/com/midm/model/org/SiteFile.java +++ b/src/main/java/com/midm/model/org/SiteFile.java @@ -7,69 +7,179 @@ import java.util.UUID; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code SiteFile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code category}(String):字段 category
  • + *
  • {@code forWhat}(String):用于What
  • + *
  • {@code requested}(Date):时间字段
  • + *
  • {@code expiry}(Date):时间字段
  • + *
  • {@code siteName}(String):站点名称
  • + *
  • {@code requestedFrom}(User):requested从
  • + *
+ * + * 协作对象:{@code User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class SiteFile extends BaseFile { + /** + * 字段 category。 + */ private String category; + /** + * 用于What。 + */ private String forWhat; + /** + * 时间字段。 + */ private Date requested; + /** + * 时间字段。 + */ private Date expiry; + /** + * 站点名称。 + */ private String siteName; + /** + * requested从;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private User requestedFrom; + /** + * 构造 {@code SiteFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { this.setUserUuid(requestedFrom); this.setFileUuid(fileUuid); this.setFileInfo(file); } + /** + * 获取 {@code category}。 + * @return 字符串结果 + */ public String getCategory() { return this.category; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } + /** + * 获取 {@code requestedFrom}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getRequestedFrom() { return this.requestedFrom; } + /** + * 设置 {@code requestedFrom}。 + * + * @param requestedFrom 参数 {@code requestedFrom}({@code User}) + */ public void setRequestedFrom(User requestedFrom) { this.requestedFrom = requestedFrom; } + /** + * 获取 {@code requested}。 + * @return 字段/派生属性 {@code requested} 的值 + */ public Date getRequested() { return this.requested; } + /** + * 设置 {@code requested}。 + * + * @param requested 参数 {@code requested}({@code Date}) + */ public void setRequested(Date requested) { this.requested = requested; } + /** + * 获取 {@code expiry}。 + * @return 字段/派生属性 {@code expiry} 的值 + */ public Date getExpiry() { return this.expiry; } + /** + * 设置 {@code expiry}。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + */ public void setExpiry(Date expiry) { this.expiry = expiry; } + /** + * 获取 {@code siteName}。 + * @return 字符串结果 + */ public String getSiteName() { return this.siteName; } + /** + * 设置 {@code siteName}。 + * + * @param siteName 参数 {@code siteName}({@code String}) + */ public void setSiteName(String siteName) { this.siteName = siteName; } + /** + * 获取 {@code forWhat}。 + * @return 字符串结果 + */ public String getForWhat() { return this.forWhat; } + /** + * 设置 {@code forWhat}。 + * + * @param forWhat 参数 {@code forWhat}({@code String}) + */ public void setForWhat(String forWhat) { this.forWhat = forWhat; } diff --git a/src/main/java/com/midm/model/org/SiteInfo.java b/src/main/java/com/midm/model/org/SiteInfo.java index 63996e2..49cb663 100644 --- a/src/main/java/com/midm/model/org/SiteInfo.java +++ b/src/main/java/com/midm/model/org/SiteInfo.java @@ -9,17 +9,72 @@ import java.util.Set; import java.util.UUID; import org.springframework.data.mongodb.core.index.Indexed; +/** + * 【领域模型】{@code SiteInfo} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code roles}(Set):String集合
  • + *
  • {@code groupUuid}(UUID):分组UUID
  • + *
  • {@code settings}(DbObject):设置列表
  • + *
  • {@code apiOnly}(Boolean):APIOnly
  • + *
  • {@code created}(Date):创建时间
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class SiteInfo { + /** + * 用户所属站点 UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private UUID siteUuid; - private Set roles; + /** + * String集合。 + */ + private Set roles; + /** + * 分组UUID。 + */ private UUID groupUuid; + /** + * 设置列表。 + */ protected DbObject settings; + /** + * APIOnly。 + */ private Boolean apiOnly; + /** + * 创建时间。 + */ private Date created; + /** + * 最后更新时间。 + */ private Date updated; + /** + * 是否启用。 + */ private boolean enabled; + /** + * 构造 {@code SiteInfo} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new HashSet、new Date。 + */ public SiteInfo() { this.setRoles(new HashSet()); this.setCreated(new Date()); @@ -27,20 +82,40 @@ public class SiteInfo { this.setEnabled(false); } + /** + * 构造 {@code SiteInfo} 实例。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public SiteInfo(UUID siteUuid) { this(); this.setSiteUuid(siteUuid); } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } - public Set getRoles() { + /** + * 获取 {@code roles}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。 + * @return String列表,可能为空 + */ + public Set getRoles() { if (this.roles == null) { this.roles = new HashSet(); } @@ -48,10 +123,24 @@ public class SiteInfo { return this.roles; } + /** + * 判断是否Role。 + * + * @param role 参数 {@code role}({@code String}) + * @return 字段/派生属性 {@code role} 的值 + */ public boolean hasRole(String role) { return this.isEnabled() && !this.getRoles().isEmpty() && this.getRoles().contains(role); } + /** + * 判断是否Role。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param roles 参数 {@code roles}({@code Collection}) + * @return 字段/派生属性 {@code role} 的值 + */ public boolean hasRole(Collection roles) { if (this.isEnabled() && !this.getRoles().isEmpty()) { for(String role : roles) { @@ -64,6 +153,13 @@ public class SiteInfo { return false; } + /** + * 添加Role。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param role 参数 {@code role}({@code String}) + */ public void addRole(String role) { role = UserRole.toRole(role); if (!Strings.isNullOrEmpty(role)) { @@ -72,6 +168,13 @@ public class SiteInfo { } + /** + * 设置 {@code roles}。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param roles 参数 {@code roles}({@code Set}) + */ public void setRoles(Set roles) { if (roles != null && !roles.isEmpty()) { for(String role : roles) { @@ -91,26 +194,53 @@ public class SiteInfo { } + /** + * 清理Roles。 + */ public void clearRoles() { this.getRoles().clear(); } + /** + * 获取 {@code groupUuid}。 + * @return UUID + */ public UUID getGroupUuid() { return this.groupUuid; } + /** + * 设置 {@code groupUuid}。 + * + * @param groupUuid 分组 UUID({@code UUID}) + */ public void setGroupUuid(UUID groupUuid) { this.groupUuid = groupUuid; } + /** + * 判断 {@code apiOnly}。 + * @return 字段/派生属性 {@code apiOnly} 的值 + */ public boolean isApiOnly() { return this.apiOnly != null && this.apiOnly; } + /** + * 设置 {@code apiOnly}。 + * + * @param apiOnly 参数 {@code apiOnly}({@code boolean}) + */ public void setApiOnly(boolean apiOnly) { this.apiOnly = apiOnly; } + /** + * 获取 {@code settings}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getSettings() { if (this.settings == null) { this.settings = new DbObject(); @@ -119,50 +249,113 @@ public class SiteInfo { return this.settings; } + /** + * 设置 {@code settings}。 + * + * @param settings 参数 {@code settings}({@code DbObject}) + */ public void setSettings(DbObject settings) { this.settings = settings; } + /** + * 设置设置。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setSetting(String key, Object value) { this.getSettings().put(key, value); } + /** + * 获取设置。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code setting} 的值 + */ public Object getSetting(String key) { return this.getSettings().get(key); } + /** + * 获取设置AsString。 + * + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ public String getSettingAsString(String key) { return this.getSettings().getString(key, (String)null); } + /** + * 获取分页设置。 + * + * @param url 参数 {@code url}({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getPageSetting(String 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) { this.getPageSetting(url).put(key, value); } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } + /** + * 判断 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public boolean isEnabled() { return this.enabled; } + /** + * 设置 {@code enabled}。 + * + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void setEnabled(boolean enabled) { this.enabled = enabled; } diff --git a/src/main/java/com/midm/model/org/SiteLicense.java b/src/main/java/com/midm/model/org/SiteLicense.java index 69822f6..63077a0 100644 --- a/src/main/java/com/midm/model/org/SiteLicense.java +++ b/src/main/java/com/midm/model/org/SiteLicense.java @@ -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.Document; +/** + * 【MongoDB 文档实体】{@code SiteLicense} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code site}(Site):站点
  • + *
  • {@code childSite}(Site):子站点
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code licenseModel}(LicenseModel):许可证模型
  • + *
  • {@code amount}(int):字段 amount
  • + *
+ * + * 协作对象:{@code Site、User、LicenseModel、DbObject、STATUS}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class SiteLicense { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 站点;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site site; + /** + * 子站点;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site childSite; + /** + * 字段 writer;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private User writer; + /** + * 许可证模型;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private LicenseModel licenseModel; + /** + * 字段 amount。 + */ private int amount; + /** + * 字段 reference。 + */ private DbObject reference; + /** + * 计划。 + */ private String plan; + /** + * 报表;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DbObject report; + /** + * 状态。 + */ private STATUS status; + /** + * 是否启用。 + */ private boolean enabled; + /** + * 最后更新时间。 + */ private Date updated; + /** + * 创建时间。 + */ private Date created; + /** + * 构造 {@code SiteLicense} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new Date。 + */ public SiteLicense() { this.plan = "standard"; this.status = SiteLicense.STATUS.UNKNOWN; @@ -42,23 +124,48 @@ public class SiteLicense { this.setCreated(new Date()); } + /** + * 构造 {@code SiteLicense} 实例。 + * + * @param site 站点/企业({@code Site}) + */ public SiteLicense(Site site) { this(); this.setSite(site); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code site}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getSite() { return this.site; } + /** + * 设置 {@code site}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + */ public void setSite(Site site) { if (site.isChild()) { this.site = site.getReseller(); @@ -69,42 +176,88 @@ public class SiteLicense { } + /** + * 获取 {@code childSite}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getChildSite() { return this.childSite; } + /** + * 判断 {@code forChildSite}。 + * @return 字段/派生属性 {@code forChildSite} 的值 + */ public boolean isForChildSite() { return this.childSite != null; } + /** + * 设置 {@code childSite}。 + * + * @param reseller 参数 {@code reseller}({@code Site}) + */ public void setChildSite(Site reseller) { this.childSite = reseller; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param user 当前用户({@code User}) + */ public void setWriter(User user) { this.writer = user; } + /** + * 获取 {@code plan}。 + * @return 字符串结果 + */ public String getPlan() { return this.plan; } + /** + * 设置 {@code plan}。 + * + * @param plan 参数 {@code plan}({@code String}) + */ public void setPlan(String plan) { this.plan = plan; } + /** + * 判断 {@code lite}。 + * @return 字段/派生属性 {@code lite} 的值 + */ public boolean isLite() { return "lite".equals(this.getPlan()); } + /** + * 获取 {@code licenseModel}。 + * @return 字段/派生属性 {@code licenseModel} 的值 + */ public LicenseModel getLicenseModel() { return this.licenseModel; } + /** + * 设置 {@code licenseModel}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param licenseModel 参数 {@code licenseModel}({@code LicenseModel}) + */ public void setLicenseModel(LicenseModel licenseModel) { if (this.isUpdated() && !this.licenseModel.getUuid().equals(licenseModel.getUuid())) { this.addNote("License model changed: " + licenseModel.getName()); @@ -113,18 +266,37 @@ public class SiteLicense { this.licenseModel = licenseModel; } + /** + * 获取 {@code type}。 + * @return 字段/派生属性 {@code type} 的值 + */ public Character getType() { return this.licenseModel.getType(); } + /** + * 获取 {@code period}。 + * @return 数量/长度 + */ public Integer getPeriod() { return this.licenseModel.getPeriod(); } + /** + * 获取 {@code amount}。 + * @return 数量/长度 + */ public int getAmount() { return this.amount; } + /** + * 设置 {@code amount}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param amount 参数 {@code amount}({@code int}) + */ public void setAmount(int amount) { if (this.isUpdated() && this.amount != amount) { this.addNote("Amount changed: " + amount); @@ -133,6 +305,12 @@ public class SiteLicense { this.amount = amount; } + /** + * 获取 {@code reference}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReference() { if (this.reference == null) { this.reference = new DbObject(); @@ -141,14 +319,30 @@ public class SiteLicense { return this.reference; } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code DbObject}) + */ public void setReference(DbObject reference) { this.reference = reference; } + /** + * 获取 {@code po}。 + * @return 字符串结果 + */ public String getPo() { return this.getReference().getString("po", ""); } + /** + * 设置 {@code po}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param po 参数 {@code po}({@code String}) + */ public void setPo(String po) { if (this.isUpdated() && !this.getPo().equals(po)) { this.addNote(Strings.isNullOrEmpty(po) ? "PO has unset" : "PO changed: " + po); @@ -157,18 +351,38 @@ public class SiteLicense { this.getReference().put("po", po); } + /** + * 获取 {@code desc}。 + * @return 字符串结果 + */ public String getDesc() { return this.getReference().getString("desc", ""); } + /** + * 设置 {@code desc}。 + * + * @param desc 参数 {@code desc}({@code String}) + */ public void setDesc(String desc) { this.getReference().put("desc", desc); } - public List getNotes() { + /** + * 获取 {@code notes}。 + * @return 数据库Object列表,可能为空 + */ + public List getNotes() { return this.getReference().getList("notes", DbObject.class); } + /** + * 添加备注。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param status 状态({@code STATUS}) + */ public void addNote(STATUS status) { if (this.isUpdated()) { 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) { DbObject noteObj = new DbObject("name", this.writer.getName()); noteObj.append("email", this.writer.getEmail()).append("note", note).append("updated", this.updated); @@ -190,39 +411,81 @@ public class SiteLicense { notes.add(noteObj); } + /** + * 获取 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public boolean getEnabled() { return this.enabled; } + /** + * 设置 {@code enabled}。 + * + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void setEnabled(boolean enabled) { this.enabled = enabled; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } + /** + * 判断 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ private boolean isUpdated() { return !this.created.equals(this.updated); } + /** + * 处理updated。 + * + * 实现要点:主要调用:new Date。 + */ public void updated() { this.updated = new Date(); } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; this.updated = created; } + /** + * 获取 {@code report}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReport() { if (this.report == null) { this.report = new DbObject(); @@ -231,31 +494,74 @@ public class SiteLicense { return this.report; } + /** + * 设置 {@code report}。 + * + * @param report 参数 {@code report}({@code DbObject}) + */ public void setReport(DbObject report) { this.report = report; } + /** + * 设置报表。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setReport(String key, Object value) { this.getReport().put(key, value); } + /** + * 判断 {@code trial}。 + * @return 字段/派生属性 {@code trial} 的值 + */ public boolean isTrial() { return this.getLicenseModel().isTrial(); } + /** + * 判断 {@code perpetual}。 + * @return 字段/派生属性 {@code perpetual} 的值 + */ public boolean isPerpetual() { return this.getLicenseModel().isPerpetual(); } + /** + * 获取 {@code status}。 + * @return 字段/派生属性 {@code status} 的值 + */ public STATUS getStatus() { return this.status; } + /** + * 设置 {@code status}。 + * + * @param status 状态({@code STATUS}) + */ public void setStatus(STATUS status) { this.addNote(status); this.status = status; } + /** + * 【枚举常量】{@code STATUS} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public static enum STATUS { ORDERED, PROCESSING, diff --git a/src/main/java/com/midm/model/org/SitePlan.java b/src/main/java/com/midm/model/org/SitePlan.java index fc9e310..3975fc9 100644 --- a/src/main/java/com/midm/model/org/SitePlan.java +++ b/src/main/java/com/midm/model/org/SitePlan.java @@ -5,42 +5,115 @@ import java.util.UUID; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code SitePlan} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code model}(String):模型
  • + *
  • {@code plan}(DbObject):计划
  • + *
  • {@code isReseller}(boolean):判断是否Reseller
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class SitePlan { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 模型。 + */ private String model = "midm"; + /** + * 计划。 + */ private DbObject plan; + /** + * 判断是否Reseller。 + */ private boolean isReseller = false; + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code model}。 + * @return 字符串结果 + */ public String getModel() { return this.model; } + /** + * 设置 {@code model}。 + * + * @param model 参数 {@code model}({@code String}) + */ public void setModel(String model) { this.model = model; } + /** + * 获取 {@code plan}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getPlan() { return this.plan; } + /** + * 设置 {@code plan}。 + * + * @param plan 参数 {@code plan}({@code DbObject}) + */ public void setPlan(DbObject plan) { this.plan = plan; } + /** + * 判断 {@code reseller}。 + * @return 字段/派生属性 {@code reseller} 的值 + */ public boolean isReseller() { return this.isReseller; } + /** + * 设置 {@code reseller}。 + * + * @param isReseller 参数 {@code isReseller}({@code boolean}) + */ public void setReseller(boolean isReseller) { this.isReseller = isReseller; } diff --git a/src/main/java/com/midm/model/org/SiteRequest.java b/src/main/java/com/midm/model/org/SiteRequest.java index f9cd725..22f422f 100644 --- a/src/main/java/com/midm/model/org/SiteRequest.java +++ b/src/main/java/com/midm/model/org/SiteRequest.java @@ -5,87 +5,228 @@ import java.util.UUID; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code SiteRequest} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code name}(String):名称
  • + *
  • {@code email}(String):用户邮箱(登录名,建立索引)
  • + *
  • {@code company}(String):字段 company
  • + *
  • {@code title}(String):字段 title
  • + *
  • {@code phone}(String):字段 phone
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class SiteRequest { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 名称。 + */ private String name; + /** + * 用户邮箱(登录名,建立索引)。 + */ private String email; + /** + * 字段 company。 + */ private String company; + /** + * 字段 title。 + */ private String title; + /** + * 字段 phone。 + */ private String phone; + /** + * 字段 country。 + */ private String country; + /** + * 字段 industry。 + */ private String industry; + /** + * 时间字段。 + */ private Date requestedAt; + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code email}。 + * @return 字符串结果 + */ public String getEmail() { return this.email; } + /** + * 设置 {@code email}。 + * + * @param email 邮箱({@code String}) + */ public void setEmail(String email) { this.email = email; } + /** + * 获取 {@code company}。 + * @return 字符串结果 + */ public String getCompany() { return this.company; } + /** + * 设置 {@code company}。 + * + * @param company 参数 {@code company}({@code String}) + */ public void setCompany(String company) { this.company = company; } + /** + * 获取 {@code title}。 + * @return 字符串结果 + */ public String getTitle() { return this.title; } + /** + * 设置 {@code title}。 + * + * @param title 参数 {@code title}({@code String}) + */ public void setTitle(String title) { this.title = title; } + /** + * 获取 {@code phone}。 + * @return 字符串结果 + */ public String getPhone() { return this.phone; } + /** + * 设置 {@code phone}。 + * + * @param phone 参数 {@code phone}({@code String}) + */ public void setPhone(String phone) { this.phone = phone; } + /** + * 获取 {@code country}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字符串结果 + */ public String getCountry() { return this.country; } + /** + * 设置 {@code country}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param country 参数 {@code country}({@code String}) + */ public void setCountry(String country) { this.country = country; } + /** + * 获取 {@code industry}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字符串结果 + */ public String getIndustry() { return this.industry; } + /** + * 设置 {@code industry}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param industry 参数 {@code industry}({@code String}) + */ public void setIndustry(String industry) { this.industry = industry; } + /** + * 获取 {@code requestedAt}。 + * @return 字段/派生属性 {@code requestedAt} 的值 + */ public Date getRequestedAt() { return this.requestedAt; } + /** + * 设置 {@code requestedAt}。 + * + * @param requestedAt 参数 {@code requestedAt}({@code Date}) + */ public void setRequestedAt(Date requestedAt) { this.requestedAt = requestedAt; } diff --git a/src/main/java/com/midm/model/org/USER_PROPERTY.java b/src/main/java/com/midm/model/org/USER_PROPERTY.java index 7a0a818..d702975 100644 --- a/src/main/java/com/midm/model/org/USER_PROPERTY.java +++ b/src/main/java/com/midm/model/org/USER_PROPERTY.java @@ -1,5 +1,20 @@ package com.midm.model.org; +/** + * 【枚举常量】{@code USER_PROPERTY} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum USER_PROPERTY { email, email_addr, @@ -21,6 +36,14 @@ public enum USER_PROPERTY { mobile_phone, unknown; + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static USER_PROPERTY get(String key) { try { return valueOf(key.trim().toLowerCase()); diff --git a/src/main/java/com/midm/model/org/User.java b/src/main/java/com/midm/model/org/User.java index 4b43916..9e30657 100644 --- a/src/main/java/com/midm/model/org/User.java +++ b/src/main/java/com/midm/model/org/User.java @@ -22,52 +22,163 @@ import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.core.GrantedAuthority; +/** + * 【MongoDB 文档实体】{@code User} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code MAX_LOGIN_ATTEMPT}(int):最大连续登录失败次数,超过后触发临时锁定
  • + *
  • {@code LOGIN_AFTER_MINUTES}(int):登录锁定时长(分钟)
  • + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code email}(String):用户邮箱(登录名,建立索引)
  • + *
  • {@code password}(String):密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化)
  • + *
  • {@code sites}(List):用户可访问的站点列表(多租户)
  • + *
+ * + * 协作对象:{@code SiteInfo、Site、UserGroup}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class User extends GeneralProfile { + /** + * 最大连续登录失败次数,超过后触发临时锁定。 + */ public static final int MAX_LOGIN_ATTEMPT = 5; + /** + * 登录锁定时长(分钟)。 + */ public static final int LOGIN_AFTER_MINUTES = 10; + /** + * 用户所属站点 UUID;建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private UUID siteUuid; + /** + * 用户邮箱(登录名,建立索引);建有索引,常用于查询条件。 + * + * 注解:{@code @Indexed}。 + */ @Indexed private String email; + /** + * 密码字段(数据库中通常保存 BCrypt 哈希,不在 JSON 中序列化);Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private String password; + /** + * 用户可访问的站点列表(多租户)。 + */ private List sites; + /** + * 判断是否Multi站点用户;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private boolean isMultiSiteUser; + /** + * 判断是否API用户;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private boolean isApiUser; + /** + * 站点信息;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private SiteInfo siteInfo; - private Set systemRoles; + /** + * 系统级角色集合(如 SYSTEM_ADMIN),与站点角色分离。 + */ + private Set systemRoles; + /** + * 分组UUID;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private UUID groupUuid; + /** + * 账号激活时间。 + */ protected Date activated; + /** + * 站点;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Site site; + /** + * 用户分组;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private UserGroup userGroup; + /** + * 构造 {@code User} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public User() { } + /** + * 构造 {@code User} 实例。 + * + * @param userUuid 用户 UUID({@code UUID}) + */ public User(UUID userUuid) { this.setUuid(userUuid); } + /** + * 构造 {@code User} 实例。 + * + * @param email 邮箱({@code String}) + */ public User(String email) { this(); this.setEmail(email); } + /** + * 构造 {@code User} 实例。 + * + * @param email 邮箱({@code String}) + * @param password 密码({@code String}) + */ public User(String email, String password) { this(email); this.setPassword(password); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + */ public void init() { super.init(); if (this.hasRole("SUPERVISOR") || this.hasSystemRole("SYSTEM_ADMIN")) { @@ -81,6 +192,12 @@ public class User extends GeneralProfile { } + /** + * 获取 {@code siteUuid}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * @return UUID + */ public UUID getSiteUuid() { if (this.siteUuid == null && !this.hasSystemRole()) { List sites = this.getSites(); @@ -92,6 +209,13 @@ public class User extends GeneralProfile { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; SiteInfo siteInfo = this.getSiteInfo(siteUuid); @@ -101,42 +225,92 @@ public class User extends GeneralProfile { } + /** + * 获取 {@code site}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getSite() { return this.site; } + /** + * 设置 {@code site}。 + * + * @param site 站点/企业({@code Site}) + */ public void setSite(Site site) { this.site = site; } + /** + * 判断 {@code reseller}。 + * @return 字段/派生属性 {@code reseller} 的值 + */ public boolean isReseller() { return this.site != null && this.site.isReseller(); } + /** + * 判断 {@code lite}。 + * @return 字段/派生属性 {@code lite} 的值 + */ public boolean isLite() { return this.site != null && this.site.isLite(); } + /** + * 判断 {@code standard}。 + * @return 字段/派生属性 {@code standard} 的值 + */ public boolean isStandard() { return this.site != null && this.site.isStandard(); } + /** + * 判断 {@code standardWithBatteryPro}。 + * @return 字段/派生属性 {@code standardWithBatteryPro} 的值 + */ public boolean isStandardWithBatteryPro() { return this.site != null && this.site.isStandardWithBatteryPro(); } + /** + * 判断是否FeatureAllowed。 + * + * @param subCategory 参数 {@code subCategory}({@code String}) + * @param item 参数 {@code item}({@code String}) + * @return 字段/派生属性 {@code featureAllowed} 的值 + */ public boolean isFeatureAllowed(String subCategory, String item) { return this.isLite() ? this.site != null && this.site.isFeatureAllowed(subCategory, item) : true; } + /** + * 判断是否文件列表FeatureAllowed。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code filesFeatureAllowed} 的值 + */ public boolean isFilesFeatureAllowed(String category, String key) { return this.isFeatureAllowed(category, key) && (this.hasRole("SUPERVISOR") || this.hasRole("PROFILE_MANAGER")); } + /** + * 获取 {@code email}。 + * @return 字符串结果 + */ public String getEmail() { return this.email; } + /** + * 设置 {@code email}。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param email 邮箱({@code String}) + */ public void setEmail(String email) { if (!Strings.isNullOrEmpty(email)) { if (McEmailUtils.isValid(email)) { @@ -150,15 +324,31 @@ public class User extends GeneralProfile { } } + /** + * 获取 {@code password}。 + * @return 字符串结果 + */ public String getPassword() { return this.password; } + /** + * 设置 {@code password}。 + * + * @param password 密码({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setPassword(String password) { this.password = password; return !Strings.isNullOrEmpty(password) && password.length() >= 8 ? McStringUtils.hasUpperLowerDigit(password) : false; } + /** + * 获取 {@code name}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getName() { String name = super.getName(); if (Strings.isNullOrEmpty(name)) { @@ -168,10 +358,21 @@ public class User extends GeneralProfile { return name; } + /** + * 设置 {@code siteInfo}。 + * + * @param siteInfo 参数 {@code siteInfo}({@code SiteInfo}) + */ public void setSiteInfo(SiteInfo siteInfo) { this.siteInfo = siteInfo; } + /** + * 获取 {@code sites}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return 站点信息列表,可能为空 + */ public List getSites() { if (this.sites == null) { this.sites = new ArrayList(); @@ -180,10 +381,20 @@ public class User extends GeneralProfile { return this.sites; } + /** + * 获取 {@code siteUuids}。 + * @return UUID列表,可能为空 + */ public List getSiteUuids() { return this.sites != null && !this.sites.isEmpty() ? (List)this.sites.stream().map(SiteInfo::getSiteUuid).collect(Collectors.toList()) : null; } + /** + * 清理Undefined站点列表。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:remove。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean clearUndefinedSites() { boolean hasChanges = false; if (this.sites != null) { @@ -201,14 +412,28 @@ public class User extends GeneralProfile { return hasChanges; } + /** + * 设置 {@code sites}。 + * + * @param sites 参数 {@code sites}({@code List}) + */ public void setSites(List sites) { this.sites = sites; } + /** + * 判断 {@code multiSiteUser}。 + * @return 字段/派生属性 {@code multiSiteUser} 的值 + */ public boolean isMultiSiteUser() { return this.isMultiSiteUser; } + /** + * 设置Multi站点用户。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ public void setMultiSiteUser() { this.isMultiSiteUser = this.getSites().size() > 1; if (!this.isMultiSiteUser) { @@ -217,14 +442,32 @@ public class User extends GeneralProfile { } + /** + * 获取 {@code siteInfo}。 + * @return 字段/派生属性 {@code siteInfo} 的值 + */ public SiteInfo getSiteInfo() { return this.getSiteInfo(this.getSiteUuid()); } + /** + * 获取站点信息。 + * + * @param site 站点/企业({@code Site}) + * @return 字段/派生属性 {@code siteInfo} 的值 + */ public SiteInfo getSiteInfo(Site site) { return this.getSiteInfo(site.getUuid()); } + /** + * 获取站点信息。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字段/派生属性 {@code siteInfo} 的值 + */ public SiteInfo getSiteInfo(UUID siteUuid) { if (siteUuid == null) { return null; @@ -239,10 +482,24 @@ public class User extends GeneralProfile { } } + /** + * 判断是否Belonged转换为站点。 + * + * @param site 站点/企业({@code Site}) + * @return 字段/派生属性 {@code belongedToSite} 的值 + */ public boolean isBelongedToSite(Site site) { return this.isBelongedToSite(site.getUuid()); } + /** + * 判断是否Belonged转换为站点。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字段/派生属性 {@code belongedToSite} 的值 + */ public boolean isBelongedToSite(UUID siteUuid) { for(SiteInfo siteInfo : this.getSites()) { if (siteInfo.getSiteUuid() != null && siteInfo.getSiteUuid().equals(siteUuid)) { @@ -253,6 +510,15 @@ public class User extends GeneralProfile { return false; } + /** + * 判断是否处理。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param roles 参数 {@code roles}({@code String[]}) + * @return 字段/派生属性 {@code handle} 的值 + */ public boolean canHandle(UUID siteUuid, String... roles) { SiteInfo info = this.getSiteInfo(siteUuid); if (info != null) { @@ -270,6 +536,14 @@ public class User extends GeneralProfile { return false; } + /** + * 添加站点。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new SiteInfo。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 处理结果 + */ public SiteInfo addSite(UUID siteUuid) { if (siteUuid == null) { return null; @@ -288,6 +562,13 @@ public class User extends GeneralProfile { } } + /** + * 移除站点。 + * + * 实现要点:包含 6 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void removeSite(UUID siteUuid) { if (siteUuid != null) { SiteInfo existSite = null; @@ -321,20 +602,45 @@ public class User extends GeneralProfile { } } - public Set getRoles() { + /** + * 获取 {@code roles}。 + * @return String列表,可能为空 + */ + public Set getRoles() { return this.getRolesBySite(this.getSiteUuid()); } - public Set getRoles(UUID siteUuid) { + /** + * 获取Roles。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return String列表,可能为空 + */ + public Set getRoles(UUID siteUuid) { return this.getRolesBySite(siteUuid); } - public Set getRolesBySite(UUID siteUuid) { + /** + * 获取站点的Roles。 + * + * 实现要点:主要调用:new HashSet。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return String列表,可能为空 + */ + public Set getRolesBySite(UUID siteUuid) { SiteInfo info = this.getSiteInfo(siteUuid); return (Set)(info != null ? this.getSiteInfo(siteUuid).getRoles() : new HashSet()); } - public void setRoles(Set roles) { + /** + * 设置 {@code roles}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param roles 参数 {@code roles}({@code Set}) + */ + public void setRoles(Set roles) { SiteInfo info = this.getSiteInfo(this.getSiteUuid()); if (info != null) { this.getSiteInfo(this.getSiteUuid()).setRoles(roles); @@ -342,6 +648,14 @@ public class User extends GeneralProfile { } + /** + * 添加Role转换为站点。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param role 参数 {@code role}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + */ public void addRoleToSite(String role, UUID siteUuid) { role = UserRole.toRole(role); if (role != null) { @@ -354,10 +668,23 @@ public class User extends GeneralProfile { } + /** + * 移除Role。 + * + * @param role 参数 {@code role}({@code String}) + */ public void removeRole(String role) { this.getRoles().remove(role); } + /** + * 移除Role。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param role 参数 {@code role}({@code String}) + */ public void removeRole(UUID siteUuid, String role) { SiteInfo siteInfo = this.getSiteInfo(siteUuid); if (siteInfo != null) { @@ -366,7 +693,13 @@ public class User extends GeneralProfile { } - public Set getSystemRoles() { + /** + * 获取 {@code systemRoles}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。 + * @return String列表,可能为空 + */ + public Set getSystemRoles() { if (this.systemRoles == null) { this.systemRoles = new HashSet(); } @@ -374,76 +707,163 @@ public class User extends GeneralProfile { return this.systemRoles; } - public void setSystemRoles(Set systemRoles) { + /** + * 设置 {@code systemRoles}。 + * + * @param systemRoles 参数 {@code systemRoles}({@code Set}) + */ + public void setSystemRoles(Set systemRoles) { this.systemRoles = systemRoles; } + /** + * 添加系统Role。 + * + * @param role 参数 {@code role}({@code String}) + */ public void addSystemRole(String role) { this.getSystemRoles().add(role); } + /** + * 移除系统Role。 + * + * @param role 参数 {@code role}({@code String}) + */ public void removeSystemRole(String role) { this.getSystemRoles().remove(role); } + /** + * 判断 {@code systemRole}。 + * @return 字段/派生属性 {@code systemRole} 的值 + */ public boolean hasSystemRole() { return !this.getSystemRoles().isEmpty(); } + /** + * 判断是否系统Role。 + * + * @param role 参数 {@code role}({@code String}) + * @return 字段/派生属性 {@code systemRole} 的值 + */ public boolean hasSystemRole(String role) { return this.getSystemRoles().contains(role); } + /** + * 判断是否Role。 + * + * @param role 参数 {@code role}({@code String}) + * @return 字段/派生属性 {@code role} 的值 + */ public boolean hasRole(String role) { return this.hasRole(this.getSiteUuid(), role); } + /** + * 判断是否Role。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param role 参数 {@code role}({@code String}) + * @return 字段/派生属性 {@code role} 的值 + */ public boolean hasRole(UUID siteUuid, String role) { SiteInfo site = this.getSiteInfo(siteUuid); return site != null ? site.hasRole(role) : false; } + /** + * 判断 {@code supervisor}。 + * @return 字段/派生属性 {@code supervisor} 的值 + */ public boolean isSupervisor() { return this.hasRole("SUPERVISOR"); } + /** + * 判断 {@code systemUser}。 + * @return 字段/派生属性 {@code systemUser} 的值 + */ public boolean isSystemUser() { return !this.getSystemRoles().isEmpty(); } + /** + * 判断 {@code systemAdmin}。 + * @return 字段/派生属性 {@code systemAdmin} 的值 + */ public boolean isSystemAdmin() { return this.getSystemRoles().contains("SYSTEM_ADMIN"); } + /** + * 获取 {@code groupUuid}。 + * @return UUID + */ public UUID getGroupUuid() { return this.groupUuid; } + /** + * 设置 {@code groupUuid}。 + * + * @param groupUuid 分组 UUID({@code UUID}) + */ public void setGroupUuid(UUID groupUuid) { this.groupUuid = groupUuid; } + /** + * 获取 {@code activated}。 + * @return 字段/派生属性 {@code activated} 的值 + */ public Date getActivated() { return this.activated; } + /** + * 设置 {@code activated}。 + * + * @param activated 参数 {@code activated}({@code Date}) + */ public void setActivated(Date activated) { this.activated = activated; } + /** + * 设置Activated。 + * + * 实现要点:主要调用:new Date。 + */ public void setActivated() { this.activated = new Date(); this.enabled = true; } + /** + * 判断 {@code activated}。 + * @return 字段/派生属性 {@code activated} 的值 + */ public boolean isActivated() { return true; } + /** + * 判断 {@code available}。 + * @return 字段/派生属性 {@code available} 的值 + */ public boolean isAvailable() { return this.getEnabled() && this.isActivated(); } + /** + * 获取 {@code emailAddress}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getEmailAddress() { String EMAIL_FORMAT = "%s<%s>"; String name = this.getName(); @@ -454,10 +874,21 @@ public class User extends GeneralProfile { } } + /** + * 获取 {@code userGroup}。 + * @return 字段/派生属性 {@code userGroup} 的值 + */ public UserGroup getUserGroup() { return this.userGroup; } + /** + * 设置 {@code userGroup}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param userGroup 参数 {@code userGroup}({@code UserGroup}) + */ public void setUserGroup(UserGroup userGroup) { this.userGroup = userGroup; if (userGroup != null) { @@ -471,22 +902,47 @@ public class User extends GeneralProfile { } + /** + * 编码Password。 + * + * @param encoder 参数 {@code encoder}({@code PasswordEncoder}) + * @param password 密码({@code String}) + */ public void encodePassword(PasswordEncoder encoder, String password) { this.password = encoder.encode(password); } + /** + * 编码Password。 + * + * @param encoder 参数 {@code encoder}({@code PasswordEncoder}) + */ public void encodePassword(PasswordEncoder encoder) { this.password = encoder.encode(this.password); } + /** + * 判断 {@code register}。 + * @return 字段/派生属性 {@code register} 的值 + */ public boolean canRegister() { return !McStringUtils.isNullOrEmpty(this.getEmail()) && !McStringUtils.isNullOrEmpty(this.getPassword()); } - public List getAuthorities() { + /** + * 获取 {@code authorities}。 + * @return GrantedAuthority列表,可能为空 + */ + public List getAuthorities() { return UserRole.getAuthorities(this.getRoles()); } + /** + * 获取 {@code theme}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getTheme() { String theme = "default"; if (this.site != null) { @@ -499,31 +955,67 @@ public class User extends GeneralProfile { return theme; } + /** + * 获取 {@code locale}。 + * @return 字符串结果 + */ public String getLocale() { String locale = this.getSettingAsString("language"); return McStringUtils.isNullOrEmpty(locale) ? LocaleConst.DEFAULT_LOCALE.toLanguageTag() : locale; } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code Locale}) + */ public void setLocale(Locale locale) { this.setLocale(locale.toLanguageTag()); } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code String}) + */ public void setLocale(String locale) { this.setSetting("language", locale); } + /** + * 判断是否Same语言区域。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @return 字段/派生属性 {@code sameLocale} 的值 + */ public boolean isSameLocale(Locale locale) { return this.isSameLocale(locale.toLanguageTag()); } + /** + * 判断是否Same语言区域。 + * + * @param localeTag 参数 {@code localeTag}({@code String}) + * @return 字段/派生属性 {@code sameLocale} 的值 + */ public boolean isSameLocale(String localeTag) { return this.getLocale().equals(localeTag); } + /** + * 处理keep签名在。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean keepSignIn() { return this.getSettingAsBoolean("keepSignIn"); } + /** + * 获取 {@code lastSite}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return UUID + */ public UUID getLastSite() { UUID uuid = this.getSettingAsUuid("lastSite"); if (uuid == null && this.sites != null && !this.sites.isEmpty() && !this.hasSystemRole()) { @@ -534,16 +1026,31 @@ public class User extends GeneralProfile { return uuid; } + /** + * 设置 {@code lastSite}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setLastSite(UUID uuid) { this.setSetting("lastSite", uuid); } + /** + * 获取 {@code lastPage}。 + * @return 字符串结果 + */ public String getLastPage() { SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); return siteInfo == null ? this.getSettingAsString("lastPage") : siteInfo.getSettingAsString("lastPage"); } - public List getDashboardSettings() { + /** + * 获取 {@code dashboardSettings}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return ?列表,可能为空 + */ + public List getDashboardSettings() { SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); if (siteInfo != null) { Object settings = siteInfo.getSetting("dashboard"); @@ -555,12 +1062,25 @@ public class User extends GeneralProfile { return new ArrayList(); } + /** + * 获取 {@code reportSettings}。 + * + * 实现要点:主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReportSettings() { SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); return siteInfo != null ? siteInfo.getSettings().getDbObject(new String[]{"report"}) : new DbObject(); } - public void setDashboardSettings(List dashboard) { + /** + * 设置 {@code dashboardSettings}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param dashboard 参数 {@code dashboard}({@code List}) + */ + public void setDashboardSettings(List dashboard) { SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); if (siteInfo != null) { siteInfo.setSetting("dashboard", dashboard); @@ -568,6 +1088,13 @@ public class User extends GeneralProfile { } + /** + * 设置 {@code lastPage}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param url 参数 {@code url}({@code String}) + */ public void setLastPage(String url) { SiteInfo siteInfo = this.getSiteInfo(this.siteUuid); if (siteInfo != null) { @@ -576,6 +1103,14 @@ public class User extends GeneralProfile { } + /** + * 获取分页设置列表。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new DbObject。 + * + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getPageSettings(String pageUrl) { Object settings = this.getSetting("page", pageUrl); DbObject var3; @@ -597,10 +1132,26 @@ public class User extends GeneralProfile { return var3; } + /** + * 获取分页设置。 + * + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code pageSetting} 的值 + */ public Object getPageSetting(String pageUrl, String key) { return this.getPageSettings(pageUrl).get(key); } + /** + * 设置分页设置。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setPageSetting(String pageUrl, String key, Object value) { if (value == null) { this.getPageSettings(pageUrl).remove(key); @@ -610,6 +1161,13 @@ public class User extends GeneralProfile { } + /** + * 更新配置档案。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param newProfile 参数 {@code newProfile}({@code DbObject}) + */ public void updateProfile(DbObject newProfile) { DbObject profile = this.getProfile(); newProfile.forEach((key, value) -> { @@ -620,28 +1178,62 @@ public class User extends GeneralProfile { }); } + /** + * 设置 {@code eula}。 + * + * 实现要点:主要调用:new DbObject、new Date。 + * + * @param agreement 参数 {@code agreement}({@code PolicyAgreement}) + */ public void setEula(PolicyAgreement agreement) { this.setProfile("eula", (new DbObject("uuid", agreement.getUuid().toString())).append("version", agreement.getVersion()).append("acceptDate", new Date())); } + /** + * 设置 {@code eula}。 + * + * 实现要点:主要调用:new DbObject、parse。 + * + * @param value 值({@code String}) + */ public void setEula(String value) { Object object = McStringUtils.isNullOrEmpty(value) ? new DbObject() : DbObject.parse(value); this.setProfile("eula", object); } + /** + * 获取 {@code mfaMethod}。 + * @return 字符串结果 + */ public String getMfaMethod() { return this.getSettingAsString("mfa"); } + /** + * 判断 {@code eulaAgreed}。 + * @return 字段/派生属性 {@code eulaAgreed} 的值 + */ public boolean isEulaAgreed() { return this.isApiUser() || this.getCategoryProfile("eula", "acceptDate") != null; } + /** + * 判断 {@code apiUser}。 + * @return 字段/派生属性 {@code apiUser} 的值 + */ public boolean isApiUser() { SiteInfo siteInfo = this.getSiteInfo(); return siteInfo != null && siteInfo.isApiOnly(); } + /** + * 比较当前对象与另一个对象是否相等。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param user 当前用户({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean equals(Object user) { if (user == null) { return false; @@ -654,6 +1246,9 @@ public class User extends GeneralProfile { } } + /** + * 设置配置档案Only。 + */ public void setProfileOnly() { this.siteUuid = null; this.sites = null; @@ -665,10 +1260,19 @@ public class User extends GeneralProfile { this.getProfile().remove("eula"); } + /** + * 获取 {@code loginAttempt}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getLoginAttempt() { return this.getSettings().getDbObject(new String[]{"loginAttempt"}); } + /** + * 登录Failed。 + * + * 实现要点:主要调用:new Date。 + */ public void loginFailed() { DbObject loginAttempt = this.getLoginAttempt(); loginAttempt.put("attemptAt", new Date()); @@ -677,10 +1281,17 @@ public class User extends GeneralProfile { this.setSetting("loginAttempt", loginAttempt); } + /** + * 重置登录Attempt。 + */ public void resetLoginAttempt() { this.getSettings().remove("loginAttempt"); } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return this.getEmail(); } diff --git a/src/main/java/com/midm/model/org/UserAccess.java b/src/main/java/com/midm/model/org/UserAccess.java index cab8e0a..e7294db 100644 --- a/src/main/java/com/midm/model/org/UserAccess.java +++ b/src/main/java/com/midm/model/org/UserAccess.java @@ -3,11 +3,50 @@ package com.midm.model.org; import java.util.Date; import java.util.UUID; +/** + * 【领域模型】{@code UserAccess} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code sessionId}(String):会话ID
  • + *
  • {@code userUuid}(UUID):用户UUID
  • + *
  • {@code browser}(String):字段 browser
  • + *
  • {@code os}(String):操作系统
  • + *
  • {@code device}(String):设备
  • + *
  • {@code lastAccess}(Date):最后Access
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class UserAccess { + /** + * 会话ID。 + */ private String sessionId; + /** + * 用户UUID。 + */ private UUID userUuid; + /** + * 字段 browser。 + */ private String browser; + /** + * 操作系统。 + */ private String os; + /** + * 设备。 + */ private String device; + /** + * 最后Access。 + */ private Date lastAccess; } diff --git a/src/main/java/com/midm/model/org/UserGroup.java b/src/main/java/com/midm/model/org/UserGroup.java index d56ab13..2945f20 100644 --- a/src/main/java/com/midm/model/org/UserGroup.java +++ b/src/main/java/com/midm/model/org/UserGroup.java @@ -4,16 +4,62 @@ import com.midm.model.GeneralProfile; import java.util.UUID; import org.springframework.data.annotation.Transient; +/** + * 【领域模型】{@code UserGroup} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteUuid}(UUID):用户所属站点 UUID
  • + *
  • {@code parentUuid}(UUID):父级UUID
  • + *
  • {@code order}(Integer):字段 order
  • + *
  • {@code userNumbers}(Long):用户Numbers
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class UserGroup extends GeneralProfile { + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 父级UUID。 + */ private UUID parentUuid; + /** + * 字段 order。 + */ private Integer order; + /** + * 用户Numbers;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Long userNumbers; + /** + * 构造 {@code UserGroup} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { this.setSiteUuid(siteUuid); if (parentGroup != null) { @@ -23,34 +69,70 @@ public class UserGroup extends GeneralProfile { this.setName(name); } + /** + * 获取 {@code siteUuid}。 + * @return UUID + */ public UUID getSiteUuid() { return this.siteUuid; } + /** + * 设置 {@code siteUuid}。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setSiteUuid(UUID siteUuid) { this.siteUuid = siteUuid; } + /** + * 获取 {@code parentUuid}。 + * @return UUID + */ public UUID getParentUuid() { return this.parentUuid; } + /** + * 设置 {@code parentUuid}。 + * + * @param parentUuid 参数 {@code parentUuid}({@code UUID}) + */ public void setParentUuid(UUID parentUuid) { this.parentUuid = parentUuid; } + /** + * 获取 {@code order}。 + * @return 数量/长度 + */ public Integer getOrder() { return this.order; } + /** + * 设置 {@code order}。 + * + * @param order 参数 {@code order}({@code Integer}) + */ public void setOrder(Integer order) { this.order = order; } + /** + * 获取 {@code userNumbers}。 + * @return 数量/长度 + */ public Long getUserNumbers() { return this.userNumbers; } + /** + * 设置 {@code userNumbers}。 + * + * @param numbers 参数 {@code numbers}({@code Long}) + */ public void setUserNumbers(Long numbers) { this.userNumbers = numbers; } diff --git a/src/main/java/com/midm/model/org/UserRole.java b/src/main/java/com/midm/model/org/UserRole.java index 4c2bb1c..9064e1e 100644 --- a/src/main/java/com/midm/model/org/UserRole.java +++ b/src/main/java/com/midm/model/org/UserRole.java @@ -5,28 +5,114 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.GrantedAuthority; +/** + * 【领域模型】{@code UserRole} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code ROLES}(String):字段 ROLES
  • + *
  • {@code SYSTEM_ROLES}(String):字段 SYSTEM_ROLES
  • + *
  • {@code ROLE_SUPER_USER}(String):字段 ROLE_SUPER_USER
  • + *
  • {@code ROLE_SUPERVISOR}(String):字段 ROLE_SUPERVISOR
  • + *
  • {@code ROLE_SYSTEM_ADMIN}(String):字段 ROLE_SYSTEM_ADMIN
  • + *
  • {@code ROLE_SITE_MANAGER}(String):字段 ROLE_SITE_MANAGER
  • + *
+ * + * 协作对象:{@code String[]}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class UserRole { + /** + * 字段 ROLES。 + */ public static final String ROLES = "roles"; + /** + * 字段 SYSTEM_ROLES。 + */ public static final String SYSTEM_ROLES = "systemRoles"; + /** + * 字段 ROLE_SUPER_USER。 + */ public static final String ROLE_SUPER_USER = "SUPER_USER"; + /** + * 字段 ROLE_SUPERVISOR。 + */ public static final String ROLE_SUPERVISOR = "SUPERVISOR"; + /** + * 字段 ROLE_SYSTEM_ADMIN。 + */ public static final String ROLE_SYSTEM_ADMIN = "SYSTEM_ADMIN"; + /** + * 字段 ROLE_SITE_MANAGER。 + */ public static final String ROLE_SITE_MANAGER = "SITE_MANAGER"; + /** + * 字段 ROLE_SALES。 + */ public static final String ROLE_SALES = "SALES"; + /** + * 字段 ROLE_RESELLER。 + */ public static final String ROLE_RESELLER = "RESELLER"; + /** + * 字段 ROLE_FINANCE。 + */ public static final String ROLE_FINANCE = "FINANCE"; + /** + * 字段 ROLE_USER。 + */ public static final String ROLE_USER = "USER"; + /** + * 字段 ROLE_USER_MANAGER。 + */ public static final String ROLE_USER_MANAGER = "USER_MANAGER"; + /** + * 字段 ROLE_DEVICE_MANAGER。 + */ public static final String ROLE_DEVICE_MANAGER = "DEVICE_MANAGER"; + /** + * 字段 ROLE_PROFILE_MANAGER。 + */ public static final String ROLE_PROFILE_MANAGER = "PROFILE_MANAGER"; + /** + * 字段 ROLE_DEVIE_OWNER。 + */ public static final String ROLE_DEVIE_OWNER = "DEVICE_OWNER"; + /** + * 字段 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"}; + /** + * 字段 DEVICE_MANAGE_ROLES。 + */ 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 List getAuthorities(final String role) { + /** + * 获取Authorities。 + * + * 实现要点:主要调用:new ArrayList、new SimpleGrantedAuthority。 + * + * @param role 参数 {@code role}({@code String}) + * @return GrantedAuthority列表,可能为空 + */ + public static List getAuthorities(final String role) { return new ArrayList() { { 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}) + * @return GrantedAuthority列表,可能为空 + */ + public static List getAuthorities(final Set roles) { return new ArrayList() { { 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) { if (Strings.isNullOrEmpty(role)) { return null; diff --git a/src/main/java/com/midm/model/org/UserToken.java b/src/main/java/com/midm/model/org/UserToken.java index 922d1c4..8c71517 100644 --- a/src/main/java/com/midm/model/org/UserToken.java +++ b/src/main/java/com/midm/model/org/UserToken.java @@ -14,43 +14,135 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code UserToken} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code TOKEN_CONFIRMATION}(char):字段 TOKEN_CONFIRMATION
  • + *
  • {@code TOKEN_ACTIVATION}(char):字段 TOKEN_ACTIVATION
  • + *
  • {@code TOKEN_LOGIN}(char):字段 TOKEN_LOGIN
  • + *
  • {@code TOKEN_REMEMBER_LOGIN}(char):字段 TOKEN_REMEMBER_LOGIN
  • + *
  • {@code TOKEN_RESET_PASSWORD}(char):字段 TOKEN_RESET_PASSWORD
  • + *
  • {@code TOKEN_MFA_AUTH}(char):字段 TOKEN_MFA_AUTH
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class UserToken implements Serializable { + /** + * 字段 TOKEN_CONFIRMATION。 + */ public static final char TOKEN_CONFIRMATION = 'C'; + /** + * 字段 TOKEN_ACTIVATION。 + */ public static final char TOKEN_ACTIVATION = 'A'; + /** + * 字段 TOKEN_LOGIN。 + */ public static final char TOKEN_LOGIN = 'L'; + /** + * 字段 TOKEN_REMEMBER_LOGIN。 + */ public static final char TOKEN_REMEMBER_LOGIN = 'R'; + /** + * 字段 TOKEN_RESET_PASSWORD。 + */ public static final char TOKEN_RESET_PASSWORD = 'P'; + /** + * 字段 TOKEN_MFA_AUTH。 + */ public static final char TOKEN_MFA_AUTH = 'M'; + /** + * 字段 TOKEN_DEVICE_ACCESS。 + */ public static final char TOKEN_DEVICE_ACCESS = 'D'; + /** + * 令牌UUID;MongoDB 主键;Gson 序列化控制。 + * + * 注解:{@code @Id @Expose(serialize = false)}。 + */ @Id @Expose( serialize = false ) private UUID tokenUuid; + /** + * access令牌;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private String accessToken; + /** + * 用户UUID;Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private UUID userUuid; + /** + * 令牌类型;Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private char tokenType; + /** + * 创建时间;Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private Date created; + /** + * 时间字段;Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private Date expired; + /** + * 字段 reference。 + */ private DbObject reference; + /** + * 构造 {@code UserToken} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ 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) { this.tokenUuid = UUID.randomUUID(); this.userUuid = user.getUuid(); @@ -60,6 +152,11 @@ public class UserToken implements Serializable { this.expired = date.plus(validPeriod).toDate(); } + /** + * 处理renew。 + * + * 实现要点:主要调用:new Date、new DateTime。 + */ public void renew() { this.tokenUuid = UUID.randomUUID(); this.encryptToken(); @@ -69,10 +166,19 @@ public class UserToken implements Serializable { this.expired = date.plus(validPeriod).toDate(); } + /** + * 加密令牌。 + */ public void encryptToken() { this.accessToken = McUuidUtils.toBase64String(this.tokenUuid); } + /** + * 获取 {@code accessToken}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getAccessToken() { if (Strings.isNullOrEmpty(this.accessToken)) { this.encryptToken(); @@ -81,38 +187,81 @@ public class UserToken implements Serializable { return this.accessToken; } + /** + * 获取 {@code tokenUuid}。 + * @return UUID + */ public UUID getTokenUuid() { return this.tokenUuid; } + /** + * 设置 {@code tokenUuid}。 + * + * @param uid 参数 {@code uid}({@code UUID}) + */ public void setTokenUuid(UUID uid) { this.tokenUuid = uid; } + /** + * 获取 {@code userUuid}。 + * @return UUID + */ public UUID getUserUuid() { return this.userUuid; } + /** + * 设置 {@code userUuid}。 + * + * @param userUuid 用户 UUID({@code UUID}) + */ public void setUserUuid(UUID userUuid) { this.userUuid = userUuid; } + /** + * 获取 {@code tokenType}。 + * @return 字段/派生属性 {@code tokenType} 的值 + */ public char getTokenType() { return this.tokenType; } + /** + * 设置 {@code tokenType}。 + * + * @param tokenType 参数 {@code tokenType}({@code char}) + */ public void setTokenType(char tokenType) { this.tokenType = tokenType; } + /** + * 获取Mfa令牌。 + * + * @param length 参数 {@code length}({@code int}) + * @return 字符串结果 + */ public String getMfaToken(int length) { return this.getMfaToken().substring(0, length); } + /** + * 获取 {@code mfaToken}。 + * @return 字符串结果 + */ public String getMfaToken() { return String.valueOf(this.tokenUuid.getMostSignificantBits() * this.tokenUuid.getLeastSignificantBits()); } + /** + * 获取 {@code reference}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReference() { if (this.reference == null) { this.reference = new DbObject(); @@ -121,10 +270,23 @@ public class UserToken implements Serializable { return this.reference; } + /** + * 设置 {@code reference}。 + * + * @param reference 参数 {@code reference}({@code DbObject}) + */ public void setReference(DbObject reference) { this.reference = reference; } + /** + * 设置Reference。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setReference(String key, Object value) { if (value == null) { this.getReference().remove(key); @@ -134,38 +296,80 @@ public class UserToken implements Serializable { } + /** + * 获取 {@code deviceUuid}。 + * @return UUID + */ public UUID getDeviceUuid() { return this.getReference().getUuid("deviceUuid"); } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param registered 参数 {@code registered}({@code Date}) + */ public void setCreated(Date registered) { this.created = registered; } + /** + * 获取 {@code expired}。 + * @return 字段/派生属性 {@code expired} 的值 + */ public Date getExpired() { return this.expired; } + /** + * 设置 {@code expired}。 + * + * @param expired 参数 {@code expired}({@code Date}) + */ public void setExpired(Date expired) { this.expired = expired; } + /** + * 处理plusExpired。 + * + * 实现要点:主要调用:new DateTime。 + * + * @param time 参数 {@code time}({@code long}) + */ public void plusExpired(long time) { DateTime expiredDate = new DateTime(this.getExpired()); expiredDate.plus(time); } + /** + * 判断 {@code expired}。 + * + * 实现要点:主要调用:new Date。 + * @return 字段/派生属性 {@code expired} 的值 + */ public boolean isExpired() { return this.getExpired().getTime() < (new Date()).getTime(); } + /** + * 处理转换为设备Access。 + * + * 实现要点:主要调用:new DbObject。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @return MongoDB 文档扩展对象 + */ public DbObject toDeviceAccess(HttpServletRequest request) { - String var10000 = McUrlUtils.getHostUrl(request); - String accessUrl = var10000 + "/device/" + McUuidUtils.toBase64String(this.tokenUuid, true); + String accessUrl = McUrlUtils.getHostUrl(request) + "/device/" + McUuidUtils.toBase64String(this.tokenUuid, true); DbObject deviceAccess = new DbObject("accessUrl", accessUrl); deviceAccess.append("expiry", this.getExpired()); return deviceAccess; diff --git a/src/main/java/com/midm/model/org/package-info.java b/src/main/java/com/midm/model/org/package-info.java new file mode 100644 index 0000000..7ea28d1 --- /dev/null +++ b/src/main/java/com/midm/model/org/package-info.java @@ -0,0 +1,23 @@ +/** + * 组织架构模型:站点、用户、用户组、License、令牌。 + * + *

本包主要类型: + *

    + *
  • {@link Site}
  • + *
  • {@link SiteFile}
  • + *
  • {@link SiteInfo}
  • + *
  • {@link SiteLicense}
  • + *
  • {@link SitePlan}
  • + *
  • {@link SiteRequest}
  • + *
  • {@link USER_PROPERTY}
  • + *
  • {@link User}
  • + *
  • {@link UserAccess}
  • + *
  • {@link UserGroup}
  • + *
  • {@link UserRole}
  • + *
  • {@link UserToken}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.org; diff --git a/src/main/java/com/midm/model/package-info.java b/src/main/java/com/midm/model/package-info.java new file mode 100644 index 0000000..0993105 --- /dev/null +++ b/src/main/java/com/midm/model/package-info.java @@ -0,0 +1,14 @@ +/** + * 领域模型根包:所有 MongoDB 文档/值对象的公共基类与通用模型。 + * + *

本包主要类型: + *

    + *
  • {@link GeneralProfile}
  • + *
  • {@link GroupByResult}
  • + *
  • {@link IF_EXISTS_OPTION}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model; diff --git a/src/main/java/com/midm/model/store/AppReleaseNote.java b/src/main/java/com/midm/model/store/AppReleaseNote.java index 20efa49..07c23ba 100644 --- a/src/main/java/com/midm/model/store/AppReleaseNote.java +++ b/src/main/java/com/midm/model/store/AppReleaseNote.java @@ -5,79 +5,217 @@ import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code AppReleaseNote} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code noteId}(NoteId):备注ID
  • + *
  • {@code versionName}(String):版本名称
  • + *
  • {@code minSdkVersion}(int):minSDK版本
  • + *
  • {@code files}(List):文件列表
  • + *
+ * + * 协作对象:{@code NoteId}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class AppReleaseNote extends ReleaseNote { + /** + * 备注ID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private NoteId noteId; + /** + * 版本名称。 + */ private String versionName; + /** + * minSDK版本。 + */ private int minSdkVersion; - private List files; + /** + * 文件列表。 + */ + private List files; + /** + * 构造 {@code AppReleaseNote} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public AppReleaseNote() { } + /** + * 构造 {@code AppReleaseNote} 实例。 + * + * 实现要点:主要调用:new NoteId。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + */ public AppReleaseNote(String packageName, int versionCode, String versionName, int minSdkVersion) { this.noteId = new NoteId(packageName, versionCode); this.versionName = versionName; this.setMinSdkVersion(minSdkVersion); } + /** + * 构造 {@code AppReleaseNote} 实例。 + * + * @param appFile 参数 {@code appFile}({@code StoreAppFile}) + */ public AppReleaseNote(StoreAppFile appFile) { this(appFile.getPackageName(), (int)appFile.getVersionCode(), appFile.getVersionName(), appFile.getMinSdkVersion()); } + /** + * 获取 {@code versionCode}。 + * @return 数量/长度 + */ public int getVersionCode() { return this.noteId.getVersionCode(); } + /** + * 获取 {@code versionName}。 + * @return 字符串结果 + */ public String getVersionName() { return this.versionName; } + /** + * 设置 {@code versionName}。 + * + * @param versionName 参数 {@code versionName}({@code String}) + */ public void setVersionName(String versionName) { this.versionName = versionName; } - public List getFiles() { + /** + * 获取 {@code files}。 + * @return Store应用文件列表,可能为空 + */ + public List getFiles() { return this.files; } - public void setFiles(List files) { + /** + * 设置 {@code files}。 + * + * @param files 参数 {@code files}({@code List}) + */ + public void setFiles(List files) { this.files = files; } + /** + * 获取 {@code minSdkVersion}。 + * @return 数量/长度 + */ public int getMinSdkVersion() { return this.minSdkVersion; } + /** + * 设置 {@code minSdkVersion}。 + * + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + */ public void setMinSdkVersion(int minSdkVersion) { this.minSdkVersion = minSdkVersion; } + /** + * 【领域模型】{@code NoteId} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code packageName}(String):package名称
  • + *
  • {@code versionCode}(int):版本代码
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public static class NoteId implements Serializable { + /** + * package名称。 + */ private String packageName; + /** + * 版本代码。 + */ private int versionCode; + /** + * 构造 {@code NoteId} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public NoteId() { } + /** + * 构造 {@code NoteId} 实例。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + */ public NoteId(String packageName, int versionCode) { this.packageName = packageName; this.versionCode = versionCode; } + /** + * 获取 {@code appUuid}。 + * @return 字符串结果 + */ public String getAppUuid() { return this.packageName; } + /** + * 设置 {@code appUuid}。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public void setAppUuid(String packageName) { this.packageName = packageName; } + /** + * 获取 {@code versionCode}。 + * @return 数量/长度 + */ public int getVersionCode() { return this.versionCode; } + /** + * 设置 {@code versionCode}。 + * + * @param versionCode 参数 {@code versionCode}({@code int}) + */ public void setVersionCode(int versionCode) { this.versionCode = versionCode; } diff --git a/src/main/java/com/midm/model/store/KeyStore.java b/src/main/java/com/midm/model/store/KeyStore.java index d324b6b..708078f 100644 --- a/src/main/java/com/midm/model/store/KeyStore.java +++ b/src/main/java/com/midm/model/store/KeyStore.java @@ -9,64 +9,168 @@ import org.apache.commons.codec.digest.DigestUtils; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code KeyStore} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code id}(String):ID
  • + *
  • {@code description}(String):字段 description
  • + *
  • {@code alias}(String):字段 alias
  • + *
  • {@code keyPassword}(String):密钥Password
  • + *
  • {@code storePassword}(String):字段 storePassword
  • + *
  • {@code certMd5}(String):证书Md5
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class KeyStore { + /** + * ID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String id; + /** + * 字段 description。 + */ private String description; + /** + * 字段 alias。 + */ private String alias; + /** + * 密钥Password。 + */ private String keyPassword; + /** + * 字段 storePassword。 + */ private String storePassword; + /** + * 证书Md5。 + */ private String certMd5; + /** + * 获取 {@code id}。 + * @return 字符串结果 + */ public String getId() { return this.id; } + /** + * 设置 {@code id}。 + * + * @param id 参数 {@code id}({@code String}) + */ public void setId(String id) { this.id = id; } + /** + * 获取 {@code description}。 + * @return 字符串结果 + */ public String getDescription() { return this.description; } + /** + * 设置 {@code description}。 + * + * @param description 参数 {@code description}({@code String}) + */ public void setDescription(String description) { this.description = description; } + /** + * 获取 {@code alias}。 + * @return 字符串结果 + */ public String getAlias() { return this.alias; } + /** + * 设置 {@code alias}。 + * + * @param alias 参数 {@code alias}({@code String}) + */ public void setAlias(String alias) { this.alias = alias; } + /** + * 获取 {@code keyPassword}。 + * @return 字符串结果 + */ public String getKeyPassword() { return this.keyPassword; } + /** + * 设置 {@code keyPassword}。 + * + * @param keyPassword 参数 {@code keyPassword}({@code String}) + */ public void setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; } + /** + * 获取 {@code storePassword}。 + * @return 字符串结果 + */ public String getStorePassword() { return this.storePassword; } + /** + * 设置 {@code storePassword}。 + * + * @param storePassword 参数 {@code storePassword}({@code String}) + */ public void setStorePassword(String storePassword) { this.storePassword = storePassword; } + /** + * 获取 {@code certMd5}。 + * @return 字符串结果 + */ public String getCertMd5() { return this.certMd5; } + /** + * 设置 {@code certMd5}。 + * + * @param certMd5 参数 {@code certMd5}({@code String}) + */ public void setCertMd5(String certMd5) { this.certMd5 = certMd5; } + /** + * 设置 {@code certMd5}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param storeFile 参数 {@code storeFile}({@code McFile}) + */ public void setCertMd5(McFile storeFile) { try { InputStream input = storeFile.getInputStream(); diff --git a/src/main/java/com/midm/model/store/OtaReleaseNote.java b/src/main/java/com/midm/model/store/OtaReleaseNote.java index b804929..95c7318 100644 --- a/src/main/java/com/midm/model/store/OtaReleaseNote.java +++ b/src/main/java/com/midm/model/store/OtaReleaseNote.java @@ -3,56 +3,162 @@ package com.midm.model.store; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code OtaReleaseNote} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code noteId}(NoteId):备注ID
  • + *
  • {@code displayId}(String):displayID
  • + *
+ * + * 协作对象:{@code NoteId}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class OtaReleaseNote extends ReleaseNote { + /** + * 备注ID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private NoteId noteId; + /** + * displayID。 + */ private String displayId; + /** + * 构造 {@code OtaReleaseNote} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public OtaReleaseNote() { } + /** + * 构造 {@code OtaReleaseNote} 实例。 + * + * 实现要点:主要调用:new NoteId。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + */ public OtaReleaseNote(String productId, long buildDate) { this.noteId = new NoteId(productId, buildDate); } + /** + * 构造 {@code OtaReleaseNote} 实例。 + * + * @param otaFile 参数 {@code otaFile}({@code StoreOtaFile}) + */ public OtaReleaseNote(StoreOtaFile otaFile) { this(otaFile.getProductId(), otaFile.getBuildDate()); this.setDisplayId(otaFile.getDisplayId()); } + /** + * 获取 {@code displayId}。 + * @return 字符串结果 + */ public String getDisplayId() { return this.displayId; } + /** + * 设置 {@code displayId}。 + * + * @param versionName 参数 {@code versionName}({@code String}) + */ public void setDisplayId(String versionName) { this.displayId = versionName; } + /** + * 【领域模型】{@code NoteId} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code productId}(String):productID
  • + *
  • {@code buildDate}(long):构建日期
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class NoteId { + /** + * productID。 + */ private String productId; + /** + * 构建日期。 + */ private long buildDate; + /** + * 构造 {@code NoteId} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public NoteId() { } + /** + * 构造 {@code NoteId} 实例。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + */ public NoteId(String productId, long buildDate) { this.productId = productId; this.buildDate = buildDate; } + /** + * 获取 {@code productId}。 + * @return 字符串结果 + */ public String getProductId() { return this.productId; } + /** + * 设置 {@code productId}。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void setProductId(String productId) { this.productId = productId; } + /** + * 获取 {@code buildDate}。 + * @return 数量/长度 + */ public long getBuildDate() { return this.buildDate; } + /** + * 设置 {@code buildDate}。 + * + * @param buildDate 参数 {@code buildDate}({@code long}) + */ public void setBuildDate(long buildDate) { this.buildDate = buildDate; } diff --git a/src/main/java/com/midm/model/store/ReleaseNote.java b/src/main/java/com/midm/model/store/ReleaseNote.java index 6a84a28..3076998 100644 --- a/src/main/java/com/midm/model/store/ReleaseNote.java +++ b/src/main/java/com/midm/model/store/ReleaseNote.java @@ -2,48 +2,125 @@ package com.midm.model.store; import java.util.Date; +/** + * 【领域模型】{@code ReleaseNote} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code note}(String[]):备注
  • + *
  • {@code noteNewFunction}(String[]):备注新Function
  • + *
  • {@code isFormal}(Boolean):判断是否Formal
  • + *
  • {@code releasedAt}(Date):时间字段
  • + *
+ * + * 协作对象:{@code String[]}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ReleaseNote { + /** + * 备注。 + */ private String[] note; + /** + * 备注新Function。 + */ private String[] noteNewFunction; + /** + * 判断是否Formal。 + */ private Boolean isFormal; + /** + * 时间字段。 + */ private Date releasedAt = new Date(); + /** + * 获取 {@code releasedAt}。 + * @return 字段/派生属性 {@code releasedAt} 的值 + */ public Date getReleasedAt() { return this.releasedAt; } + /** + * 设置 {@code releasedAt}。 + * + * @param releasedAt 参数 {@code releasedAt}({@code Date}) + */ public void setReleasedAt(Date releasedAt) { this.releasedAt = releasedAt; } + /** + * 判断 {@code note}。 + * @return 字段/派生属性 {@code note} 的值 + */ public boolean hasNote() { return this.note != null && this.note.length > 0; } + /** + * 判断 {@code noteNewFunction}。 + * @return 字段/派生属性 {@code noteNewFunction} 的值 + */ public boolean hasNoteNewFunction() { return this.noteNewFunction != null && this.noteNewFunction.length > 0; } + /** + * 获取 {@code note}。 + * @return 字段/派生属性 {@code note} 的值 + */ public String[] getNote() { return this.note; } + /** + * 设置 {@code notes}。 + * + * @param note 参数 {@code note}({@code String[]}) + */ public void setNotes(String[] note) { this.note = note; } + /** + * 获取 {@code noteNewFunction}。 + * @return 字段/派生属性 {@code noteNewFunction} 的值 + */ public String[] getNoteNewFunction() { return this.noteNewFunction; } + /** + * 设置 {@code noteNewFunctions}。 + * + * @param noteNewFunction 参数 {@code noteNewFunction}({@code String[]}) + */ public void setNoteNewFunctions(String[] noteNewFunction) { this.noteNewFunction = noteNewFunction; } + /** + * 判断 {@code formal}。 + * @return 字段/派生属性 {@code formal} 的值 + */ public Boolean isFormal() { return this.isFormal; } + /** + * 设置 {@code isFormal}。 + * + * @param isFormal 参数 {@code isFormal}({@code Boolean}) + */ public void setIsFormal(Boolean isFormal) { this.isFormal = isFormal; } diff --git a/src/main/java/com/midm/model/store/StoreApp.java b/src/main/java/com/midm/model/store/StoreApp.java index 8eda891..b55c050 100644 --- a/src/main/java/com/midm/model/store/StoreApp.java +++ b/src/main/java/com/midm/model/store/StoreApp.java @@ -1,6 +1,7 @@ package com.midm.model.store; import com.mitac.cell.db.DbObject; +import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -8,35 +9,103 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreApp} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code packageName}(String):package名称
  • + *
  • {@code isFormal}(Boolean):判断是否Formal
  • + *
  • {@code appInfo}(DbObject):应用信息
  • + *
  • {@code sdkVersions}(Set):SDKVersions
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreApp extends StoreBase { + /** + * package名称;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String packageName; + /** + * 判断是否Formal。 + */ private Boolean isFormal; + /** + * 应用信息。 + */ private DbObject appInfo; + /** + * SDKVersions;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient - private Set sdkVersions; + private Set sdkVersions; + /** + * 构造 {@code StoreApp} 实例。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public StoreApp(String packageName) { this.packageName = packageName; } + /** + * 判断 {@code formal}。 + * @return 字段/派生属性 {@code formal} 的值 + */ public Boolean isFormal() { return this.isFormal; } + /** + * 设置 {@code isFormal}。 + * + * @param isFormal 参数 {@code isFormal}({@code Boolean}) + */ public void setIsFormal(Boolean isFormal) { this.isFormal = isFormal; } + /** + * 获取 {@code packageName}。 + * @return 字符串结果 + */ public String getPackageName() { return this.packageName; } + /** + * 设置 {@code packageName}。 + * + * @param packageName 参数 {@code packageName}({@code String}) + */ public void setPackageName(String packageName) { this.packageName = packageName; } + /** + * 获取 {@code appInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getAppInfo() { if (this.appInfo == null) { this.appInfo = new DbObject(); @@ -45,26 +114,53 @@ public class StoreApp extends StoreBase { return this.appInfo; } + /** + * 设置 {@code appInfo}。 + * + * @param appInfo 参数 {@code appInfo}({@code DbObject}) + */ public void setAppInfo(DbObject appInfo) { this.appInfo = appInfo; } + /** + * 设置应用信息。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setAppInfo(String key, Object value) { this.getAppInfo().append(key, value); } - public Set getSdkVersions() { + /** + * 获取 {@code sdkVersions}。 + * @return Integer列表,可能为空 + */ + public Set getSdkVersions() { return this.sdkVersions; } - public void setSdkVersions(Set sdkVersions) { + /** + * 设置 {@code sdkVersions}。 + * + * @param sdkVersions 参数 {@code sdkVersions}({@code Set}) + */ + public void setSdkVersions(Set sdkVersions) { this.sdkVersions = sdkVersions; } - public void setSdkVersions(List sdkVersions) { + /** + * 设置 {@code sdkVersions}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashSet。 + * + * @param sdkVersions 参数 {@code sdkVersions}({@code List}) + */ + public void setSdkVersions(List sdkVersions) { if (sdkVersions != null) { this.sdkVersions = new HashSet(); - this.sdkVersions.addAll(sdkVersions); + this.sdkVersions.addAll((Collection)sdkVersions); } else { this.sdkVersions = null; } diff --git a/src/main/java/com/midm/model/store/StoreAppFile.java b/src/main/java/com/midm/model/store/StoreAppFile.java index 84654bd..2024929 100644 --- a/src/main/java/com/midm/model/store/StoreAppFile.java +++ b/src/main/java/com/midm/model/store/StoreAppFile.java @@ -6,11 +6,35 @@ import com.mitac.cell.io.McFile; import java.util.UUID; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreAppFile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreAppFile extends AppFile { + /** + * 构造 {@code StoreAppFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public StoreAppFile() { } + /** + * 构造 {@code StoreAppFile} 实例。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param file 文件({@code McFile}) + * @param generateIcon 参数 {@code generateIcon}({@code boolean}) + */ public StoreAppFile(User user, UUID fileUuid, McFile file, boolean generateIcon) { super(user, fileUuid, file, generateIcon); } diff --git a/src/main/java/com/midm/model/store/StoreBase.java b/src/main/java/com/midm/model/store/StoreBase.java index e2eaf6b..8069f05 100644 --- a/src/main/java/com/midm/model/store/StoreBase.java +++ b/src/main/java/com/midm/model/store/StoreBase.java @@ -4,18 +4,66 @@ import com.midm.constant.LocaleConst; import com.mitac.cell.db.DbObject; import java.util.Date; +/** + * 【领域模型】{@code StoreBase} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code title}(DbObject):字段 title
  • + *
  • {@code summary}(DbObject):字段 summary
  • + *
  • {@code desc}(DbObject):字段 desc
  • + *
  • {@code createdAt}(Date):时间字段
  • + *
  • {@code lastUpdated}(Date):最后Updated
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class StoreBase { + /** + * 字段 title。 + */ private DbObject title; + /** + * 字段 summary。 + */ private DbObject summary; + /** + * 字段 desc。 + */ private DbObject desc; + /** + * 时间字段。 + */ private Date createdAt = new Date(); + /** + * 最后Updated。 + */ private Date lastUpdated = new Date(); + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.createdAt = new Date(); this.lastUpdated = new Date(); } + /** + * 获取 {@code title}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getTitle() { if (this.title == null) { this.title = new DbObject(); @@ -24,18 +72,40 @@ public class StoreBase { return this.title; } + /** + * 设置 {@code title}。 + * + * @param title 参数 {@code title}({@code DbObject}) + */ public void setTitle(DbObject title) { this.title = title; } + /** + * 设置Title。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setTitle(String key, Object value) { this.getTitle().append(key, value); } + /** + * 设置 {@code title}。 + * + * @param title 参数 {@code title}({@code String}) + */ public void setTitle(String title) { this.setTitle(LocaleConst.DEFAULT_LOCALE.toLanguageTag(), title); } + /** + * 获取 {@code summary}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getSummary() { if (this.summary == null) { this.summary = new DbObject(); @@ -44,14 +114,31 @@ public class StoreBase { return this.summary; } + /** + * 设置 {@code summary}。 + * + * @param summary 参数 {@code summary}({@code DbObject}) + */ public void setSummary(DbObject summary) { this.summary = summary; } + /** + * 设置Summary。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setSummary(String key, Object value) { this.getSummary().append(key, value); } + /** + * 获取 {@code desc}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getDesc() { if (this.desc == null) { this.desc = new DbObject(); @@ -60,26 +147,55 @@ public class StoreBase { return this.desc; } + /** + * 设置 {@code description}。 + * + * @param desc 参数 {@code desc}({@code DbObject}) + */ public void setDescription(DbObject desc) { this.desc = desc; } + /** + * 设置Description。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setDescription(String key, Object value) { this.getDesc().append(key, value); } + /** + * 获取 {@code createdAt}。 + * @return 字段/派生属性 {@code createdAt} 的值 + */ public Date getCreatedAt() { return this.createdAt; } + /** + * 设置 {@code createdAt}。 + * + * @param createdAt 参数 {@code createdAt}({@code Date}) + */ public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } + /** + * 获取 {@code lastUpdated}。 + * @return 字段/派生属性 {@code lastUpdated} 的值 + */ public Date getLastUpdated() { return this.lastUpdated; } + /** + * 设置 {@code lastUpdated}。 + * + * @param lastUpdated 参数 {@code lastUpdated}({@code Date}) + */ public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } diff --git a/src/main/java/com/midm/model/store/StoreOta.java b/src/main/java/com/midm/model/store/StoreOta.java index 7ad00c0..f810c72 100644 --- a/src/main/java/com/midm/model/store/StoreOta.java +++ b/src/main/java/com/midm/model/store/StoreOta.java @@ -5,66 +5,172 @@ import java.util.Date; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreOta} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code productId}(String):productID
  • + *
  • {@code deviceId}(String):设备ID
  • + *
  • {@code otaInfo}(DbObject):OTA 固件信息
  • + *
  • {@code isFormal}(Boolean):判断是否Formal
  • + *
  • {@code createdAt}(Date):时间字段
  • + *
  • {@code lastUpdated}(Date):最后Updated
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreOta { + /** + * productID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String productId; + /** + * 设备ID。 + */ private String deviceId; + /** + * OTA 固件信息。 + */ private DbObject otaInfo; + /** + * 判断是否Formal。 + */ private Boolean isFormal; + /** + * 时间字段。 + */ private Date createdAt; + /** + * 最后Updated。 + */ private Date lastUpdated; + /** + * 构造 {@code StoreOta} 实例。 + * + * 实现要点:主要调用:new Date。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public StoreOta(String productId) { this.productId = productId; this.createdAt = new Date(); this.lastUpdated = new Date(); } + /** + * 判断 {@code formal}。 + * @return 字段/派生属性 {@code formal} 的值 + */ Boolean isFormal() { return this.isFormal; } + /** + * 设置 {@code isFormal}。 + * + * @param isFormal 参数 {@code isFormal}({@code Boolean}) + */ public void setIsFormal(Boolean isFormal) { this.isFormal = isFormal; } + /** + * 获取 {@code productId}。 + * @return 字符串结果 + */ public String getProductId() { return this.productId; } + /** + * 设置 {@code productId}。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void setProductId(String productId) { this.productId = productId; } + /** + * 获取 {@code deviceId}。 + * @return 字符串结果 + */ public String getDeviceId() { return this.deviceId; } + /** + * 设置 {@code deviceId}。 + * + * @param deviceId 参数 {@code deviceId}({@code String}) + */ public void setDeviceId(String deviceId) { this.deviceId = deviceId; } + /** + * 获取 {@code createdAt}。 + * @return 字段/派生属性 {@code createdAt} 的值 + */ public Date getCreatedAt() { return this.createdAt; } + /** + * 设置 {@code createdAt}。 + * + * @param createdAt 参数 {@code createdAt}({@code Date}) + */ public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } + /** + * 获取 {@code lastUpdated}。 + * @return 字段/派生属性 {@code lastUpdated} 的值 + */ public Date getLastUpdated() { return this.lastUpdated; } + /** + * 设置 {@code lastUpdated}。 + * + * @param lastUpdated 参数 {@code lastUpdated}({@code Date}) + */ public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } + /** + * 获取 {@code otaInfo}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getOtaInfo() { return this.otaInfo; } + /** + * 设置 {@code otaInfo}。 + * + * @param otaInfo 参数 {@code otaInfo}({@code DbObject}) + */ public void setOtaInfo(DbObject otaInfo) { this.otaInfo = otaInfo; } diff --git a/src/main/java/com/midm/model/store/StoreOtaFile.java b/src/main/java/com/midm/model/store/StoreOtaFile.java index 095d6c8..2f98f12 100644 --- a/src/main/java/com/midm/model/store/StoreOtaFile.java +++ b/src/main/java/com/midm/model/store/StoreOtaFile.java @@ -6,21 +6,64 @@ import com.mitac.cell.io.McFile; import java.util.UUID; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreOtaFile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code note}(String[]):备注
  • + *
+ * + * 协作对象:{@code String[]}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreOtaFile extends OtaFile { + /** + * 备注。 + */ private String[] note; + /** + * 构造 {@code StoreOtaFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public StoreOtaFile() { } + /** + * 构造 {@code StoreOtaFile} 实例。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param file 文件({@code McFile}) + */ public StoreOtaFile(User user, UUID fileUuid, McFile file) { super(user, fileUuid, file); } + /** + * 获取 {@code note}。 + * @return 字段/派生属性 {@code note} 的值 + */ public String[] getNote() { return this.note; } + /** + * 设置 {@code notes}。 + * + * @param note 参数 {@code note}({@code String[]}) + */ public void setNotes(String[] note) { this.note = note; } diff --git a/src/main/java/com/midm/model/store/StoreOtherFile.java b/src/main/java/com/midm/model/store/StoreOtherFile.java index ac4cb31..2761b95 100644 --- a/src/main/java/com/midm/model/store/StoreOtherFile.java +++ b/src/main/java/com/midm/model/store/StoreOtherFile.java @@ -6,21 +6,62 @@ import com.mitac.cell.io.McFile; import java.util.UUID; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreOtherFile} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code alias}(String):字段 alias
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreOtherFile extends BaseFile { + /** + * 字段 alias。 + */ private String alias; + /** + * 构造 {@code StoreOtherFile} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public StoreOtherFile() { } + /** + * 构造 {@code StoreOtherFile} 实例。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param file 文件({@code McFile}) + */ public StoreOtherFile(User user, UUID fileUuid, McFile file) { super(user, fileUuid, file); } + /** + * 获取 {@code alias}。 + * @return 字符串结果 + */ public String getAlias() { return this.alias; } + /** + * 设置 {@code alias}。 + * + * @param alias 参数 {@code alias}({@code String}) + */ public void setAlias(String alias) { this.alias = alias; } diff --git a/src/main/java/com/midm/model/store/StoreWebApp.java b/src/main/java/com/midm/model/store/StoreWebApp.java index 839e3f9..7a0fe15 100644 --- a/src/main/java/com/midm/model/store/StoreWebApp.java +++ b/src/main/java/com/midm/model/store/StoreWebApp.java @@ -17,34 +17,100 @@ import java.util.zip.ZipEntry; import org.joda.time.DateTime; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StoreWebApp} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code appInfo}(DbObject):应用信息
  • + *
  • {@code isFormal}(Boolean):判断是否Formal
  • + *
  • {@code releaseNote}(List):release备注
  • + *
  • {@code releaseNoteNewFunction}(List):release备注新Function
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StoreWebApp extends BaseFile { + /** + * 应用信息。 + */ private DbObject appInfo; + /** + * 判断是否Formal。 + */ private Boolean isFormal; - private List releaseNote; - private List releaseNoteNewFunction; + /** + * release备注。 + */ + private List releaseNote; + /** + * release备注新Function。 + */ + private List releaseNoteNewFunction; + /** + * 构造 {@code StoreWebApp} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public StoreWebApp() { } + /** + * 构造 {@code StoreWebApp} 实例。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param file 文件({@code McFile}) + */ public StoreWebApp(User user, UUID fileUuid, McFile file) { super(user, fileUuid, file); this.setAppInfo((File)file); } + /** + * 构造 {@code StoreWebApp} 实例。 + * + * @param file 文件({@code McFile}) + */ public StoreWebApp(McFile file) { super((User)null, (UUID)null, file); this.setAppInfo((File)file); } + /** + * 判断 {@code formal}。 + * @return 字段/派生属性 {@code formal} 的值 + */ public boolean isFormal() { return this.isFormal != null && this.isFormal; } + /** + * 设置 {@code isFormal}。 + * + * @param isFormal 参数 {@code isFormal}({@code boolean}) + */ public void setIsFormal(boolean isFormal) { this.isFormal = isFormal; } + /** + * 获取 {@code appInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getAppInfo() { if (this.appInfo == null) { this.appInfo = new DbObject(); @@ -53,10 +119,23 @@ public class StoreWebApp extends BaseFile { return this.appInfo; } + /** + * 设置 {@code appInfo}。 + * + * @param appInfo 参数 {@code appInfo}({@code DbObject}) + */ public void setAppInfo(DbObject appInfo) { this.appInfo = appInfo; } + /** + * 设置应用信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setAppInfo(String key, Object value) { if (!this.getAppInfo().containsKey(key)) { this.getAppInfo().append(key, value); @@ -64,6 +143,13 @@ public class StoreWebApp extends BaseFile { } + /** + * 设置 {@code appInfo}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:parse。 + * + * @param properties 参数 {@code properties}({@code Properties}) + */ public void setAppInfo(Properties properties) { properties.forEach((key, value) -> { String name = (String)key; @@ -99,23 +185,45 @@ public class StoreWebApp extends BaseFile { }); } + /** + * 获取 {@code groupId}。 + * @return 字符串结果 + */ public String getGroupId() { return this.getAppInfo().getString("groupId"); } + /** + * 获取 {@code artifactId}。 + * @return 字符串结果 + */ public String getArtifactId() { return this.getAppInfo().getString("artifactId"); } + /** + * 获取 {@code version}。 + * @return 字符串结果 + */ public String getVersion() { return this.getAppInfo().getString("version"); } + /** + * 获取 {@code buildTime}。 + * @return 字段/派生属性 {@code buildTime} 的值 + */ public Date getBuildTime() { return this.getAppInfo().getDate("buildTime"); } - public List getReleaseNote() { + /** + * 获取 {@code releaseNote}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return String列表,可能为空 + */ + public List getReleaseNote() { if (this.releaseNote == null) { this.releaseNote = new ArrayList(); } @@ -123,15 +231,30 @@ public class StoreWebApp extends BaseFile { return this.releaseNote; } - public void setReleaseNote(List releaseNote) { + /** + * 设置 {@code releaseNote}。 + * + * @param releaseNote 参数 {@code releaseNote}({@code List}) + */ + public void setReleaseNote(List releaseNote) { this.releaseNote = releaseNote; } + /** + * 判断 {@code releaseNote}。 + * @return 字段/派生属性 {@code releaseNote} 的值 + */ public boolean hasReleaseNote() { return !this.getReleaseNote().isEmpty(); } - public List getReleaseNoteNewFunction() { + /** + * 获取 {@code releaseNoteNewFunction}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return String列表,可能为空 + */ + public List getReleaseNoteNewFunction() { if (this.releaseNoteNewFunction == null) { this.releaseNoteNewFunction = new ArrayList(); } @@ -139,18 +262,37 @@ public class StoreWebApp extends BaseFile { return this.releaseNoteNewFunction; } - public void setReleaseNoteNewFunction(List releaseNoteNewFunction) { + /** + * 设置 {@code releaseNoteNewFunction}。 + * + * @param releaseNoteNewFunction 参数 {@code releaseNoteNewFunction}({@code List}) + */ + public void setReleaseNoteNewFunction(List releaseNoteNewFunction) { this.releaseNoteNewFunction = releaseNoteNewFunction; } + /** + * 判断 {@code releaseNoteNewFunction}。 + * @return 字段/派生属性 {@code releaseNoteNewFunction} 的值 + */ public boolean hasReleaseNoteNewFunction() { return !this.getReleaseNoteNewFunction().isEmpty(); } + /** + * 判断 {@code webApp}。 + * @return 字段/派生属性 {@code webApp} 的值 + */ public boolean isWebApp() { return !Strings.isNullOrEmpty(this.getGroupId()) && !Strings.isNullOrEmpty(this.getArtifactId()); } + /** + * 获取 {@code fileName}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getFileName() { String fileName = super.getFileName(); if (Strings.isNullOrEmpty(fileName)) { @@ -160,6 +302,13 @@ public class StoreWebApp extends BaseFile { return fileName; } + /** + * 设置 {@code appInfo}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new JarFile、new Properties、close。 + * + * @param file 文件({@code File}) + */ private void setAppInfo(File file) { try { JarFile jarFile = new JarFile(file); @@ -201,6 +350,15 @@ public class StoreWebApp extends BaseFile { } + /** + * 查找ZipEntry。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环。 + * + * @param jarFile 参数 {@code jarFile}({@code JarFile}) + * @param name 参数 {@code name}({@code String}) + * @return 处理结果 + */ private ZipEntry findZipEntry(JarFile jarFile, String name) { Enumeration entries = jarFile.entries(); diff --git a/src/main/java/com/midm/model/store/package-info.java b/src/main/java/com/midm/model/store/package-info.java new file mode 100644 index 0000000..d39229a --- /dev/null +++ b/src/main/java/com/midm/model/store/package-info.java @@ -0,0 +1,22 @@ +/** + * 应用商店模型:StoreApp、WebApp、ReleaseNote、OTA 发布信息。 + * + *

本包主要类型: + *

    + *
  • {@link AppReleaseNote}
  • + *
  • {@link KeyStore}
  • + *
  • {@link OtaReleaseNote}
  • + *
  • {@link ReleaseNote}
  • + *
  • {@link StoreApp}
  • + *
  • {@link StoreAppFile}
  • + *
  • {@link StoreBase}
  • + *
  • {@link StoreOta}
  • + *
  • {@link StoreOtaFile}
  • + *
  • {@link StoreOtherFile}
  • + *
  • {@link StoreWebApp}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.store; diff --git a/src/main/java/com/midm/model/system/AltLocale.java b/src/main/java/com/midm/model/system/AltLocale.java index 888adb8..92391e3 100644 --- a/src/main/java/com/midm/model/system/AltLocale.java +++ b/src/main/java/com/midm/model/system/AltLocale.java @@ -4,28 +4,77 @@ import java.util.Locale; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code AltLocale} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code locale}(String):语言区域
  • + *
  • {@code altLocale}(String):alt语言区域
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class AltLocale { + /** + * 语言区域;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String locale; + /** + * alt语言区域。 + */ private String altLocale; + /** + * 获取 {@code locale}。 + * @return 字符串结果 + */ public String getLocale() { return this.locale; } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code String}) + */ public void setLocale(String locale) { this.locale = locale; } + /** + * 获取 {@code altLocale}。 + * @return 字符串结果 + */ public String getAltLocale() { return this.altLocale; } + /** + * 设置 {@code altLocale}。 + * + * @param altLocale 参数 {@code altLocale}({@code String}) + */ public void setAltLocale(String altLocale) { this.altLocale = altLocale; } + /** + * 处理转换为语言区域。 + * @return 处理结果 + */ public Locale toLocale() { return Locale.forLanguageTag(this.getAltLocale()); } diff --git a/src/main/java/com/midm/model/system/Category.java b/src/main/java/com/midm/model/system/Category.java index 67609ea..2267003 100644 --- a/src/main/java/com/midm/model/system/Category.java +++ b/src/main/java/com/midm/model/system/Category.java @@ -6,21 +6,76 @@ import java.util.Locale; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code Category} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code id}(CategoryId):ID
  • + *
  • {@code order}(int):字段 order
  • + *
  • {@code profile}(DbObject):配置档案
  • + *
  • {@code features}(List):许可证Feature集合
  • + *
+ * + * 协作对象:{@code CategoryId、DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class Category { + /** + * ID;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id public CategoryId id; + /** + * 字段 order。 + */ public int order; + /** + * 配置档案。 + */ public DbObject profile; - public List features; + /** + * 许可证Feature集合。 + */ + public List features; + /** + * 构造 {@code Category} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Category() { } + /** + * 构造 {@code Category} 实例。 + * + * 实现要点:主要调用:new CategoryId。 + * + * @param use 参数 {@code use}({@code String}) + * @param categoryId 参数 {@code categoryId}({@code String}) + */ public Category(String use, String categoryId) { this.id = new CategoryId(use, categoryId); } + /** + * 获取 {@code id}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new CategoryId。 + * @return 字段/派生属性 {@code id} 的值 + */ public CategoryId getId() { if (this.id == null) { this.id = new CategoryId(); @@ -29,46 +84,99 @@ public class Category { return this.id; } + /** + * 设置 {@code id}。 + * + * @param id 参数 {@code id}({@code CategoryId}) + */ public void setId(CategoryId id) { this.id = id; } + /** + * 获取 {@code use}。 + * @return 字符串结果 + */ public String getUse() { return this.getId().getUse(); } + /** + * 设置 {@code use}。 + * + * @param use 参数 {@code use}({@code String}) + */ public void setUse(String use) { this.getId().setUse(use); } + /** + * 获取 {@code categoryId}。 + * @return 字符串结果 + */ public String getCategoryId() { return this.getId().getId(); } + /** + * 设置 {@code categoryId}。 + * + * @param id 参数 {@code id}({@code String}) + */ public void setCategoryId(String id) { this.getId().setId(id); } + /** + * 设置Category。 + * + * @param use 参数 {@code use}({@code String}) + * @param categoryId 参数 {@code categoryId}({@code String}) + */ public void setCategory(String use, String categoryId) { this.getId().set(use, categoryId); } - public List getFeatures() { + /** + * 获取 {@code features}。 + * @return 许可证Feature列表,可能为空 + */ + public List getFeatures() { return this.features; } - public void setFeatures(List features) { + /** + * 设置 {@code features}。 + * + * @param features 参数 {@code features}({@code List}) + */ + public void setFeatures(List features) { this.features = features; } + /** + * 获取 {@code order}。 + * @return 数量/长度 + */ public int getOrder() { return this.order; } + /** + * 设置 {@code order}。 + * + * @param order 参数 {@code order}({@code int}) + */ public void setOrder(int order) { this.order = order; } + /** + * 获取 {@code profile}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile() { if (this.profile == null) { this.profile = new DbObject(); @@ -77,10 +185,24 @@ public class Category { return this.profile; } + /** + * 设置 {@code profile}。 + * + * @param profile 设备配置档案({@code DbObject}) + */ public void setProfile(DbObject profile) { this.profile = profile; } + /** + * 设置配置档案。 + * + * 实现要点:主要调用:new DbObject。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @param name 参数 {@code name}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + */ public void setProfile(Locale locale, String name, String desc) { DbObject profile = new DbObject(); profile.put("name", name); @@ -88,6 +210,12 @@ public class Category { this.getProfile().put(locale.toString(), profile); } + /** + * 获取配置档案。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile(Locale locale) { return (DbObject)this.getProfile().get(locale.toString()); } diff --git a/src/main/java/com/midm/model/system/CategoryId.java b/src/main/java/com/midm/model/system/CategoryId.java index 3f96a57..25c6cd4 100644 --- a/src/main/java/com/midm/model/system/CategoryId.java +++ b/src/main/java/com/midm/model/system/CategoryId.java @@ -2,33 +2,90 @@ package com.midm.model.system; import java.io.Serializable; +/** + * 【领域模型】{@code CategoryId} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code use}(String):字段 use
  • + *
  • {@code id}(String):ID
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class CategoryId implements Serializable { + /** + * 字段 use。 + */ private String use; + /** + * ID。 + */ private String id; + /** + * 构造 {@code CategoryId} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public CategoryId() { } + /** + * 构造 {@code CategoryId} 实例。 + * + * @param use 参数 {@code use}({@code String}) + * @param id 参数 {@code id}({@code String}) + */ public CategoryId(String use, String id) { this.set(use, id); } + /** + * 获取 {@code use}。 + * @return 字符串结果 + */ public String getUse() { return this.use; } + /** + * 设置 {@code use}。 + * + * @param use 参数 {@code use}({@code String}) + */ public void setUse(String use) { this.use = use; } + /** + * 获取 {@code id}。 + * @return 字符串结果 + */ public String getId() { return this.id; } + /** + * 设置 {@code id}。 + * + * @param id 参数 {@code id}({@code String}) + */ public void setId(String id) { this.id = id; } + /** + * 处理设置。 + * + * @param use 参数 {@code use}({@code String}) + * @param id 参数 {@code id}({@code String}) + */ public void set(String use, String id) { this.setUse(use); this.setId(id); diff --git a/src/main/java/com/midm/model/system/DbTemplate.java b/src/main/java/com/midm/model/system/DbTemplate.java index db7380b..1f31fe4 100644 --- a/src/main/java/com/midm/model/system/DbTemplate.java +++ b/src/main/java/com/midm/model/system/DbTemplate.java @@ -3,51 +3,133 @@ package com.midm.model.system; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code DbTemplate} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(String):代码
  • + *
  • {@code name}(String):名称
  • + *
  • {@code content}(String):字段 content
  • + *
  • {@code comment}(String):字段 comment
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class DbTemplate { + /** + * 代码;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String code; + /** + * 名称。 + */ private String name; + /** + * 字段 content。 + */ private String content; + /** + * 字段 comment。 + */ private String comment; + /** + * 构造 {@code DbTemplate} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DbTemplate() { } + /** + * 构造 {@code DbTemplate} 实例。 + * + * @param code 状态码/业务码({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param content 参数 {@code content}({@code String}) + */ public DbTemplate(String code, String name, String content) { this.setCode(code); this.setName(name); this.setContent(content); } + /** + * 获取 {@code code}。 + * @return 字符串结果 + */ public String getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code String}) + */ public void setCode(String code) { this.code = code; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code content}。 + * @return 字符串结果 + */ public String getContent() { return this.content; } + /** + * 设置 {@code content}。 + * + * @param content 参数 {@code content}({@code String}) + */ public void setContent(String content) { this.content = content; } + /** + * 获取 {@code comment}。 + * @return 字符串结果 + */ public String getComment() { return this.comment; } + /** + * 设置 {@code comment}。 + * + * @param comment 参数 {@code comment}({@code String}) + */ public void setComment(String comment) { this.comment = comment; } diff --git a/src/main/java/com/midm/model/system/HelpMessage.java b/src/main/java/com/midm/model/system/HelpMessage.java index 0fed051..16ba26b 100644 --- a/src/main/java/com/midm/model/system/HelpMessage.java +++ b/src/main/java/com/midm/model/system/HelpMessage.java @@ -5,35 +5,105 @@ import com.mitac.cell.db.DbObject; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code HelpMessage} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(String):代码
  • + *
  • {@code message}(DbObject):消息
  • + *
  • {@code options}(DbObject):选项列表
  • + *
  • {@code comment}(String):字段 comment
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class HelpMessage { + /** + * 代码;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String code; + /** + * 消息。 + */ private DbObject message; + /** + * 选项列表。 + */ private DbObject options; + /** + * 字段 comment。 + */ private String comment; + /** + * 构造 {@code HelpMessage} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public HelpMessage() { } + /** + * 构造 {@code HelpMessage} 实例。 + * + * @param code 状态码/业务码({@code String}) + */ public HelpMessage(String code) { this.setCode(code); } + /** + * 构造 {@code HelpMessage} 实例。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param title 参数 {@code title}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @param comment 参数 {@code comment}({@code String}) + */ public HelpMessage(String code, String locale, String title, String desc, String comment) { this.setCode(code); this.setMessage(locale, title, desc); this.setComment(comment); } + /** + * 获取 {@code code}。 + * @return 字符串结果 + */ public String getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code String}) + */ public void setCode(String code) { this.code = code; } + /** + * 获取 {@code message}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage() { if (this.message == null) { this.message = new DbObject(); @@ -42,26 +112,64 @@ public class HelpMessage { return this.message; } + /** + * 设置 {@code messages}。 + * + * @param messages 参数 {@code messages}({@code DbObject}) + */ public void setMessages(DbObject messages) { this.message = messages; } + /** + * 设置消息。 + * + * 实现要点:主要调用:new DbObject。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param title 参数 {@code title}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + */ public void setMessage(String locale, String title, String desc) { this.getMessage().append(locale, (new DbObject("title", title)).append("desc", this.message)); } + /** + * 获取Title。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getTitle(String locale) { return this.getMessage(locale).getString("title"); } + /** + * 获取消息。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage(String locale) { return this.getMessage().getDbObject(new String[]{Strings.isNullOrEmpty(locale) ? "en-US" : locale}); } + /** + * 获取Description。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getDescription(String locale) { return this.getMessage(locale).getString("desc"); } + /** + * 获取 {@code options}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getOptions() { if (this.options == null) { this.options = new DbObject(); @@ -70,6 +178,14 @@ public class HelpMessage { return this.options; } + /** + * 获取选项列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getOptions(String category) { Object categoryObject = this.getOptions().get(category); if (categoryObject == null) { @@ -80,22 +196,49 @@ public class HelpMessage { return (DbObject)categoryObject; } + /** + * 设置 {@code options}。 + * + * @param options 参数 {@code options}({@code DbObject}) + */ public void setOptions(DbObject options) { this.options = options; } + /** + * 设置选项列表。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param options 参数 {@code options}({@code DbObject}) + */ public void setOptions(String category, DbObject options) { this.getOptions().put(category, options); } + /** + * 设置选项列表。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @param desc 参数 {@code desc}({@code String}) + */ public void setOptions(String category, String key, String desc) { this.getOptions(category).put(key, desc); } + /** + * 获取 {@code comment}。 + * @return 字符串结果 + */ public String getComment() { return this.comment; } + /** + * 设置 {@code comment}。 + * + * @param comment 参数 {@code comment}({@code String}) + */ public void setComment(String comment) { this.comment = comment; } diff --git a/src/main/java/com/midm/model/system/HostLicense.java b/src/main/java/com/midm/model/system/HostLicense.java index 594b645..3ae7eec 100644 --- a/src/main/java/com/midm/model/system/HostLicense.java +++ b/src/main/java/com/midm/model/system/HostLicense.java @@ -20,45 +20,156 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code HostLicense} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code trialPeriod}(Integer):字段 trialPeriod
  • + *
  • {@code trialDeviceLimit}(Integer):trial设备Limit
  • + *
  • {@code trialSiteLimit}(Integer):trial站点Limit
  • + *
  • {@code hostId}(String):hostID
  • + *
  • {@code siteLimit}(Integer):站点Limit
  • + *
  • {@code deviceLimit}(Integer):设备Limit
  • + *
+ * + * 协作对象:{@code DbObject、McTextEncryptor}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class HostLicense { + /** + * 字段 trialPeriod。 + */ public static final Integer trialPeriod = 45; + /** + * trial设备Limit。 + */ private static final Integer trialDeviceLimit = -1; + /** + * trial站点Limit。 + */ private static final Integer trialSiteLimit = -1; + /** + * hostID;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private String hostId; + /** + * 站点Limit;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Integer siteLimit; + /** + * 设备Limit;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Integer deviceLimit; + /** + * valid从;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Long validFrom; + /** + * valid转换为;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Long validTo; + /** + * 判断是否Standalone;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private boolean isStandalone; + /** + * 判断是否Valid密钥;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Boolean isValidKey; + /** + * 系统哈希;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String systemHash; + /** + * 许可证密钥。 + */ private String licenseKey; + /** + * 字段 properties。 + */ private DbObject properties; + /** + * 判断是否Primary。 + */ private boolean isPrimary; + /** + * 字段 validated;Gson 序列化控制。 + * + * 注解:{@code @Expose(serialize = false)}。 + */ @Expose( serialize = false ) private String validated; + /** + * 字段 validatedAt;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private Long validatedAt; + /** + * 字段 encryptor;不持久化到 MongoDB,仅运行时使用;Gson 序列化控制。 + * + * 注解:{@code @Transient @Expose(serialize = false)}。 + */ @Transient @Expose( serialize = false ) private McTextEncryptor encryptor; + /** + * 令牌Password。 + */ private static final String tokenPassword = "MiDM@MiTAC.com"; + /** + * 令牌Salt。 + */ private static final String tokenSalt = "171891893b5cef2f"; + /** + * 字段 sourceEncryptor。 + */ public static final McTextEncryptor sourceEncryptor = new McTextEncryptor("MiDM@MiTAC.com", "171891893b5cef2f"); + /** + * 构造 {@code HostLicense} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public HostLicense() { this.siteLimit = trialSiteLimit; this.deviceLimit = trialDeviceLimit; @@ -68,10 +179,23 @@ public class HostLicense { this.isValidKey = false; } + /** + * 构造 {@code HostLicense} 实例。 + * + * @param hostId 参数 {@code hostId}({@code String}) + * @param systemHash 参数 {@code systemHash}({@code String}) + */ public HostLicense(String hostId, String systemHash) { this(hostId, systemHash, (String)null); } + /** + * 构造 {@code HostLicense} 实例。 + * + * @param hostId 参数 {@code hostId}({@code String}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param licenseKey 参数 {@code licenseKey}({@code String}) + */ public HostLicense(String hostId, String systemHash, String licenseKey) { this.siteLimit = trialSiteLimit; this.deviceLimit = trialDeviceLimit; @@ -85,23 +209,46 @@ public class HostLicense { this.dispatch(); } + /** + * 获取 {@code systemHash}。 + * @return 字符串结果 + */ public String getSystemHash() { return this.systemHash; } + /** + * 设置 {@code systemHash}。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + */ public void setSystemHash(String systemHash) { this.systemHash = systemHash; } + /** + * 获取 {@code hostId}。 + * @return 字符串结果 + */ public String getHostId() { return this.hostId; } + /** + * 设置 {@code hostId}。 + * + * @param hostId 参数 {@code hostId}({@code String}) + */ public void setHostId(String hostId) { this.hostId = hostId; this.refreshEncryptor(); } + /** + * 刷新Encryptor。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new McTextEncryptor。 + */ private void refreshEncryptor() { if (!Strings.isNullOrEmpty(this.hostId) && !Strings.isNullOrEmpty(this.systemHash)) { try { @@ -115,14 +262,29 @@ public class HostLicense { } + /** + * 获取 {@code licenseKey}。 + * @return 字符串结果 + */ public String getLicenseKey() { return this.licenseKey; } + /** + * 判断 {@code licenseKey}。 + * @return 字段/派生属性 {@code licenseKey} 的值 + */ public boolean hasLicenseKey() { return !Strings.isNullOrEmpty(this.licenseKey); } + /** + * 设置 {@code licenseKey}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param licenseKey 参数 {@code licenseKey}({@code String}) + */ public void setLicenseKey(String licenseKey) { this.licenseKey = licenseKey; if (Strings.isNullOrEmpty(licenseKey)) { @@ -134,50 +296,104 @@ public class HostLicense { } + /** + * 判断 {@code validKey}。 + * @return 字段/派生属性 {@code validKey} 的值 + */ public boolean isValidKey() { return this.isValidKey; } + /** + * 获取 {@code siteLimit}。 + * @return 数量/长度 + */ public int getSiteLimit() { return this.siteLimit; } + /** + * 设置 {@code siteLimit}。 + * + * @param siteLimit 参数 {@code siteLimit}({@code int}) + */ public void setSiteLimit(int siteLimit) { this.siteLimit = siteLimit; } + /** + * 获取 {@code deviceLimit}。 + * @return 数量/长度 + */ public int getDeviceLimit() { return this.deviceLimit; } + /** + * 设置 {@code deviceLimit}。 + * + * @param deviceLimit 参数 {@code deviceLimit}({@code int}) + */ public void setDeviceLimit(int deviceLimit) { this.deviceLimit = deviceLimit; } + /** + * 获取 {@code validFrom}。 + * @return 数量/长度 + */ public Long getValidFrom() { return this.validFrom; } + /** + * 设置 {@code validFrom}。 + * + * @param validFrom 参数 {@code validFrom}({@code Long}) + */ public void setValidFrom(Long validFrom) { this.validFrom = validFrom; } + /** + * 获取 {@code validTo}。 + * @return 数量/长度 + */ public Long getValidTo() { return this.validTo; } + /** + * 设置 {@code validTo}。 + * + * @param validTo 参数 {@code validTo}({@code Long}) + */ public void setValidTo(Long validTo) { this.validTo = validTo; } + /** + * 判断 {@code standalone}。 + * @return 字段/派生属性 {@code standalone} 的值 + */ public boolean isStandalone() { return this.isStandalone; } + /** + * 设置 {@code isStandalone}。 + * + * @param isStandalone 参数 {@code isStandalone}({@code boolean}) + */ public void setIsStandalone(boolean isStandalone) { this.isStandalone = isStandalone; } + /** + * 设置AsTrial。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date、new DateTime。 + */ public void setAsTrial() { this.setIsStandalone(true); this.setDeviceLimit(trialDeviceLimit); @@ -188,18 +404,40 @@ public class HostLicense { this.validTo = (new DateTime(this.validFrom)).plusDays(trialPeriod).getMillis(); } + /** + * 判断 {@code valid}。 + * @return 字段/派生属性 {@code valid} 的值 + */ public boolean isValid() { return !this.isExpired() && this.isValidated(); } + /** + * 判断 {@code validated}。 + * + * 实现要点:主要调用:new DateTime。 + * @return 字段/派生属性 {@code validated} 的值 + */ private boolean isValidated() { return DateTime.now().isBefore((new DateTime(this.validatedDate())).plusDays(trialPeriod)); } + /** + * 判断 {@code expired}。 + * + * 实现要点:主要调用:new DateTime。 + * @return 字段/派生属性 {@code expired} 的值 + */ private boolean isExpired() { return this.validTo != -1L && (new DateTime(this.validTo)).plusDays(1).isBeforeNow(); } + /** + * 获取 {@code properties}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProperties() { if (this.properties == null) { this.properties = new DbObject(); @@ -208,14 +446,30 @@ public class HostLicense { return this.properties; } + /** + * 设置 {@code properties}。 + * + * @param properties 参数 {@code properties}({@code DbObject}) + */ public void setProperties(DbObject properties) { this.properties = properties; } + /** + * 设置Property。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + */ public void setProperty(String key, String value) { this.getProperties().append(key, value); } + /** + * 处理dispatch。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ public void dispatch() { if (!Strings.isNullOrEmpty(this.getLicenseKey())) { this.dispatch(this.getLicenseKey()); @@ -224,6 +478,11 @@ public class HostLicense { this.validatedDate(); } + /** + * 处理校验。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:encrypt、new Date。 + */ public void validate() { this.setProperty("ip_addr", McNetUtils.getIpAddress()); this.setProperty("host_name", McNetUtils.hostName()); @@ -233,6 +492,12 @@ public class HostLicense { } + /** + * 处理validated日期。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:decrypt。 + * @return 数量/长度 + */ public Long validatedDate() { this.validatedAt = null; if (!Strings.isNullOrEmpty(this.validated)) { @@ -245,14 +510,30 @@ public class HostLicense { return this.validatedAt; } + /** + * 判断 {@code primary}。 + * @return 字段/派生属性 {@code primary} 的值 + */ public boolean isPrimary() { return this.isPrimary; } + /** + * 设置 {@code primary}。 + * + * @param isPrimary 参数 {@code isPrimary}({@code boolean}) + */ public void setPrimary(boolean isPrimary) { this.isPrimary = isPrimary; } + /** + * 处理dispatch。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:decrypt。 + * + * @param encryptedLicense 参数 {@code encryptedLicense}({@code String}) + */ public void dispatch(String encryptedLicense) { if (this.encryptor == null) { this.refreshEncryptor(); @@ -279,6 +560,14 @@ public class HostLicense { } } + /** + * 生成系统哈希。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new McSystemInfo。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 字符串结果 + */ public static String generateSystemHash(String systemHash) { if (!Strings.isNullOrEmpty(systemHash)) { return systemHash; @@ -306,20 +595,52 @@ public class HostLicense { } } + /** + * 处理加密。 + * + * 实现要点:主要调用:encrypt。 + * + * @param value 值({@code String}) + * @return 字符串结果 + */ public static String encrypt(String value) { return sourceEncryptor.encrypt(value); } + /** + * 处理解密。 + * + * 实现要点:主要调用:decrypt。 + * + * @param value 值({@code String}) + * @return 字符串结果 + */ public static String decrypt(String value) { return sourceEncryptor.decrypt(value); } + /** + * 生成许可证。 + * @return 字符串结果 + */ public String generateLicense() { String licenseKey = this.generateLicense(this.siteLimit, this.deviceLimit, this.validTo, false, this.isStandalone); this.setLicenseKey(licenseKey); return licenseKey; } + /** + * 生成许可证。 + * + * 实现要点:包含 7 个条件分支、0 个循环;主要调用:new JsonObject、encrypt。 + * + * @param siteLimit 参数 {@code siteLimit}({@code Integer}) + * @param deviceLimit 参数 {@code deviceLimit}({@code Integer}) + * @param validTo 参数 {@code validTo}({@code Long}) + * @param isLicenseServer 参数 {@code isLicenseServer}({@code Boolean}) + * @param isStandalone 参数 {@code isStandalone}({@code Boolean}) + * @return 字符串结果 + */ public String generateLicense(Integer siteLimit, Integer deviceLimit, Long validTo, Boolean isLicenseServer, Boolean isStandalone) { if (this.encryptor == null) { this.refreshEncryptor(); diff --git a/src/main/java/com/midm/model/system/LicenseFeature.java b/src/main/java/com/midm/model/system/LicenseFeature.java index 690c4d8..5cc8570 100644 --- a/src/main/java/com/midm/model/system/LicenseFeature.java +++ b/src/main/java/com/midm/model/system/LicenseFeature.java @@ -5,29 +5,86 @@ import java.util.Locale; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code LicenseFeature} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(String):代码
  • + *
  • {@code categoryId}(CategoryId):categoryID
  • + *
  • {@code profile}(DbObject):配置档案
  • + *
+ * + * 协作对象:{@code CategoryId、DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class LicenseFeature { + /** + * 代码;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id String code; + /** + * categoryID。 + */ CategoryId categoryId; + /** + * 配置档案。 + */ DbObject profile; + /** + * 获取 {@code code}。 + * @return 字符串结果 + */ public String getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code String}) + */ public void setCode(String code) { this.code = code; } + /** + * 获取 {@code categoryId}。 + * @return 字段/派生属性 {@code categoryId} 的值 + */ public CategoryId getCategoryId() { return this.categoryId; } + /** + * 设置 {@code categoryId}。 + * + * @param categoryId 参数 {@code categoryId}({@code CategoryId}) + */ public void setCategoryId(CategoryId categoryId) { this.categoryId = categoryId; } + /** + * 获取 {@code profile}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile() { if (this.profile == null) { this.profile = new DbObject(); @@ -36,10 +93,24 @@ public class LicenseFeature { return this.profile; } + /** + * 设置 {@code profile}。 + * + * @param profile 设备配置档案({@code DbObject}) + */ public void setProfile(DbObject profile) { this.profile = profile; } + /** + * 设置配置档案。 + * + * 实现要点:主要调用:new DbObject。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @param name 参数 {@code name}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + */ public void setProfile(Locale locale, String name, String desc) { DbObject profile = new DbObject(); profile.put("name", name); @@ -47,6 +118,12 @@ public class LicenseFeature { this.getProfile().put(locale.toString(), profile); } + /** + * 获取配置档案。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile(Locale locale) { return (DbObject)this.getProfile().get(locale.toString()); } diff --git a/src/main/java/com/midm/model/system/LicenseModel.java b/src/main/java/com/midm/model/system/LicenseModel.java index e4761b8..73fcb57 100644 --- a/src/main/java/com/midm/model/system/LicenseModel.java +++ b/src/main/java/com/midm/model/system/LicenseModel.java @@ -10,32 +10,127 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code LicenseModel} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code TYPE_TRIAL}(char):字段 TYPE_TRIAL
  • + *
  • {@code TYPE_PERPETUAL}(char):字段 TYPE_PERPETUAL
  • + *
  • {@code TYPE_YEARLY}(char):字段 TYPE_YEARLY
  • + *
  • {@code TYPE_MONTHLY}(char):字段 TYPE_MONTHLY
  • + *
  • {@code TYPE_DAILY}(char):字段 TYPE_DAILY
  • + *
  • {@code DEFAULT_TRIAL_DAYS}(int):字段 DEFAULT_TRIAL_DAYS
  • + *
+ * + * 协作对象:{@code DbObject、Character}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class LicenseModel { + /** + * 字段 TYPE_TRIAL。 + */ public static final char TYPE_TRIAL = 't'; + /** + * 字段 TYPE_PERPETUAL。 + */ public static final char TYPE_PERPETUAL = 'p'; + /** + * 字段 TYPE_YEARLY。 + */ public static final char TYPE_YEARLY = 'y'; + /** + * 字段 TYPE_MONTHLY。 + */ public static final char TYPE_MONTHLY = 'm'; + /** + * 字段 TYPE_DAILY。 + */ public static final char TYPE_DAILY = 'd'; + /** + * 字段 DEFAULT_TRIAL_DAYS。 + */ public static final int DEFAULT_TRIAL_DAYS = 45; + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 名称。 + */ private String name; + /** + * ID名称。 + */ private String idName; + /** + * 配置档案。 + */ private DbObject profile; + /** + * 类型。 + */ private Character type; + /** + * 字段 period。 + */ private Integer period; + /** + * 字段 freshExpiry。 + */ private String freshExpiry; + /** + * 字段 activatedExpiry。 + */ private String activatedExpiry; + /** + * 字段 autoExtend。 + */ private String autoExtend; + /** + * 字段 maxActivation。 + */ private Integer maxActivation = 2; + /** + * 判断是否Formal。 + */ private boolean isFormal; + /** + * 报表;不持久化到 MongoDB,仅运行时使用。 + * + * 注解:{@code @Transient}。 + */ @Transient private DbObject report; + /** + * 构造 {@code LicenseModel} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public LicenseModel() { } + /** + * 构造 {@code LicenseModel} 实例。 + * + * @param name 参数 {@code name}({@code String}) + * @param type 类型({@code Character}) + * @param period 参数 {@code period}({@code Integer}) + * @param maxActivation 参数 {@code maxActivation}({@code Integer}) + */ public LicenseModel(String name, Character type, Integer period, Integer maxActivation) { this.initUuid(); this.name = name; @@ -44,82 +139,171 @@ public class LicenseModel { this.maxActivation = maxActivation; } + /** + * 初始化UUID。 + */ public void initUuid() { this.setUuid(UUID.randomUUID()); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code idName}。 + * @return 字符串结果 + */ public String getIdName() { return this.idName; } + /** + * 设置 {@code idName}。 + * + * @param idName 参数 {@code idName}({@code String}) + */ public void setIdName(String idName) { this.idName = idName; } + /** + * 获取 {@code period}。 + * @return 数量/长度 + */ public Integer getPeriod() { return this.period; } + /** + * 设置 {@code period}。 + * + * @param period 参数 {@code period}({@code int}) + */ public void setPeriod(int period) { this.period = period; } + /** + * 获取 {@code type}。 + * @return 字段/派生属性 {@code type} 的值 + */ public Character getType() { return this.type; } + /** + * 设置 {@code type}。 + * + * @param type 类型({@code char}) + */ public void setType(char type) { this.type = type; } + /** + * 判断 {@code trial}。 + * @return 字段/派生属性 {@code trial} 的值 + */ public boolean isTrial() { return this.getType() == 't'; } + /** + * 判断 {@code perpetual}。 + * @return 字段/派生属性 {@code perpetual} 的值 + */ public boolean isPerpetual() { return this.getType() == 'p'; } + /** + * 获取 {@code maxActivation}。 + * @return 数量/长度 + */ public Integer getMaxActivation() { return this.maxActivation; } + /** + * 设置 {@code maxActivation}。 + * + * @param maxCount 参数 {@code maxCount}({@code int}) + */ public void setMaxActivation(int maxCount) { this.maxActivation = maxCount; } + /** + * 获取 {@code profile}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getProfile() { return this.profile; } + /** + * 判断 {@code formal}。 + * @return 字段/派生属性 {@code formal} 的值 + */ public boolean isFormal() { return this.isFormal; } + /** + * 设置 {@code formal}。 + * + * @param isFormal 参数 {@code isFormal}({@code boolean}) + */ public void setFormal(boolean isFormal) { this.isFormal = isFormal; } + /** + * 设置 {@code profile}。 + * + * @param profile 设备配置档案({@code DbObject}) + */ public void setProfile(DbObject profile) { this.profile = profile; } + /** + * 获取 {@code report}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getReport() { if (this.report == null) { this.report = new DbObject(); @@ -128,18 +312,41 @@ public class LicenseModel { return this.report; } + /** + * 获取报表AsLong。 + * + * @param key 键/配置项({@code String}) + * @return 数量/长度 + */ public long getReportAsLong(String key) { return this.getReport().getLong(key); } + /** + * 设置 {@code report}。 + * + * @param report 参数 {@code report}({@code DbObject}) + */ public void setReport(DbObject report) { this.report = report; } + /** + * 设置报表。 + * + * @param key 键/配置项({@code String}) + * @param data 参数 {@code data}({@code Object}) + */ public void setReport(String key, Object data) { this.getReport().put(key, data); } + /** + * 获取 {@code freshExpiry}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getFreshExpiry() { if (Strings.isNullOrEmpty(this.freshExpiry)) { switch (this.getType()) { @@ -151,18 +358,28 @@ public class LicenseModel { this.freshExpiry = "45d"; break; default: - String var10001 = String.valueOf(this.period); - this.freshExpiry = var10001 + this.type; + this.freshExpiry = String.valueOf(this.period) + this.type; } } return this.freshExpiry; } + /** + * 设置 {@code freshExpiry}。 + * + * @param expiry 参数 {@code expiry}({@code String}) + */ public void setFreshExpiry(String expiry) { this.freshExpiry = expiry; } + /** + * 获取 {@code activatedExpiry}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getActivatedExpiry() { if (Strings.isNullOrEmpty(this.activatedExpiry)) { switch (this.getType()) { @@ -173,18 +390,28 @@ public class LicenseModel { this.activatedExpiry = "45d"; break; default: - String var10001 = String.valueOf(this.period); - this.activatedExpiry = var10001 + this.type; + this.activatedExpiry = String.valueOf(this.period) + this.type; } } return this.activatedExpiry; } + /** + * 设置 {@code activatedExpiry}。 + * + * @param expiry 参数 {@code expiry}({@code String}) + */ public void setActivatedExpiry(String expiry) { this.activatedExpiry = expiry; } + /** + * 获取 {@code autoExtend}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getAutoExtend() { if (this.isPerpetual()) { this.autoExtend = "1y"; @@ -193,35 +420,106 @@ public class LicenseModel { return this.autoExtend; } + /** + * 设置 {@code autoExtend}。 + * + * @param extend 参数 {@code extend}({@code String}) + */ public void setAutoExtend(String extend) { this.autoExtend = extend; } + /** + * 获取FreshExpiry。 + * + * 实现要点:主要调用:new Period。 + * + * @param from 起始时间({@code Date}) + * @return 字段/派生属性 {@code freshExpiry} 的值 + */ public Date getFreshExpiry(Date from) { return (new Period(this.getFreshExpiry())).from(from); } + /** + * 获取ActivatedExpiry。 + * + * 实现要点:主要调用:new Period。 + * + * @param from 起始时间({@code Date}) + * @return 字段/派生属性 {@code activatedExpiry} 的值 + */ public Date getActivatedExpiry(Date from) { return (new Period(this.getActivatedExpiry())).from(from); } + /** + * 获取NextExpiry。 + * + * 实现要点:主要调用:new Period。 + * + * @param from 起始时间({@code Date}) + * @return 字段/派生属性 {@code nextExpiry} 的值 + */ public Date getNextExpiry(Date from) { return (new Period(this.getAutoExtend())).from(from); } + /** + * 处理defaultTrial。 + * + * 实现要点:主要调用:new LicenseModel。 + * @return 处理结果 + */ public static LicenseModel defaultTrial() { return new LicenseModel("Trial", 't', 45, 45); } + /** + * 【领域模型】{@code Period} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code period}(int):字段 period
  • + *
  • {@code unit}(char):字段 unit
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class Period { + /** + * 字段 period。 + */ private int period = 0; + /** + * 字段 unit。 + */ private char unit = 'd'; + /** + * 构造 {@code Period} 实例。 + * + * @param period 参数 {@code period}({@code int}) + * @param unit 参数 {@code unit}({@code char}) + */ public Period(int period, char unit) { this.period = period; this.unit = unit; } + /** + * 构造 {@code Period} 实例。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param expireBy 参数 {@code expireBy}({@code String}) + */ public Period(String expireBy) { if (!Strings.isNullOrEmpty(expireBy)) { String[] tokens = expireBy.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); @@ -231,18 +529,40 @@ public class LicenseModel { } + /** + * 获取 {@code period}。 + * @return 数量/长度 + */ public int getPeriod() { return this.period; } + /** + * 获取 {@code unit}。 + * @return 字段/派生属性 {@code unit} 的值 + */ public char getUnit() { return this.unit; } + /** + * 处理从Now。 + * + * 实现要点:主要调用:new Date。 + * @return 处理结果 + */ public Date fromNow() { return this.from(new Date()); } + /** + * 处理从。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DateTime。 + * + * @param date 参数 {@code date}({@code Date}) + * @return 处理结果 + */ public Date from(Date date) { if (this.period > 0) { LocalDate localDate = (new DateTime(date)).plusDays(1).toLocalDate(); @@ -262,6 +582,10 @@ public class LicenseModel { } } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return "" + this.period + this.unit; } diff --git a/src/main/java/com/midm/model/system/PolicyAgreement.java b/src/main/java/com/midm/model/system/PolicyAgreement.java index dd5b317..6e19c4e 100644 --- a/src/main/java/com/midm/model/system/PolicyAgreement.java +++ b/src/main/java/com/midm/model/system/PolicyAgreement.java @@ -9,66 +9,173 @@ import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code PolicyAgreement} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code category}(String):字段 category
  • + *
  • {@code version}(String):版本
  • + *
  • {@code message}(DbObject):消息
  • + *
  • {@code created}(Date):创建时间
  • + *
+ * + * 协作对象:{@code User、DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class PolicyAgreement { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 字段 writer;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private User writer; + /** + * 字段 category。 + */ private String category; + /** + * 版本。 + */ private String version; + /** + * 消息。 + */ private DbObject message; + /** + * 创建时间。 + */ private Date created; + /** + * 构造 {@code PolicyAgreement} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public PolicyAgreement() { this.init(); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.uuid = UUID.randomUUID(); this.created = new Date(); } + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param writer 参数 {@code writer}({@code User}) + */ public void setWriter(User writer) { this.writer = writer; } + /** + * 获取 {@code category}。 + * @return 字符串结果 + */ public String getCategory() { return this.category; } + /** + * 设置 {@code category}。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + */ public void setCategory(String category) { this.category = category; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code version}。 + * @return 字符串结果 + */ public String getVersion() { return this.version; } + /** + * 设置 {@code version}。 + * + * @param version 参数 {@code version}({@code String}) + */ public void setVersion(String version) { this.version = version; } + /** + * 获取 {@code message}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage() { if (this.message == null) { this.message = new DbObject(); @@ -77,19 +184,42 @@ public class PolicyAgreement { return this.message; } + /** + * 获取 {@code content}。 + * @return 字符串结果 + */ public String getContent() { return this.message.getString("content"); } + /** + * 设置 {@code content}。 + * + * @param content 参数 {@code content}({@code String}) + */ public void setContent(String content) { this.setContent(Locale.US.toLanguageTag(), content); } + /** + * 设置Content。 + * + * @param languageTag 参数 {@code languageTag}({@code String}) + * @param content 参数 {@code content}({@code String}) + */ public void setContent(String languageTag, String content) { DbObject message = this.getMessage(languageTag); message.put("content", content); } + /** + * 获取消息。 + * + * 实现要点:主要调用:new DbObject。 + * + * @param languageTag 参数 {@code languageTag}({@code String}) + * @return MongoDB 文档扩展对象 + */ public DbObject getMessage(String languageTag) { DbObject message = this.getMessage(); DbObject localedMessage = new DbObject(); diff --git a/src/main/java/com/midm/model/system/ResourceLocale.java b/src/main/java/com/midm/model/system/ResourceLocale.java index 4c555ad..f450325 100644 --- a/src/main/java/com/midm/model/system/ResourceLocale.java +++ b/src/main/java/com/midm/model/system/ResourceLocale.java @@ -4,25 +4,84 @@ import java.util.Locale; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code ResourceLocale} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code locale}(String):语言区域
  • + *
  • {@code name}(String):名称
  • + *
  • {@code order}(Integer):字段 order
  • + *
  • {@code enabled}(Boolean):是否启用
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class ResourceLocale { + /** + * 语言区域;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String locale; + /** + * 名称。 + */ private String name; + /** + * 字段 order。 + */ private Integer order; + /** + * 是否启用。 + */ private Boolean enabled; + /** + * 构造 {@code ResourceLocale} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public ResourceLocale() { } + /** + * 构造 {@code ResourceLocale} 实例。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param name 参数 {@code name}({@code String}) + */ public ResourceLocale(String locale, String name) { this.init(locale, name, true); } + /** + * 构造 {@code ResourceLocale} 实例。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public ResourceLocale(String locale, String name, boolean enabled) { this.init(locale, name, enabled); } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void init(String locale, String name, boolean enabled) { this.setLocale(locale); this.setName(name); @@ -30,38 +89,78 @@ public class ResourceLocale { this.setOrder(0); } + /** + * 获取 {@code locale}。 + * @return 字符串结果 + */ public String getLocale() { return this.locale; } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code String}) + */ public void setLocale(String locale) { this.locale = locale; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 判断 {@code enabled}。 + * @return 字段/派生属性 {@code enabled} 的值 + */ public Boolean isEnabled() { return this.enabled; } + /** + * 设置 {@code enabled}。 + * + * @param enabled 参数 {@code enabled}({@code Boolean}) + */ public void setEnabled(Boolean enabled) { this.enabled = enabled; } + /** + * 获取 {@code order}。 + * @return 数量/长度 + */ public Integer getOrder() { return this.order; } + /** + * 设置 {@code order}。 + * + * @param order 参数 {@code order}({@code Integer}) + */ public void setOrder(Integer order) { this.order = order; } + /** + * 处理转换为语言区域。 + * @return 处理结果 + */ public Locale toLocale() { return Locale.forLanguageTag(this.getLocale()); } diff --git a/src/main/java/com/midm/model/system/ResourceMessage.java b/src/main/java/com/midm/model/system/ResourceMessage.java index 77cb1a7..b3d9cb5 100644 --- a/src/main/java/com/midm/model/system/ResourceMessage.java +++ b/src/main/java/com/midm/model/system/ResourceMessage.java @@ -5,34 +5,99 @@ import com.mitac.cell.utils.McStringUtils; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code ResourceMessage} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(String):代码
  • + *
  • {@code messages}(DbObject):消息列表
  • + *
  • {@code comment}(String):字段 comment
  • + *
+ * + * 协作对象:{@code DbObject}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class ResourceMessage { + /** + * 代码;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String code; + /** + * 消息列表。 + */ private DbObject messages; + /** + * 字段 comment。 + */ private String comment; + /** + * 构造 {@code ResourceMessage} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public ResourceMessage() { } + /** + * 构造 {@code ResourceMessage} 实例。 + * + * @param code 状态码/业务码({@code String}) + */ public ResourceMessage(String code) { this.setCode(code); } + /** + * 构造 {@code ResourceMessage} 实例。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param message 消息内容({@code String}) + * @param comment 参数 {@code comment}({@code String}) + */ public ResourceMessage(String code, String locale, String message, String comment) { this.setCode(code); this.setMessage(locale, message); this.setComment(comment); } + /** + * 获取 {@code code}。 + * @return 字符串结果 + */ public String getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code String}) + */ public void setCode(String code) { this.code = code; } + /** + * 获取 {@code messages}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DbObject。 + * @return MongoDB 文档扩展对象 + */ public DbObject getMessages() { if (this.messages == null) { this.messages = new DbObject(); @@ -41,27 +106,59 @@ public class ResourceMessage { return this.messages; } + /** + * 设置 {@code messages}。 + * + * @param messages 参数 {@code messages}({@code DbObject}) + */ public void setMessages(DbObject messages) { this.messages = messages; } + /** + * 设置消息。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param message 消息内容({@code String}) + */ public void setMessage(String locale, String message) { this.getMessages().append(locale, message); } + /** + * 获取消息。 + * + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getMessage(String locale) { String message = this.getMessages().getString(locale); return McStringUtils.isNullOrEmpty(message) ? getDefaultMessage(this.code) : message; } + /** + * 获取Default消息。 + * + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ public static String getDefaultMessage(String code) { return "#" + code; } + /** + * 获取 {@code comment}。 + * @return 字符串结果 + */ public String getComment() { return this.comment; } + /** + * 设置 {@code comment}。 + * + * @param comment 参数 {@code comment}({@code String}) + */ public void setComment(String comment) { this.comment = comment; } diff --git a/src/main/java/com/midm/model/system/StandaloneLicense.java b/src/main/java/com/midm/model/system/StandaloneLicense.java index 3ec4ce2..f01cc7b 100644 --- a/src/main/java/com/midm/model/system/StandaloneLicense.java +++ b/src/main/java/com/midm/model/system/StandaloneLicense.java @@ -11,30 +11,115 @@ import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code StandaloneLicense} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uuid}(UUID):对象唯一标识(MongoDB 主键)
  • + *
  • {@code site}(Site):站点
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code hostId}(String):hostID
  • + *
  • {@code systemHash}(String):系统哈希
  • + *
  • {@code licenseType}(String):许可证类型
  • + *
+ * + * 协作对象:{@code Site、User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class StandaloneLicense { + /** + * 对象唯一标识(MongoDB 主键);MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private UUID uuid; + /** + * 站点;以 DBRef 引用其他文档。 + * + * 注解:{@code @DBRef}。 + */ @DBRef private Site site; + /** + * 字段 writer。 + */ private User writer; + /** + * hostID。 + */ private String hostId; + /** + * 系统哈希。 + */ private String systemHash; + /** + * 许可证类型。 + */ private String licenseType; + /** + * 许可证密钥。 + */ private String licenseKey; + /** + * 状态。 + */ private String status; + /** + * 设备Limit。 + */ private Integer deviceLimit; + /** + * valid转换为。 + */ private long validTo = -1L; + /** + * 字段 period。 + */ private Integer period; + /** + * 判断是否Standalone。 + */ private boolean isStandalone = true; - private List notes; + /** + * 备注集合。 + */ + private List notes; + /** + * 最后更新时间。 + */ private Date updated; + /** + * 创建时间。 + */ protected Date created; + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return this.uuid; } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + * + * @param user 当前用户({@code User}) + */ public void init(User user) { this.uuid = UUID.randomUUID(); this.writer = user; @@ -42,91 +127,192 @@ public class StandaloneLicense { this.updated = new Date(); } + /** + * 设置 {@code uuid}。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void setUuid(UUID uuid) { this.uuid = uuid; } + /** + * 获取 {@code hostId}。 + * @return 字符串结果 + */ public String getHostId() { return this.hostId; } + /** + * 设置 {@code hostId}。 + * + * @param hostId 参数 {@code hostId}({@code String}) + */ public void setHostId(String hostId) { this.hostId = hostId; } + /** + * 获取 {@code systemHash}。 + * @return 字符串结果 + */ public String getSystemHash() { return this.systemHash; } + /** + * 设置 {@code systemHash}。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + */ public void setSystemHash(String systemHash) { this.systemHash = systemHash; } + /** + * 获取 {@code licenseKey}。 + * @return 字符串结果 + */ public String getLicenseKey() { return this.licenseKey; } + /** + * 设置 {@code licenseKey}。 + * + * @param licenseKey 参数 {@code licenseKey}({@code String}) + */ public void setLicenseKey(String licenseKey) { this.licenseKey = licenseKey; } + /** + * 获取 {@code deviceLimit}。 + * @return 数量/长度 + */ public Integer getDeviceLimit() { return this.deviceLimit; } + /** + * 设置 {@code deviceLimit}。 + * + * @param deviceLimit 参数 {@code deviceLimit}({@code Integer}) + */ public void setDeviceLimit(Integer deviceLimit) { this.deviceLimit = deviceLimit; } + /** + * 获取 {@code validTo}。 + * @return 数量/长度 + */ public long getValidTo() { return this.validTo; } + /** + * 设置 {@code validTo}。 + * + * @param validTo 参数 {@code validTo}({@code long}) + */ public void setValidTo(long validTo) { this.validTo = validTo; } + /** + * 判断 {@code standalone}。 + * @return 字段/派生属性 {@code standalone} 的值 + */ public boolean isStandalone() { return this.isStandalone; } + /** + * 设置 {@code standalone}。 + * + * @param isStandalone 参数 {@code isStandalone}({@code boolean}) + */ public void setStandalone(boolean isStandalone) { this.isStandalone = isStandalone; } + /** + * 获取 {@code site}。 + * @return 站点对象;未找到时返回 {@code null} + */ public Site getSite() { return this.site; } + /** + * 设置 {@code site}。 + * + * @param site 站点/企业({@code Site}) + */ public void setSite(Site site) { this.site = site; } + /** + * 获取 {@code licenseType}。 + * @return 字符串结果 + */ public String getLicenseType() { return this.licenseType; } + /** + * 设置 {@code licenseType}。 + * + * @param licenseType 参数 {@code licenseType}({@code String}) + */ public void setLicenseType(String licenseType) { this.licenseType = licenseType; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } - public List getNotes() { + /** + * 获取 {@code notes}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return 备注列表,可能为空 + */ + public List getNotes() { if (this.notes == null) { this.notes = new ArrayList(); } @@ -134,30 +320,75 @@ public class StandaloneLicense { return this.notes; } - public void setNotes(List notes) { + /** + * 设置 {@code notes}。 + * + * @param notes 参数 {@code notes}({@code List}) + */ + public void setNotes(List notes) { this.notes = notes; } + /** + * 添加备注。 + * + * 实现要点:主要调用:new Note。 + * + * @param note 参数 {@code note}({@code String}) + */ public void addNote(String note) { this.getNotes().add(new Note(this.writer, note)); } + /** + * 获取 {@code status}。 + * @return 字符串结果 + */ public String getStatus() { return this.status; } + /** + * 设置 {@code status}。 + * + * @param status 状态({@code String}) + */ public void setStatus(String status) { this.status = status; } + /** + * 获取 {@code period}。 + * @return 数量/长度 + */ public Integer getPeriod() { return this.period; } + /** + * 设置 {@code period}。 + * + * @param period 参数 {@code period}({@code Integer}) + */ public void setPeriod(Integer period) { this.period = period; } + /** + * 【枚举常量】{@code STATUS} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public static enum STATUS { REQUESTED, PROCESSING, @@ -168,6 +399,14 @@ public class StandaloneLicense { RENEWED, UNKNOWN; + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static STATUS get(String key) { try { return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); @@ -177,40 +416,108 @@ public class StandaloneLicense { } } + /** + * 【领域模型】{@code Note} + * + * 类职责: + *
    + *
  • 表达领域对象的数据结构、字段约束与派生属性。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code recordedBy}(User):recorded按
  • + *
  • {@code note}(String):备注
  • + *
  • {@code noted}(Date):时间字段
  • + *
+ * + * 协作对象:{@code User}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public static class Note { + /** + * recorded按。 + */ private User recordedBy; + /** + * 备注。 + */ private String note; + /** + * 时间字段。 + */ private Date noted; + /** + * 构造 {@code Note} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Note() { } + /** + * 构造 {@code Note} 实例。 + * + * 实现要点:主要调用:new Date。 + * + * @param user 当前用户({@code User}) + * @param note 参数 {@code note}({@code String}) + */ public Note(User user, String note) { this.recordedBy = user; this.note = note; this.noted = new Date(); } + /** + * 获取 {@code recordedBy}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getRecordedBy() { return this.recordedBy; } + /** + * 设置 {@code recordedBy}。 + * + * @param recordedBy 参数 {@code recordedBy}({@code User}) + */ public void setRecordedBy(User recordedBy) { this.recordedBy = recordedBy; } + /** + * 获取 {@code note}。 + * @return 字符串结果 + */ public String getNote() { return this.note; } + /** + * 设置 {@code note}。 + * + * @param note 参数 {@code note}({@code String}) + */ public void setNote(String note) { this.note = note; } + /** + * 获取 {@code noted}。 + * @return 字段/派生属性 {@code noted} 的值 + */ public Date getNoted() { return this.noted; } + /** + * 设置 {@code noted}。 + * + * @param noted 参数 {@code noted}({@code Date}) + */ public void setNoted(Date noted) { this.noted = noted; } diff --git a/src/main/java/com/midm/model/system/SystemSetting.java b/src/main/java/com/midm/model/system/SystemSetting.java index c6ac679..a1e1540 100644 --- a/src/main/java/com/midm/model/system/SystemSetting.java +++ b/src/main/java/com/midm/model/system/SystemSetting.java @@ -4,44 +4,111 @@ import com.mitac.cell.utils.McNumberUtils; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code SystemSetting} + * + * 类职责: + *
    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code key}(String):密钥
  • + *
  • {@code value}(String):值
  • + *
+ * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class SystemSetting { + /** + * 密钥;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String key; + /** + * 值。 + */ private String value; + /** + * 构造 {@code SystemSetting} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public SystemSetting() { } + /** + * 构造 {@code SystemSetting} 实例。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public SystemSetting(String key, Object value) { this.setKey(key); this.setValue(value != null ? String.valueOf(value) : null); } + /** + * 获取 {@code key}。 + * @return 字符串结果 + */ public String getKey() { return this.key; } + /** + * 设置 {@code key}。 + * + * @param key 键/配置项({@code String}) + */ public void setKey(String key) { this.key = key; } + /** + * 获取 {@code value}。 + * @return 字符串结果 + */ public String getValue() { return this.value; } + /** + * 设置 {@code value}。 + * + * @param value 值({@code String}) + */ public void setValue(String value) { this.value = value; } + /** + * 获取 {@code asInteger}。 + * @return 数量/长度 + */ public Integer getAsInteger() { return McNumberUtils.toInt(this.getValue()); } + /** + * 获取 {@code asLong}。 + * @return 数量/长度 + */ public Long getAsLong() { return McNumberUtils.toLong(this.getValue()); } + /** + * 获取 {@code asBoolean}。 + * @return 字段/派生属性 {@code asBoolean} 的值 + */ public Boolean getAsBoolean() { return this.value.equalsIgnoreCase("true"); } diff --git a/src/main/java/com/midm/model/system/package-info.java b/src/main/java/com/midm/model/system/package-info.java new file mode 100644 index 0000000..1832087 --- /dev/null +++ b/src/main/java/com/midm/model/system/package-info.java @@ -0,0 +1,24 @@ +/** + * 系统设置模型:SystemSetting、LicenseModel、HostLicense、语言资源等。 + * + *

本包主要类型: + *

    + *
  • {@link AltLocale}
  • + *
  • {@link Category}
  • + *
  • {@link CategoryId}
  • + *
  • {@link DbTemplate}
  • + *
  • {@link HelpMessage}
  • + *
  • {@link HostLicense}
  • + *
  • {@link LicenseFeature}
  • + *
  • {@link LicenseModel}
  • + *
  • {@link PolicyAgreement}
  • + *
  • {@link ResourceLocale}
  • + *
  • {@link ResourceMessage}
  • + *
  • {@link StandaloneLicense}
  • + *
  • {@link SystemSetting}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.system; diff --git a/src/main/java/com/midm/model/template/MailTemplate.java b/src/main/java/com/midm/model/template/MailTemplate.java index b76d47b..e03a5bf 100644 --- a/src/main/java/com/midm/model/template/MailTemplate.java +++ b/src/main/java/com/midm/model/template/MailTemplate.java @@ -6,74 +6,190 @@ import java.util.Date; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; +/** + * 【MongoDB 文档实体】{@code MailTemplate} + * + * 类职责: + *

    + *
  • 作为 MongoDB 集合文档,承载该领域对象的持久化字段与索引。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code idName}(String):ID名称
  • + *
  • {@code name}(String):名称
  • + *
  • {@code description}(String):字段 description
  • + *
  • {@code template}(DbObject):模板
  • + *
  • {@code writer}(User):字段 writer
  • + *
  • {@code created}(Date):创建时间
  • + *
+ * + * 协作对象:{@code DbObject、User}。 + * + * 持久化/框架标记:{@code @Document} 映射为 MongoDB 集合。 + * + * 学习提示:先看字段与 @Field/@Indexed,再看对应 Service/Repository 如何构造查询条件。 + */ @Document public class MailTemplate { + /** + * ID名称;MongoDB 主键。 + * + * 注解:{@code @Id}。 + */ @Id private String idName; + /** + * 名称。 + */ private String name; + /** + * 字段 description。 + */ private String description; + /** + * 模板。 + */ private DbObject template; + /** + * 字段 writer。 + */ private User writer; + /** + * 创建时间。 + */ private Date created; + /** + * 最后更新时间。 + */ private Date updated; + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new Date。 + */ public void init() { this.created = new Date(); this.updated = new Date(); } + /** + * 获取 {@code idName}。 + * @return 字符串结果 + */ public String getIdName() { return this.idName; } + /** + * 设置 {@code idName}。 + * + * @param idName 参数 {@code idName}({@code String}) + */ public void setIdName(String idName) { this.idName = idName; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code description}。 + * @return 字符串结果 + */ public String getDescription() { return this.description; } + /** + * 设置 {@code description}。 + * + * @param description 参数 {@code description}({@code String}) + */ public void setDescription(String description) { this.description = description; } + /** + * 获取 {@code template}。 + * @return MongoDB 文档扩展对象 + */ public DbObject getTemplate() { return this.template; } + /** + * 设置 {@code template}。 + * + * @param template 参数 {@code template}({@code DbObject}) + */ public void setTemplate(DbObject template) { this.template = template; } + /** + * 获取 {@code writer}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getWriter() { return this.writer; } + /** + * 设置 {@code writer}。 + * + * @param writer 参数 {@code writer}({@code User}) + */ public void setWriter(User writer) { this.writer = writer; } + /** + * 获取 {@code created}。 + * @return 字段/派生属性 {@code created} 的值 + */ public Date getCreated() { return this.created; } + /** + * 设置 {@code created}。 + * + * @param created 参数 {@code created}({@code Date}) + */ public void setCreated(Date created) { this.created = created; } + /** + * 获取 {@code updated}。 + * @return 字段/派生属性 {@code updated} 的值 + */ public Date getUpdated() { return this.updated; } + /** + * 设置 {@code updated}。 + * + * @param updated 参数 {@code updated}({@code Date}) + */ public void setUpdated(Date updated) { this.updated = updated; } diff --git a/src/main/java/com/midm/model/template/package-info.java b/src/main/java/com/midm/model/template/package-info.java new file mode 100644 index 0000000..75f2319 --- /dev/null +++ b/src/main/java/com/midm/model/template/package-info.java @@ -0,0 +1,12 @@ +/** + * 邮件/消息模板模型。 + * + *

本包主要类型: + *

    + *
  • {@link MailTemplate}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.model.template; diff --git a/src/main/java/com/midm/package-info.java b/src/main/java/com/midm/package-info.java new file mode 100644 index 0000000..b5a626b --- /dev/null +++ b/src/main/java/com/midm/package-info.java @@ -0,0 +1,12 @@ +/** + * MiDM 启动入口与全局基础设施:Spring Boot 引导、配置装配、全局异常/拦截器。 + * + *

本包主要类型: + *

    + *
  • {@link MainApplication}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm; diff --git a/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java b/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java index b615167..d8cab01 100644 --- a/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java +++ b/src/main/java/com/midm/repository/device/DeviceLicenseRepository.java @@ -1,6 +1,18 @@ package com.midm.repository.device; import org.springframework.data.mongodb.repository.MongoRepository; +import com.midm.model.device.DeviceLicense; +import java.util.UUID; -public interface DeviceLicenseRepository extends MongoRepository { +/** + * 【接口契约】{@code DeviceLicenseRepository} + * + * 类职责: + *

    + *
  • 定义调用方与实现方之间的契约,屏蔽具体实现。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ +public interface DeviceLicenseRepository extends MongoRepository { } diff --git a/src/main/java/com/midm/repository/device/package-info.java b/src/main/java/com/midm/repository/device/package-info.java new file mode 100644 index 0000000..6ab74af --- /dev/null +++ b/src/main/java/com/midm/repository/device/package-info.java @@ -0,0 +1,12 @@ +/** + * 设备相关 Repository:License 等。 + * + *

本包主要类型: + *

    + *
  • {@link DeviceLicenseRepository}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.repository.device; diff --git a/src/main/java/com/midm/resolver/DbResourceResolver.java b/src/main/java/com/midm/resolver/DbResourceResolver.java index bfbfee8..5818b7e 100644 --- a/src/main/java/com/midm/resolver/DbResourceResolver.java +++ b/src/main/java/com/midm/resolver/DbResourceResolver.java @@ -1,4 +1,14 @@ package com.midm.resolver; +/** + * 【Java 类型】{@code DbResourceResolver} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class DbResourceResolver { } diff --git a/src/main/java/com/midm/resolver/DbTemplateResolver.java b/src/main/java/com/midm/resolver/DbTemplateResolver.java index 0f9b5b2..5429e78 100644 --- a/src/main/java/com/midm/resolver/DbTemplateResolver.java +++ b/src/main/java/com/midm/resolver/DbTemplateResolver.java @@ -4,9 +4,32 @@ import com.google.common.collect.Sets; import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.templatemode.TemplateMode; +/** + * 【Java 类型】{@code DbTemplateResolver} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code PREFIX}(String):字段 PREFIX
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class DbTemplateResolver extends SpringResourceTemplateResolver { + /** + * 字段 PREFIX。 + */ private static final String PREFIX = "dbTemplate:"; + /** + * 构造 {@code DbTemplateResolver} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DbTemplateResolver() { this.setTemplateMode(TemplateMode.HTML); this.setCacheable(true); diff --git a/src/main/java/com/midm/resolver/package-info.java b/src/main/java/com/midm/resolver/package-info.java new file mode 100644 index 0000000..fb5ba4a --- /dev/null +++ b/src/main/java/com/midm/resolver/package-info.java @@ -0,0 +1,13 @@ +/** + * 视图/资源解析器:把逻辑名解析为 Thymeleaf 模板或数据库资源。 + * + *

本包主要类型: + *

    + *
  • {@link DbResourceResolver}
  • + *
  • {@link DbTemplateResolver}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.resolver; diff --git a/src/main/java/com/midm/security/UserPrincipal.java b/src/main/java/com/midm/security/UserPrincipal.java index 79babc7..c8021dc 100644 --- a/src/main/java/com/midm/security/UserPrincipal.java +++ b/src/main/java/com/midm/security/UserPrincipal.java @@ -8,37 +8,98 @@ import java.util.UUID; import org.springframework.security.core.Authentication; import org.springframework.web.socket.WebSocketSession; +/** + * 【Java 类型】{@code UserPrincipal} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code user}(User):用户
  • + *
+ * + * 协作对象:{@code User}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class UserPrincipal implements Principal, Serializable { + /** + * 用户。 + */ private User user; + /** + * 构造 {@code UserPrincipal} 实例。 + * + * @param user 当前用户({@code User}) + */ public UserPrincipal(User user) { this.setUser(user); } + /** + * 获取 {@code userUuid}。 + * @return UUID + */ public UUID getUserUuid() { return this.user == null ? null : this.user.getUuid(); } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.user == null ? null : this.user.getUuid().toString(); } + /** + * 获取 {@code user}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getUser() { return this.user; } + /** + * 设置 {@code user}。 + * + * @param user 当前用户({@code User}) + */ public void setUser(User user) { this.user = user; } + /** + * 获取用户。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 用户对象;未找到时返回 {@code null} + */ public static User getUser(Authentication authentication) { return authentication == null ? null : ((UserPrincipal)authentication.getPrincipal()).getUser(); } + /** + * 获取用户。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @return 用户对象;未找到时返回 {@code null} + */ public static User getUser(WebSocketSession session) { return getUser((Authentication)session.getPrincipal()); } + /** + * 获取用户令牌。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字段/派生属性 {@code userToken} 的值 + */ public static UserToken getUserToken(Authentication authentication) { return authentication == null ? null : (UserToken)authentication.getCredentials(); } diff --git a/src/main/java/com/midm/security/package-info.java b/src/main/java/com/midm/security/package-info.java new file mode 100644 index 0000000..c1a312f --- /dev/null +++ b/src/main/java/com/midm/security/package-info.java @@ -0,0 +1,12 @@ +/** + * Spring Security 集成:UserPrincipal 等认证主体。 + * + *

本包主要类型: + *

    + *
  • {@link UserPrincipal}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.security; diff --git a/src/main/java/com/midm/service/Aggregations.java b/src/main/java/com/midm/service/Aggregations.java index 195484f..f3cb4c5 100644 --- a/src/main/java/com/midm/service/Aggregations.java +++ b/src/main/java/com/midm/service/Aggregations.java @@ -8,19 +8,61 @@ import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationOperation; import org.springframework.data.mongodb.core.aggregation.AggregationOperationContext; +/** + * 【Java 类型】{@code Aggregations} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class Aggregations { + /** + * 处理新Operation。 + * + * 实现要点:主要调用:new CustomOperation。 + * + * @param operation 参数 {@code operation}({@code Document}) + * @return 处理结果 + */ public static AggregationOperation newOperation(Document operation) { return new CustomOperation(operation); } + /** + * 处理新Operation。 + * + * 实现要点:主要调用:new CustomOperation。 + * + * @param jOperation 参数 {@code jOperation}({@code String}) + * @return 处理结果 + */ public static AggregationOperation newOperation(String jOperation) { return new CustomOperation(jOperation); } + /** + * 处理新Operation。 + * + * 实现要点:主要调用:new CustomOperation、parse。 + * + * @param jOperation 参数 {@code jOperation}({@code JsonObject}) + * @return 处理结果 + */ public static AggregationOperation newOperation(JsonObject jOperation) { return new CustomOperation(Document.parse(jOperation.toString())); } + /** + * 处理从。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList、new CustomOperation。 + * + * @param jOperations 参数 {@code jOperations}({@code String[]}) + * @return 处理结果 + */ public static Aggregation from(String... jOperations) { List operations = new ArrayList(); @@ -31,6 +73,14 @@ public class Aggregations { return Aggregation.newAggregation(operations); } + /** + * 处理从。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList、new CustomOperation。 + * + * @param documents 参数 {@code documents}({@code Document[]}) + * @return 处理结果 + */ public static Aggregation from(Document... documents) { List operations = new ArrayList(); @@ -41,7 +91,15 @@ public class Aggregations { return Aggregation.newAggregation(operations); } - public static Aggregation from(List documents) { + /** + * 处理从。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList、new CustomOperation。 + * + * @param documents 参数 {@code documents}({@code List}) + * @return 处理结果 + */ + public static Aggregation from(List documents) { List operations = new ArrayList(); for(Document document : documents) { @@ -51,17 +109,56 @@ public class Aggregations { return Aggregation.newAggregation(operations); } + /** + * 【Java 类型】{@code CustomOperation} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code document}(Document):字段 document
  • + *
+ * + * 协作对象:{@code Document}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ private static class CustomOperation implements AggregationOperation { + /** + * 字段 document。 + */ private Document document; + /** + * 构造 {@code CustomOperation} 实例。 + * + * @param operation 参数 {@code operation}({@code Document}) + */ public CustomOperation(Document operation) { this.document = operation; } + /** + * 构造 {@code CustomOperation} 实例。 + * + * 实现要点:主要调用:parse。 + * + * @param jOperation 参数 {@code jOperation}({@code String}) + */ public CustomOperation(String jOperation) { this.document = Document.parse(jOperation); } + /** + * 处理转换为Document。 + * + * @param context 参数 {@code context}({@code AggregationOperationContext}) + * @return MongoDB 文档对象 + */ public Document toDocument(AggregationOperationContext context) { return context.getMappedObject(this.document); } diff --git a/src/main/java/com/midm/service/BaseService.java b/src/main/java/com/midm/service/BaseService.java index f4de98a..067c45b 100644 --- a/src/main/java/com/midm/service/BaseService.java +++ b/src/main/java/com/midm/service/BaseService.java @@ -39,37 +39,126 @@ import org.springframework.data.mongodb.core.query.Update; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; +/** + * 【Java 类型】{@code BaseService} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mongoTemplate}(MongoTemplate):MongoDB模板
  • + *
  • {@code taskExecutor}(ThreadPoolTaskExecutor):任务Executor
  • + *
  • {@code taskScheduler}(TaskScheduler):任务Scheduler
  • + *
  • {@code logger}(Logger):字段 logger
  • + *
+ * + * 协作对象:{@code MongoTemplate、ThreadPoolTaskExecutor、TaskScheduler、Logger}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class BaseService { + /** + * MongoDB模板;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected MongoTemplate mongoTemplate; + /** + * 任务Executor;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected ThreadPoolTaskExecutor taskExecutor; + /** + * 任务Scheduler;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected TaskScheduler taskScheduler; + /** + * 字段 logger。 + */ protected Logger logger = LoggerFactory.getLogger(DeviceReportService.class); - public MongoCollection getCollection(String collectionName) { + /** + * 获取Collection。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @return 字段/派生属性 {@code collection} 的值 + */ + public MongoCollection getCollection(String collectionName) { return this.mongoTemplate.getCollection(collectionName); } - public MongoCollection getCollection(Class entityClass) { + /** + * 获取Collection。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return 字段/派生属性 {@code collection} 的值 + */ + public MongoCollection getCollection(Class entityClass) { String collectionName = this.mongoTemplate.getCollectionName(entityClass); return this.mongoTemplate.getCollection(collectionName); } - public boolean collectionExists(Class entityClass) { + /** + * 处理collection存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean collectionExists(Class entityClass) { return this.mongoTemplate.collectionExists(entityClass); } - public Object saveDocument(Object document) { + /** + * 保存Document。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:save。 + * + * @param document 参数 {@code document}({@code T}) + * @return 处理结果 + */ + public T saveDocument(T document) { return this.mongoTemplate.save(document); } - public Object findById(Class entityClass, Object id) { + /** + * 根据ID查找T。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param id 参数 {@code id}({@code Object}) + * @return 处理结果 + */ + public T findById(Class entityClass, Object id) { return id == null ? null : this.mongoTemplate.findOne(this.queryById(id), entityClass); } - public List findByIds(Class entityClass, Collection ids) { + /** + * 根据Ids查找列出。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param ids ID 集合({@code Collection}) + * @return T列表,可能为空 + */ + public List findByIds(Class entityClass, Collection ids) { if (ids != null) { Query query = Query.query(Criteria.where("_id").in(ids)); return this.mongoTemplate.find(query, entityClass); @@ -78,29 +167,87 @@ public class BaseService { } } - public boolean deleteById(Class entityClass, Object id) { + /** + * 根据ID删除boolean。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param id 参数 {@code id}({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean deleteById(Class entityClass, Object id) { DeleteResult result = this.mongoTemplate.remove(this.queryById(id), entityClass); return result.getDeletedCount() > 0L; } - public boolean existsById(Class entityClass, Object id) { + /** + * 存在按ID。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param id 参数 {@code id}({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean existsById(Class entityClass, Object id) { return this.mongoTemplate.exists(this.queryById(id), entityClass); } - public List findAll(Class entityClass) { + /** + * 查找全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findAll。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return T列表,可能为空 + */ + public List findAll(Class entityClass) { return this.mongoTemplate.findAll(entityClass); } - public long count(Class entityClass) { + /** + * 处理统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count、new Query。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return 数量/长度 + */ + public long count(Class entityClass) { return this.mongoTemplate.count(new Query(), entityClass); } - public List find(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return T列表,可能为空 + */ + public List find(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction) { Query query = McMongoUtils.toQuery(filter, sortBy, direction); return this.mongoTemplate.find(query, entityClass); } - public PageImpl findByPage(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + /** + * 根据分页查找分页Impl。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:count、find、new PageImpl、new ArrayList。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 分页结果 + */ + public PageImpl findByPage(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { Query query = McMongoUtils.toQuery(filter, sortBy, direction); query.collation(LocaleConst.COLLATION_DEFAULT); Long total = this.mongoTemplate.count(query, entityClass); @@ -115,7 +262,17 @@ public class BaseService { } } - public AggregationResults groupBy(String forWhat, String field, Criteria criteria) { + /** + * 分组按。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;主要调用:aggregate。 + * + * @param forWhat 参数 {@code forWhat}({@code String}) + * @param field 参数 {@code field}({@code String}) + * @param criteria 参数 {@code criteria}({@code Criteria}) + * @return 处理结果 + */ + public AggregationResults groupBy(String forWhat, String field, Criteria criteria) { try { MatchOperation matchStage = Aggregation.match(criteria); GroupOperation groupByField = Aggregation.group(new String[]{field}).count().as("count").addToSet(field).as("groups"); @@ -127,13 +284,32 @@ public class BaseService { } } - public void update(Class entityClass, JsonObject jFilter, String key, Object value) { + /** + * 处理更新。 + * + * 实现要点:主要调用:new HashMap。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ + public void update(Class entityClass, JsonObject jFilter, String key, Object value) { Map map = new HashMap(); map.put(key, value); this.update(entityClass, jFilter, map); } - public void update(Class entityClass, JsonObject jFilter, Map valueMap) { + /** + * 处理更新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Query、new Update、updateMulti。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param valueMap 参数 {@code valueMap}({@code Map}) + */ + public void update(Class entityClass, JsonObject jFilter, Map valueMap) { Query query = new Query(); if (jFilter != null) { McMongoUtils.addFilter(query, jFilter); @@ -151,7 +327,17 @@ public class BaseService { this.mongoTemplate.updateMulti(query, update, entityClass); } - public void pull(Class entityClass, JsonObject jFilter, String key, Object arrayItem) { + /** + * 处理拉取。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、new Update、updateMulti。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param key 键/配置项({@code String}) + * @param arrayItem 参数 {@code arrayItem}({@code Object}) + */ + public void pull(Class entityClass, JsonObject jFilter, String key, Object arrayItem) { Query query = new Query(); if (jFilter != null) { McMongoUtils.addFilter(query, jFilter); @@ -162,6 +348,14 @@ public class BaseService { this.mongoTemplate.updateMulti(query, update, entityClass); } + /** + * 添加Index。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param indexes 参数 {@code indexes}({@code String[]}) + */ public void addIndex(String collectionName, final String... indexes) { if (indexes != null && indexes.length != 0) { for(String index : indexes) { @@ -171,6 +365,14 @@ public class BaseService { } } + /** + * 添加Index。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param jIndexes 参数 {@code jIndexes}({@code JsonObject}) + */ public void addIndex(String collectionName, final JsonObject jIndexes) { if (jIndexes != null) { for(Map.Entry jIndex : jIndexes.entrySet()) { @@ -180,47 +382,131 @@ public class BaseService { } } + /** + * 添加Index。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param index 参数 {@code index}({@code String}) + * @param direction 排序方向({@code String}) + */ public void addIndex(String collectionName, final String index, String direction) { this.addIndex(collectionName, index, Direction.fromString(direction)); } + /** + * 添加Index。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:ensureIndex、new Index。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param index 参数 {@code index}({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + */ public void addIndex(String collectionName, final String index, Sort.Direction direction) { IndexOperations operations = this.mongoTemplate.indexOps(collectionName); operations.ensureIndex((new Index()).on(index, direction)); } + /** + * 移除Index。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:dropIndex。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param index 参数 {@code index}({@code String}) + */ public void removeIndex(String collectionName, final String index) { IndexOperations operations = this.mongoTemplate.indexOps(collectionName); operations.dropIndex(index); } + /** + * 处理unset。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、updateMulti、new Query。 + * + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param key 键/配置项({@code String}) + */ public void unset(String collectionName, final String key) { Update update = new Update(); update.unset(key); this.mongoTemplate.updateMulti(new Query(), update, collectionName); } - public UpdateResult unset(Class entityClass, Object id, String key) { + /** + * 处理unset。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst、new Update。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param id 参数 {@code id}({@code Object}) + * @param key 键/配置项({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult unset(Class entityClass, Object id, String key) { return this.mongoTemplate.updateFirst(this.queryById(id), (new Update()).unset(key), entityClass); } - public UpdateResult unset(Class entityClass, String key) { + /** + * 处理unset。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Query、new Update。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param key 键/配置项({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult unset(Class entityClass, String key) { return this.mongoTemplate.updateMulti(new Query(), (new Update()).unset(key), entityClass); } - public AggregationResults aggregate(String collection, List pipeline) { + /** + * 处理aggregate。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:aggregate。 + * + * @param collection 参数 {@code collection}({@code String}) + * @param pipeline 参数 {@code pipeline}({@code List}) + * @return 处理结果 + */ + public AggregationResults aggregate(String collection, List pipeline) { return this.mongoTemplate.aggregate(Aggregations.from(pipeline), collection, Document.class); } + /** + * 查询按ID。 + * + * @param id 参数 {@code id}({@code Object}) + * @return 处理结果 + */ public Query queryById(Object id) { return Query.query(Criteria.where("_id").is(id)); } - public Object convertToObject(Class entityClass, Document source) { + /** + * 转换转换为Object。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param source 参数 {@code source}({@code Document}) + * @return 处理结果 + */ + public T convertToObject(Class entityClass, Document source) { return this.mongoTemplate.getConverter().read(entityClass, source); } - public List convertToList(Class entityClass, List sources) { + /** + * 转换转换为列出。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param sources 参数 {@code sources}({@code List}) + * @return T列表,可能为空 + */ + public List convertToList(Class entityClass, List sources) { if (sources != null && !sources.isEmpty()) { List list = new ArrayList(); sources.forEach((source) -> list.add(this.convertToObject(entityClass, source))); @@ -230,6 +516,16 @@ public class BaseService { } } + /** + * 处理分页。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param total 总数({@code Long}) + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @return 数量/长度 + */ public int page(Long total, int page, int size) { if (page == 0) { return page; @@ -243,23 +539,56 @@ public class BaseService { } } + /** + * 获取配置档案过滤。 + * + * 实现要点:主要调用:new JsonObject。 + * + * @param profileKey 参数 {@code profileKey}({@code String}) + * @param value 值({@code String}) + * @return 字段/派生属性 {@code profileFilter} 的值 + */ protected JsonObject getProfileFilter(String profileKey, String value) { JsonObject jFilter = new JsonObject(); jFilter.addProperty("profile." + profileKey, value); return jFilter; } + /** + * 处理转换为Document。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document。 + * + * @param obj 参数 {@code obj}({@code Object}) + * @return MongoDB 文档对象 + */ protected Document toDocument(Object obj) { Document doc = new Document(); this.mongoTemplate.getConverter().write(obj, doc); return doc; } + /** + * 处理执行。 + * + * 实现要点:主要调用:execute。 + * + * @param task 参数 {@code task}({@code Runnable}) + */ public void execute(Runnable task) { this.taskExecutor.execute(task); } - public ScheduledFuture schedule(Runnable task, Date dateTime) { + /** + * 处理调度。 + * + * 实现要点:主要调用:schedule。 + * + * @param task 参数 {@code task}({@code Runnable}) + * @param dateTime 参数 {@code dateTime}({@code Date}) + * @return 处理结果 + */ + public ScheduledFuture schedule(Runnable task, Date dateTime) { return this.taskScheduler.schedule(task, dateTime); } } diff --git a/src/main/java/com/midm/service/EmailService.java b/src/main/java/com/midm/service/EmailService.java index e2c9df4..bbc8832 100644 --- a/src/main/java/com/midm/service/EmailService.java +++ b/src/main/java/com/midm/service/EmailService.java @@ -34,19 +34,71 @@ import org.thymeleaf.context.IContext; import org.thymeleaf.context.WebContext; import ua_parser.Client; +/** + * 【业务服务】{@code EmailService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serveletContext}(ServletContext):字段 serveletContext
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code stringTemplateEngine}(TemplateEngine):string模板Engine
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code mailSender}(JavaMailSenderImpl):邮件Sender
  • + *
+ * + * 协作对象:{@code ServletContext、SettingsService、TemplateEngine、FileService、JavaMailSenderImpl}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Service public class EmailService { + /** + * 字段 serveletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired ServletContext serveletContext; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * string模板Engine;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。 + */ @Autowired @Qualifier("stringTemplateEngine") private TemplateEngine stringTemplateEngine; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 邮件Sender。 + */ private static JavaMailSenderImpl mailSender; + /** + * 发送测试邮件。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param email 邮箱({@code String}) + */ public void sendTestMail(String email) { String subject = "MiDM service test mail"; Context context = new Context(); @@ -54,7 +106,19 @@ public class EmailService { this.sendMail(email, (String)null, "MiDM service test mail", htmlContent); } - public void sendInstallerFailedMail(List users, String category, UUID fileUuid, String fileName, String reason, String ssn) { + /** + * 发送InstallerFailed邮件。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param users 参数 {@code users}({@code List}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param fileName 文件名({@code String}) + * @param reason 参数 {@code reason}({@code String}) + * @param ssn 参数 {@code ssn}({@code String}) + */ + public void sendInstallerFailedMail(List users, String category, UUID fileUuid, String fileName, String reason, String ssn) { String subject = "[MiDM] Device failed to install."; Context context = new Context(); context.setVariable("category", category); @@ -66,7 +130,19 @@ public class EmailService { this.sendMail(users, "[MiDM] Device failed to install.", htmlContent); } - public void sendBatteryConditionAbnormalMail(List users, String siteName, String batterySerial, String deviceSerial, String model, String deviceGroupName) { + /** + * 发送电池ConditionAbnormal邮件。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param users 参数 {@code users}({@code List}) + * @param siteName 参数 {@code siteName}({@code String}) + * @param batterySerial 参数 {@code batterySerial}({@code String}) + * @param deviceSerial 参数 {@code deviceSerial}({@code String}) + * @param model 参数 {@code model}({@code String}) + * @param deviceGroupName 参数 {@code deviceGroupName}({@code String}) + */ + public void sendBatteryConditionAbnormalMail(List users, String siteName, String batterySerial, String deviceSerial, String model, String deviceGroupName) { String subject = "[MiDM] Battery requires service notification"; Context context = new Context(); context.setVariable("siteName", siteName); @@ -78,6 +154,16 @@ public class EmailService { this.sendMail(users, "[MiDM] Battery requires service notification", htmlContent); } + /** + * 发送Notification请求。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param user 当前用户({@code User}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @param filePath 参数 {@code filePath}({@code String}) + * @param fileName 文件名({@code String}) + */ public void sendNotificationRequest(User user, NewsMessage newsMessage, String filePath, String fileName) { String subject = String.format("[MiDM] Report for %s is ready", newsMessage.getForWhat()); Context context = new Context(); @@ -89,6 +175,14 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent, filePath, fileName); } + /** + * 发送站点许可证请求Noti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param email 邮箱({@code String}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendSiteLicenseRequestNoti(String email, NewsMessage newsMessage) { String subject = String.format("[MiDM] Site License is requested"); Context context = new Context(); @@ -99,6 +193,14 @@ public class EmailService { this.sendMail(email, userName, subject, htmlContent); } + /** + * 发送站点Upgrade请求Noti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param email 邮箱({@code String}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendSiteUpgradeRequestNoti(String email, NewsMessage newsMessage) { String subject = String.format("[MiDM] Site Upgrade is requested"); Context context = new Context(); @@ -109,6 +211,14 @@ public class EmailService { this.sendMail(email, userName, subject, htmlContent); } + /** + * 发送站点许可证Noti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param user 当前用户({@code User}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendSiteLicenseNoti(User user, NewsMessage newsMessage) { String subject = String.format("[MiDM] Site License is ready"); Context context = new Context(); @@ -119,6 +229,14 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); } + /** + * 发送站点UpgradeNoti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param user 当前用户({@code User}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendSiteUpgradeNoti(User user, NewsMessage newsMessage) { String subject = String.format("[MiDM] Site Upgrade Success"); Context context = new Context(); @@ -129,6 +247,14 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); } + /** + * 发送Host许可证请求Noti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param email 邮箱({@code String}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendHostLicenseRequestNoti(String email, NewsMessage newsMessage) { String subject = String.format("[MiDM] Host License is requested"); Context context = new Context(); @@ -139,6 +265,14 @@ public class EmailService { this.sendMail(email, userName, subject, htmlContent); } + /** + * 发送Host许可证Noti。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param user 当前用户({@code User}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void sendHostLicenseNoti(User user, NewsMessage newsMessage) { String subject = String.format("[MiDM] Host License is ready"); Context context = new Context(); @@ -149,6 +283,16 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); } + /** + * 发送设备拉取Notification请求。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param user 当前用户({@code User}) + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @param filePath 参数 {@code filePath}({@code String}) + * @param fileName 文件名({@code String}) + */ public void sendDevicePullNotificationRequest(User user, NewsMessage newsMessage, String filePath, String fileName) { String deviceSerial = (String)newsMessage.getReference().get("deviceSerial"); String subject = String.format("[MiDM] File from device is ready", deviceSerial); @@ -162,6 +306,15 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); } + /** + * 发送Standalone消息。 + * + * 实现要点:涉及邮件发送;主要调用:new Context、sendMail。 + * + * @param subject 参数 {@code subject}({@code String}) + * @param user 当前用户({@code User}) + * @param content 参数 {@code content}({@code String}) + */ public void sendStandaloneMessage(String subject, User user, String content) { Context context = new Context(); String userName = user.getName(); @@ -171,6 +324,15 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), subject, htmlContent); } + /** + * 发送ActivatedNotification。 + * + * 实现要点:涉及邮件发送;主要调用:sendMail。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param user 当前用户({@code User}) + */ public void sendActivatedNotification(HttpServletRequest request, HttpServletResponse response, User user) { String subject = "Your MiDM account has been activated"; WebContext context = this.getContext(request, response); @@ -183,18 +345,39 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), "Your MiDM account has been activated", htmlContent); } + /** + * 发送Password重置请求。 + * + * 实现要点:涉及邮件发送;主要调用:sendMail。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param user 当前用户({@code User}) + * @param passwordResetToken 参数 {@code passwordResetToken}({@code UUID}) + */ public void sendPasswordResetRequest(HttpServletRequest request, HttpServletResponse response, User user, UUID passwordResetToken) { String subject = "Reset your MiDM password"; WebContext context = this.getContext(request, response); String userName = user.getName(); context.setVariable("name", McStringUtils.isNullOrEmpty(userName) ? "Sir/Madame" : userName); - String var10000 = McUrlUtils.getHostUrl(request); - String activationUrl = var10000 + "/resetPassword?token=" + McUuidUtils.toBase64String(passwordResetToken); + String activationUrl = McUrlUtils.getHostUrl(request) + "/resetPassword?token=" + McUuidUtils.toBase64String(passwordResetToken); context.setVariable("passwordResetUrl", activationUrl); String htmlContent = this.toHtmlContent(context, "passwordReset"); this.sendMail(user.getEmail(), user.getName(), "Reset your MiDM password", htmlContent); } + /** + * 发送Exceed登录Failure。 + * + * 实现要点:涉及邮件发送;包含异常捕获与降级/回滚分支;主要调用:sendMail。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param user 当前用户({@code User}) + * @param retryAfter 参数 {@code retryAfter}({@code DateTime}) + * @param client 参数 {@code client}({@code Client}) + * @param remoteIp 参数 {@code remoteIp}({@code String}) + */ public void sendExceedLoginFailure(HttpServletRequest request, HttpServletResponse response, User user, DateTime retryAfter, Client client, String remoteIp) { String subject = "Exceed maximum number of login failure"; WebContext context = this.getContext(request, response); @@ -210,6 +393,15 @@ public class EmailService { this.sendMail(user.getEmail(), user.getName(), "Exceed maximum number of login failure", htmlContent); } + /** + * 发送站点Trial。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、1 个循环;主要调用:sendMail。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param siteRequest 参数 {@code siteRequest}({@code SiteRequest}) + */ public void sendSiteTrial(HttpServletRequest request, HttpServletResponse response, SiteRequest siteRequest) { InternetAddress[] recipients = this.settingsService.siteRequestRecipients(); if (recipients != null && recipients.length > 0) { @@ -225,6 +417,18 @@ public class EmailService { } + /** + * 发送邮件。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;涉及邮件发送;包含 1 个条件分支、0 个循环;主要调用:send。 + * + * 框架注解:{@code @Async}。 + * + * @param toMail 参数 {@code toMail}({@code String}) + * @param toName 参数 {@code toName}({@code String}) + * @param subject 参数 {@code subject}({@code String}) + * @param htmlContent 参数 {@code htmlContent}({@code String}) + */ @Async public void sendMail(String toMail, String toName, String subject, String htmlContent) { McMailSender mailSender = this.getMailSender(); @@ -236,8 +440,19 @@ public class EmailService { } } + /** + * 发送邮件。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;涉及邮件发送;包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new ArrayList、new InternetAddress、send。 + * + * 框架注解:{@code @Async}。 + * + * @param users 参数 {@code users}({@code Collection}) + * @param subject 参数 {@code subject}({@code String}) + * @param htmlContent 参数 {@code htmlContent}({@code String}) + */ @Async - public void sendMail(Collection users, String subject, String htmlContent) { + public void sendMail(Collection users, String subject, String htmlContent) { McMailSender mailSender = this.getMailSender(); if (mailSender != null) { List addrs = new ArrayList(); @@ -268,6 +483,20 @@ public class EmailService { } } + /** + * 发送邮件。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;涉及邮件发送;包含 4 个条件分支、0 个循环;主要调用:new File、exists、send。 + * + * 框架注解:{@code @Async}。 + * + * @param toMail 参数 {@code toMail}({@code String}) + * @param toName 参数 {@code toName}({@code String}) + * @param subject 参数 {@code subject}({@code String}) + * @param htmlContent 参数 {@code htmlContent}({@code String}) + * @param filePath 参数 {@code filePath}({@code String}) + * @param fileName 文件名({@code String}) + */ @Async public void sendMail(String toMail, String toName, String subject, String htmlContent, String filePath, String fileName) { McMailSender mailSender = this.getMailSender(); @@ -290,10 +519,29 @@ public class EmailService { } } + /** + * 获取Context。 + * + * 实现要点:主要调用:new WebContext。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @return 字段/派生属性 {@code context} 的值 + */ private WebContext getContext(HttpServletRequest request, HttpServletResponse response) { return new WebContext(request, response, this.serveletContext, request.getLocale()); } + /** + * 获取邮件Sender。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环。 + * + * @param subject 参数 {@code subject}({@code String}) + * @param content 参数 {@code content}({@code String}) + * @param isHtml 参数 {@code isHtml}({@code boolean}) + * @return 字段/派生属性 {@code mailSender} 的值 + */ public McMailSender getMailSender(String subject, String content, boolean isHtml) { McMailSender sender = this.getMailSender(); if (sender != null) { @@ -304,10 +552,20 @@ public class EmailService { return sender; } + /** + * 判断 {@code mailServer}。 + * @return 字段/派生属性 {@code mailServer} 的值 + */ public boolean hasMailServer() { return !Strings.isNullOrEmpty(this.settingsService.get("mail.host")); } + /** + * 获取 {@code mailSender}。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环;主要调用:new McMailSender。 + * @return 字段/派生属性 {@code mailSender} 的值 + */ public McMailSender getMailSender() { if (mailSender == null) { this.updateMailSender(); @@ -316,6 +574,11 @@ public class EmailService { return mailSender == null ? null : new McMailSender(mailSender, this.settingsService.get("mail.from.mail"), this.settingsService.get("mail.from.name")); } + /** + * 更新邮件Sender。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new JavaMailSenderImpl。 + */ public void updateMailSender() { String host = this.settingsService.get("mail.host"); if (Strings.isNullOrEmpty(host)) { @@ -340,6 +603,15 @@ public class EmailService { } } + /** + * 处理转换为HTMLContent。 + * + * 实现要点:主要调用:process。 + * + * @param context 参数 {@code context}({@code IContext}) + * @param templateName 参数 {@code templateName}({@code String}) + * @return 字符串结果 + */ public String toHtmlContent(IContext context, String templateName) { String htmlTemplate = this.fileService.getResourceToString(String.format("mail/%s.html", templateName), false); return this.stringTemplateEngine.process(htmlTemplate, context); diff --git a/src/main/java/com/midm/service/EmailTemplateResolver.java b/src/main/java/com/midm/service/EmailTemplateResolver.java index 9422296..f320d31 100644 --- a/src/main/java/com/midm/service/EmailTemplateResolver.java +++ b/src/main/java/com/midm/service/EmailTemplateResolver.java @@ -1,4 +1,14 @@ package com.midm.service; +/** + * 【Java 类型】{@code EmailTemplateResolver} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class EmailTemplateResolver { } diff --git a/src/main/java/com/midm/service/ExternalApiService.java b/src/main/java/com/midm/service/ExternalApiService.java index 2555771..6abcbef 100644 --- a/src/main/java/com/midm/service/ExternalApiService.java +++ b/src/main/java/com/midm/service/ExternalApiService.java @@ -19,10 +19,39 @@ import okhttp3.Response; import org.bson.Document; import org.springframework.data.util.Pair; +/** + * 【Java 类型】{@code ExternalApiService} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code client}(OkHttpClient):字段 client
  • + *
+ * + * 协作对象:{@code OkHttpClient}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ public class ExternalApiService { + /** + * 字段 client。 + */ private static OkHttpClient client; - public static void doRequestCallback(Site site, Collection reports) { + /** + * 处理do请求Callback。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:parse、new Builder、new Callback、close。 + * + * @param site 站点/企业({@code Site}) + * @param reports 参数 {@code reports}({@code Collection}) + */ + public static void doRequestCallback(Site site, Collection reports) { try { if (site == null) { return; @@ -55,7 +84,17 @@ public class ExternalApiService { } - public static Pair doRequestRsaIsValid(String url, String serialNo, String encryptString) { + /** + * 处理do请求RSA判断是否Valid。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 7 个条件分支、0 个循环;主要调用:new JsonObject、parse、new Builder、close。 + * + * @param url 参数 {@code url}({@code String}) + * @param serialNo 设备序列号({@code String}) + * @param encryptString 参数 {@code encryptString}({@code String}) + * @return 处理结果 + */ + public static Pair doRequestRsaIsValid(String url, String serialNo, String encryptString) { if (Strings.isNullOrEmpty(url)) { return Pair.of(true, ""); } else { @@ -73,7 +112,7 @@ public class ExternalApiService { label73: { Pair var11; label74: { - Pair decryptStrings; + Pair failureResult; try { if (response.code() != 200) { var15 = Pair.of(false, String.format("InvalidRsa, response code: %s, url: %s ", response.code(), url)); @@ -88,7 +127,7 @@ public class ExternalApiService { break label74; } - decryptStrings = Pair.of(false, String.format("InvalidRsa, responseVmaxcode: %s, url: %s", responseCode.toString(), url)); + failureResult = Pair.of(false, String.format("InvalidRsa, responseVmaxcode: %s, url: %s", responseCode.toString(), url)); } catch (Throwable var13) { if (response != null) { try { @@ -105,7 +144,7 @@ public class ExternalApiService { response.close(); } - return decryptStrings; + return failureResult; } if (response != null) { @@ -130,6 +169,22 @@ public class ExternalApiService { client = (new OkHttpClient.Builder()).connectTimeout(5L, TimeUnit.SECONDS).writeTimeout(30L, TimeUnit.SECONDS).build(); } + /** + * 【枚举常量】{@code REPONSE_VMAX_CODE} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(String):代码
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ private static enum REPONSE_VMAX_CODE { SUCCESS("S00000"), ERROR_DEVICE_RSA_KEY_ID_NOT_FOUND("E10028"), @@ -139,12 +194,28 @@ public class ExternalApiService { UNKNOWN_EXCEPTION("E99999"), UNKNOWN_ERROR_IN_MIDM("E0000"); + /** + * 代码。 + */ private String code; + /** + * 构造 {@code REPONSE_VMAX_CODE} 实例。 + * + * @param code 状态码/业务码({@code String}) + */ private REPONSE_VMAX_CODE(String code) { this.code = code; } + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param requestText 参数 {@code requestText}({@code String}) + * @return 处理结果 + */ private static REPONSE_VMAX_CODE get(String requestText) { for(REPONSE_VMAX_CODE c : values()) { if (c.code.equalsIgnoreCase(requestText.trim())) { diff --git a/src/main/java/com/midm/service/GeneralService.java b/src/main/java/com/midm/service/GeneralService.java index 2b60767..19da5a3 100644 --- a/src/main/java/com/midm/service/GeneralService.java +++ b/src/main/java/com/midm/service/GeneralService.java @@ -14,16 +14,61 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code GeneralService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mongoTemplate}(MongoTemplate):MongoDB模板
  • + *
  • {@code mongoOperations}(MongoOperations):MongoDBOperations
  • + *
+ * + * 协作对象:{@code MongoTemplate、MongoOperations}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Service public class GeneralService { + /** + * MongoDB模板;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected MongoTemplate mongoTemplate; + /** + * MongoDBOperations。 + */ protected MongoOperations mongoOperations; + /** + * 构造 {@code GeneralService} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + */ public GeneralService() { this.mongoOperations = this.mongoTemplate; } + /** + * 处理转换为查询。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:new Query。 + * + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param directionValue 参数 {@code directionValue}({@code String}) + * @return 处理结果 + */ protected Query toQuery(JsonObject jFilter, Integer page, Integer size, String sortBy, String directionValue) { Query query = new Query(); if (McStringUtils.isValid(sortBy)) { diff --git a/src/main/java/com/midm/service/ScheduledTaskService.java b/src/main/java/com/midm/service/ScheduledTaskService.java index dc2d275..eb859f0 100644 --- a/src/main/java/com/midm/service/ScheduledTaskService.java +++ b/src/main/java/com/midm/service/ScheduledTaskService.java @@ -13,17 +13,61 @@ import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code ScheduledTaskService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code scheduledExecutorService}(ScheduledExecutorService):scheduledExecutor服务
  • + *
  • {@code scheduleMap}(Map>):调度Map
  • + *
+ * + * 协作对象:{@code ProfileService、ScheduledExecutorService}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ @Service public class ScheduledTaskService { + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * scheduledExecutor服务。 + */ private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10); - private static Map scheduleMap = new ConcurrentHashMap(); + /** + * 调度Map。 + */ + private static Map> scheduleMap = new ConcurrentHashMap(); + /** + * 调度转换为更新配置档案。 + * + * @param device 设备({@code Device}) + */ public void scheduleToUpdateProfile(Device device) { this.scheduleToUpdateProfile((Device)device, 5); } + /** + * 调度转换为更新配置档案。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:cancel、schedule、new DeviceUpdateRunnable。 + * + * @param device 设备({@code Device}) + * @param minLater 参数 {@code minLater}({@code int}) + */ public void scheduleToUpdateProfile(Device device, int minLater) { if (device != null) { ScheduledFuture task = (ScheduledFuture)scheduleMap.get(device.getUuid()); @@ -35,6 +79,14 @@ public class ScheduledTaskService { } } + /** + * 调度转换为更新配置档案。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:cancel、schedule、new DeviceUpdateRunnable。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param minLater 参数 {@code minLater}({@code int}) + */ public void scheduleToUpdateProfile(UUID deviceUuid, int minLater) { if (deviceUuid != null) { ScheduledFuture task = (ScheduledFuture)scheduleMap.get(deviceUuid); @@ -46,6 +98,13 @@ public class ScheduledTaskService { } } + /** + * 取消调度。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void cancelSchedule(UUID uuid) { if (scheduleMap.containsKey(uuid)) { ((ScheduledFuture)scheduleMap.get(uuid)).cancel(true); @@ -53,6 +112,13 @@ public class ScheduledTaskService { } + /** + * 调度转换为更新配置档案。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:cancel、schedule、new ProfileUpdateRunnable。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + */ public void scheduleToUpdateProfile(DeviceProfile deviceProfile) { if (deviceProfile != null && deviceProfile.getEnabled()) { ScheduledFuture task = (ScheduledFuture)scheduleMap.get(deviceProfile.getUuid()); @@ -64,30 +130,95 @@ public class ScheduledTaskService { } } + /** + * 【Java 类型】{@code DeviceUpdateRunnable} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceUuid}(UUID):设备UUID
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ class DeviceUpdateRunnable implements Runnable { + /** + * 设备UUID。 + */ private UUID deviceUuid; + /** + * 构造 {@code DeviceUpdateRunnable} 实例。 + * + * @param device 设备({@code Device}) + */ public DeviceUpdateRunnable(Device device) { this.deviceUuid = device.getUuid(); } + /** + * 构造 {@code DeviceUpdateRunnable} 实例。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public DeviceUpdateRunnable(UUID deviceUuid) { this.deviceUuid = deviceUuid; } + /** + * 执行本次任务的主体逻辑。 + * + * 实现要点:主要调用:remove。 + */ public void run() { ScheduledTaskService.this.profileService.notifyUpdate(this.deviceUuid); ScheduledTaskService.scheduleMap.remove(this.deviceUuid); } } + /** + * 【Java 类型】{@code ProfileUpdateRunnable} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profile}(DeviceProfile):配置档案
  • + *
+ * + * 协作对象:{@code DeviceProfile}。 + * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ class ProfileUpdateRunnable implements Runnable { + /** + * 配置档案。 + */ private DeviceProfile profile; + /** + * 构造 {@code ProfileUpdateRunnable} 实例。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + */ public ProfileUpdateRunnable(DeviceProfile profile) { this.profile = profile; } + /** + * 执行本次任务的主体逻辑。 + * + * 实现要点:主要调用:remove。 + */ public void run() { ScheduledTaskService.scheduleMap.remove(this.profile.getUuid()); ScheduledTaskService.this.profileService.notifyUpdate(this.profile, false); diff --git a/src/main/java/com/midm/service/battery/BatteryService.java b/src/main/java/com/midm/service/battery/BatteryService.java index 1d70f17..e542a3c 100644 --- a/src/main/java/com/midm/service/battery/BatteryService.java +++ b/src/main/java/com/midm/service/battery/BatteryService.java @@ -70,15 +70,35 @@ import org.springframework.stereotype.Service; @Service public class BatteryService extends BaseService { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired DeviceService deviceService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired SiteService siteService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; @@ -116,7 +136,7 @@ public class BatteryService extends BaseService { /** * 批量保存电池档案 */ - public Collection saveBatteries(Collection batteries) { + public Collection saveBatteries(Collection batteries) { Collection saveList = new ArrayList(); for(Battery battery : (Collection)batteries) { Battery saveBattery = this.save(battery); @@ -146,7 +166,7 @@ public class BatteryService extends BaseService { * @param direction 升序/降序 * @return 分页结果封装 */ - public Page findBatteries(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + public Page findBatteries(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.hardware_info.batterySerial"; direction = Direction.ASC; @@ -234,7 +254,7 @@ public class BatteryService extends BaseService { * @param to 结束时间 * @return 时序日志列表 */ - public List findBatteryLogByRange(String deviceSerial, Date from, Date to) { + public List findBatteryLogByRange(String deviceSerial, Date from, Date to) { AggregationOperation lookupOp = Aggregations.newOperation(new Document("$lookup", (new Document("from", "batteryLog")) .append("localField", "profile.hardware_info.batterySerial") .append("foreignField", "batterySerial") @@ -276,7 +296,7 @@ public class BatteryService extends BaseService { * 2. 提取最新一条日志同步更新至 Battery 主实体的 states 字段; * 3. 同步触发设备状态与告警检查。 */ - public List saveBatteryLogs(List logs, String category) { + public List saveBatteryLogs(List logs, String category) { if (logs != null && !logs.isEmpty()) { List saveList = new ArrayList(); String batterySerial = ((BatteryLog)logs.get(0)).getBatterySerial(); @@ -339,7 +359,7 @@ public class BatteryService extends BaseService { /** * 批量修改电池登记状态(enrolled, registered, decommissioned) */ - public void setRegisterState(List batteryUuids, String state) { + public void setRegisterState(List batteryUuids, String state) { if (batteryUuids != null && !batteryUuids.isEmpty()) { Query query = Query.query(Criteria.where("_id").in(batteryUuids)); Update update = Update.update("states.state", state); @@ -455,7 +475,7 @@ public class BatteryService extends BaseService { /** * 【时序存储数据降采样压缩】对数组型时序指标只截取并保留最新一条采样值 */ - private void leaveLast(DbObject states, List keys) { + private void leaveLast(DbObject states, List keys) { for(String key : (List)keys) { List tList = (List)McJsonUtils.toObject(McJsonUtils.toJson(states.get(key)), (new TypeToken() { }).getType()); diff --git a/src/main/java/com/midm/service/battery/package-info.java b/src/main/java/com/midm/service/battery/package-info.java new file mode 100644 index 0000000..585e44d --- /dev/null +++ b/src/main/java/com/midm/service/battery/package-info.java @@ -0,0 +1,12 @@ +/** + * 电池健康度服务:遥测入库、聚合、告警。 + * + *

本包主要类型: + *

    + *
  • {@link BatteryService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.battery; diff --git a/src/main/java/com/midm/service/cloudStorage/AwsS3.java b/src/main/java/com/midm/service/cloudStorage/AwsS3.java index 001b856..c33bd2c 100644 --- a/src/main/java/com/midm/service/cloudStorage/AwsS3.java +++ b/src/main/java/com/midm/service/cloudStorage/AwsS3.java @@ -22,22 +22,85 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +/** + * 【业务服务】{@code AwsS3} + * + * 类职责: + *

    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code PROPERTY_ACCESS_KEY}(String):字段 PROPERTY_ACCESS_KEY
  • + *
  • {@code PROPERTY_SECRET}(String):字段 PROPERTY_SECRET
  • + *
  • {@code PROPERTY_REGION}(String):字段 PROPERTY_REGION
  • + *
  • {@code PROPERTY_BUCKET}(String):字段 PROPERTY_BUCKET
  • + *
  • {@code PROPERTY_PREFIX}(String):字段 PROPERTY_PREFIX
  • + *
  • {@code accessKey}(String):access密钥
  • + *
+ * + * 协作对象:{@code AmazonS3}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class AwsS3 extends CloudStorage { + /** + * 字段 PROPERTY_ACCESS_KEY。 + */ private static final String PROPERTY_ACCESS_KEY = "aws.s3.accessKey"; + /** + * 字段 PROPERTY_SECRET。 + */ private static final String PROPERTY_SECRET = "aws.s3.secret"; + /** + * 字段 PROPERTY_REGION。 + */ private static final String PROPERTY_REGION = "aws.s3.region"; + /** + * 字段 PROPERTY_BUCKET。 + */ private static final String PROPERTY_BUCKET = "aws.s3.bucket"; + /** + * 字段 PROPERTY_PREFIX。 + */ private static final String PROPERTY_PREFIX = "aws.s3.prefix"; + /** + * access密钥。 + */ private String accessKey = ""; + /** + * secret密钥。 + */ private String secretKey = ""; + /** + * 区域。 + */ private String region = ""; + /** + * 字段 s3Client。 + */ private AmazonS3 s3Client; + /** + * 构造 {@code AwsS3} 实例。 + * + * @param settingsService 参数 {@code settingsService}({@code SettingsService}) + */ public AwsS3(SettingsService settingsService) { super(settingsService); this.refreshClient(); } + /** + * 获取URL。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 字符串结果 + */ public String getUrl(Object... paths) { if (this.exists(paths)) { Date expiry = this.getUrlExpiry(); @@ -48,6 +111,17 @@ public class AwsS3 extends CloudStorage { } } + /** + * 处理上传。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new PutObjectRequest、new ObjectMetadata、exists。 + * + * @param file 文件({@code File}) + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean upload(File file, String orgFileName, String contentType, Object... paths) { if (this.s3Client != null) { PutObjectRequest request = (new PutObjectRequest(this.getBucketName(), this.generateObjectKey(paths), file)).withCannedAcl(CannedAccessControlList.Private); @@ -62,6 +136,15 @@ public class AwsS3 extends CloudStorage { } } + /** + * 更新Meta信息。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new CopyObjectRequest。 + * + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + */ public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { String bucketName = this.getBucketName(); String objectName = this.generateObjectKey(paths); @@ -85,12 +168,23 @@ public class AwsS3 extends CloudStorage { } + /** + * 处理删除。 + * + * @param paths 对象存储路径片段({@code Object[]}) + */ public void delete(Object... paths) { List lists = this.list(paths); lists.forEach((s3Object) -> this.s3Client.deleteObject(this.getBucketName(), s3Object)); } - public static Map getRegions() { + /** + * 获取 {@code regions}。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new HashMap。 + * @return 处理结果 + */ + public static Map getRegions() { Map regions = new HashMap(); for(Regions region : Regions.values()) { @@ -100,7 +194,15 @@ public class AwsS3 extends CloudStorage { return regions; } - public List list(Object... paths) { + /** + * 处理列出。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return String列表,可能为空 + */ + public List list(Object... paths) { if (this.s3Client == null) { return null; } else { @@ -120,10 +222,21 @@ public class AwsS3 extends CloudStorage { } } + /** + * 处理存在。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(Object... paths) { return this.s3Client == null ? false : this.s3Client.doesObjectExist(this.getBucketName(), this.generateObjectKey(paths)); } + /** + * 刷新Client。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 9 个条件分支、0 个循环;主要调用:new AWSStaticCredentialsProvider、new BasicAWSCredentials。 + */ public void refreshClient() { boolean hasChange = false; String accessKey = this.settingsService.get("aws.s3.accessKey"); @@ -183,10 +296,18 @@ public class AwsS3 extends CloudStorage { } } + /** + * 获取 {@code bucketName}。 + * @return 字符串结果 + */ private String getBucketName() { return this.settingsService.get("aws.s3.bucket"); } + /** + * 获取 {@code prefix}。 + * @return 字符串结果 + */ public String getPrefix() { return this.settingsService.get("aws.s3.prefix"); } diff --git a/src/main/java/com/midm/service/cloudStorage/AzureBlob.java b/src/main/java/com/midm/service/cloudStorage/AzureBlob.java index 659b27d..858d20a 100644 --- a/src/main/java/com/midm/service/cloudStorage/AzureBlob.java +++ b/src/main/java/com/midm/service/cloudStorage/AzureBlob.java @@ -16,36 +16,119 @@ import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; +/** + * 【业务服务】{@code AzureBlob} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code PROPERTY_ACCOUNT_NAME}(String):字段 PROPERTY_ACCOUNT_NAME
  • + *
  • {@code PROPERTY_ACCOUNT_KEY}(String):字段 PROPERTY_ACCOUNT_KEY
  • + *
  • {@code PROPERTY_ENDPOINT_SUFFIX}(String):字段 PROPERTY_ENDPOINT_SUFFIX
  • + *
  • {@code DEFAULT_ENDPOINT}(String):字段 DEFAULT_ENDPOINT
  • + *
  • {@code PROPERTY_PROTOCOL}(String):字段 PROPERTY_PROTOCOL
  • + *
  • {@code DEFAULT_PROTOCOL}(String):字段 DEFAULT_PROTOCOL
  • + *
+ * + * 协作对象:{@code BlobServiceClient}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class AzureBlob extends CloudStorage { + /** + * 字段 PROPERTY_ACCOUNT_NAME。 + */ private static final String PROPERTY_ACCOUNT_NAME = "azure.blob.account_name"; + /** + * 字段 PROPERTY_ACCOUNT_KEY。 + */ private static final String PROPERTY_ACCOUNT_KEY = "azure.blob.account_key"; + /** + * 字段 PROPERTY_ENDPOINT_SUFFIX。 + */ private static final String PROPERTY_ENDPOINT_SUFFIX = "azure.blob.endpoint"; + /** + * 字段 DEFAULT_ENDPOINT。 + */ private static final String DEFAULT_ENDPOINT = "core.windows.net"; + /** + * 字段 PROPERTY_PROTOCOL。 + */ private static final String PROPERTY_PROTOCOL = "azure.blob.protocol"; + /** + * 字段 DEFAULT_PROTOCOL。 + */ private static final String DEFAULT_PROTOCOL = "https"; + /** + * 字段 PROPERTY_CONTAINER。 + */ private static final String PROPERTY_CONTAINER = "azure.blob.container"; + /** + * 字段 PROPERTY_PREFIX。 + */ private static final String PROPERTY_PREFIX = "azure.blob.prefix"; + /** + * 字段 connectionString。 + */ private String connectionString = ""; + /** + * 服务Client。 + */ private BlobServiceClient serviceClient; + /** + * 构造 {@code AzureBlob} 实例。 + * + * @param settingsService 参数 {@code settingsService}({@code SettingsService}) + */ public AzureBlob(SettingsService settingsService) { super(settingsService); this.connectionString = String.format("DefaultEndpointsProtocol=%s;AccountName=%s;AccountKey=%s;EndpointSuffix=%s", settingsService.get("azure.blob.protocol", "https"), settingsService.get("azure.blob.account_name"), settingsService.get("azure.blob.account_key"), settingsService.get("azure.blob.endpoint", "core.windows.net")); this.refreshClient(); } + /** + * 获取URL。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 字符串结果 + */ public String getUrl(Object... paths) { BlobClient blobClient = this.getBlobClient(paths); String sasToken = this.getSasToken(blobClient); return blobClient == null ? null : String.format("%s?%s", blobClient.getBlobUrl(), sasToken); } + /** + * 获取Sas令牌。 + * + * 实现要点:主要调用:new BlobContainerSasPermission、new BlobServiceSasSignatureValues。 + * + * @param blobClient 参数 {@code blobClient}({@code BlobClient}) + * @return 字符串结果 + */ private String getSasToken(BlobClient blobClient) { BlobContainerSasPermission blobContainerSasPermission = (new BlobContainerSasPermission()).setReadPermission(true).setWritePermission(true).setListPermission(true); BlobServiceSasSignatureValues values = (new BlobServiceSasSignatureValues(OffsetDateTime.now().plusDays(7L), blobContainerSasPermission)).setProtocol(SasProtocol.HTTPS_ONLY); return blobClient.generateSas(values); } + /** + * 处理上传。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param file 文件({@code File}) + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean upload(File file, String orgFileName, String contentType, Object... paths) { BlobClient blobClient = this.getBlobClient(paths); if (blobClient != null) { @@ -57,6 +140,13 @@ public class AzureBlob extends CloudStorage { } } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists、delete。 + * + * @param paths 对象存储路径片段({@code Object[]}) + */ public void delete(Object... paths) { BlobClient blobClient = this.getBlobClient(paths); if (blobClient.exists()) { @@ -65,11 +155,23 @@ public class AzureBlob extends CloudStorage { } + /** + * 获取BlobClient。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 字段/派生属性 {@code blobClient} 的值 + */ private BlobClient getBlobClient(Object... paths) { BlobContainerClient client = this.getContainerClient(); return client == null ? null : client.getBlobClient(this.generateObjectKey(paths)); } + /** + * 获取 {@code containerClient}。 + * + * 实现要点:包含 4 个条件分支、0 个循环;主要调用:exists。 + * @return 字段/派生属性 {@code containerClient} 的值 + */ public BlobContainerClient getContainerClient() { String container = this.settingsService.get("azure.blob.container"); if (Strings.isNullOrEmpty(container)) { @@ -92,11 +194,24 @@ public class AzureBlob extends CloudStorage { } } + /** + * 刷新Client。 + * + * 实现要点:主要调用:new BlobServiceClientBuilder。 + */ public void refreshClient() { this.serviceClient = (new BlobServiceClientBuilder()).connectionString(this.connectionString).buildClient(); } - public List list(Object... paths) { + /** + * 处理列出。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return String列表,可能为空 + */ + public List list(Object... paths) { BlobContainerClient client = this.getContainerClient(); if (client != null) { List items = new ArrayList(); @@ -107,11 +222,28 @@ public class AzureBlob extends CloudStorage { } } + /** + * 处理存在。 + * + * 实现要点:主要调用:exists。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(Object... paths) { BlobClient blobClient = this.getBlobClient(paths); return blobClient == null ? false : blobClient.exists(); } + /** + * 更新Meta信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + */ public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { BlobClient blobClient = this.getBlobClient(paths); if (blobClient.exists()) { @@ -120,6 +252,15 @@ public class AzureBlob extends CloudStorage { } + /** + * 设置Meta数据。 + * + * 实现要点:主要调用:new BlobHttpHeaders。 + * + * @param blobClient 参数 {@code blobClient}({@code BlobClient}) + * @param fileName 文件名({@code String}) + * @param contentType Content-Type({@code String}) + */ private void setMetaData(BlobClient blobClient, String fileName, String contentType) { BlobHttpHeaders headers = new BlobHttpHeaders(); headers.setContentType(contentType); @@ -127,6 +268,10 @@ public class AzureBlob extends CloudStorage { blobClient.setHttpHeaders(headers); } + /** + * 获取 {@code prefix}。 + * @return 字符串结果 + */ public String getPrefix() { return this.settingsService.get("azure.blob.prefix"); } diff --git a/src/main/java/com/midm/service/cloudStorage/CloudStorage.java b/src/main/java/com/midm/service/cloudStorage/CloudStorage.java index 6e3d3be..f1e5e8d 100644 --- a/src/main/java/com/midm/service/cloudStorage/CloudStorage.java +++ b/src/main/java/com/midm/service/cloudStorage/CloudStorage.java @@ -85,7 +85,7 @@ public abstract class CloudStorage { * @param paths 路径前缀 * @return 对象列表 */ - public abstract List list(Object... paths); + public abstract List list(Object... paths); /** * 上传本地文件到云存储 diff --git a/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java b/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java index b561ab3..d6edd24 100644 --- a/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java +++ b/src/main/java/com/midm/service/cloudStorage/CloudStorageService.java @@ -26,6 +26,11 @@ import org.springframework.stereotype.Service; @Service public class CloudStorageService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected SettingsService settingsService; @@ -84,7 +89,7 @@ public class CloudStorageService { /** * 获取文件列表 */ - public List list() { + public List list() { return this.cloudStorage == null ? null : this.cloudStorage.list(); } @@ -159,8 +164,6 @@ public class CloudStorageService { * 更新云端对象的元数据属性 */ public void updateMetaInfo(String fileName, String contentType, Object... paths) { - if (this.cloudStorage != null) { - this.cloudStorage.updateMetaInfo(fileName, contentType, paths); - } + this.cloudStorage.updateMetaInfo(fileName, contentType, paths); } } diff --git a/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java b/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java index af4b99b..7f1f12d 100644 --- a/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java +++ b/src/main/java/com/midm/service/cloudStorage/GoogleCloudStorage.java @@ -17,25 +17,91 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; +/** + * 【业务服务】{@code GoogleCloudStorage} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code PROPERTY_PROJECT_ID}(String):字段 PROPERTY_PROJECT_ID
  • + *
  • {@code PROPERTY_CREDENTIAL}(String):字段 PROPERTY_CREDENTIAL
  • + *
  • {@code PROPERTY_BUCKET}(String):字段 PROPERTY_BUCKET
  • + *
  • {@code PROPERTY_PREFIX}(String):字段 PROPERTY_PREFIX
  • + *
  • {@code projectId}(String):projectID
  • + *
  • {@code credential}(String):字段 credential
  • + *
+ * + * 协作对象:{@code Storage}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class GoogleCloudStorage extends CloudStorage { + /** + * 字段 PROPERTY_PROJECT_ID。 + */ private static final String PROPERTY_PROJECT_ID = "google.cloud.projectId"; + /** + * 字段 PROPERTY_CREDENTIAL。 + */ private static final String PROPERTY_CREDENTIAL = "google.cloud.credential"; + /** + * 字段 PROPERTY_BUCKET。 + */ private static final String PROPERTY_BUCKET = "google.cloud.bucket"; + /** + * 字段 PROPERTY_PREFIX。 + */ private static final String PROPERTY_PREFIX = "google.cloud.prefix"; + /** + * projectID。 + */ private String projectId = ""; + /** + * 字段 credential。 + */ private String credential = ""; + /** + * 存储。 + */ protected Storage storage; + /** + * 构造 {@code GoogleCloudStorage} 实例。 + * + * @param settingsService 参数 {@code settingsService}({@code SettingsService}) + */ public GoogleCloudStorage(SettingsService settingsService) { super(settingsService); this.refreshClient(); } + /** + * 获取URL。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 字符串结果 + */ public String getUrl(Object... paths) { BlobId blobId = this.getBlobId(paths); return blobId == null ? null : blobId.toGsUtilUri(); } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new McFile。 + * + * @param file 文件({@code File}) + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean upload(File file, String orgFileName, String contentType, Object... paths) { BlobId blobId = this.getBlobId(paths); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentDisposition(McHttpClient.toContentDisposition(orgFileName)).setContentType(contentType).build(); @@ -50,6 +116,13 @@ public class GoogleCloudStorage extends CloudStorage { } } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * @param paths 对象存储路径片段({@code Object[]}) + */ public void delete(Object... paths) { if (this.storage != null) { BlobId blobId = this.getBlobId(paths); @@ -58,10 +131,19 @@ public class GoogleCloudStorage extends CloudStorage { } + /** + * 获取 {@code bucketName}。 + * @return 字符串结果 + */ private String getBucketName() { return this.settingsService.get("google.cloud.bucket"); } + /** + * 刷新Client。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:new ByteArrayInputStream。 + */ public void refreshClient() { String projectId = this.settingsService.get("google.cloud.projectId"); if (Strings.isNullOrEmpty(projectId)) { @@ -90,18 +172,41 @@ public class GoogleCloudStorage extends CloudStorage { } - public List list(Object... paths) { + /** + * 处理列出。 + * + * 实现要点:主要调用:new ArrayList。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return String列表,可能为空 + */ + public List list(Object... paths) { List lists = this.storage.get(new BlobId[]{this.getBlobId(paths)}); List names = new ArrayList(); lists.forEach((blob) -> names.add(blob.getName())); return names; } + /** + * 处理存在。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(Object... paths) { BlobId blobId = this.getBlobId(paths); return this.storage.get(blobId).exists(new Blob.BlobSourceOption[0]); } + /** + * 更新Meta信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param orgFileName 参数 {@code orgFileName}({@code String}) + * @param contentType Content-Type({@code String}) + * @param paths 对象存储路径片段({@code Object[]}) + */ public void updateMetaInfo(String orgFileName, String contentType, Object... paths) { BlobId blobId = this.getBlobId(paths); Blob blob = this.storage.get(blobId); @@ -111,10 +216,20 @@ public class GoogleCloudStorage extends CloudStorage { } + /** + * 获取BlobID。 + * + * @param paths 对象存储路径片段({@code Object[]}) + * @return 字段/派生属性 {@code blobId} 的值 + */ private BlobId getBlobId(Object... paths) { return BlobId.of(this.getBucketName(), this.generateObjectKey(paths)); } + /** + * 获取 {@code prefix}。 + * @return 字符串结果 + */ public String getPrefix() { return this.settingsService.get("google.cloud.prefix"); } diff --git a/src/main/java/com/midm/service/cloudStorage/package-info.java b/src/main/java/com/midm/service/cloudStorage/package-info.java new file mode 100644 index 0000000..e0fd676 --- /dev/null +++ b/src/main/java/com/midm/service/cloudStorage/package-info.java @@ -0,0 +1,16 @@ +/** + * 多云对象存储策略:AWS S3、Azure Blob、GCP Storage 的统一抽象。 + * + *

本包主要类型: + *

    + *
  • {@link AwsS3}
  • + *
  • {@link AzureBlob}
  • + *
  • {@link CloudStorage}
  • + *
  • {@link CloudStorageService}
  • + *
  • {@link GoogleCloudStorage}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.cloudStorage; diff --git a/src/main/java/com/midm/service/device/DeviceAppsService.java b/src/main/java/com/midm/service/device/DeviceAppsService.java index 47d68c0..8fc9665 100644 --- a/src/main/java/com/midm/service/device/DeviceAppsService.java +++ b/src/main/java/com/midm/service/device/DeviceAppsService.java @@ -17,10 +17,37 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code DeviceAppsService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code appsMap}(Map):应用列表Map
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class DeviceAppsService extends BaseService { - private Map appsMap = new ConcurrentHashMap(); + /** + * 应用列表Map。 + */ + private Map appsMap = new ConcurrentHashMap(); + /** + * 处理保存。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param apps 参数 {@code apps}({@code DeviceApps}) + * @return 处理结果 + */ public DeviceApps save(DeviceApps apps) { apps.fixAbnormal(); UUID deviceUuid = apps.getDeviceUuid(); @@ -37,7 +64,16 @@ public class DeviceAppsService extends BaseService { } } - public DeviceApps save(UUID deviceUuid, List apps) { + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new DeviceApps、save。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param apps 参数 {@code apps}({@code List}) + * @return 处理结果 + */ + public DeviceApps save(UUID deviceUuid, List apps) { if (apps != null && !apps.isEmpty()) { DeviceApps deviceApps = new DeviceApps(); deviceApps.setDeviceUuid(deviceUuid); @@ -48,6 +84,14 @@ public class DeviceAppsService extends BaseService { } } + /** + * 获取Installed应用列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字段/派生属性 {@code installedApps} 的值 + */ public DeviceApps getInstalledApps(UUID deviceUuid) { if (this.appsMap.containsKey(deviceUuid)) { return (DeviceApps)this.appsMap.get(deviceUuid); @@ -61,12 +105,33 @@ public class DeviceAppsService extends BaseService { } } + /** + * 获取应用列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 字段/派生属性 {@code apps} 的值 + */ public DeviceApps getApps(UUID deviceUuid, String category) { Query query = this.queryByIdAndCategory(deviceUuid, category); DeviceApps deviceApps = (DeviceApps)this.mongoTemplate.findOne(query, DeviceApps.class); return deviceApps; } + /** + * 处理installed应用。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Document。 + * + * @param device 设备({@code Device}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdk 参数 {@code minSdk}({@code int}) + * @return MongoDB 文档对象 + */ public Document installedApp(Device device, String packageName, int versionCode, String versionName, int minSdk) { Document document = (new Document("deviceUuid", device.getUuid())).append("packageName", packageName); DeviceApps apps = this.getInstalledApps(device.getUuid()); @@ -84,6 +149,14 @@ public class DeviceAppsService extends BaseService { return document; } + /** + * 判断是否Installed应用列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字段/派生属性 {@code installedApps} 的值 + */ public boolean hasInstalledApps(UUID deviceUuid) { if (!this.appsMap.containsKey(deviceUuid)) { Query query = this.queryByIdAndCategory(deviceUuid, "installed"); @@ -93,10 +166,25 @@ public class DeviceAppsService extends BaseService { } } + /** + * 查询按ID并Category。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 处理结果 + */ private Query queryByIdAndCategory(UUID deviceUuid, String category) { return Query.query(Criteria.where("_id").is(deviceUuid).and("category").is(category)); } + /** + * 处理新Client应用Installed。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean newClientAppInstalled(UUID deviceUuid) { DeviceApps apps = this.getInstalledApps(deviceUuid); if (apps == null) { @@ -112,6 +200,18 @@ public class DeviceAppsService extends BaseService { } } + /** + * 更新设备应用状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new DeviceApps、new AppInfo、new Date、findOne、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param label 参数 {@code label}({@code String}) + * @return 处理结果 + */ public DeviceApps updateDeviceAppState(UUID deviceUuid, String packageName, int versionCode, String versionName, String label) { DeviceApps apps = this.getInstalledApps(deviceUuid); if (apps != null) { @@ -147,17 +247,39 @@ public class DeviceAppsService extends BaseService { return apps; } + /** + * 移除设备应用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、new Document、updateMulti。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + */ public void removeDeviceApp(UUID deviceUuid, String packageName) { Update update = new Update(); update.pull("apps", new Document("packageName", packageName)); this.mongoTemplate.updateMulti(this.queryById(deviceUuid), update, DeviceApps.class); } + /** + * 处理删除。 + * + * 实现要点:主要调用:remove。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void delete(UUID deviceUuid) { this.deleteById(DeviceApps.class, deviceUuid); this.appsMap.remove(deviceUuid); } + /** + * 移除缓存。 + * + * 实现要点:主要调用:remove。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void removeCache(UUID deviceUuid) { this.appsMap.remove(deviceUuid); } diff --git a/src/main/java/com/midm/service/device/DeviceKeyService.java b/src/main/java/com/midm/service/device/DeviceKeyService.java index 5e3e216..9a47d86 100644 --- a/src/main/java/com/midm/service/device/DeviceKeyService.java +++ b/src/main/java/com/midm/service/device/DeviceKeyService.java @@ -41,11 +41,21 @@ public class DeviceKeyService extends BaseService { private static Object lock = new Object(); /** 内存高频读缓存:以设备序列号为 Key,加速高频接口的非对称密钥提取 */ - private static Map keyBySerailNo = new HashMap(); + private static Map keyBySerailNo = new HashMap(); + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired DeviceService deviceService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired SettingsService settingsService; @@ -128,7 +138,7 @@ public class DeviceKeyService extends BaseService { * @param encryptString 终端携带的加密签名串 * @return Pair(是否有效 true/false, 错误描述原因) */ - public Pair isValidRsa(String serialNo, String encryptString) { + public Pair isValidRsa(String serialNo, String encryptString) { // 1. 检查全局是否开启了严格 RSA 硬件鉴权开关 if (!this.settingsService.rsaEnabled()) { return Pair.of(true, ""); diff --git a/src/main/java/com/midm/service/device/DeviceReportService.java b/src/main/java/com/midm/service/device/DeviceReportService.java index 9e62ef1..893d6de 100644 --- a/src/main/java/com/midm/service/device/DeviceReportService.java +++ b/src/main/java/com/midm/service/device/DeviceReportService.java @@ -61,38 +61,124 @@ import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; +/** + * 【业务服务】{@code DeviceReportService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code MIN_DATA_USAGE_GAP}(long):字段 MIN_DATA_USAGE_GAP
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code deviceAppsService}(DeviceAppsService):设备应用列表服务
  • + *
+ * + * 协作对象:{@code SiteService、DeviceService、ProfileService、FileService、DeviceAppsService、SettingsService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class DeviceReportService extends BaseService { + /** + * 字段 MIN_DATA_USAGE_GAP。 + */ private static final long MIN_DATA_USAGE_GAP = 900000L; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteService siteService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceService deviceService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private ProfileService profileService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private FileService fileService; + /** + * 设备应用列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceAppsService deviceAppsService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SettingsService settingsService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private WebSocketSessionManager sessionManager; + /** + * string模板Engine;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。 + */ @Autowired @Qualifier("stringTemplateEngine") private TemplateEngine stringTemplateEngine; - private Map profileNotifySchedules = new HashMap(); - private Map profileStateUpdateSchedules = new HashMap(); - private Map dataUsageSchedules = new HashMap(); - private Map dataUsageMap = new HashMap(); + /** + * 配置档案通知Schedules。 + */ + private Map> profileNotifySchedules = new HashMap(); + /** + * 配置档案状态更新Schedules。 + */ + private Map> profileStateUpdateSchedules = new HashMap(); + /** + * 数据用量Schedules。 + */ + private Map> dataUsageSchedules = new HashMap(); + /** + * 数据用量Map。 + */ + private Map dataUsageMap = new HashMap(); + /** + * 处理保存。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new Date。 + * + * @param report 参数 {@code report}({@code DeviceReport}) + * @return 处理结果 + */ public DeviceReport save(DeviceReport report) { if (report.getDeviceUuid() == null) { return report; @@ -113,7 +199,16 @@ public class DeviceReportService extends BaseService { } } - public Collection save(UUID siteUuid, Collection reports) { + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new ArrayList、save。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param reports 参数 {@code reports}({@code Collection}) + * @return 设备报表列表,可能为空 + */ + public Collection save(UUID siteUuid, Collection reports) { Collection reportedList = null; try { @@ -133,6 +228,16 @@ public class DeviceReportService extends BaseService { return reportedList; } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new DeviceReport、save。 + * + * @param device 设备({@code Device}) + * @param item 参数 {@code item}({@code String}) + * @param content 参数 {@code content}({@code Object}) + * @return 处理结果 + */ public DeviceReport save(Device device, String item, Object content) { DeviceReport report = new DeviceReport(); report.init(); @@ -144,6 +249,13 @@ public class DeviceReportService extends BaseService { return report; } + /** + * 处理请求转换为应用OTA 固件第一。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + */ public void requestToApplyOtaFirst(Device device) { List profiles = this.profileService.findAllByDevice(device, false, true, false); if (profiles != null && !profiles.isEmpty()) { @@ -166,6 +278,14 @@ public class DeviceReportService extends BaseService { } } + /** + * 更新设备配置档案状态。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 17 个条件分支、1 个循环;主要调用:find。 + * + * @param curState 参数 {@code curState}({@code DeviceProfileState}) + * @param profileReference 参数 {@code profileReference}({@code DeviceProfile}) + */ public void updateDeviceProfileState(DeviceProfileState curState, DeviceProfile profileReference) { UUID profileUuid = curState.getProfileUuid(); DeviceProfile profile = profileReference != null ? profileReference : this.profileService.find(profileUuid, true); @@ -268,6 +388,15 @@ public class DeviceReportService extends BaseService { } } + /** + * 通知更新配置档案。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:schedule、remove。 + * + * @param device 设备({@code Device}) + * @param profile 设备配置档案({@code DeviceProfile}) + * @param notifyAfter 参数 {@code notifyAfter}({@code int}) + */ public void notifyUpdateProfile(Device device, DeviceProfile profile, int notifyAfter) { String taskId = this.getTaskId(device.getUuid(), profile.getUuid()); if (this.profileNotifySchedules.containsKey(taskId)) { @@ -281,14 +410,37 @@ public class DeviceReportService extends BaseService { this.profileNotifySchedules.put(taskId, scheduledTask); } + /** + * 更新设备配置档案状态。 + * + * 实现要点:主要调用:new DeviceProfileState。 + * + * @param device 设备({@code Device}) + * @param profile 设备配置档案({@code DeviceProfile}) + */ public void updateDeviceProfileState(Device device, DeviceProfile profile) { this.scheduleUpdateProfileState(new DeviceProfileState(device, profile), profile); } + /** + * 更新设备配置档案状态。 + * + * 实现要点:主要调用:new DeviceProfileState。 + * + * @param report 参数 {@code report}({@code DeviceReport}) + */ public void updateDeviceProfileState(DeviceReport report) { this.scheduleUpdateProfileState(new DeviceProfileState((DeviceReport)McJsonUtils.clone(report)), (DeviceProfile)null); } + /** + * 调度更新配置档案状态。 + * + * 实现要点:主要调用:schedule、remove。 + * + * @param state 参数 {@code state}({@code DeviceProfileState}) + * @param profile 设备配置档案({@code DeviceProfile}) + */ public void scheduleUpdateProfileState(DeviceProfileState state, DeviceProfile profile) { String taskId = this.getTaskId(state.getDeviceUuid(), state.getProfileUuid()); this.cancelProfileUpdateSchedule(taskId); @@ -299,6 +451,13 @@ public class DeviceReportService extends BaseService { this.profileStateUpdateSchedules.put(taskId, scheduledTask); } + /** + * 取消配置档案更新调度。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param taskId 参数 {@code taskId}({@code String}) + */ private void cancelProfileUpdateSchedule(String taskId) { if (this.profileStateUpdateSchedules.containsKey(taskId)) { ((ScheduledFuture)this.profileStateUpdateSchedules.get(taskId)).cancel(true); @@ -306,11 +465,24 @@ public class DeviceReportService extends BaseService { } + /** + * 获取任务ID。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ private String getTaskId(UUID deviceUuid, UUID profileUuid) { - String var10000 = deviceUuid.toString(); - return var10000 + profileUuid.toString(); + return deviceUuid.toString() + profileUuid.toString(); } + /** + * 停止配置档案通知调度。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void stopProfileNotifySchedule(UUID deviceUuid) { String uuid = deviceUuid.toString(); this.profileNotifySchedules.keySet().forEach((taskId) -> { @@ -322,12 +494,32 @@ public class DeviceReportService extends BaseService { }); } + /** + * 更新配置档案状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param state 参数 {@code state}({@code String}) + */ public void updateProfileState(UUID profileUuid, UUID deviceUuid, String state) { Criteria criteria = Criteria.where("_id.profileUuid").is(profileUuid).and("_id.deviceUuid").is(deviceUuid); Update update = Update.update("state", state); this.mongoTemplate.updateFirst(Query.query(criteria), update, DeviceProfileState.class); } + /** + * 处理日志配置档案状态。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new MidmLog。 + * + * @param curState 参数 {@code curState}({@code DeviceProfileState}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param profileName 参数 {@code profileName}({@code String}) + * @param applyOrder 参数 {@code applyOrder}({@code String}) + * @param isApplyFirstReport 参数 {@code isApplyFirstReport}({@code boolean}) + */ private void logProfileState(DeviceProfileState curState, UUID profileUuid, String profileName, String applyOrder, boolean isApplyFirstReport) { String log = null; if (curState.isDone()) { @@ -348,7 +540,17 @@ public class DeviceReportService extends BaseService { this.saveDocument(stateLog); } - public List find(UUID deviceUuid, String key, int limit) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @param limit 数量上限({@code int}) + * @return 设备报表列表,可能为空 + */ + public List find(UUID deviceUuid, String key, int limit) { Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid); if (!Strings.isNullOrEmpty(key)) { criteria.and(this.propertyName(key)).exists(true); @@ -359,7 +561,20 @@ public class DeviceReportService extends BaseService { return this.mongoTemplate.find(query, DeviceReport.class); } - public Page find(UUID deviceUuid, String key, Integer page, Integer size, String sortBy, String direction) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find、new PageImpl。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @return 分页结果 + */ + public Page find(UUID deviceUuid, String key, Integer page, Integer size, String sortBy, String direction) { Sort sort = Sort.by(Direction.DESC, new String[]{"reportedAt"}); Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).and(this.propertyName(key)).exists(true); Query query = Query.query(criteria).with(sort); @@ -368,6 +583,14 @@ public class DeviceReportService extends BaseService { return resultPage; } + /** + * 查找最新位置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 处理结果 + */ public DeviceReport findLatestLocation(UUID deviceUuid) { Sort sort = Sort.by(Direction.DESC, new String[]{"properties.location.time"}); Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid).and(this.propertyName("location.latitude")).exists(true); @@ -375,7 +598,17 @@ public class DeviceReportService extends BaseService { return (DeviceReport)this.mongoTemplate.findOne(query, DeviceReport.class); } - public List findByDeviceUuidAndLocationExists(UUID deviceUuid, Long from, Long to) { + /** + * 根据设备UUID并位置存在查找列出。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param from 起始时间({@code Long}) + * @param to 结束时间({@code Long}) + * @return Document列表,可能为空 + */ + public List findByDeviceUuidAndLocationExists(UUID deviceUuid, Long from, Long to) { if (from == null) { from = 0L; } @@ -391,7 +624,21 @@ public class DeviceReportService extends BaseService { return this.mongoTemplate.findDistinct(query, "properties.location", DeviceReport.class, Document.class); } - public List getDataUsage(Device device, Date from, Date to, McDateTimeUtils.FREQUENCY frequency, String networkType, TimeZone timeZone, boolean separate) { + /** + * 获取数据用量。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 7 个条件分支、0 个循环;主要调用:new Document、new SortOperation、aggregate。 + * + * @param device 设备({@code Device}) + * @param from 起始时间({@code Date}) + * @param to 结束时间({@code Date}) + * @param frequency 参数 {@code frequency}({@code McDateTimeUtils.FREQUENCY}) + * @param networkType 参数 {@code networkType}({@code String}) + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + * @param separate 参数 {@code separate}({@code boolean}) + * @return Document列表,可能为空 + */ + public List getDataUsage(Device device, Date from, Date to, McDateTimeUtils.FREQUENCY frequency, String networkType, TimeZone timeZone, boolean separate) { Document matches = new Document("deviceUuid", device.getUuid()); Document matchStage = new Document("$match", matches); AggregationOperation matchOp = Aggregations.newOperation(matchStage); @@ -441,6 +688,15 @@ public class DeviceReportService extends BaseService { return results.isEmpty() ? null : results; } + /** + * 判断是否保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:exists。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param usage 参数 {@code usage}({@code DataUsage}) + * @return 字段/派生属性 {@code save} 的值 + */ public boolean canSave(UUID deviceUuid, DataUsage usage) { if (usage.getFrom().equals(usage.getTo())) { return false; @@ -460,6 +716,14 @@ public class DeviceReportService extends BaseService { } } + /** + * 处理最新数据用量。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 处理结果 + */ private DataUsage latestDataUsage(UUID deviceUuid) { DataUsage usage; if (this.dataUsageMap.containsKey(deviceUuid)) { @@ -474,6 +738,15 @@ public class DeviceReportService extends BaseService { return usage; } + /** + * 保存数据用量。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new DataUsage、save。 + * + * @param device 设备({@code Device}) + * @param usage 参数 {@code usage}({@code DbObject}) + * @return 处理结果 + */ public DataUsage saveDataUsage(Device device, DbObject usage) { DataUsage newUsage = new DataUsage(device, usage); if (this.canSave(device.getUuid(), newUsage)) { @@ -485,6 +758,14 @@ public class DeviceReportService extends BaseService { } } + /** + * 更新数据用量。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:schedule、remove。 + * + * @param device 设备({@code Device}) + * @param to 结束时间({@code Date}) + */ public void updateDataUsage(Device device, Date to) { UUID deviceUuid = device.getUuid(); if (this.sessionManager.isOnline(deviceUuid) && !this.dataUsageSchedules.containsKey(deviceUuid)) { @@ -496,6 +777,16 @@ public class DeviceReportService extends BaseService { } } + /** + * 更新Missing数据用量。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:findOne、new DateTime。 + * + * 框架注解:{@code @Async}。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param curUsage 参数 {@code curUsage}({@code DataUsage}) + */ @Async private void updateMissingDataUsage(UUID deviceUuid, DataUsage curUsage) { DataUsage latest = this.latestDataUsage(deviceUuid); @@ -511,6 +802,15 @@ public class DeviceReportService extends BaseService { } } + /** + * 处理请求数据用量。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 6 个条件分支、2 个循环;主要调用:new DateTime。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param fromDate 参数 {@code fromDate}({@code DateTime}) + * @param toDate 参数 {@code toDate}({@code DateTime}) + */ private void requestDataUsage(UUID deviceUuid, DateTime fromDate, DateTime toDate) { DataUsage latest = this.latestDataUsage(deviceUuid); DateTime toDay = toDate == null ? LocalDate.now().toDateTimeAtStartOfDay() : toDate.withTimeAtStartOfDay(); @@ -566,6 +866,14 @@ public class DeviceReportService extends BaseService { } + /** + * 保存Document。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param state 参数 {@code state}({@code DeviceProfileState}) + * @return 处理结果 + */ public DeviceProfileState saveDocument(DeviceProfileState state) { if (state.isDone()) { state.setApplyFirstState((String)null); @@ -574,11 +882,29 @@ public class DeviceReportService extends BaseService { return (DeviceProfileState)super.saveDocument(state); } + /** + * 判断是否配置档案Applied。 + * + * 实现要点:主要调用:find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字段/派生属性 {@code profileApplied} 的值 + */ public boolean isProfileApplied(UUID deviceUuid, UUID profileUuid) { DeviceProfile deviceProfile = this.profileService.find(profileUuid, true); return this.isProfileApplied(deviceUuid, deviceProfile); } + /** + * 判断是否配置档案Applied。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 字段/派生属性 {@code profileApplied} 的值 + */ public boolean isProfileApplied(UUID deviceUuid, DeviceProfile deviceProfile) { if (deviceProfile == null) { return false; @@ -588,6 +914,15 @@ public class DeviceReportService extends BaseService { } } + /** + * 获取配置档案状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 字段/派生属性 {@code profileState} 的值 + */ public DeviceProfileState getProfileState(UUID deviceUuid, DeviceProfile deviceProfile) { if (deviceProfile == null) { return null; @@ -597,6 +932,15 @@ public class DeviceReportService extends BaseService { } } + /** + * 处理配置档案Progress转换为HTMLContent。 + * + * 实现要点:主要调用:new Context、process。 + * + * @param device 设备({@code Device}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ public String profileProgressToHtmlContent(Device device, UUID profileUuid) { DbObject progress = this.profileProgress(device, profileUuid); String progressTemplate = this.fileService.getResourceToString("help/profileProgress.html", false); @@ -605,7 +949,13 @@ public class DeviceReportService extends BaseService { return this.stringTemplateEngine.process(progressTemplate, context); } - public List profileProgress(Device device) { + /** + * 处理配置档案Progress。 + * + * @param device 设备({@code Device}) + * @return 设备配置档案列表,可能为空 + */ + public List profileProgress(Device device) { List profiles = this.profileService.findAllByDevice(device, false, false, true); profiles.forEach((profile) -> { DbObject progress = this.profileProgress(device, profile.getUuid()); @@ -614,6 +964,15 @@ public class DeviceReportService extends BaseService { return profiles; } + /** + * 处理配置档案Progress。 + * + * 实现要点:包含 14 个条件分支、2 个循环;主要调用:new DbObject、find、new Date、new Document。 + * + * @param device 设备({@code Device}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return MongoDB 文档扩展对象 + */ public DbObject profileProgress(Device device, UUID profileUuid) { DbObject progress = new DbObject(); UUID deviceUuid = device.getUuid(); @@ -706,12 +1065,26 @@ public class DeviceReportService extends BaseService { return progress; } + /** + * 重置配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + */ public void resetProfile(UUID profileUuid) { Criteria criteria = Criteria.where("_id.profileUuid").is(profileUuid); Query query = Query.query(criteria); this.mongoTemplate.remove(query, DeviceProfileState.class); } + /** + * 重置设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void resetDevice(UUID deviceUuid) { this.deleteByDeviceUuid(deviceUuid); Criteria criteria = Criteria.where("_id.deviceUuid").is(deviceUuid); @@ -719,6 +1092,13 @@ public class DeviceReportService extends BaseService { this.mongoTemplate.remove(query, DeviceProfileState.class); } + /** + * 根据设备UUID删除void。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:bulkOps、remove、execute。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void deleteByDeviceUuid(UUID deviceUuid) { Criteria criteria = Criteria.where("deviceUuid").is(deviceUuid); Query query = Query.query(criteria); @@ -727,25 +1107,59 @@ public class DeviceReportService extends BaseService { bulkOp.execute(); } + /** + * 处理状态查询。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profile 设备配置档案({@code DeviceProfile}) + * @return 处理结果 + */ private Query stateQuery(UUID deviceUuid, DeviceProfile profile) { long updated = profile.getUpdated().getTime(); Criteria criteria = Criteria.where("_id.profileUuid").is(profile.getUuid()).and("_id.deviceUuid").is(deviceUuid).orOperator(new Criteria[]{Criteria.where("updated").is(updated), Criteria.where("updated").is(updated - 1L)}); return Query.query(criteria); } + /** + * 处理property名称。 + * + * @param item 参数 {@code item}({@code String}) + * @return 字符串结果 + */ private String propertyName(String item) { return this.propertyName(item, (String)null); } + /** + * 处理property名称。 + * + * @param item 参数 {@code item}({@code String}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ private String propertyName(String item, String key) { return Joiner.on('.').skipNulls().join("properties", item, new Object[]{key}); } + /** + * 处理secondsLater。 + * + * @param seconds 参数 {@code seconds}({@code int}) + * @return 处理结果 + */ private Date secondsLater(int seconds) { return DateTime.now().plusSeconds(seconds).toDate(); } - private void requestCallbackApi(UUID siteUuid, Collection reports) { + /** + * 处理请求CallbackAPI。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param reports 参数 {@code reports}({@code Collection}) + */ + private void requestCallbackApi(UUID siteUuid, Collection reports) { if (reports != null && !reports.isEmpty()) { Iterator it = reports.iterator(); @@ -764,6 +1178,14 @@ public class DeviceReportService extends BaseService { } } + /** + * 处理请求CallbackAPI。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param report 参数 {@code report}({@code DeviceReport}) + */ private void requestCallbackApi(UUID siteUuid, DeviceReport report) { if (report != null) { ExternalApiService.doRequestCallback(this.siteService.findByUuid(siteUuid), Arrays.asList(report)); diff --git a/src/main/java/com/midm/service/device/DeviceService.java b/src/main/java/com/midm/service/device/DeviceService.java index d91cabc..feaf17b 100644 --- a/src/main/java/com/midm/service/device/DeviceService.java +++ b/src/main/java/com/midm/service/device/DeviceService.java @@ -114,55 +114,153 @@ import org.thymeleaf.context.Context; @Service @EnableScheduling public class DeviceService extends BaseService { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private UserService userService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SettingsService settingsService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteService siteService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private ProfileService profileService; + /** + * 电池服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private BatteryService batteryService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private WebSocketSessionManager sessionManager; + /** + * scheduled任务服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private ScheduledTaskService scheduledTaskService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 设备许可证仓库;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceLicenseRepository deviceLicenseRepository; + /** + * 设备报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceReportService deviceReportService; + /** + * 设备应用列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceAppsService deviceAppsService; + /** + * 设备密钥服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceKeyService deviceKeyService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private EmailService emailService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; - private static Set sitesBlockAllowed = new HashSet(); - private static final Set roamingProblemClientVersions = new HashSet(Arrays.asList(240L, 241L, 1085L)); + /** + * 站点列表BlockAllowed。 + */ + private static Set sitesBlockAllowed = new HashSet(); + /** + * Long集合。 + */ + private static final Set roamingProblemClientVersions = new HashSet(Arrays.asList(240L, 241L, 1085L)); + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param device 设备({@code Device}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device save(Device device) { return this.save(device, true); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 12 个条件分支、0 个循环;主要调用:close、save。 + * + * @param device 设备({@code Device}) + * @param notify 参数 {@code notify}({@code boolean}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device save(Device device, boolean notify) { if (device != null && device.canRegister()) { if (!device.getEnabled()) { @@ -219,11 +317,25 @@ public class DeviceService extends BaseService { } } + /** + * 调度转换为更新配置档案。 + * + * @param device 设备({@code Device}) + * @param minLater 参数 {@code minLater}({@code int}) + */ public void scheduleToUpdateProfile(Device device, int minLater) { this.scheduledTaskService.scheduleToUpdateProfile(device, minLater); } - public List saveDevices(List devices) { + /** + * 保存设备列表。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 1 个条件分支、1 个循环;主要调用:new ArrayList、save。 + * + * @param devices 参数 {@code devices}({@code List}) + * @return 设备列表,可能为空 + */ + public List saveDevices(List devices) { List savedDevices = new ArrayList(); for(Device device : devices) { @@ -238,6 +350,16 @@ public class DeviceService extends BaseService { return savedDevices; } + /** + * 处理注册。 + * + * 实现要点:调用持久化方法保存数据;包含 7 个条件分支、0 个循环;主要调用:save。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param device 设备({@code Device}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device register(HttpServletRequest request, HttpServletResponse response, Device device) { if (this.isExceedDeviceLimit()) { return null; @@ -275,6 +397,14 @@ public class DeviceService extends BaseService { } } + /** + * 设置 {@code trialLicense}。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、1 个循环;主要调用:save、new DeviceLicense。 + * + * @param device 设备({@code Device}) + * @return 处理结果 + */ public DeviceLicense setTrialLicense(Device device) { if (this.hostLicenseService.isStandalone()) { return null; @@ -315,6 +445,15 @@ public class DeviceService extends BaseService { } } + /** + * 设置Trial许可证站点。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param trialLicense 参数 {@code trialLicense}({@code DeviceLicense}) + * @param site 站点/企业({@code Site}) + * @return 处理结果 + */ public DeviceLicense setTrialLicenseSite(DeviceLicense trialLicense, Site site) { if (site.isChild()) { trialLicense.setSite(site.getReseller()); @@ -327,14 +466,30 @@ public class DeviceService extends BaseService { return trialLicense; } + /** + * 获取 {@code deviceLimit}。 + * @return 数量/长度 + */ public int getDeviceLimit() { return this.hostLicenseService.getDeviceLimit(); } + /** + * 判断 {@code exceedDeviceLimit}。 + * @return 字段/派生属性 {@code exceedDeviceLimit} 的值 + */ public boolean isExceedDeviceLimit() { return this.hostLicenseService.isExceedDeviceLimit(); } + /** + * 查找UUID的设备。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device findDeviceByUuid(UUID uuid) { if (uuid == null) { return null; @@ -360,6 +515,14 @@ public class DeviceService extends BaseService { } } + /** + * 获取站点UUID。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return UUID + */ public UUID getSiteUuid(UUID deviceUuid) { if (deviceUuid == null) { return null; @@ -371,6 +534,14 @@ public class DeviceService extends BaseService { } } + /** + * 获取站点UUID。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param serialNo 设备序列号({@code String}) + * @return UUID + */ public UUID getSiteUuid(String serialNo) { if (Strings.isNullOrEmpty(serialNo)) { return null; @@ -382,16 +553,42 @@ public class DeviceService extends BaseService { } } + /** + * 查找Online设备第一。 + * + * 实现要点:通过 WebSocket 会话推送消息。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device findOnlineDeviceFirst(UUID deviceUuid) { Device device = this.sessionManager.getOnlineDevice(deviceUuid); return device != null ? device : (Device)this.findById(Device.class, deviceUuid); } - public List findDevicesBySiteUuid(UUID siteUuid) { + /** + * 查找站点UUID的设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 设备列表,可能为空 + */ + public List findDevicesBySiteUuid(UUID siteUuid) { return this.mongoTemplate.find(Query.query(Criteria.where("siteUuid").is(siteUuid)), Device.class); } - public List findDevicesOrderByExpiry(UUID siteUuid, boolean includedDisabled, int limit) { + /** + * 查找Expiry的设备列表Order。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param includedDisabled 参数 {@code includedDisabled}({@code boolean}) + * @param limit 数量上限({@code int}) + * @return 设备列表,可能为空 + */ + public List findDevicesOrderByExpiry(UUID siteUuid, boolean includedDisabled, int limit) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("states.state").ne("retired"); if (!includedDisabled) { criteria.and("enabled").is(true); @@ -401,7 +598,16 @@ public class DeviceService extends BaseService { return this.mongoTemplate.find(query, Device.class); } - public List findDevicesToApplyLicense(UUID siteUuid, boolean includedDisabled) { + /** + * 查找设备列表转换为应用许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param includedDisabled 参数 {@code includedDisabled}({@code boolean}) + * @return 设备列表,可能为空 + */ + public List findDevicesToApplyLicense(UUID siteUuid, boolean includedDisabled) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("states.state").ne("retired"); if (!includedDisabled) { criteria.and("enabled").is(true); @@ -411,14 +617,38 @@ public class DeviceService extends BaseService { return this.mongoTemplate.find(query, Device.class); } - public List findDevicesByUser(UUID userUuid) { + /** + * 查找用户的设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return 设备列表,可能为空 + */ + public List findDevicesByUser(UUID userUuid) { return this.mongoTemplate.find(Query.query(Criteria.where("owner.$id").is(userUuid)), Device.class); } + /** + * 移除所有者。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Update。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult removeOwner(UUID userUuid) { return this.mongoTemplate.updateMulti(Query.query(Criteria.where("owner.$id").is(userUuid)), (new Update()).unset("owner"), Device.class); } + /** + * 根据序列号查找设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param serialNo 设备序列号({@code String}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device findBySerialNo(String serialNo) { if (Strings.isNullOrEmpty(serialNo)) { return null; @@ -430,6 +660,15 @@ public class DeviceService extends BaseService { } } + /** + * 根据序列号查找设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device findBySerialNo(UUID siteUuid, String serialNo) { if (Strings.isNullOrEmpty(serialNo)) { return null; @@ -446,6 +685,14 @@ public class DeviceService extends BaseService { } } + /** + * 获取设备UUID。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param serialNo 设备序列号({@code String}) + * @return UUID + */ public UUID getDeviceUuid(String serialNo) { if (Strings.isNullOrEmpty(serialNo)) { return null; @@ -458,6 +705,14 @@ public class DeviceService extends BaseService { } } + /** + * 获取设备序列。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字符串结果 + */ public String getDeviceSerial(UUID deviceUuid) { if (deviceUuid == null) { return null; @@ -470,12 +725,28 @@ public class DeviceService extends BaseService { } } + /** + * 查找LastestVisit。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device findLastestVisit(UUID siteUuid) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid); Sort sort = Sort.by(Direction.DESC, new String[]{"updated"}); return (Device)this.mongoTemplate.findOne(Query.query(criteria).with(sort), Device.class); } + /** + * 处理存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(Device device) { if (device != null) { boolean exists = this.existsById(Device.class, device.getUuid()); @@ -485,6 +756,15 @@ public class DeviceService extends BaseService { } } + /** + * 处理存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(UUID siteUuid, String serialNo) { Criteria criteria = Criteria.where("profile.hardware_info.serial_no").is(serialNo); if (siteUuid != null) { @@ -494,7 +774,22 @@ public class DeviceService extends BaseService { return this.mongoTemplate.exists(Query.query(criteria), Device.class); } - public Page findDevices(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction, boolean blocked, Integer expiry) { + /** + * 查找设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含异常捕获与降级/回滚分支;包含 15 个条件分支、3 个循环;主要调用:new ArrayList、new Criteria、new Date、new DateTime、count、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param blocked 参数 {@code blocked}({@code boolean}) + * @param expiry 参数 {@code expiry}({@code Integer}) + * @return 分页结果 + */ + public Page findDevices(UUID siteUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction, boolean blocked, Integer expiry) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.hardware_info.serial_no"; direction = Direction.ASC; @@ -601,7 +896,18 @@ public class DeviceService extends BaseService { } } - public List findDevices(JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { + /** + * 查找设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:new Query、new Criteria、new Date、new DateTime、count、find。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param expiry 参数 {@code expiry}({@code Integer}) + * @return 设备列表,可能为空 + */ + public List findDevices(JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.hardware_info.serial_no"; direction = Direction.ASC; @@ -632,7 +938,16 @@ public class DeviceService extends BaseService { return result; } - public List findDevices(UUID siteUuid, String... devices) { + /** + * 查找设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:new ArrayList、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param devices 参数 {@code devices}({@code String[]}) + * @return 设备列表,可能为空 + */ + public List findDevices(UUID siteUuid, String... devices) { if (devices.length == 0) { return null; } else { @@ -665,11 +980,29 @@ public class DeviceService extends BaseService { } } - public List findDeviceByGroupUuid(UUID groupUuid) { + /** + * 查找分组UUID的设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 设备列表,可能为空 + */ + public List findDeviceByGroupUuid(UUID groupUuid) { return this.mongoTemplate.find(Query.query(Criteria.where("deviceGroup.$id").is(groupUuid)), Device.class); } - public List findDeviceByGroupUuids(UUID siteUuid, List groupUuids, String... fieldsToInclude) { + /** + * 查找分组Uuids的设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new ArrayList、new Criteria、new Query、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param groupUuids 参数 {@code groupUuids}({@code List}) + * @param fieldsToInclude 参数 {@code fieldsToInclude}({@code String[]}) + * @return 设备列表,可能为空 + */ + public List findDeviceByGroupUuids(UUID siteUuid, List groupUuids, String... fieldsToInclude) { if (groupUuids != null && !groupUuids.isEmpty()) { List groups = new ArrayList(); groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); @@ -699,7 +1032,15 @@ public class DeviceService extends BaseService { } } - public List findGroupFamily(UUID groupUuid) { + /** + * 查找分组Family。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new ArrayList、aggregate。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 设备分组列表,可能为空 + */ + public List findGroupFamily(UUID groupUuid) { List groups = new ArrayList(); Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").is(groupUuid)), Aggregation.graphLookup("deviceGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children")}); AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceGroup.class, DeviceGroup.class); @@ -717,18 +1058,43 @@ public class DeviceService extends BaseService { return groups; } - public List findGroupUUids(Collection groupUuids) { + /** + * 查找分组UUids。 + * + * 实现要点:主要调用:new ArrayList。 + * + * @param groupUuids 参数 {@code groupUuids}({@code Collection}) + * @return UUID列表,可能为空 + */ + public List findGroupUUids(Collection groupUuids) { List groups = new ArrayList(); groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); return (List)groups.stream().map((groupElement) -> groupElement.getUuid()).collect(Collectors.toList()); } - public List findChildGroups(UUID parentGroupUuid) { + /** + * 查找子分组列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param parentGroupUuid 参数 {@code parentGroupUuid}({@code UUID}) + * @return 设备分组列表,可能为空 + */ + public List findChildGroups(UUID parentGroupUuid) { Query query = Query.query(Criteria.where("parentUuid").is(parentGroupUuid)); return this.mongoTemplate.find(query, DeviceGroup.class); } - public List findAllDevicesInGroup(UUID groupUuid, JsonObject jFilter) { + /** + * 查找全部设备列表在分组。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:new JsonObject、find。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @return 设备列表,可能为空 + */ + public List findAllDevicesInGroup(UUID groupUuid, JsonObject jFilter) { String sortBy = "profile.hardware_info.serial_no"; Sort.Direction direction = Direction.ASC; if (jFilter == null) { @@ -745,10 +1111,25 @@ public class DeviceService extends BaseService { return devices; } - public List findAllDevices() { + /** + * 查找全部设备列表。 + * + * 实现要点:主要调用:findAll。 + * @return 设备列表,可能为空 + */ + public List findAllDevices() { return this.findAll(Device.class); } + /** + * 判断是否在设备分组。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param device 设备({@code Device}) + * @param groupUuid 分组 UUID({@code UUID}) + * @return 字段/派生属性 {@code inDeviceGroup} 的值 + */ public boolean isInDeviceGroup(Device device, UUID groupUuid) { if (device != null && device.getGroupUuid() != null) { if (device.getGroupUuid().equals(groupUuid)) { @@ -767,7 +1148,16 @@ public class DeviceService extends BaseService { } } - public int delete(UUID siteUuid, List deviceUuids) { + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:find、delete。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuids 设备 UUID 数组({@code List}) + * @return 数量/长度 + */ + public int delete(UUID siteUuid, List deviceUuids) { if (siteUuid != null && deviceUuids != null && !deviceUuids.isEmpty()) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids); Query query = Query.query(criteria); @@ -786,6 +1176,13 @@ public class DeviceService extends BaseService { } } + /** + * 根据站点删除void。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find、delete、remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void deleteBySite(UUID siteUuid) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid); Query query = Query.query(criteria); @@ -794,11 +1191,27 @@ public class DeviceService extends BaseService { this.mongoTemplate.remove(query, DeviceGroup.class); } + /** + * 删除设备的Notes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void deleteNotesByDevice(UUID deviceUuid) { Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); this.mongoTemplate.remove(query, DeviceNote.class); } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 7 个条件分支、0 个循环;主要调用:save、close。 + * + * @param device 设备({@code Device}) + * @param forceToRemove 参数 {@code forceToRemove}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean delete(Device device, boolean forceToRemove) { if (device != null && device.getUuid() != null) { if (!forceToRemove) { @@ -833,22 +1246,55 @@ public class DeviceService extends BaseService { } } + /** + * 删除站点UUID的设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteDeviceGroupBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.remove(query, DeviceGroup.class); } - public List findAllDeviceGroupBySiteUuid(UUID siteUuid) { + /** + * 查找站点UUID的全部设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 设备分组列表,可能为空 + */ + public List findAllDeviceGroupBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.find(query, DeviceGroup.class); } + /** + * 删除站点许可证的设备许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteLicense 参数 {@code siteLicense}({@code SiteLicense}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteDeviceLicenseBySiteLicense(SiteLicense siteLicense) { Query query = Query.query(Criteria.where("siteLicense.$id").is(siteLicense.getUuid())); return this.mongoTemplate.remove(query, DeviceLicense.class); } - public UpdateResult retire(UUID siteUuid, List deviceUuids) { + /** + * 处理retire。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:find、updateMulti、close。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuids 设备 UUID 数组({@code List}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult retire(UUID siteUuid, List deviceUuids) { if (siteUuid != null && deviceUuids != null && !deviceUuids.isEmpty()) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids).and("states.state").ne("retired"); Query query = Query.query(criteria); @@ -867,6 +1313,13 @@ public class DeviceService extends BaseService { } } + /** + * 处理retire设备许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * @param device 设备({@code Device}) + */ public void retireDeviceLicense(Device device) { DeviceLicense license = this.getTrialLicense(device); if (license != null && !license.isExpired()) { @@ -884,6 +1337,15 @@ public class DeviceService extends BaseService { this.save(device); } + /** + * 更新设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date、updateMulti。 + * + * @param device 设备({@code Device}) + * @param group 分组对象({@code DeviceGroup}) + * @return 数量/长度 + */ public long updateDeviceGroup(Device device, DeviceGroup group) { if (device != null && group != null) { if (!device.getSiteUuid().equals(group.getSiteUuid())) { @@ -899,6 +1361,14 @@ public class DeviceService extends BaseService { } } + /** + * 处理unset设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Date、updateFirst。 + * + * @param device 设备({@code Device}) + * @return 数量/长度 + */ public long unsetDeviceGroup(Device device) { if (device != null && device.getDeviceGroup() != null) { Criteria criteria = Criteria.where("_id").is(device.getUuid()); @@ -910,7 +1380,16 @@ public class DeviceService extends BaseService { } } - public long updateDeviceGroup(List devices, DeviceGroup group) { + /** + * 更新设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、2 个循环;主要调用:new ArrayList、new Criteria、new Date、new DbObject、updateMulti。 + * + * @param devices 参数 {@code devices}({@code List}) + * @param group 分组对象({@code DeviceGroup}) + * @return 数量/长度 + */ + public long updateDeviceGroup(List devices, DeviceGroup group) { if (devices != null && !devices.isEmpty()) { List criterias = new ArrayList(); @@ -943,6 +1422,16 @@ public class DeviceService extends BaseService { } } + /** + * 更新设备所有者。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new DBRef、new Update、updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param user 当前用户({@code User}) + * @param registered 参数 {@code registered}({@code boolean}) + * @return 数量/长度 + */ public long updateDeviceOwner(UUID siteUuid, User user, boolean registered) { if (siteUuid == null) { return 0L; @@ -959,7 +1448,16 @@ public class DeviceService extends BaseService { } } - public long updateDeviceOwner(List devices, User owner) { + /** + * 更新设备所有者。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、2 个循环;主要调用:new ArrayList、new Criteria、new Date、new Document、updateMulti。 + * + * @param devices 参数 {@code devices}({@code List}) + * @param owner 参数 {@code owner}({@code User}) + * @return 数量/长度 + */ + public long updateDeviceOwner(List devices, User owner) { if (devices != null && !devices.isEmpty()) { List criterias = new ArrayList(); @@ -998,12 +1496,31 @@ public class DeviceService extends BaseService { } } + /** + * 更新配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Date、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateProfile(UUID deviceUuid, String key, Object value) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); Update update = Update.update("profile." + key, value).set("updated", new Date()); return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 更新设备信息。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:new Query、new Date、new DbObject、updateFirst。 + * + * @param device 设备({@code Device}) + * @param profile 设备配置档案({@code Document}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateDeviceInfo(Device device, Document profile) { Query query = new Query(Criteria.where("_id").is(device.getUuid())); Update update = Update.update("updated", new Date()); @@ -1027,6 +1544,15 @@ public class DeviceService extends BaseService { return result; } + /** + * 更新设备状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、new Update、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param states 参数 {@code states}({@code Document}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateDeviceStatus(UUID deviceUuid, Document states) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); Update update = new Update(); @@ -1042,6 +1568,15 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 更新Online状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、new Update、new Date、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param isOnline 参数 {@code isOnline}({@code boolean}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateOnlineStatus(UUID deviceUuid, boolean isOnline) { String key = "states.isOnline"; Query query = new Query(Criteria.where("_id").is(deviceUuid).and("states.isOnline").ne(isOnline)); @@ -1055,7 +1590,17 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } - public UpdateResult updateActiveNetwork(UUID deviceUuid, String ipAddress, Map data) { + /** + * 更新Active网络。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param ipAddress 参数 {@code ipAddress}({@code String}) + * @param data 参数 {@code data}({@code Map}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult updateActiveNetwork(UUID deviceUuid, String ipAddress, Map data) { if (data != null) { if (!Strings.isNullOrEmpty(ipAddress)) { data.put("public_ip", ipAddress); @@ -1067,14 +1612,37 @@ public class DeviceService extends BaseService { } } + /** + * 更新PublicIp。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param ipAddress 参数 {@code ipAddress}({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updatePublicIp(UUID deviceUuid, String ipAddress) { return !Strings.isNullOrEmpty(ipAddress) ? this.update(deviceUuid, "profile.network.active.public_ip", ipAddress) : null; } + /** + * 更新Telephony。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param data 参数 {@code data}({@code DbObject}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateTelephony(UUID deviceUuid, DbObject data) { return data != null ? this.update(deviceUuid, "profile.network.telephony", data) : null; } + /** + * 更新Camera状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Update、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param status 状态({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateCameraStatus(UUID deviceUuid, String status) { String key = "states.camera"; Query query = new Query(Criteria.where("_id").is(deviceUuid)); @@ -1083,6 +1651,14 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 更新最后Checked在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Date、new Update、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateLastCheckedIn(UUID deviceUuid) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); Date date = new Date(); @@ -1090,6 +1666,14 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 校验许可证。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device validateLicense(Device device) { if (device != null && device.getEnabled()) { if (!this.hostLicenseService.isStandalone()) { @@ -1111,6 +1695,15 @@ public class DeviceService extends BaseService { } } + /** + * 更新设备时间Zone。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Update、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param timeZone 参数 {@code timeZone}({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateDeviceTimeZone(UUID deviceUuid, String timeZone) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); String key = "states.timeZone"; @@ -1118,6 +1711,16 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 更新Block状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Document、new Update、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param from 起始时间({@code Date}) + * @param to 结束时间({@code Date}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateBlockState(UUID deviceUuid, Date from, Date to) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); String key = "states.blocked"; @@ -1125,6 +1728,15 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, Device.class); } + /** + * 处理更新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、1 个循环;主要调用:new Query、new Date、updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param keyValue 参数 {@code keyValue}({@code Object[]}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult update(UUID deviceUuid, Object... keyValue) { if (deviceUuid != null && keyValue != null && keyValue.length != 0 && keyValue.length % 2 <= 0) { Query query = new Query(Criteria.where("_id").is(deviceUuid)); @@ -1149,6 +1761,18 @@ public class DeviceService extends BaseService { } } + /** + * 处理系统镜像Updated。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:saveDeviceLog、new Date。 + * + * @param device 设备({@code Device}) + * @param isSameSku 参数 {@code isSameSku}({@code boolean}) + * @param prevDisplayId 参数 {@code prevDisplayId}({@code String}) + * @param curDisplayId 参数 {@code curDisplayId}({@code String}) + * @param prevBuildDate 参数 {@code prevBuildDate}({@code long}) + * @param curBuildDate 参数 {@code curBuildDate}({@code long}) + */ public void systemImageUpdated(Device device, boolean isSameSku, String prevDisplayId, String curDisplayId, long prevBuildDate, long curBuildDate) { boolean isUpgraded = false; String state; @@ -1164,6 +1788,17 @@ public class DeviceService extends BaseService { this.updateProfileState(device); } + /** + * 处理区域镜像Updated。 + * + * 实现要点:主要调用:saveDeviceLog、new Date。 + * + * @param device 设备({@code Device}) + * @param prevRegionVersion 参数 {@code prevRegionVersion}({@code String}) + * @param curRegionVersion 参数 {@code curRegionVersion}({@code String}) + * @param prevScriptVersion 参数 {@code prevScriptVersion}({@code String}) + * @param curScriptVersion 参数 {@code curScriptVersion}({@code String}) + */ public void regionImageUpdated(Device device, String prevRegionVersion, String curRegionVersion, String prevScriptVersion, String curScriptVersion) { String curVersion = Strings.isNullOrEmpty(curRegionVersion) ? "" : String.format("%s(%s)", curRegionVersion, curScriptVersion); String prevVersion = Strings.isNullOrEmpty(prevRegionVersion) ? "" : String.format("%s(%s)", prevRegionVersion, prevScriptVersion); @@ -1172,6 +1807,13 @@ public class DeviceService extends BaseService { this.updateProfileState(device); } + /** + * 更新配置档案状态。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + */ private void updateProfileState(Device device) { List profiles = this.profileService.findAllByDevice(device, false, true, false); if (profiles != null && !profiles.isEmpty()) { @@ -1185,10 +1827,24 @@ public class DeviceService extends BaseService { } } + /** + * 处理blockAllowed。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean blockAllowed(UUID siteUuid) { return sitesBlockAllowed != null && sitesBlockAllowed.contains(siteUuid); } + /** + * 设置BlockAllowed。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param allowed 参数 {@code allowed}({@code boolean}) + */ public void setBlockAllowed(UUID siteUuid, boolean allowed) { if (allowed) { sitesBlockAllowed.add(siteUuid); @@ -1199,6 +1855,11 @@ public class DeviceService extends BaseService { } + /** + * 初始化设备状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;主要调用:find、updateMulti、new Update、save、new Query。 + */ public void initDeviceStatus() { Query query = Query.query(Criteria.where("settings.device.blockAllowed").is(true)); query.fields().include("_id"); @@ -1217,11 +1878,25 @@ public class DeviceService extends BaseService { this.mongoTemplate.updateMulti(new Query(), update, Device.class); } + /** + * 处理存在。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(UUID deviceUuid) { return this.existsById(Device.class, deviceUuid); } - private JsonObject groupByResultToJson(AggregationResults groupByPlatforms) { + /** + * 分组按Result转换为JSON。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new JsonObject。 + * + * @param groupByPlatforms 参数 {@code groupByPlatforms}({@code AggregationResults}) + * @return 处理结果 + */ + private JsonObject groupByResultToJson(AggregationResults groupByPlatforms) { if (groupByPlatforms != null && groupByPlatforms.getMappedResults().size() > 0) { JsonObject jPlatform = new JsonObject(); @@ -1245,19 +1920,45 @@ public class DeviceService extends BaseService { } } + /** + * 按设备分组UUID统计long数量。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 数量/长度 + */ public long countByDeviceGroupUuid(UUID groupUuid) { return this.mongoTemplate.count(Query.query(Criteria.where("deviceGroup.$id").is(groupUuid)), Device.class); } + /** + * 处理保存。 + * + * @param note 参数 {@code note}({@code DeviceNote}) + */ public void save(DeviceNote note) { this.saveDocument(note); } + /** + * 处理删除。 + * + * @param noteUuid 参数 {@code noteUuid}({@code UUID}) + */ public void delete(UUID noteUuid) { this.deleteById(DeviceNote.class, noteUuid); } - public List getRecentNotes(UUID deviceUuid) { + /** + * 获取RecentNotes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 0 个条件分支、1 个循环;主要调用:find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 设备备注列表,可能为空 + */ + public List getRecentNotes(UUID deviceUuid) { Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); query.limit(5); query.with(Sort.by(Direction.DESC, new String[]{"registeredAt"})); @@ -1271,7 +1972,15 @@ public class DeviceService extends BaseService { return notes; } - public List getNotes(UUID deviceUuid) { + /** + * 获取Notes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 0 个条件分支、1 个循环;主要调用:find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 设备备注列表,可能为空 + */ + public List getNotes(UUID deviceUuid) { Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); query.with(Sort.by(new String[]{"registeredAt"})); List notes = this.mongoTemplate.find(query, DeviceNote.class); @@ -1284,7 +1993,17 @@ public class DeviceService extends BaseService { return notes; } - public Page getNotes(UUID deviceUuid, Integer pageNum, Integer size) { + /** + * 获取Notes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 0 个条件分支、1 个循环;主要调用:count、find、new PageImpl。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param pageNum 参数 {@code pageNum}({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字段/派生属性 {@code notes} 的值 + */ + public Page getNotes(UUID deviceUuid, Integer pageNum, Integer size) { Query query = Query.query(Criteria.where("deviceUuid").is(deviceUuid)); long total = this.mongoTemplate.count(query, DeviceNote.class); PageRequest pageRequest = PageRequest.of(pageNum, size); @@ -1301,6 +2020,14 @@ public class DeviceService extends BaseService { return new PageImpl(notes, pageRequest, total); } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param group 分组对象({@code DeviceGroup}) + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup save(DeviceGroup group) { if (group.getUuid() == null) { group.init(); @@ -1309,6 +2036,12 @@ public class DeviceService extends BaseService { return (DeviceGroup)this.saveDocument(group); } + /** + * 获取分组路径。 + * + * @param group 分组对象({@code DeviceGroup}) + * @return 字符串结果 + */ public String getGroupPath(DeviceGroup group) { List groups = this.getDeviceGroupTree(group); List names = (List)groups.stream().map((groupElement) -> groupElement.getName()).collect(Collectors.toList()); @@ -1316,10 +2049,26 @@ public class DeviceService extends BaseService { return groupPath; } + /** + * 查找设备分组。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup findDeviceGroup(UUID groupUuid) { return groupUuid == null ? null : (DeviceGroup)this.findById(DeviceGroup.class, groupUuid); } + /** + * 查找设备分组。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、1 个循环;主要调用:save、new DeviceGroup。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + * @param addIfNotExist 参数 {@code addIfNotExist}({@code boolean}) + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup findDeviceGroup(UUID siteUuid, String path, boolean addIfNotExist) { if (McStringUtils.isNullOrEmpty(path)) { return null; @@ -1345,6 +2094,15 @@ public class DeviceService extends BaseService { } } + /** + * 查找名称的设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup findDeviceGroupByName(UUID siteUuid, String name) { if (siteUuid == null) { return null; @@ -1355,6 +2113,16 @@ public class DeviceService extends BaseService { } } + /** + * 查找设备分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param parent 参数 {@code parent}({@code DeviceGroup}) + * @param childName 参数 {@code childName}({@code String}) + * @return 设备分组;未找到时返回 {@code null} + */ private DeviceGroup findDeviceGroup(UUID siteUuid, DeviceGroup parent, String childName) { if (siteUuid == null) { return null; @@ -1370,7 +2138,16 @@ public class DeviceService extends BaseService { } } - public List findAllDeviceGroups(UUID siteUuid, boolean needCount) { + /** + * 查找全部设备分组列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:find、new Criteria、aggregate、new HashMap。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param needCount 参数 {@code needCount}({@code boolean}) + * @return 设备分组列表,可能为空 + */ + public List findAllDeviceGroups(UUID siteUuid, boolean needCount) { Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); query.with(sort); @@ -1396,7 +2173,15 @@ public class DeviceService extends BaseService { return deviceGroups; } - public List getDeviceGroupTree(DeviceGroup group) { + /** + * 获取设备分组树。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new ArrayList、aggregate、new DeviceGroup。 + * + * @param group 分组对象({@code DeviceGroup}) + * @return 设备分组列表,可能为空 + */ + public List getDeviceGroupTree(DeviceGroup group) { List groups = new ArrayList(); if (group == null) { return groups; @@ -1416,11 +2201,25 @@ public class DeviceService extends BaseService { } } - public Set findDevieGroupUuids(UUID... uuids) { + /** + * 查找Devie分组Uuids。 + * + * @param uuids UUID 集合({@code UUID[]}) + * @return UUID列表,可能为空 + */ + public Set findDevieGroupUuids(UUID... uuids) { return this.findDevieGroupUuids((Set)Sets.newHashSet(uuids)); } - public Set findDevieGroupUuids(Set uuids) { + /** + * 查找Devie分组Uuids。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:aggregate、new DbObject、new HashSet。 + * + * @param uuids UUID 集合({@code Set}) + * @return UUID列表,可能为空 + */ + public Set findDevieGroupUuids(Set uuids) { if (uuids != null && !uuids.isEmpty()) { Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").in(uuids)), Aggregation.graphLookup("deviceGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children"), Aggregations.newOperation("{$group: {_id: null, uuids: {$addToSet: '$_id'}, children: {$addToSet: '$children._id'}}}"), Aggregations.newOperation("{$project: {_id: 0, uuids: 1, childUuids: {$reduce: {input: '$children', initialValue: [], in: {$concatArrays: ['$$value', '$$this']}}}}}"), Aggregations.newOperation("{$project: {uuids: {$concatArrays: ['$uuids', '$childUuids']}}}")}); AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceGroup.class, Document.class); @@ -1436,10 +2235,26 @@ public class DeviceService extends BaseService { } } + /** + * 获取设备统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 数量/长度 + */ public long getDeviceCount(UUID siteUuid) { return this.mongoTemplate.count(Query.query(Criteria.where("siteUuid").is(siteUuid)), Device.class); } + /** + * 获取子设备统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:new Criteria、count。 + * + * @param site 站点/企业({@code Site}) + * @return 数量/长度 + */ public long getChildDeviceCount(Site site) { if (!site.isReseller()) { return 0L; @@ -1461,7 +2276,19 @@ public class DeviceService extends BaseService { } } - public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找用户分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -1471,6 +2298,13 @@ public class DeviceService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:delete、updateMulti、new Query、new Update。 + * + * @param group 分组对象({@code DeviceGroup}) + */ public void delete(DeviceGroup group) { if (group != null && group.getUuid() != null) { for(DeviceGroup childGroup : this.findChildGroups(group.getUuid())) { @@ -1482,6 +2316,12 @@ public class DeviceService extends BaseService { } } + /** + * 清理分组If非存在。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:findAll。 + * @return 数量/长度 + */ public int clearGroupIfNotExists() { List devices = this.findAll(Device.class); int i = 0; @@ -1495,19 +2335,48 @@ public class DeviceService extends BaseService { return i; } + /** + * 获取应用列表。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字段/派生属性 {@code apps} 的值 + */ public DeviceApps getApps(UUID deviceUuid) { return (DeviceApps)this.findById(DeviceApps.class, deviceUuid); } - public List getClients() { + /** + * 获取 {@code clients}。 + * @return 设备应用列表列表,可能为空 + */ + public List getClients() { return null; } + /** + * 判断是否Installed应用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字段/派生属性 {@code installedApp} 的值 + */ public boolean hasInstalledApp(UUID deviceUuid) { Criteria criteria = Criteria.where("_id").is(deviceUuid).and("category").is("installed"); return this.mongoTemplate.exists(Query.query(criteria), DeviceApps.class); } + /** + * 处理installed应用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Document、exists。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @return MongoDB 文档对象 + */ public Document installedApp(UUID deviceUuid, String packageName, int versionCode, String versionName) { Document document = (new Document("deviceUuid", deviceUuid)).append("packageName", packageName); Criteria criteria = Criteria.where("_id").is(deviceUuid).and("apps.packageName").is(packageName); @@ -1527,6 +2396,14 @@ public class DeviceService extends BaseService { return document; } + /** + * 处理新Client应用Installed。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean newClientAppInstalled(UUID deviceUuid) { DeviceApps apps = this.getApps(deviceUuid); if (apps == null) { @@ -1542,10 +2419,26 @@ public class DeviceService extends BaseService { } } + /** + * 设置Client版本。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param clientVersion 参数 {@code clientVersion}({@code int}) + */ public void setClientVersion(UUID deviceUuid, int clientVersion) { this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(deviceUuid)), Update.update("states.clientVersion", clientVersion), Device.class); } + /** + * 重置设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:updateFirst、new Update、delete、new McFile。 + * + * @param device 设备({@code Device}) + * @param isDelete 参数 {@code isDelete}({@code boolean}) + */ public void resetDevice(Device device, boolean isDelete) { UUID deviceUuid = device.getUuid(); if (!isDelete) { @@ -1563,15 +2456,35 @@ public class DeviceService extends BaseService { (new McFile(deviceFilePath)).delete(); } + /** + * 处理保存。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + * @return 处理结果 + */ public DeviceLicense save(DeviceLicense license) { return (DeviceLicense)this.saveDocument(license); } - public List saveDeviceLicenses(List licenses) { + /** + * 保存设备Licenses。 + * + * @param licenses 参数 {@code licenses}({@code List}) + * @return 设备许可证列表,可能为空 + */ + public List saveDeviceLicenses(List licenses) { return this.deviceLicenseRepository.saveAll(licenses); } - public List findAllLicenses(Site site) { + /** + * 查找全部Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findAll、find。 + * + * @param site 站点/企业({@code Site}) + * @return 设备许可证列表,可能为空 + */ + public List findAllLicenses(Site site) { if (site == null) { return this.findAll(DeviceLicense.class); } else { @@ -1582,7 +2495,24 @@ public class DeviceService extends BaseService { } } - public Page findLicenses(Site site, LicenseModel licenseModel, String plan, boolean licensed, JsonObject jFilter, Integer page, Integer size, String sortBy, Sort.Direction direction, Integer expiry) { + /** + * 查找Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 11 个条件分支、1 个循环;主要调用:new Query、new Date、new Criteria、new DateTime、count、find。 + * + * @param site 站点/企业({@code Site}) + * @param licenseModel 参数 {@code licenseModel}({@code LicenseModel}) + * @param plan 参数 {@code plan}({@code String}) + * @param licensed 参数 {@code licensed}({@code boolean}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param expiry 参数 {@code expiry}({@code Integer}) + * @return 分页结果 + */ + public Page findLicenses(Site site, LicenseModel licenseModel, String plan, boolean licensed, JsonObject jFilter, Integer page, Integer size, String sortBy, Sort.Direction direction, Integer expiry) { Pageable pageable = PageRequest.of(page, size); if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "expiry"; @@ -1651,7 +2581,20 @@ public class DeviceService extends BaseService { return pageResult; } - public List findLicenses(Site site, LicenseModel licenseModel, JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { + /** + * 查找Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 8 个条件分支、1 个循环;主要调用:new Query、new Date、new Criteria、new DateTime、find。 + * + * @param site 站点/企业({@code Site}) + * @param licenseModel 参数 {@code licenseModel}({@code LicenseModel}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param expiry 参数 {@code expiry}({@code Integer}) + * @return 设备许可证列表,可能为空 + */ + public List findLicenses(Site site, LicenseModel licenseModel, JsonObject filter, String sortBy, Sort.Direction direction, Integer expiry) { Query query = new Query(); if (site.isChild()) { query.addCriteria(Criteria.where("site.$id").is(site.getReseller().getUuid()).and("childSite.$id").is(site.getUuid())); @@ -1695,16 +2638,41 @@ public class DeviceService extends BaseService { return result; } - public List getLicenses(Device device) { + /** + * 获取Licenses。 + * + * @param device 设备({@code Device}) + * @return 设备许可证列表,可能为空 + */ + public List getLicenses(Device device) { return this.getLicenses(device.getSerialNo()); } - public List getLicenses(String serial) { + /** + * 获取Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param serial 参数 {@code serial}({@code String}) + * @return 设备许可证列表,可能为空 + */ + public List getLicenses(String serial) { Query query = Query.query(Criteria.where("deviceSerial").is(serial)); return this.mongoTemplate.find(query, DeviceLicense.class); } - public List getFreshLicenses(UUID siteUuid, String plan, UUID licenseModelUuid, int amount) { + /** + * 获取FreshLicenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Date、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param plan 参数 {@code plan}({@code String}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param amount 参数 {@code amount}({@code int}) + * @return 设备许可证列表,可能为空 + */ + public List getFreshLicenses(UUID siteUuid, String plan, UUID licenseModelUuid, int amount) { Query query = new Query(); query.addCriteria(Criteria.where("site.$id").is(siteUuid).and("licenseModel.$id").is(licenseModelUuid).and("plan").is(plan).and("childSite").exists(false).and("deviceUuid").exists(false).and("activatedAt").exists(false).and("expiry").gte(new Date())); query.with(Sort.by(Direction.ASC, new String[]{"created"})); @@ -1713,6 +2681,14 @@ public class DeviceService extends BaseService { return licenses; } + /** + * 获取Trial许可证。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:new DeviceLicense。 + * + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code trialLicense} 的值 + */ public DeviceLicense getTrialLicense(Device device) { if (this.hostLicenseService.isStandalone()) { return null; @@ -1742,11 +2718,27 @@ public class DeviceService extends BaseService { } } + /** + * 设置许可证。 + * + * @param device 设备({@code Device}) + * @param licenseIdName 参数 {@code licenseIdName}({@code String}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @return 处理结果 + */ public DeviceLicense setLicense(Device device, String licenseIdName, boolean autoRenew, boolean renewToSameModel) { LicenseModel model = this.licenseService.findLicenseModelByIdName(licenseIdName); return model == null ? null : this.setLicense(device, model.getUuid(), true, autoRenew, renewToSameModel); } + /** + * 过期全部PreviousLicenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Date、updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void expireAllPreviousLicenses(UUID siteUuid) { if (siteUuid != null) { Date expiry = new Date(); @@ -1757,6 +2749,14 @@ public class DeviceService extends BaseService { } } + /** + * 更新序列号。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param device 设备({@code Device}) + * @param serialNo 设备序列号({@code String}) + */ public void updateSerialNo(Device device, String serialNo) { this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(device.getUuid())), Update.update("profile.hardware_info.serial_no", serialNo), Device.class); if (!this.hostLicenseService.isStandalone()) { @@ -1765,6 +2765,18 @@ public class DeviceService extends BaseService { } + /** + * 设置许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 14 个条件分支、0 个循环;主要调用:save、addLicenseLog。 + * + * @param device 设备({@code Device}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param keepModel 参数 {@code keepModel}({@code boolean}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @return 处理结果 + */ public DeviceLicense setLicense(Device device, UUID licenseModelUuid, boolean keepModel, boolean autoRenew, boolean renewToSameModel) { DeviceLicense prevLicense = device.getLicense(); if (prevLicense != null) { @@ -1836,6 +2848,15 @@ public class DeviceService extends BaseService { } } + /** + * 处理transfer许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save、addLicenseLog。 + * + * @param device 设备({@code Device}) + * @param receiver 参数 {@code receiver}({@code Device}) + * @return 处理结果 + */ public DeviceLicense transferLicense(Device device, Device receiver) { if (device != null && receiver != null) { if (device.getUuid().equals(receiver.getUuid())) { @@ -1861,6 +2882,14 @@ public class DeviceService extends BaseService { } } + /** + * 激活许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Update、updateFirst。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + * @return 处理结果 + */ public DeviceLicense activateLicense(DeviceLicense license) { Query query = Query.query(Criteria.where("_id").is(license.getUuid())); Update update = (new Update()).inc("activationCount", 1); @@ -1877,6 +2906,14 @@ public class DeviceService extends BaseService { } } + /** + * 重置许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult resetLicense(DeviceLicense license) { license.reset(); Query query = Query.query(Criteria.where("_id").is(license.getUuid())); @@ -1884,16 +2921,39 @@ public class DeviceService extends BaseService { return this.mongoTemplate.updateFirst(query, update, DeviceLicense.class); } + /** + * 设置许可证Expiry。 + * + * @param device 设备({@code Device}) + * @param expiry 参数 {@code expiry}({@code Date}) + */ public void setLicenseExpiry(Device device, Date expiry) { this.updateLicenseExpiry(device, expiry); this.updateLicenseExpiry(device.getLicense(), expiry, (List)null); } + /** + * 更新许可证Expiry。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param device 设备({@code Device}) + * @param expiry 参数 {@code expiry}({@code Date}) + */ public void updateLicenseExpiry(Device device, Date expiry) { this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(device.getUuid())), Update.update("licenseExpiry", expiry), Device.class); } - public void updateLicenseExpiry(DeviceLicense license, Date expiry, List reactivated) { + /** + * 更新许可证Expiry。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + * @param expiry 参数 {@code expiry}({@code Date}) + * @param reactivated 参数 {@code reactivated}({@code List}) + */ + public void updateLicenseExpiry(DeviceLicense license, Date expiry, List reactivated) { Update update = Update.update("expiry", expiry); if (reactivated != null) { update.set("reactivated", reactivated); @@ -1902,6 +2962,13 @@ public class DeviceService extends BaseService { this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(license.getUuid())), update, DeviceLicense.class); } + /** + * 移除许可证。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 5 个条件分支、1 个循环;主要调用:addLicenseLog、new Date、save、close。 + * + * @param device 设备({@code Device}) + */ public void removeLicense(Device device) { if (device != null && device.hasLicense()) { DeviceLicense license = device.getLicense(); @@ -1943,6 +3010,14 @@ public class DeviceService extends BaseService { } + /** + * 重置Licenses。 + * + * 实现要点:调用持久化方法保存数据;包含 5 个条件分支、0 个循环;主要调用:save。 + * + * @param device 设备({@code Device}) + * @return 处理结果 + */ public DeviceLicense resetLicenses(Device device) { if (device == null) { return null; @@ -1979,6 +3054,14 @@ public class DeviceService extends BaseService { } } + /** + * 判断是否许可证Available。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:save。 + * + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code licenseAvailable} 的值 + */ public boolean isLicenseAvailable(Device device) { if (this.hostLicenseService.isStandalone()) { return true; @@ -1996,6 +3079,14 @@ public class DeviceService extends BaseService { } } + /** + * 处理renew许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save、addLicenseLog。 + * + * @param device 设备({@code Device}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean renewLicense(Device device) { if (device != null && device.hasLicense()) { DeviceLicense prevLicense = device.getLicense(); @@ -2026,12 +3117,29 @@ public class DeviceService extends BaseService { } } + /** + * 获取Available许可证。 + * + * @param device 设备({@code Device}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param sameModelOnly 参数 {@code sameModelOnly}({@code boolean}) + * @return 字段/派生属性 {@code availableLicense} 的值 + */ public DeviceLicense getAvailableLicense(Device device, UUID licenseModelUuid, boolean sameModelOnly) { Site site = this.siteService.findByUuid(device.getSiteUuid()); DeviceLicense license = this.getAvailableLicense(site, licenseModelUuid); return license == null && !sameModelOnly ? this.getAvailableLicense(site, (UUID)null) : license; } + /** + * 获取Available许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date、findOne。 + * + * @param site 站点/企业({@code Site}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @return 字段/派生属性 {@code availableLicense} 的值 + */ public DeviceLicense getAvailableLicense(Site site, UUID licenseModelUuid) { Criteria criteria = Criteria.where("plan").is(site.getPlanName()).and("deviceUuid").exists(false).orOperator(new Criteria[]{Criteria.where("expiry").gte(new Date()), Criteria.where("expiry").exists(false)}); if (licenseModelUuid != null) { @@ -2051,6 +3159,17 @@ public class DeviceService extends BaseService { return license; } + /** + * 添加许可证日志。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:new MidmLog、new DbObject、save。 + * + * @param license 参数 {@code license}({@code DeviceLicense}) + * @param from 起始时间({@code Device}) + * @param to 结束时间({@code Device}) + * @param activity 参数 {@code activity}({@code String}) + * @param message 消息内容({@code String}) + */ public void addLicenseLog(DeviceLicense license, Device from, Device to, String activity, String message) { MidmLog addLog = new MidmLog(); addLog.setForWhat(license.getChildSite() == null ? license.getSite().getUuid() : license.getChildSite().getUuid()); @@ -2072,6 +3191,13 @@ public class DeviceService extends BaseService { this.logService.save(addLog); } + /** + * 校验许可证任务。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;由 Spring 调度器按 cron/fixedDelay 触发;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 5 个条件分支、1 个循环;主要调用:new Date、find、new Criteria、close。 + * + * 框架注解:{@code @Scheduled(cron = "0 5 0 * * *")}、{@code @Async}。 + */ @Scheduled( cron = "0 5 0 * * *" ) @@ -2096,6 +3222,16 @@ public class DeviceService extends BaseService { } } + /** + * 获取设备统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、new Criteria、new Date、count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param field 参数 {@code field}({@code String}) + * @return 数量/长度 + */ public long getDeviceStat(UUID siteUuid, String filter, String field) { Query query = new Query(); Criteria andCriteria = new Criteria(); @@ -2123,6 +3259,16 @@ public class DeviceService extends BaseService { return total; } + /** + * 获取设备状态分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new JsonObject、new Criteria。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param field 参数 {@code field}({@code String}) + * @return 字段/派生属性 {@code deviceStateGroup} 的值 + */ public JsonObject getDeviceStateGroup(UUID siteUuid, String filter, String field) { Criteria andCriteria = null; Criteria criteria = null; @@ -2157,6 +3303,15 @@ public class DeviceService extends BaseService { return jModelType; } + /** + * 获取设备总数。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @return 数量/长度 + */ public long getDeviceTotal(UUID siteUuid, String filter) { Query query = new Query(); query.addCriteria(this.getDeviceCriteria(siteUuid, filter)); @@ -2164,16 +3319,41 @@ public class DeviceService extends BaseService { return total; } + /** + * 获取设备Criteria。 + * + * 实现要点:主要调用:new Criteria。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @return 字段/派生属性 {@code deviceCriteria} 的值 + */ public Criteria getDeviceCriteria(UUID siteUuid, String filter) { Criteria criteriaSite = Criteria.where("siteUuid").is(siteUuid); Criteria criteriaFilter = toCriteria(filter); return Strings.isNullOrEmpty(filter) ? criteriaSite : (new Criteria()).andOperator(new Criteria[]{criteriaFilter, criteriaSite}); } + /** + * 处理转换为Criteria。 + * + * 实现要点:主要调用:new Criteria。 + * + * @param jFilter 参数 {@code jFilter}({@code String}) + * @return 处理结果 + */ public static Criteria toCriteria(String jFilter) { return Strings.isNullOrEmpty(jFilter) ? new Criteria() : toCriteria(McJsonUtils.toJsonElement(jFilter).getAsJsonObject()); } + /** + * 处理转换为Criteria。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、2 个循环;主要调用:new ArrayList、new Criteria、new DateTime、new Date。 + * + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @return 处理结果 + */ public static Criteria toCriteria(JsonObject jFilter) { List criterias = new ArrayList(); @@ -2229,11 +3409,26 @@ public class DeviceService extends BaseService { return (new Criteria()).andOperator((Criteria[])criterias.toArray(new Criteria[0])); } + /** + * 分组按。 + * + * @param field 参数 {@code field}({@code String}) + * @param criteria 参数 {@code criteria}({@code Criteria}) + * @return 处理结果 + */ public JsonObject groupBy(String field, Criteria criteria) { AggregationResults groupByResult = this.groupBy("device", field, criteria); return this.groupByResultToJson(groupByResult); } + /** + * 启用设备列表按分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 2 个条件分支、1 个循环;主要调用:new Query、new Date、updateMulti、find、close。 + * + * @param filter 过滤条件({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void enableDevicesByGroup(String filter, boolean enabled) { Query query = new Query(); Criteria criteriaFilter = McMongoUtils.toCriteria(filter); @@ -2250,7 +3445,15 @@ public class DeviceService extends BaseService { } - public void enableDevices(List devices, boolean enabled) { + /** + * 启用设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 3 个条件分支、2 个循环;主要调用:new ArrayList、new Date、new Criteria、updateMulti、close。 + * + * @param devices 参数 {@code devices}({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ + public void enableDevices(List devices, boolean enabled) { List criterias = new ArrayList(); Update update = Update.update("enabled", enabled).set("updated", new Date()); int nUpdated = 0; @@ -2276,6 +3479,14 @@ public class DeviceService extends BaseService { } + /** + * 启用设备。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void enableDevice(Device device, boolean enabled) { if (enabled != device.getEnabled()) { this.enableDevice(device.getUuid(), enabled); @@ -2283,7 +3494,16 @@ public class DeviceService extends BaseService { } - public void enableDevice(UUID siteUuid, List deviceUuids, boolean enabled) { + /** + * 启用设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:updateMulti、close。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuids 设备 UUID 数组({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ + public void enableDevice(UUID siteUuid, List deviceUuids, boolean enabled) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("_id").in(deviceUuids)); Update update = Update.update("enabled", enabled); this.mongoTemplate.updateMulti(query, update, Device.class); @@ -2293,6 +3513,14 @@ public class DeviceService extends BaseService { } + /** + * 启用设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:new Date、updateFirst、close。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ public void enableDevice(UUID deviceUuid, boolean enabled) { Query query = Query.query(Criteria.where("_id").is(deviceUuid)); Update update = Update.update("enabled", enabled).set("updated", new Date()); @@ -2303,14 +3531,39 @@ public class DeviceService extends BaseService { } + /** + * 判断是否Authorized。 + * + * @param device 设备({@code Device}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字段/派生属性 {@code authorized} 的值 + */ public boolean isAuthorized(Device device, UUID siteUuid) { return device.getSiteUuid().equals(siteUuid) && this.isAuthorized(device); } + /** + * 判断是否Authorized。 + * + * 实现要点:通过 WebSocket 会话推送消息。 + * + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code authorized} 的值 + */ public boolean isAuthorized(Device device) { return device != null && device.getEnabled() && device.isEnrolled() && this.sessionManager.isOnline(device.getUuid()); } + /** + * 处理qr模板。 + * + * 实现要点:涉及邮件发送;包含异常捕获与降级/回滚分支;主要调用:encrypt、new String、new Context。 + * + * @param user 当前用户({@code User}) + * @param code 状态码/业务码({@code String}) + * @param print 参数 {@code print}({@code boolean}) + * @return 字符串结果 + */ public String qrTemplate(User user, String code, boolean print) { String src = McBase64.fromBase64ToString(code); JsonElement jParams = McJsonUtils.toJsonElement(src); @@ -2331,6 +3584,14 @@ public class DeviceService extends BaseService { } } + /** + * 处理加密。 + * + * 实现要点:主要调用:new McTextEncryptor、encrypt。 + * + * @param source 参数 {@code source}({@code String}) + * @return 字符串结果 + */ public String encrypt(String source) { String tokenPassword = "MiDM@MiTAC.com"; String tokenSalt = "597bf471358daf9c"; @@ -2338,10 +3599,24 @@ public class DeviceService extends BaseService { return encryptor.encrypt(source); } + /** + * 判断是否RoamingProblem。 + * + * @param clientVersion 参数 {@code clientVersion}({@code long}) + * @return 字段/派生属性 {@code roamingProblem} 的值 + */ public boolean hasRoamingProblem(long clientVersion) { return roamingProblemClientVersions.contains(clientVersion); } + /** + * 判断是否日期时间Problem。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param clientVersion 参数 {@code clientVersion}({@code long}) + * @return 字段/派生属性 {@code dateTimeProblem} 的值 + */ public boolean hasDateTimeProblem(long clientVersion) { if (clientVersion > 1000L) { return clientVersion >= 1087L && clientVersion <= 1090L; @@ -2350,6 +3625,13 @@ public class DeviceService extends BaseService { } } + /** + * 清理Orphans。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:aggregate、delete。 + * + * 框架注解:{@code @Async}。 + */ @Async public void clearOrphans() { LookupOperation lookupOp = Aggregation.lookup("site", "siteUuid", "_id", "site"); @@ -2364,6 +3646,21 @@ public class DeviceService extends BaseService { orphenDeviceApps.forEach((deviceApps) -> this.deviceAppsService.delete(deviceApps.getDeviceUuid())); } + /** + * 【枚举常量】{@code KEY} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public static enum KEY { device, battery_condition, @@ -2386,6 +3683,14 @@ public class DeviceService extends BaseService { normal, unknown; + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static KEY get(String key) { try { return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); diff --git a/src/main/java/com/midm/service/device/DevicesParser.java b/src/main/java/com/midm/service/device/DevicesParser.java index 893339c..e3eae8a 100644 --- a/src/main/java/com/midm/service/device/DevicesParser.java +++ b/src/main/java/com/midm/service/device/DevicesParser.java @@ -33,20 +33,88 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.bson.Document; import org.springframework.web.multipart.MultipartFile; +/** + * 【业务服务】{@code DevicesParser} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code licenseService}(LicenseService):许可证服务
  • + *
  • {@code columns}(Map):映射表
  • + *
  • {@code users}(Map):用户列表
  • + *
  • {@code deviceGroups}(Map):设备分组列表
  • + *
+ * + * 协作对象:{@code UserService、DeviceService、LicenseService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class DevicesParser { + /** + * 用户服务。 + */ private UserService userService; + /** + * 设备服务。 + */ private DeviceService deviceService; + /** + * 许可证服务。 + */ private LicenseService licenseService; - private Map columns = null; - private Map users = new HashMap(); - private Map deviceGroups = new HashMap(); - private Map licenseModels = new HashMap(); + /** + * 映射表。 + */ + private Map columns = null; + /** + * 用户列表。 + */ + private Map users = new HashMap(); + /** + * 设备分组列表。 + */ + private Map deviceGroups = new HashMap(); + /** + * 许可证Models。 + */ + private Map licenseModels = new HashMap(); + /** + * 用户所属站点 UUID。 + */ private UUID siteUuid; + /** + * 判断是否Standalone。 + */ private boolean isStandalone; - private List devices = new ArrayList(); + /** + * 设备列表。 + */ + private List devices = new ArrayList(); + /** + * 序列号ColumnIndex。 + */ private int serialNoColumnIndex = -1; + /** + * if存在选项ColumnIndex。 + */ private int ifExistsOptionColumnIndex = -1; + /** + * 构造 {@code DevicesParser} 实例。 + * + * @param isStandalone 参数 {@code isStandalone}({@code boolean}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param userService 参数 {@code userService}({@code UserService}) + * @param deviceService 参数 {@code deviceService}({@code DeviceService}) + * @param licenseService 参数 {@code licenseService}({@code LicenseService}) + */ public DevicesParser(boolean isStandalone, UUID siteUuid, UserService userService, DeviceService deviceService, LicenseService licenseService) { this.isStandalone = isStandalone; this.siteUuid = siteUuid; @@ -55,6 +123,14 @@ public class DevicesParser { this.licenseService = licenseService; } + /** + * 处理解析。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环。 + * + * @param file 文件({@code MultipartFile}) + * @return 字符串结果 + */ public String parse(MultipartFile file) { String fileType = file.getContentType(); String fileName = file.getOriginalFilename(); @@ -76,7 +152,15 @@ public class DevicesParser { } } - private List parseXls(InputStream is) { + /** + * 解析Excel。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new HSSFWorkbook、close。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return ?列表,可能为空 + */ + private List parseXls(InputStream is) { List returnValues = null; try { @@ -89,7 +173,15 @@ public class DevicesParser { return returnValues; } - private List parseXlsx(InputStream is) { + /** + * 解析Xlsx。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new XSSFWorkbook、close。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return ?列表,可能为空 + */ + private List parseXlsx(InputStream is) { List returnValues = null; try { @@ -102,7 +194,15 @@ public class DevicesParser { return returnValues; } - private List parseSheets(Iterator sheets) { + /** + * 解析Sheets。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、2 个循环;主要调用:count、new ArrayList、new MidmParseException。 + * + * @param sheets 参数 {@code sheets}({@code Iterator}) + * @return ?列表,可能为空 + */ + private List parseSheets(Iterator sheets) { long curCount = this.deviceService.count(Device.class); int limit = this.deviceService.getDeviceLimit(); List exceptions = new ArrayList(); @@ -139,6 +239,15 @@ public class DevicesParser { } } + /** + * 解析Row。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 47 个条件分支、2 个循环;主要调用:new HashMap、delete、new Device、parse、save。 + * + * @param row 参数 {@code row}({@code Row}) + * @return 匹配的设备对象;未找到时返回 {@code null} + * @throws MidmParseException 当 MidmParseException 条件不满足或底层调用失败时抛出。 + */ private Device parseRow(Row row) throws MidmParseException { Iterator cells = row.cellIterator(); String licenseType = ""; @@ -413,6 +522,14 @@ public class DevicesParser { } } + /** + * 查找用户。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param email 邮箱({@code String}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUser(String email) { if (this.users.containsKey(email)) { return (User)this.users.get(email); @@ -423,6 +540,14 @@ public class DevicesParser { } } + /** + * 查找设备分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param path 参数 {@code path}({@code String}) + * @return 设备分组;未找到时返回 {@code null} + */ public DeviceGroup findDeviceGroup(String path) { if (this.deviceGroups.containsKey(path)) { return (DeviceGroup)this.deviceGroups.get(path); @@ -433,6 +558,14 @@ public class DevicesParser { } } + /** + * 查找许可证模型。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param licenseType 参数 {@code licenseType}({@code String}) + * @return 处理结果 + */ public LicenseModel findLicenseModel(String licenseType) { if (this.licenseModels.containsKey(licenseType)) { return (LicenseModel)this.licenseModels.get(licenseType); @@ -443,13 +576,48 @@ public class DevicesParser { } } + /** + * 【业务服务】{@code MidmParseException} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ private static class MidmParseException extends Exception { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = 1L; + /** + * 构造 {@code MidmParseException} 实例。 + * + * @param code 状态码/业务码({@code int}) + * @param message 消息内容({@code String}) + */ public MidmParseException(int code, String message) { super(message); } + /** + * 处理gen异常。 + * + * 实现要点:主要调用:new MidmParseException。 + * + * @param code 状态码/业务码({@code int}) + * @param rowNum 参数 {@code rowNum}({@code int}) + * @param reason 参数 {@code reason}({@code String}) + * @return 处理结果 + */ public static MidmParseException genException(int code, int rowNum, String reason) { String message = String.format("%d: %s", rowNum, reason); return new MidmParseException(code, message); diff --git a/src/main/java/com/midm/service/device/MustProfileService.java b/src/main/java/com/midm/service/device/MustProfileService.java index 0f61192..b887211 100644 --- a/src/main/java/com/midm/service/device/MustProfileService.java +++ b/src/main/java/com/midm/service/device/MustProfileService.java @@ -13,11 +13,41 @@ import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code MustProfileService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code FileService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class MustProfileService { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 处理构建。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new JsonObject、new MustBuilder、save、new File、new McFile。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + */ public void build(DeviceProfile profile) { String root = this.fileService.getMustFolderRootPath(profile.getSiteUuid(), profile.getUuid()); JsonObject jProfile = McJsonUtils.toJsonElement(profile).getAsJsonObject(); @@ -51,6 +81,15 @@ public class MustProfileService { this.compress(profile.getUuid(), root, "region"); } + /** + * 处理compress。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile、exists、new McZipFile、delete。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param rootPath 参数 {@code rootPath}({@code String}) + * @param destPath 参数 {@code destPath}({@code String}) + */ public void compress(UUID profileUuid, String rootPath, String destPath) { McFile rootFolder = new McFile(rootPath); if (rootFolder.exists() && !rootFolder.isFile()) { @@ -63,6 +102,17 @@ public class MustProfileService { } } + /** + * 处理compressSingleFolder。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile、exists、new McZipFile、delete。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param rootPath 参数 {@code rootPath}({@code String}) + * @param filePath 参数 {@code filePath}({@code String}) + * @param destPath 参数 {@code destPath}({@code String}) + * @param folderName 参数 {@code folderName}({@code String}) + */ public void compressSingleFolder(UUID profileUuid, String rootPath, String filePath, String destPath, String folderName) { McFile rootFolder = new McFile(rootPath); McFile targetFolder = new McFile(filePath); @@ -76,6 +126,15 @@ public class MustProfileService { } } + /** + * 处理checksum列出。 + * + * 实现要点:包含 5 个条件分支、1 个循环;主要调用:new JsonArray、new McFile、exists。 + * + * @param root 参数 {@code root}({@code String}) + * @param parent 参数 {@code parent}({@code File}) + * @return 处理结果 + */ public JsonArray checksumList(String root, File parent) { JsonArray checksumList = new JsonArray(); McFile file = parent != null ? new McFile(parent) : new McFile(root); diff --git a/src/main/java/com/midm/service/device/ProfileAdvisor.java b/src/main/java/com/midm/service/device/ProfileAdvisor.java index 21d5140..5b837b9 100644 --- a/src/main/java/com/midm/service/device/ProfileAdvisor.java +++ b/src/main/java/com/midm/service/device/ProfileAdvisor.java @@ -23,15 +23,58 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code ProfileAdvisor} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code DeviceService、ProfileService、FileService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class ProfileAdvisor extends BaseService { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 处理advice。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:new HashSet、find、new Criteria。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return MongoDB 文档对象 + */ public Document advice(UUID uuid) { Set groupUuids = new HashSet(); DeviceProfile profile = this.profileService.find(uuid, false); @@ -51,7 +94,15 @@ public class ProfileAdvisor extends BaseService { return this.advice(profiles); } - public Document advice(List profiles) { + /** + * 处理advice。 + * + * 实现要点:包含 4 个条件分支、0 个循环;主要调用:new DbObject。 + * + * @param profiles 参数 {@code profiles}({@code List}) + * @return MongoDB 文档对象 + */ + public Document advice(List profiles) { DbObject conflicts = new DbObject(); Document settings = this.getConflictSettings(profiles); Document apps = this.getConflictApps(profiles); @@ -78,7 +129,15 @@ public class ProfileAdvisor extends BaseService { return conflicts; } - private Document getConflictSettings(List profiles) { + /** + * 获取Conflict设置列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、7 个循环;主要调用:new DbObject、remove。 + * + * @param profiles 参数 {@code profiles}({@code List}) + * @return MongoDB 文档对象 + */ + private Document getConflictSettings(List profiles) { if (profiles != null && profiles.size() >= 2) { DbObject configs = new DbObject(); String[] customSettingsCategories = new String[]{"system", "systemProperties", "globalSettings", "systemSettings", "secureSettings", "network"}; @@ -153,7 +212,15 @@ public class ProfileAdvisor extends BaseService { } } - private Document getConflictApps(List profiles) { + /** + * 获取Conflict应用列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 20 个条件分支、8 个循环;主要调用:new DbObject、new HashSet、new ArrayList、remove。 + * + * @param profiles 参数 {@code profiles}({@code List}) + * @return MongoDB 文档对象 + */ + private Document getConflictApps(List profiles) { if (profiles != null && profiles.size() >= 2) { DbObject apps = new DbObject(); Set installPackages = new HashSet(); @@ -324,7 +391,15 @@ public class ProfileAdvisor extends BaseService { } } - private Document getOtaAdvice(List profiles) { + /** + * 获取OTA 固件Advice。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 17 个条件分支、7 个循环;主要调用:new DbObject、new ArrayList、remove。 + * + * @param profiles 参数 {@code profiles}({@code List}) + * @return MongoDB 文档对象 + */ + private Document getOtaAdvice(List profiles) { if (profiles != null && !profiles.isEmpty()) { DbObject otas = new DbObject(); List otaFiles = new ArrayList(); @@ -451,7 +526,15 @@ public class ProfileAdvisor extends BaseService { } } - private Document getConflictFiles(List profiles) { + /** + * 获取Conflict文件列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 20 个条件分支、8 个循环;主要调用:new DbObject、new ArrayList、remove。 + * + * @param profiles 参数 {@code profiles}({@code List}) + * @return MongoDB 文档对象 + */ + private Document getConflictFiles(List profiles) { if (profiles != null && profiles.size() >= 2) { DbObject files = new DbObject(); DbObject push = new DbObject(); diff --git a/src/main/java/com/midm/service/device/ProfileService.java b/src/main/java/com/midm/service/device/ProfileService.java index dcd261e..fb9e509 100644 --- a/src/main/java/com/midm/service/device/ProfileService.java +++ b/src/main/java/com/midm/service/device/ProfileService.java @@ -73,36 +73,114 @@ import org.springframework.data.mongodb.core.query.Update; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code ProfileService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code reportService}(DeviceReportService):报表服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code sessionManager}(WebSocketSessionManager):会话Manager
  • + *
  • {@code logService}(LogService):日志服务
  • + *
+ * + * 协作对象:{@code UserService、DeviceService、DeviceReportService、FileService、WebSocketSessionManager、LogService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class ProfileService extends BaseService { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private UserService userService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceService deviceService; + /** + * 报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceReportService reportService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private WebSocketSessionManager sessionManager; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; - private Map profiles = new HashMap(); + /** + * 配置档案列表。 + */ + private Map profiles = new HashMap(); + /** + * 处理存在。 + * + * 实现要点:主要调用:exists。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(DeviceProfile profile) { return this.exists(profile.getUuid()); } + /** + * 处理存在。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(UUID profileUuid) { return this.existsById(DeviceProfile.class, profileUuid); } + /** + * 处理保存。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new SimpleDateFormat、remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile save(DeviceProfile profile) { if (profile.isGlobal()) { profile.setScope((ProfileScope)null); @@ -125,6 +203,15 @@ public class ProfileService extends BaseService { return profile; } + /** + * 处理启用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:updateFirst、remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param enable 参数 {@code enable}({@code boolean}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult enable(DeviceProfile profile, boolean enable) { if (profile == null) { return null; @@ -139,7 +226,16 @@ public class ProfileService extends BaseService { } } - public void enable(UUID siteUuid, List profileUuids, boolean enabled) { + /** + * 处理启用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find、updateMulti、remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuids 参数 {@code profileUuids}({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ + public void enable(UUID siteUuid, List profileUuids, boolean enabled) { if (siteUuid != null && profileUuids != null && !profileUuids.isEmpty()) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("_id").in(profileUuids).and("enabled").is(!enabled)); List deviceProfiles = this.mongoTemplate.find(query, DeviceProfile.class); @@ -158,6 +254,15 @@ public class ProfileService extends BaseService { } } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:findOne。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param minified 参数 {@code minified}({@code boolean}) + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile find(UUID profileUuid, boolean minified) { if (minified && this.profiles.containsKey(profileUuid)) { return ((DeviceProfile)this.profiles.get(profileUuid)).clone(); @@ -182,33 +287,80 @@ public class ProfileService extends BaseService { } } + /** + * 处理统计。 + * + * 实现要点:主要调用:count。 + * @return 数量/长度 + */ public long count() { return this.count(DeviceProfile.class); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return 设备配置档案列表,可能为空 + */ + public List findAll() { return this.findAll(DeviceProfile.class); } - public UpdateResult setSequence(List sequenceUuids) { + /** + * 设置 {@code sequence}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、updateMulti。 + * + * @param sequenceUuids 参数 {@code sequenceUuids}({@code List}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult setSequence(List sequenceUuids) { Query query = Query.query(Criteria.where("_id").in(sequenceUuids)); Update update = new Update(); update.set("sequence", sequenceUuids); return this.mongoTemplate.updateMulti(query, update, DeviceProfile.class); } + /** + * 处理unsetSequence。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst、new Update、updateMulti、new Query。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult unsetSequence(UUID uuid) { this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(uuid)), (new Update()).unset("sequence"), DeviceProfile.class); this.mongoTemplate.updateMulti(new Query(), (new Update()).pull("sequence", uuid), DeviceProfile.class); return this.mongoTemplate.updateFirst(Query.query(Criteria.where("sequence").exists(true).and("sequence.1").exists(false)), (new Update()).unset("sequence"), DeviceProfile.class); } - public UpdateResult removeSequence(List sequenceUuids) { + /** + * 移除Sequence。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Update。 + * + * @param sequenceUuids 参数 {@code sequenceUuids}({@code List}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult removeSequence(List sequenceUuids) { Query query = Query.query(Criteria.where("_id").in(sequenceUuids)); return this.mongoTemplate.updateMulti(query, (new Update()).unset("sequence"), DeviceProfile.class); } - public List findAllByDevice(Device device, boolean withRef, Boolean minified, boolean forApply) { + /** + * 查找设备的全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 19 个条件分支、5 个循环;主要调用:new ArrayList、new Criteria、find、new HashSet、remove。 + * + * @param device 设备({@code Device}) + * @param withRef 参数 {@code withRef}({@code boolean}) + * @param minified 参数 {@code minified}({@code Boolean}) + * @param forApply 参数 {@code forApply}({@code boolean}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllByDevice(Device device, boolean withRef, Boolean minified, boolean forApply) { List deviceCriteria = new ArrayList(); deviceCriteria.add(Criteria.where("isGlobal").is(true)); if (device.getSerialNo() != null) { @@ -324,7 +476,16 @@ public class ProfileService extends BaseService { } } - private void removeToBeApplied(Device device, UUID curUuid, List uuids) { + /** + * 移除转换为BeApplied。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:remove。 + * + * @param device 设备({@code Device}) + * @param curUuid 参数 {@code curUuid}({@code UUID}) + * @param uuids UUID 集合({@code List}) + */ + private void removeToBeApplied(Device device, UUID curUuid, List uuids) { Iterator it = uuids.iterator(); boolean found = false; @@ -346,6 +507,15 @@ public class ProfileService extends BaseService { } + /** + * 判断是否配置档案Applied。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code profileApplied} 的值 + */ public boolean isProfileApplied(UUID profileUuid, Device device) { DeviceProfile profile = this.find(profileUuid, true); boolean isProfileApplied = this.reportService.isProfileApplied(device.getUuid(), profile); @@ -356,7 +526,15 @@ public class ProfileService extends BaseService { } } - public List profileStatesByDevice(Device device) { + /** + * 处理配置档案States按设备。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 10 个条件分支、0 个循环;主要调用:new ArrayList、new HashSet、new MatchOperation、new AddFieldsOperation、new Document、aggregate。 + * + * @param device 设备({@code Device}) + * @return Document列表,可能为空 + */ + public List profileStatesByDevice(Device device) { UUID deviceUuid = device.getUuid(); Criteria criteria = Criteria.where("siteUuid").is(device.getSiteUuid()).and("enabled").is(true); List deviceCriteria = new ArrayList(); @@ -415,12 +593,25 @@ public class ProfileService extends BaseService { return profiles; } + /** + * 移除NonExisting文件列表。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param device 设备({@code Device}) + */ private void removeNonExistingFiles(DeviceProfile profile, Device device) { this.removeNonExistingApps(profile, device); this.removeNonExistingOtas(profile); this.removeNonExistingEtcFiles(profile); } + /** + * 移除NonExistingOtas。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + */ private void removeNonExistingOtas(DeviceProfile profile) { List otas = profile.getOtas(); if (otas != null && !otas.isEmpty()) { @@ -441,6 +632,14 @@ public class ProfileService extends BaseService { } + /** + * 移除NonExisting应用列表。 + * + * 实现要点:包含 15 个条件分支、2 个循环;主要调用:new HashMap、remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param device 设备({@code Device}) + */ private void removeNonExistingApps(DeviceProfile profile, Device device) { List installUuids = profile.getInstallUuids(); if (installUuids != null && !installUuids.isEmpty()) { @@ -515,6 +714,13 @@ public class ProfileService extends BaseService { } } + /** + * 移除NonExistingEtc文件列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 7 个条件分支、2 个循环;主要调用:remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + */ private void removeNonExistingEtcFiles(DeviceProfile profile) { DbObject files = profile.getFiles(); if (files != null) { @@ -551,7 +757,15 @@ public class ProfileService extends BaseService { } } - public List findGroupFamily(UUID groupUuid) { + /** + * 查找分组Family。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new ArrayList、aggregate。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 设备配置档案分组列表,可能为空 + */ + public List findGroupFamily(UUID groupUuid) { List groups = new ArrayList(); Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match(Criteria.where("_id").is(groupUuid)), Aggregation.graphLookup("deviceProfileGroup").startWith(new String[]{"$_id"}).connectFrom("_id").connectTo("parentUuid").as("children")}); AggregationResults results = this.mongoTemplate.aggregate(aggregation, DeviceProfileGroup.class, DeviceProfileGroup.class); @@ -566,13 +780,30 @@ public class ProfileService extends BaseService { return groups; } - public List findGroupUUids(Collection groupUuids) { + /** + * 查找分组UUids。 + * + * 实现要点:主要调用:new ArrayList。 + * + * @param groupUuids 参数 {@code groupUuids}({@code Collection}) + * @return UUID列表,可能为空 + */ + public List findGroupUUids(Collection groupUuids) { List groups = new ArrayList(); groupUuids.forEach((uuid) -> groups.addAll(this.findGroupFamily(uuid))); return (List)groups.stream().map((groupElement) -> groupElement.getUuid()).collect(Collectors.toList()); } - public List findAllWithGroupPathAndAppliedQtyBySiteUuid(UUID siteUuid, List groupUuids) { + /** + * 查找站点UUID的全部使用分组路径并AppliedQty。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Document、new ArrayList、aggregate、new Criteria。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param groupUuids 参数 {@code groupUuids}({@code List}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllWithGroupPathAndAppliedQtyBySiteUuid(UUID siteUuid, List groupUuids) { AggregationOperation profileStateLookupOp = Aggregations.newOperation("{$lookup: {from: 'deviceProfileState', let: {devices: '$devices', profileUuid:'$_id', updated: {$toLong: '$updated'}},pipeline: [{$match: {$expr: {$and: [{$eq: ['$_id.profileUuid', '$$profileUuid']}, {$eq:['$updated', '$$updated']}, {$in: ['$_id.deviceUuid', '$$devices._id']}, {$eq: ['$state', 'done']}]}}}, {$count: 'count'}],as: 'profile.appliedQty'}},"); AggregationOperation qtyFieldOp = Aggregations.newOperation("{$addFields: {'profile.deviceQty':{$size:'$devices'}, 'profile.appliedQty': {$first: '$profile.appliedQty.count'}} }}"); AggregationOperation projectHideDevicesOp = Aggregation.project(new String[0]).andExclude(new String[]{"devices"}); @@ -594,7 +825,15 @@ public class ProfileService extends BaseService { return profiles; } - public List findAllByDeviceGroup(UUID groupUuid) { + /** + * 查找设备分组的全部。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ArrayList、new JsonObject、find。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllByDeviceGroup(UUID groupUuid) { List profiles = new ArrayList(); if (groupUuid == null) { return profiles; @@ -615,6 +854,17 @@ public class ProfileService extends BaseService { } } + /** + * 根据设备并配置档案查找设备配置档案。 + * + * 实现要点:包含 7 个条件分支、0 个循环;主要调用:find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param withRef 参数 {@code withRef}({@code boolean}) + * @param minified 参数 {@code minified}({@code boolean}) + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile findByDeviceAndProfile(UUID deviceUuid, UUID profileUuid, boolean withRef, boolean minified) { DeviceProfile deviceProfile = this.find(profileUuid, minified); if (deviceUuid != null && deviceProfile != null) { @@ -649,6 +899,15 @@ public class ProfileService extends BaseService { } } + /** + * 处理excludeOrdered。 + * + * 实现要点:包含 10 个条件分支、0 个循环;主要调用:new DeviceProfileState、new Date。 + * + * @param device 设备({@code Device}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @param minified 参数 {@code minified}({@code boolean}) + */ private void excludeOrdered(Device device, DeviceProfile deviceProfile, boolean minified) { String order = deviceProfile.applyOrder(); if (!order.equals("none")) { @@ -722,6 +981,15 @@ public class ProfileService extends BaseService { } } + /** + * 判断是否全部应用列表Installed。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code allAppsInstalled} 的值 + */ public boolean isAllAppsInstalled(DeviceProfile deviceProfile, Device device) { List installAppUuids = deviceProfile.getInstallUuids(); if (installAppUuids != null && !installAppUuids.isEmpty()) { @@ -743,6 +1011,15 @@ public class ProfileService extends BaseService { } } + /** + * 判断是否全部OtasInstalled。 + * + * 实现要点:包含 8 个条件分支、1 个循环。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @param device 设备({@code Device}) + * @return 字段/派生属性 {@code allOtasInstalled} 的值 + */ public boolean isAllOtasInstalled(DeviceProfile deviceProfile, Device device) { List otas = deviceProfile.getOtas(); if (otas != null && !otas.isEmpty()) { @@ -779,6 +1056,15 @@ public class ProfileService extends BaseService { } } + /** + * 判断是否设备Scoped。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 字段/派生属性 {@code deviceScoped} 的值 + */ public boolean isDeviceScoped(Device device, DeviceProfile deviceProfile) { if (deviceProfile.getEnabled() && !deviceProfile.isEnded()) { if (deviceProfile.isGlobal()) { @@ -802,6 +1088,15 @@ public class ProfileService extends BaseService { } } + /** + * 判断是否分组Scoped。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param deviceGroup 设备分组对象({@code DeviceGroup}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 字段/派生属性 {@code groupScoped} 的值 + */ public boolean isGroupScoped(DeviceGroup deviceGroup, DeviceProfile deviceProfile) { Set groupUuids = deviceProfile.getScopedDeviceGroups(); if (groupUuids != null && !groupUuids.isEmpty()) { @@ -815,17 +1110,42 @@ public class ProfileService extends BaseService { return false; } + /** + * 根据站点UUID并配置档案名称查找设备配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileName 参数 {@code profileName}({@code String}) + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile findBySiteUuidAndProfileName(UUID siteUuid, String profileName) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("profile.name").is(profileName)); return (DeviceProfile)this.mongoTemplate.findOne(query, DeviceProfile.class); } + /** + * 查找One。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param user 当前用户({@code User}) + * @return 设备配置档案;未找到时返回 {@code null} + */ public DeviceProfile findOne(User user) { Query query = Query.query(Criteria.where("siteUuid").is(user.getSiteUuid())); return (DeviceProfile)this.mongoTemplate.findOne(query, DeviceProfile.class); } - public List findAllByApp(UUID appUuid) { + /** + * 查找应用的全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Criteria、find。 + * + * @param appUuid 参数 {@code appUuid}({@code UUID}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllByApp(UUID appUuid) { Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("apps.install").is(appUuid.toString()), Criteria.where("apps.install").is(appUuid), Criteria.where("apps.install").elemMatch(Criteria.where("uuid").is(appUuid.toString())), Criteria.where("apps.install").elemMatch(Criteria.where("uuid").is(appUuid))}); Sort sort = Sort.by(Direction.DESC, new String[]{"isGlobal"}); Query query = Query.query(criteria).with(sort); @@ -833,7 +1153,15 @@ public class ProfileService extends BaseService { return profiles; } - public List findAllByOta(UUID otaUuid) { + /** + * 查找OTA 固件的全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param otaUuid 参数 {@code otaUuid}({@code UUID}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllByOta(UUID otaUuid) { Criteria criteria = Criteria.where("otas").is(otaUuid); Sort sort = Sort.by(Direction.DESC, new String[]{"isGlobal"}); Query query = Query.query(criteria).with(sort); @@ -841,7 +1169,15 @@ public class ProfileService extends BaseService { return profiles; } - public List findAllByFile(UUID fileUuid) { + /** + * 查找文件的全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Criteria、find。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllByFile(UUID fileUuid) { String uuidString = fileUuid.toString(); Criteria criteria = new Criteria(); criteria.orOperator(new Criteria[]{Criteria.where("files.push").elemMatch(Criteria.where("sources").is(uuidString)), Criteria.where("settings.system.display.wallpaper").is(uuidString)}); @@ -851,7 +1187,19 @@ public class ProfileService extends BaseService { return profiles; } - public Page findProfiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找配置档案列表。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findProfiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -870,7 +1218,17 @@ public class ProfileService extends BaseService { return resultPage; } - public List findProfiles(JsonObject filter, String sortBy, Sort.Direction direction) { + /** + * 查找配置档案列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 设备配置档案列表,可能为空 + */ + public List findProfiles(JsonObject filter, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -880,7 +1238,20 @@ public class ProfileService extends BaseService { return profiles; } - public Page findDevices(UUID profileUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 15 个条件分支、3 个循环;主要调用:new MatchOperation、new HashSet、new ArrayList、new PageImpl、count、new Document。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findDevices(UUID profileUuid, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { DeviceProfile profile = (DeviceProfile)this.findById(DeviceProfile.class, profileUuid); if (profile == null) { return Page.empty(); @@ -994,7 +1365,18 @@ public class ProfileService extends BaseService { } } - public boolean updateScope(DeviceProfile profile, String command, Set devices, Set groups) { + /** + * 更新范围。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 9 个条件分支、0 个循环;主要调用:new Update、updateFirst、remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param command 参数 {@code command}({@code String}) + * @param devices 参数 {@code devices}({@code Set}) + * @param groups 参数 {@code groups}({@code Set}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean updateScope(DeviceProfile profile, String command, Set devices, Set groups) { Update update = new Update(); if (command.equals("add")) { if (groups != null && !groups.isEmpty()) { @@ -1036,6 +1418,14 @@ public class ProfileService extends BaseService { return updated; } + /** + * 处理unscope。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst、new Update。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param serialNo 设备序列号({@code String}) + */ public void unscope(DeviceProfile profile, String serialNo) { UUID profileUuid = profile.getUuid(); Criteria criteria = Criteria.where("_id").is(profileUuid); @@ -1043,6 +1433,13 @@ public class ProfileService extends BaseService { this.removeIfNoScope(profileUuid); } + /** + * 移除If号范围。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete、remove。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + */ private void removeIfNoScope(UUID profileUuid) { if (profileUuid != null) { DeviceProfile profile = (DeviceProfile)this.findById(DeviceProfile.class, profileUuid); @@ -1054,10 +1451,24 @@ public class ProfileService extends BaseService { } } + /** + * 处理删除。 + * + * 实现要点:主要调用:delete。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + */ public void delete(DeviceProfile profile) { this.delete(profile.getUuid()); } + /** + * 处理删除。 + * + * 实现要点:主要调用:remove。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + */ public void delete(UUID profileUuid) { this.logService.clearAllLogsFor(profileUuid); this.deleteById(DeviceProfile.class, profileUuid); @@ -1066,20 +1477,56 @@ public class ProfileService extends BaseService { this.profiles.remove(profileUuid); } + /** + * 删除配置档案的配置档案状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param profileUuid 配置档案 UUID({@code UUID}) + */ public void deleteProfileStateByProfile(UUID profileUuid) { this.mongoTemplate.remove(Query.query(Criteria.where("_id.profileUuid").is(profileUuid)), DeviceProfileState.class); } + /** + * 通知转换为同步。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param request HTTP 请求({@code String}) + * @param code 状态码/业务码({@code int}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyToSync(UUID deviceUuid, UUID profileUuid, String request, int code) { Device device = this.deviceService.findOnlineDeviceFirst(deviceUuid); return device != null && this.notifyToSync(device, profileUuid, request, code); } + /** + * 通知转换为同步。 + * + * @param serialNo 设备序列号({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param request HTTP 请求({@code String}) + * @param code 状态码/业务码({@code int}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyToSync(String serialNo, UUID profileUuid, String request, int code) { Device device = this.deviceService.findBySerialNo(serialNo); return device != null && this.notifyToSync(device, profileUuid, request, code); } + /** + * 通知转换为同步。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:new MidmQuery、new MidmPacket。 + * + * @param device 设备({@code Device}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param request HTTP 请求({@code String}) + * @param code 状态码/业务码({@code int}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyToSync(Device device, UUID profileUuid, String request, int code) { if (this.sessionManager.isOnline(device.getUuid())) { MidmQuery query = new MidmQuery(); @@ -1096,10 +1543,24 @@ public class ProfileService extends BaseService { } } + /** + * 通知更新。 + * + * @param device 设备({@code Device}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyUpdate(Device device) { return this.notifyUpdate(device.getUuid()); } + /** + * 通知更新。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:new MidmQuery、new MidmPacket。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyUpdate(UUID deviceUuid) { if (!this.sessionManager.isOnline(deviceUuid)) { return true; @@ -1115,7 +1576,15 @@ public class ProfileService extends BaseService { } } - public List getScopedDevices(DeviceProfile deviceProfile) { + /** + * 获取Scoped设备列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:new ArrayList、find。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 设备列表,可能为空 + */ + public List getScopedDevices(DeviceProfile deviceProfile) { Criteria criteria = Criteria.where("siteUuid").is(deviceProfile.getSiteUuid()).and("enabled").is(true); if (!deviceProfile.isGlobal()) { Set groupUuids = deviceProfile.getScopedDeviceGroups(); @@ -1140,6 +1609,15 @@ public class ProfileService extends BaseService { return this.mongoTemplate.find(Query.query(criteria), Device.class); } + /** + * 通知更新After。 + * + * 实现要点:主要调用:schedule、find。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param secondAfter 参数 {@code secondAfter}({@code int}) + */ public void notifyUpdateAfter(UUID deviceUuid, UUID profileUuid, int secondAfter) { Date schedule = DateTime.now().plusSeconds(secondAfter).toDate(); this.schedule(() -> { @@ -1149,6 +1627,15 @@ public class ProfileService extends BaseService { }, schedule); } + /** + * 通知更新。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param forceToUpdate 参数 {@code forceToUpdate}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyUpdate(DeviceProfile profile, boolean forceToUpdate) { if (profile != null && profile.getEnabled()) { List devices = this.getScopedDevices(profile); @@ -1168,6 +1655,17 @@ public class ProfileService extends BaseService { } } + /** + * 通知更新。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:new MidmQuery、new MidmPacket。 + * + * 框架注解:{@code @Async}。 + * + * @param device 设备({@code Device}) + * @param profile 设备配置档案({@code DeviceProfile}) + * @param forceToUpdate 参数 {@code forceToUpdate}({@code boolean}) + */ @Async public void notifyUpdate(Device device, DeviceProfile profile, boolean forceToUpdate) { if (device != null && profile != null && this.sessionManager.isOnline(device.getUuid()) && profile.getEnabled()) { @@ -1187,6 +1685,14 @@ public class ProfileService extends BaseService { } } + /** + * 通知更新全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);通过 WebSocket 会话推送消息;包含 6 个条件分支、1 个循环;主要调用:new MidmQuery、new MidmPacket、find。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean notifyUpdateAll(DeviceProfile deviceProfile) { if (deviceProfile == null) { return true; @@ -1226,6 +1732,14 @@ public class ProfileService extends BaseService { } } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param group 分组对象({@code DeviceProfileGroup}) + * @return 处理结果 + */ public DeviceProfileGroup save(DeviceProfileGroup group) { if (group.getUuid() == null) { group.init(); @@ -1234,10 +1748,24 @@ public class ProfileService extends BaseService { return (DeviceProfileGroup)this.saveDocument(group); } + /** + * 查找设备配置档案分组。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 处理结果 + */ public DeviceProfileGroup findDeviceProfileGroup(UUID groupUuid) { return groupUuid == null ? null : (DeviceProfileGroup)this.findById(DeviceProfileGroup.class, groupUuid); } + /** + * 查找设备配置档案分组。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param path 参数 {@code path}({@code String}) + * @return 处理结果 + */ public DeviceProfileGroup findDeviceProfileGroup(String path) { if (McStringUtils.isNullOrEmpty(path)) { return null; @@ -1258,18 +1786,43 @@ public class ProfileService extends BaseService { } } - public List findDeviceProfileGroupByName(String name) { + /** + * 查找名称的设备配置档案分组。 + * + * 实现要点:主要调用:find。 + * + * @param name 参数 {@code name}({@code String}) + * @return 设备配置档案分组列表,可能为空 + */ + public List findDeviceProfileGroupByName(String name) { String sortBy = "profile.name"; Sort.Direction direction = Direction.ASC; List groups = this.find(DeviceProfileGroup.class, this.getProfileFilter("name", name), "profile.name", direction); return groups; } - public List findDeviceProfileGroupByParentGroup(UUID parentGroupUuid) { + /** + * 查找父级分组的设备配置档案分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param parentGroupUuid 参数 {@code parentGroupUuid}({@code UUID}) + * @return 设备配置档案分组列表,可能为空 + */ + public List findDeviceProfileGroupByParentGroup(UUID parentGroupUuid) { Query query = Query.query(Criteria.where("parentUuid").is(parentGroupUuid)); return this.mongoTemplate.find(query, DeviceProfileGroup.class); } + /** + * 查找设备配置档案分组。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param parent 参数 {@code parent}({@code DeviceProfileGroup}) + * @param childName 参数 {@code childName}({@code String}) + * @return 处理结果 + */ private DeviceProfileGroup findDeviceProfileGroup(DeviceProfileGroup parent, String childName) { List groups = null; if (parent == null) { @@ -1287,7 +1840,15 @@ public class ProfileService extends BaseService { return null; } - public List findAllDeviceProfileGroups(UUID siteUuid) { + /** + * 查找全部设备配置档案分组列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:find、count、new Query。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 设备配置档案分组列表,可能为空 + */ + public List findAllDeviceProfileGroups(UUID siteUuid) { Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); query.with(sort); @@ -1306,11 +1867,26 @@ public class ProfileService extends BaseService { return groups; } + /** + * 获取配置档案统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 数量/长度 + */ public long getProfileCount(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.count(query, DeviceProfile.class); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:delete、updateMulti、new Query、new Update。 + * + * @param group 分组对象({@code DeviceProfileGroup}) + */ public void delete(DeviceProfileGroup group) { if (group != null && group.getUuid() != null) { for(DeviceProfileGroup childGroup : this.findDeviceProfileGroupByParentGroup(group.getUuid())) { @@ -1322,6 +1898,14 @@ public class ProfileService extends BaseService { } } + /** + * 更新Reference。 + * + * 实现要点:包含 8 个条件分支、1 个循环;主要调用:new HashMap、remove。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @param device 设备({@code Device}) + */ private void updateReference(DeviceProfile profile, Device device) { profile.initApps(); List appUuids = profile.getInstallUuids(); @@ -1389,40 +1973,88 @@ public class ProfileService extends BaseService { } + /** + * 获取分组路径。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param group 分组对象({@code DeviceProfileGroup}) + * @return 字符串结果 + */ public String getGroupPath(DeviceProfileGroup group) { String path = ""; if (group != null) { path = group.getProfile("name").toString(); if (group.getParentUuid() != null) { DeviceProfileGroup parent = (DeviceProfileGroup)this.findById(DeviceProfileGroup.class, group.getParentUuid()); - String var10000 = this.getGroupPath(parent); - path = var10000 + "/" + path; + path = this.getGroupPath(parent) + "/" + path; } } return path; } - public List findAllBySiteUuid(UUID siteUuid) { + /** + * 查找站点UUID的全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 设备配置档案列表,可能为空 + */ + public List findAllBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.find(query, DeviceProfile.class); } - public List findAllGroupBySiteUuid(UUID siteUuid) { + /** + * 查找站点UUID的全部分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 设备配置档案分组列表,可能为空 + */ + public List findAllGroupBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.find(query, DeviceProfileGroup.class); } + /** + * 删除站点UUID的配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteProfileBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.remove(query, DeviceProfile.class); } + /** + * 删除站点UUID的配置档案分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteProfileGroupBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.remove(query, DeviceProfileGroup.class); } + /** + * 获取新名称。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileName 参数 {@code profileName}({@code String}) + * @return 字符串结果 + */ public String getNewName(UUID siteUuid, String profileName) { int number = 1; @@ -1433,6 +2065,14 @@ public class ProfileService extends BaseService { return newName; } + /** + * 获取配置档案状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new Document、new ArrayList、new MatchOperation、new ProjectionOperation、aggregate。 + * + * @param profile 设备配置档案({@code DeviceProfile}) + * @return MongoDB 文档对象 + */ public Document getProfileState(DeviceProfile profile) { if (profile == null) { return null; @@ -1472,7 +2112,15 @@ public class ProfileService extends BaseService { } } - public void notifyDevicesToRemoveProfile(Collection devices, UUID profileUuid) { + /** + * 通知设备列表转换为移除配置档案。 + * + * 实现要点:包含 5 个条件分支、1 个循环。 + * + * @param devices 参数 {@code devices}({@code Collection}) + * @param profileUuid 配置档案 UUID({@code UUID}) + */ + public void notifyDevicesToRemoveProfile(Collection devices, UUID profileUuid) { if (devices != null && !devices.isEmpty() && profileUuid != null) { int code = 136; String command = "remove_profile"; diff --git a/src/main/java/com/midm/service/device/package-info.java b/src/main/java/com/midm/service/device/package-info.java new file mode 100644 index 0000000..74a0f51 --- /dev/null +++ b/src/main/java/com/midm/service/device/package-info.java @@ -0,0 +1,19 @@ +/** + * 设备全生命周期服务:注册、分组、策略、License、报表、密钥、OTA 检查。 + * + *

本包主要类型: + *

    + *
  • {@link DeviceAppsService}
  • + *
  • {@link DeviceKeyService}
  • + *
  • {@link DeviceReportService}
  • + *
  • {@link DeviceService}
  • + *
  • {@link DevicesParser}
  • + *
  • {@link MustProfileService}
  • + *
  • {@link ProfileAdvisor}
  • + *
  • {@link ProfileService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.device; diff --git a/src/main/java/com/midm/service/file/DeviceFilesService.java b/src/main/java/com/midm/service/file/DeviceFilesService.java index 39b9e5f..4fe3053 100644 --- a/src/main/java/com/midm/service/file/DeviceFilesService.java +++ b/src/main/java/com/midm/service/file/DeviceFilesService.java @@ -30,22 +30,74 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code DeviceFilesService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code newsMessageService}(NewsMessageService):新闻消息服务
  • + *
  • {@code emailService}(EmailService):邮件服务
  • + *
+ * + * 协作对象:{@code NewsMessageService、EmailService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service("deviceFileService") public class DeviceFilesService extends FileService { + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 处理保存。 + * + * @param file 文件({@code SiteFile}) + */ public void save(SiteFile file) { this.saveDocument(file); } + /** + * 查找UUID的设备文件。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 处理结果 + */ public SiteFile findDeviceFileByUuid(UUID uuid) { return (SiteFile)this.findById(SiteFile.class, uuid); } - public Page findDeviceFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找设备文件列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:count、find、new PageImpl、new ArrayList。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findDeviceFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "requested"; direction = Direction.DESC; @@ -65,11 +117,32 @@ public class DeviceFilesService extends FileService { } } + /** + * 处理删除。 + * + * 实现要点:主要调用:new McFile。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteFile 参数 {@code siteFile}({@code SiteFile}) + */ public void delete(UUID siteUuid, SiteFile siteFile) { (new McFile(this.getDeviceFilePath(siteUuid, UUID.fromString((String)siteFile.getFileInfo().get("deviceUuid")), siteFile.getFileUuid()))).delete(); this.deleteById(SiteFile.class, siteFile.getFileUuid()); } + /** + * 保存文件。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new McFile、exists、new SiteFile、new Date、new LocalDate、save。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param fileName 文件名({@code String}) + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param device 设备({@code Device}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @return 处理结果 + */ public SiteFile saveFile(UUID fileUuid, String fileName, User user, Site site, Device device, String forWhat) { try { if (fileUuid == null) { @@ -109,6 +182,14 @@ public class DeviceFilesService extends FileService { return null; } + /** + * 设置Notification。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;包含 1 个条件分支、0 个循环;主要调用:new NewsMessage、new LocalDate、save、new SimpleDateFormat。 + * + * @param siteFile 参数 {@code siteFile}({@code SiteFile}) + * @param site 站点/企业({@code Site}) + */ public void setNotification(SiteFile siteFile, Site site) { String deviceSerial = siteFile.getFileInfo().getString("deviceSerial"); String fileName = siteFile.getFileName(); diff --git a/src/main/java/com/midm/service/file/FileService.java b/src/main/java/com/midm/service/file/FileService.java index 79bacba..7c1adde 100644 --- a/src/main/java/com/midm/service/file/FileService.java +++ b/src/main/java/com/midm/service/file/FileService.java @@ -60,25 +60,92 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; +/** + * 【业务服务】{@code FileService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profileWidth}(int):配置档案Width
  • + *
  • {@code profileHeight}(int):配置档案Height
  • + *
  • {@code logoHeight}(int):字段 logoHeight
  • + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
+ * + * 协作对象:{@code ServletContext、SettingsService、ProfileService、CloudStorageService、HostLicenseService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service("fileService") public class FileService extends BaseService { + /** + * 配置档案Width。 + */ private int profileWidth = 512; + /** + * 配置档案Height。 + */ private int profileHeight = 512; + /** + * 字段 logoHeight。 + */ private int logoHeight = 72; + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired ServletContext servletContext; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy protected ProfileService profileService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; - private Map filesMap = new HashMap(); + /** + * 文件列表Map。 + */ + private Map filesMap = new HashMap(); + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 0 个条件分支、1 个循环;主要调用:save。 + * + * @param app 参数 {@code app}({@code AppFile}) + */ public void save(AppFile app) { app = (AppFile)this.saveDocument(app); this.filesMap.put(app.getFileUuid(), app); @@ -90,7 +157,17 @@ public class FileService extends BaseService { } - public boolean rename(UUID fileUuid, String name, Class entityClass) { + /** + * 处理重命名。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean rename(UUID fileUuid, String name, Class entityClass) { UpdateResult result = this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(fileUuid)), Update.update("name", name), entityClass); boolean updated = result.getModifiedCount() > 0L; if (updated) { @@ -111,7 +188,18 @@ public class FileService extends BaseService { return updated; } - public boolean nameExists(UUID siteUuid, UUID fileUuid, String name, Class entityClass) { + /** + * 处理名称存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean nameExists(UUID siteUuid, UUID fileUuid, String name, Class entityClass) { Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); if (fileUuid != null) { criteria.and("_id").ne(fileUuid); @@ -121,6 +209,15 @@ public class FileService extends BaseService { return this.mongoTemplate.exists(query, entityClass); } + /** + * 查找应用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param minify 参数 {@code minify}({@code boolean}) + * @return 应用文件元数据;未找到时返回 {@code null} + */ public AppFile findApp(UUID fileUuid, boolean minify) { if (this.filesMap.containsKey(fileUuid)) { AppFile file = (AppFile)this.filesMap.get(fileUuid); @@ -142,12 +239,31 @@ public class FileService extends BaseService { } } + /** + * 查找最新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + * @return 应用文件元数据;未找到时返回 {@code null} + */ public AppFile findLatest(UUID siteUuid, String packageName) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("appInfo.packageName").is(packageName)); query.with(Sort.by(Direction.DESC, new String[]{"appInfo.versionCode"})); return (AppFile)this.mongoTemplate.findOne(query, AppFile.class); } + /** + * 查找最新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param curVersion 参数 {@code curVersion}({@code int}) + * @return 应用文件元数据;未找到时返回 {@code null} + */ public AppFile findLatest(UUID siteUuid, String packageName, int curVersion) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid).and("appInfo.packageName").is(packageName); if (curVersion < 1000) { @@ -161,7 +277,17 @@ public class FileService extends BaseService { return (AppFile)this.mongoTemplate.findOne(query, AppFile.class); } - public Collection findApps(Collection uuids, String packageName, int minSdkVersion) { + /** + * 查找应用列表。 + * + * 实现要点:包含 5 个条件分支、0 个循环;主要调用:new ArrayList、new HashMap。 + * + * @param uuids UUID 集合({@code Collection}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @return 应用文件列表,可能为空 + */ + public Collection findApps(Collection uuids, String packageName, int minSdkVersion) { if (uuids != null && !uuids.isEmpty()) { if (minSdkVersion == Integer.MAX_VALUE) { List apps = new ArrayList(); @@ -192,7 +318,18 @@ public class FileService extends BaseService { } } - public List findApps(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + /** + * 查找应用列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 应用文件列表,可能为空 + */ + public List findApps(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid); Query query = Query.query(criteria); if (jFilter != null && jFilter.size() > 0) { @@ -208,7 +345,19 @@ public class FileService extends BaseService { return this.mongoTemplate.find(query, AppFile.class); } - public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找应用列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "name"; direction = Direction.ASC; @@ -217,6 +366,14 @@ public class FileService extends BaseService { return this.findByPage(AppFile.class, filter, sortBy, direction, page, size); } + /** + * 处理删除。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param appsArray 参数 {@code appsArray}({@code AppFile[]}) + */ public void delete(UUID siteUuid, AppFile... appsArray) { for(AppFile app : appsArray) { this.deleteApp(siteUuid, app.getFileUuid()); @@ -224,6 +381,14 @@ public class FileService extends BaseService { } + /** + * 删除应用。 + * + * 实现要点:调用持久化方法保存数据;包含 5 个条件分支、1 个循环;主要调用:remove、new McFile、exists、delete、save。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param appUuid 参数 {@code appUuid}({@code UUID}) + */ public void deleteApp(UUID siteUuid, UUID appUuid) { this.filesMap.remove(appUuid); this.deleteById(AppFile.class, appUuid); @@ -255,11 +420,24 @@ public class FileService extends BaseService { } + /** + * 处理保存。 + * + * @param otaFile 参数 {@code otaFile}({@code OtaFile}) + */ public void save(OtaFile otaFile) { otaFile = (OtaFile)this.saveDocument(otaFile); this.filesMap.put(otaFile.getFileUuid(), otaFile); } + /** + * 查找OTA 固件。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:remove。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return OTA 固件元数据;未找到时返回 {@code null} + */ public OtaFile findOta(UUID fileUuid) { OtaFile otaFile = null; if (this.filesMap.containsKey(fileUuid)) { @@ -279,12 +457,29 @@ public class FileService extends BaseService { return otaFile; } + /** + * 查找OTA 固件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param buildDate 参数 {@code buildDate}({@code long}) + * @return OTA 固件元数据;未找到时返回 {@code null} + */ public OtaFile findOta(UUID siteUuid, long buildDate) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid).and("otaInfo.buildDate").is(buildDate)); return (OtaFile)this.mongoTemplate.findOne(query, OtaFile.class); } - public List findOtas(Collection uuids) { + /** + * 查找Otas。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param uuids UUID 集合({@code Collection}) + * @return OTA 固件文件列表,可能为空 + */ + public List findOtas(Collection uuids) { if (uuids != null && !uuids.isEmpty()) { ArrayList otas = new ArrayList(); uuids.forEach((uuid) -> { @@ -300,7 +495,18 @@ public class FileService extends BaseService { } } - public List findOtas(Collection uuids, String deviceId, String skuId, String customerId) { + /** + * 查找Otas。 + * + * 实现要点:包含 5 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param uuids UUID 集合({@code Collection}) + * @param deviceId 参数 {@code deviceId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param customerId 参数 {@code customerId}({@code String}) + * @return OTA 固件文件列表,可能为空 + */ + public List findOtas(Collection uuids, String deviceId, String skuId, String customerId) { if (uuids != null && !uuids.isEmpty()) { ArrayList otas = new ArrayList(); uuids.forEach((uuid) -> { @@ -322,7 +528,18 @@ public class FileService extends BaseService { } } - public List findOtas(Collection uuids, Device device, boolean checkBuildDate, boolean partialFirst) { + /** + * 查找Otas。 + * + * 实现要点:包含 25 个条件分支、2 个循环;主要调用:new ArrayList、remove。 + * + * @param uuids UUID 集合({@code Collection}) + * @param device 设备({@code Device}) + * @param checkBuildDate 参数 {@code checkBuildDate}({@code boolean}) + * @param partialFirst 参数 {@code partialFirst}({@code boolean}) + * @return OTA 固件文件列表,可能为空 + */ + public List findOtas(Collection uuids, Device device, boolean checkBuildDate, boolean partialFirst) { if (uuids != null && !uuids.isEmpty()) { List otas = this.findOtas(uuids, device.getDeviceId(), device.getSkuId(), device.getCustomerId()); if (otas != null && !otas.isEmpty()) { @@ -447,7 +664,25 @@ public class FileService extends BaseService { } } - public OtaFile findOta(List uuids, String deviceId, String skuId, String customerId, String scriptVersion, long regionBuildDate, String fingerPrint, long buildDate, boolean partialFirst, boolean ignorePartNo, boolean checkBuildDate) { + /** + * 查找OTA 固件。 + * + * 实现要点:包含 21 个条件分支、2 个循环;主要调用:new ArrayList、remove。 + * + * @param uuids UUID 集合({@code List}) + * @param deviceId 参数 {@code deviceId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param customerId 参数 {@code customerId}({@code String}) + * @param scriptVersion 参数 {@code scriptVersion}({@code String}) + * @param regionBuildDate 参数 {@code regionBuildDate}({@code long}) + * @param fingerPrint 参数 {@code fingerPrint}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + * @param partialFirst 参数 {@code partialFirst}({@code boolean}) + * @param ignorePartNo 参数 {@code ignorePartNo}({@code boolean}) + * @param checkBuildDate 参数 {@code checkBuildDate}({@code boolean}) + * @return OTA 固件元数据;未找到时返回 {@code null} + */ + public OtaFile findOta(List uuids, String deviceId, String skuId, String customerId, String scriptVersion, long regionBuildDate, String fingerPrint, long buildDate, boolean partialFirst, boolean ignorePartNo, boolean checkBuildDate) { List partialOtas = new ArrayList(); OtaFile fullImage = null; OtaFile partialImage = null; @@ -528,7 +763,19 @@ public class FileService extends BaseService { } } - public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Otas。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "name"; direction = Direction.ASC; @@ -537,7 +784,17 @@ public class FileService extends BaseService { return this.findByPage(OtaFile.class, filter, sortBy, direction, page, size); } - public List findAvailableOtas(String productId, Long buildDate, String otaCert) { + /** + * 查找AvailableOtas。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:new Query、find。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @param otaCert 参数 {@code otaCert}({@code String}) + * @return OTA 固件文件列表,可能为空 + */ + public List findAvailableOtas(String productId, Long buildDate, String otaCert) { Query query = new Query(); if (buildDate == null) { buildDate = 0L; @@ -557,12 +814,30 @@ public class FileService extends BaseService { return result; } + /** + * 处理matchOTA 固件。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param otaCert 参数 {@code otaCert}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean matchOta(UUID fileUuid, String otaCert) { OtaFile otaFile = (OtaFile)this.findById(OtaFile.class, fileUuid); return otaFile.getOtaCertHash().equals(otaCert); } - public List findOtas(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + /** + * 查找Otas。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return OTA 固件文件列表,可能为空 + */ + public List findOtas(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid); Query query = Query.query(criteria); if (jFilter != null && jFilter.size() > 0) { @@ -577,6 +852,14 @@ public class FileService extends BaseService { return this.mongoTemplate.find(query, OtaFile.class); } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、1 个循环;主要调用:new McFile、delete、remove、save。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param otaFile 参数 {@code otaFile}({@code OtaFile}) + */ public void delete(UUID siteUuid, OtaFile otaFile) { UUID fileUuid = otaFile.getFileUuid(); this.deleteById(OtaFile.class, fileUuid); @@ -606,6 +889,14 @@ public class FileService extends BaseService { this.filesMap.remove(fileUuid); } + /** + * 查找文件。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 文件元数据;未找到时返回 {@code null} + */ public BaseFile findFile(UUID fileUuid) { if (this.filesMap.containsKey(fileUuid)) { BaseFile file = (BaseFile)this.filesMap.get(fileUuid); @@ -622,7 +913,15 @@ public class FileService extends BaseService { } } - public List findFiles(Collection uuids) { + /** + * 查找文件列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList。 + * + * @param uuids UUID 集合({@code Collection}) + * @return Base文件列表,可能为空 + */ + public List findFiles(Collection uuids) { if (uuids != null && !uuids.isEmpty()) { ArrayList files = new ArrayList(); uuids.forEach((uuid) -> { @@ -638,11 +937,26 @@ public class FileService extends BaseService { } } + /** + * 处理保存。 + * + * @param file 文件({@code BaseFile}) + */ public void save(BaseFile file) { file = (BaseFile)this.saveDocument(file); this.filesMap.put(file.getFileUuid(), file); } + /** + * 处理文件名称存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean fileNameExists(UUID fileUuid, String name, UUID siteUuid) { Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); Query query = Query.query(criteria); @@ -650,6 +964,15 @@ public class FileService extends BaseService { return file != null && !file.getFileUuid().equals(fileUuid); } + /** + * 获取文件名称。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param type 类型({@code FILE_TYPE}) + * @return 字符串结果 + */ public String getFileName(UUID fileUuid, FILE_TYPE type) { BaseFile file = (BaseFile)this.filesMap.get(fileUuid); if (file != null) { @@ -667,7 +990,18 @@ public class FileService extends BaseService { } } - public List findFiles(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { + /** + * 查找文件列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return Base文件列表,可能为空 + */ + public List findFiles(UUID siteUuid, JsonObject jFilter, String sortBy, Sort.Direction direction) { Criteria criteria = Criteria.where("siteUuid").is(siteUuid); Query query = Query.query(criteria); if (jFilter != null && jFilter.size() > 0) { @@ -682,7 +1016,19 @@ public class FileService extends BaseService { return this.mongoTemplate.find(query, BaseFile.class); } - public Page findFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找文件列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findFiles(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "name"; direction = Direction.ASC; @@ -691,6 +1037,14 @@ public class FileService extends BaseService { return this.findByPage(BaseFile.class, filter, sortBy, direction, page, size); } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;包含 11 个条件分支、3 个循环;主要调用:new McFile、delete、remove、save。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param file 文件({@code BaseFile}) + */ public void delete(UUID siteUuid, BaseFile file) { UUID fileUuid = file.getFileUuid(); this.deleteById(BaseFile.class, fileUuid); @@ -758,72 +1112,196 @@ public class FileService extends BaseService { this.filesMap.remove(fileUuid); } + /** + * 获取用户配置档案路径。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return 字符串结果 + */ public String getUserProfilePath(UUID userUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, "profile"}); } + /** + * 获取用户文件路径。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getUserFilePath(UUID userUuid, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, "other", fileUuid}); } + /** + * 获取用户文件路径。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getUserFilePath(UUID userUuid, String category, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "user", new Object[]{userUuid, category, fileUuid}); } + /** + * 获取文件路径。 + * + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getFilePath(String fileType, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), fileType, new Object[]{fileUuid}); } + /** + * 获取文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getFilePath(UUID siteUuid, String fileType, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid != null ? siteUuid : "system", new Object[]{fileType, fileUuid}); } + /** + * 获取文件路径。 + * + * @param siteUuid 站点 UUID({@code String}) + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code String}) + * @return 字符串结果 + */ public String getFilePath(String siteUuid, String fileType, String fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid != null ? siteUuid : "system", new Object[]{fileType, fileUuid}); } + /** + * 获取设备文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code Object}) + * @return 字符串结果 + */ public String getDeviceFilePath(UUID siteUuid, UUID deviceUuid, String fileType, Object fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "device", new Object[]{siteUuid, deviceUuid, fileType, fileUuid}); } + /** + * 获取设备文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code Object}) + * @return 字符串结果 + */ public String getDeviceFilePath(UUID siteUuid, UUID deviceUuid, Object fileUuid) { return this.getDeviceFilePath(siteUuid, deviceUuid, "file", fileUuid); } + /** + * 获取站点文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileType 参数 {@code fileType}({@code String}) + * @return 字符串结果 + */ public String getSiteFilePath(UUID siteUuid, String fileType) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid == null ? "unknown" : siteUuid, new Object[]{fileType}); } + /** + * 获取MustFolderRoot路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ public String getMustFolderRootPath(UUID siteUuid, UUID profileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{profileUuid}); } + /** + * 获取Must下载文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param tempPath 参数 {@code tempPath}({@code String}) + * @return 字符串结果 + */ public String getMustDownloadFilePath(UUID siteUuid, UUID profileUuid, String tempPath) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{tempPath, profileUuid}); } + /** + * 获取Must下载配置档案路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param tempPath 参数 {@code tempPath}({@code String}) + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ public String getMustDownloadProfilePath(UUID siteUuid, UUID profileUuid, String tempPath, String fileName) { return Joiner.on('/').join(this.getMustDownloadFilePath(siteUuid, profileUuid, tempPath), fileName, new Object[0]); } + /** + * 获取MustFolder文件路径。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + * @return 字符串结果 + */ public String getMustFolderFilePath(UUID siteUuid, UUID profileUuid, String path) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), siteUuid, new Object[]{profileUuid, path}); } + /** + * 获取 {@code backgroundPath}。 + * @return 字符串结果 + */ public String getBackgroundPath() { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "system", new Object[]{"background.jpg"}); } + /** + * 获取 {@code faviconPath}。 + * @return 字符串结果 + */ public String getFaviconPath() { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "system", new Object[]{"favicon.png"}); } + /** + * 获取报表模板。 + * + * 实现要点:主要调用:new McFile、exists。 + * + * @param fileName 文件名({@code String}) + * @return 字段/派生属性 {@code reportTemplate} 的值 + */ public File getReportTemplate(String fileName) { String path = Joiner.on('/').join(this.settingsService.getFilesRootPath(), "report", new Object[]{fileName}); McFile file = new McFile(path); return file.exists() ? file : this.getResourceFile("report/" + fileName, false); } + /** + * 获取配置档案镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:read。 + * + * @param file 文件({@code MultipartFile}) + * @return 字段/派生属性 {@code profileImage} 的值 + */ public BufferedImage getProfileImage(MultipartFile file) { try { BufferedImage image = ImageIO.read(file.getInputStream()); @@ -834,6 +1312,14 @@ public class FileService extends BaseService { } } + /** + * 获取Logo镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:read。 + * + * @param file 文件({@code MultipartFile}) + * @return 字段/派生属性 {@code logoImage} 的值 + */ public BufferedImage getLogoImage(MultipartFile file) { try { BufferedImage image = ImageIO.read(file.getInputStream()); @@ -847,6 +1333,14 @@ public class FileService extends BaseService { } } + /** + * 获取Bg镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:read。 + * + * @param file 文件({@code MultipartFile}) + * @return 字段/派生属性 {@code bgImage} 的值 + */ public BufferedImage getBgImage(MultipartFile file) { try { BufferedImage image = ImageIO.read(file.getInputStream()); @@ -858,6 +1352,15 @@ public class FileService extends BaseService { } } + /** + * 处理scaled镜像。 + * + * 实现要点:主要调用:new BufferedImage。 + * + * @param image 参数 {@code image}({@code BufferedImage}) + * @param scale 参数 {@code scale}({@code float}) + * @return 处理结果 + */ public BufferedImage scaledImage(BufferedImage image, float scale) { int width = (int)((float)image.getWidth() * scale); int height = (int)((float)image.getHeight() * scale); @@ -867,6 +1370,16 @@ public class FileService extends BaseService { return scaledImage; } + /** + * 生成Thumbnail。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new BufferedImage。 + * + * @param image 参数 {@code image}({@code BufferedImage}) + * @param width 参数 {@code width}({@code int}) + * @param height 参数 {@code height}({@code int}) + * @return 处理结果 + */ public BufferedImage generateThumbnail(BufferedImage image, int width, int height) { int orgWidth = image.getWidth(); int orgHeight = image.getHeight(); @@ -893,7 +1406,13 @@ public class FileService extends BaseService { return thumbnail; } - public Map sync() { + /** + * 处理同步。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new HashMap、new McFile。 + * @return 处理结果 + */ + public Map sync() { Map deleted = new HashMap(); McFile filesRoot = new McFile(this.settingsService.getFilesRootPath()); File[] rootFiles = filesRoot.listFiles(); @@ -925,6 +1444,15 @@ public class FileService extends BaseService { return deleted; } + /** + * 清理站点。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:delete、new HashMap。 + * + * @param siteFolder 参数 {@code siteFolder}({@code File}) + * @return 处理结果 + */ + @SuppressWarnings("fallthrough") private Object clearSite(File siteFolder) { UUID siteUuid = null; @@ -947,7 +1475,8 @@ public class FileService extends BaseService { while(var7 < var6) { File file = var5[var7]; - switch (file.getName()) { + String category = file.getName(); + switch (category) { default: File[] files = file.listFiles(); if (files != null && files.length > 0) { @@ -958,6 +1487,7 @@ public class FileService extends BaseService { } else { siteResults.put(category, "No category files."); } + // fall through: the default branch above and the empty cases share the ++var7 loop increment case "profile": case "logo": case "background": @@ -972,7 +1502,17 @@ public class FileService extends BaseService { } } - private Map clearSiteFiles(UUID siteUuid, String category, File[] categoryFiles) { + /** + * 清理站点文件列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、1 个循环;主要调用:new HashMap、new McFile、delete。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param categoryFiles 参数 {@code categoryFiles}({@code File[]}) + * @return 处理结果 + */ + private Map clearSiteFiles(UUID siteUuid, String category, File[] categoryFiles) { Map removed = new HashMap(); for(File file : categoryFiles) { @@ -1026,7 +1566,16 @@ public class FileService extends BaseService { return removed; } - public Map clearDeviceFiles(UUID siteUuid, File deviceFolder) { + /** + * 清理设备文件列表。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:new HashMap、delete、new McFile。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceFolder 参数 {@code deviceFolder}({@code File}) + * @return 处理结果 + */ + public Map clearDeviceFiles(UUID siteUuid, File deviceFolder) { Map removed = new HashMap(); UUID deviceUuid = UUID.fromString(deviceFolder.getName()); if (this.existsById(Device.class, deviceUuid)) { @@ -1055,6 +1604,14 @@ public class FileService extends BaseService { return removed; } + /** + * 清理用户文件列表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;由 Spring 调度器按 cron/fixedDelay 触发;包含 12 个条件分支、2 个循环;主要调用:new McFile、new HashMap、exists、delete。 + * + * 框架注解:{@code @Scheduled(cron = "0 15 0 * * *")}、{@code @Async}。 + * @return 处理结果 + */ @Scheduled( cron = "0 15 0 * * *" ) @@ -1117,6 +1674,11 @@ public class FileService extends BaseService { } } + /** + * 同步Local转换为Cloud。 + * + * 实现要点:主要调用:findAll。 + */ public void syncLocalToCloud() { List appFiles = this.findAll(AppFile.class); this.updateMetaInfo("app", appFiles); @@ -1126,7 +1688,15 @@ public class FileService extends BaseService { this.updateMetaInfo("other", otherFiles); } - public void updateMetaInfo(String category, List files) { + /** + * 更新Meta信息。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:exists、new McFile、upload。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param files 参数 {@code files}({@code List}) + */ + public void updateMetaInfo(String category, List files) { for(Object objectFile : files) { BaseFile baseFile = (BaseFile)objectFile; UUID siteUuid = baseFile.getSiteUuid(); @@ -1138,8 +1708,7 @@ public class FileService extends BaseService { if (category.equals("app")) { paths = new Object[]{siteUuid, category, fileUuid.toString() + ".png"}; if (this.cloudStorageService.exists(paths)) { - McFile var10000 = new McFile(fileName); - fileName = var10000.getNameWithoutExtension() + ".png"; + fileName = new McFile(fileName).getNameWithoutExtension() + ".png"; this.cloudStorageService.updateMetaInfo(fileName, "image/png", paths); } } @@ -1154,6 +1723,11 @@ public class FileService extends BaseService { } + /** + * 同步Cloud转换为Local。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + */ public void syncCloudToLocal() { for(Object object : this.cloudStorageService.list()) { if (object instanceof String) { @@ -1162,20 +1736,43 @@ public class FileService extends BaseService { } + /** + * 获取 {@code dateStr}。 + * @return 字符串结果 + */ public String getDateStr() { return McDateTimeUtils.toString(DateTime.now(), "yyyMMdd"); } + /** + * 获取 {@code dateTimeStr}。 + * @return 字符串结果 + */ public String getDateTimeStr() { return McDateTimeUtils.toString(DateTime.now(), "yyMMddHHmmss"); } + /** + * 获取日期时间Str。 + * + * @param offsetMins 参数 {@code offsetMins}({@code int}) + * @return 字符串结果 + */ public String getDateTimeStr(int offsetMins) { DateTime now = DateTime.now().plusMinutes(-offsetMins); return McDateTimeUtils.toString(now, "yyMMddHHmmss"); } - public int getDeviceQty(UUID groupUuid, List allDeviceGroup) { + /** + * 获取设备Qty。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @param allDeviceGroup 参数 {@code allDeviceGroup}({@code List}) + * @return 数量/长度 + */ + public int getDeviceQty(UUID groupUuid, List allDeviceGroup) { int deviceCount = 0; for(DeviceGroup singleDeviceGroup : allDeviceGroup) { @@ -1187,7 +1784,17 @@ public class FileService extends BaseService { return deviceCount; } - public List getFileList(UUID siteUuid, UUID profileUuid, String path) { + /** + * 获取文件列出。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:new ArrayList、new McFile、new HashMap。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + * @return ?列表,可能为空 + */ + public List getFileList(UUID siteUuid, UUID profileUuid, String path) { if (path.equalsIgnoreCase("root")) { path = ""; } @@ -1212,6 +1819,16 @@ public class FileService extends BaseService { return jObject; } + /** + * 添加Folder。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + * @param newFolder 参数 {@code newFolder}({@code String}) + */ public void addFolder(UUID siteUuid, UUID profileUuid, String path, String newFolder) { if (path.equalsIgnoreCase("root")) { path = ""; @@ -1221,6 +1838,15 @@ public class FileService extends BaseService { (new McFile(filePath)).mkdirs(); } + /** + * 删除文件列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + */ public void deleteFiles(UUID siteUuid, UUID profileUuid, String path) { if (path.equalsIgnoreCase("root")) { path = ""; @@ -1230,6 +1856,15 @@ public class FileService extends BaseService { (new McFile(filePath)).delete(); } + /** + * 获取Resource文件。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ClassPathResource、new McFile、getFile。 + * + * @param resourcePath 参数 {@code resourcePath}({@code String}) + * @param isStatic 参数 {@code isStatic}({@code boolean}) + * @return 字段/派生属性 {@code resourceFile} 的值 + */ public McFile getResourceFile(String resourcePath, boolean isStatic) { ClassPathResource resource = new ClassPathResource((isStatic ? "static" : "") + resourcePath); @@ -1240,11 +1875,29 @@ public class FileService extends BaseService { } } + /** + * 处理resource存在。 + * + * 实现要点:主要调用:exists。 + * + * @param resourcePath 参数 {@code resourcePath}({@code String}) + * @param isStatic 参数 {@code isStatic}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean resourceExists(String resourcePath, boolean isStatic) { ClassPathResource resource = this.classPathResource(resourcePath, isStatic); return resource.exists(); } + /** + * 获取Resource转换为String。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:exists、close。 + * + * @param resourcePath 参数 {@code resourcePath}({@code String}) + * @param isStatic 参数 {@code isStatic}({@code boolean}) + * @return 字符串结果 + */ public String getResourceToString(String resourcePath, boolean isStatic) { ClassPathResource resource = this.classPathResource(resourcePath, isStatic); @@ -1261,11 +1914,30 @@ public class FileService extends BaseService { return null; } + /** + * 处理class路径Resource。 + * + * 实现要点:主要调用:new ClassPathResource。 + * + * @param resourcePath 参数 {@code resourcePath}({@code String}) + * @param isStatic 参数 {@code isStatic}({@code boolean}) + * @return 处理结果 + */ private ClassPathResource classPathResource(String resourcePath, boolean isStatic) { return new ClassPathResource((isStatic ? "static" : "") + resourcePath); } - public UpdateResult updateExtras(Class classType, UUID uuid, Map parameterMap) { + /** + * 更新Extras。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Update、updateFirst。 + * + * @param classType 参数 {@code classType}({@code Class}) + * @param uuid 对象 UUID({@code UUID}) + * @param parameterMap 参数 {@code parameterMap}({@code Map}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult updateExtras(Class classType, UUID uuid, Map parameterMap) { Query query = Query.query(Criteria.where("_id").is(uuid)); Update update = new Update(); parameterMap.forEach((key, values) -> { @@ -1281,6 +1953,21 @@ public class FileService extends BaseService { return this.mongoTemplate.updateFirst(query, update, classType); } + /** + * 【枚举常量】{@code KEY} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public static enum KEY { serial_no, group, @@ -1331,6 +2018,14 @@ public class FileService extends BaseService { site_devices, unknown; + /** + * 处理获取。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static KEY get(String key) { try { return valueOf(CharMatcher.whitespace().removeFrom(key).toLowerCase()); diff --git a/src/main/java/com/midm/service/file/ReportService.java b/src/main/java/com/midm/service/file/ReportService.java index 562df87..7c6dcf8 100644 --- a/src/main/java/com/midm/service/file/ReportService.java +++ b/src/main/java/com/midm/service/file/ReportService.java @@ -90,37 +90,131 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code ReportService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code NONE}(String):字段 NONE
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code newsMesageSerivce}(NewsMessageService):新闻MesageSerivce
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
+ * + * 协作对象:{@code DeviceService、UserService、NewsMessageService、SiteService、SettingsService、SiteLicenseService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service("reportService") public class ReportService extends FileService { + /** + * 字段 NONE。 + */ private static final String NONE = "-"; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 新闻MesageSerivce;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMesageSerivce; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 站点许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteLicenseService siteLicenseService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; - private static final Map hashesMap = new HashMap(); + /** + * 映射表。 + */ + private static final Map hashesMap = new HashMap(); + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:save。 + * + * @param file 文件({@code SiteFile}) + */ public void save(SiteFile file) { this.mongoTemplate.save(file); } + /** + * 查找UUID的报表。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 处理结果 + */ public SiteFile findReportByUuid(UUID uuid) { return (SiteFile)this.findById(SiteFile.class, uuid); } - public Page findReports(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Reports。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:count、find、new PageImpl、new ArrayList。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findReports(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "requested"; direction = Direction.DESC; @@ -140,11 +234,26 @@ public class ReportService extends FileService { } } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove、new McFile。 + * + * @param siteReport 参数 {@code siteReport}({@code SiteFile}) + */ public void delete(SiteFile siteReport) { this.mongoTemplate.remove(siteReport); (new McFile(this.getFilePath(siteReport.getSiteUuid(), "report", siteReport.getFileUuid()))).delete(); } + /** + * 处理installed应用列表。 + * + * 实现要点:主要调用:new Document。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 文档对象 + */ public Document installedApps(UUID siteUuid) { List pipeline = Arrays.asList(new Document("$lookup", (new Document("from", "device")).append("foreignField", "_id").append("localField", "_id").append("as", "device")), new Document("$match", (new Document("device.siteUuid", siteUuid)).append("category", "installed")), new Document("$project", new Document("packages", new Document("$arrayToObject", new Document("$map", (new Document("input", "$apps")).append("as", "app").append("in", (new Document("k", "$$app.packageName")).append("v", new Document("$cond", Arrays.asList(new Document("$gt", Arrays.asList("$$app.label", null)), "$$app.label", "$$app.packageName")))))))), new Document("$group", (new Document("_id", (Object)null)).append("apps", new Document("$addToSet", "$packages"))), new Document("$replaceRoot", new Document("newRoot", new Document("$mergeObjects", "$apps")))); AggregateIterable results = this.getCollection(DeviceApps.class).aggregate(pipeline); @@ -152,14 +261,31 @@ public class ReportService extends FileService { return result == null ? new Document() : result; } - private Collection installedPackages(List deviceUuids) { + /** + * 处理installedPackages。 + * + * 实现要点:主要调用:new Document、new ArrayList。 + * + * @param deviceUuids 设备 UUID 数组({@code List}) + * @return String列表,可能为空 + */ + private Collection installedPackages(List deviceUuids) { List pipeline = Arrays.asList(new Document("$match", new Document("$and", Arrays.asList(new Document("_id", new Document("$in", deviceUuids)), new Document("category", "installed")))), new Document("$project", new Document("packages", new Document("$arrayToObject", new Document("$map", (new Document("input", "$apps")).append("as", "app").append("in", (new Document("k", "$$app.packageName")).append("v", new Document("$cond", Arrays.asList(new Document("$gt", Arrays.asList("$$app.label", null)), "$$app.label", "$$app.packageName")))))))), new Document("$group", (new Document("_id", (Object)null)).append("apps", new Document("$addToSet", "$packages"))), new Document("$replaceRoot", new Document("newRoot", new Document("$mergeObjects", "$apps")))); AggregateIterable results = this.getCollection(DeviceApps.class).aggregate(pipeline); Document result = (Document)results.first(); return (Collection)(result == null ? new ArrayList() : result.keySet()); } - private Collection getDevicesForReport(UUID siteUuid, List deviceGroups) { + /** + * 获取设备列表用于报表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 8 个条件分支、0 个循环;主要调用:new ArrayList、new Document、new SortOperation、aggregate、new HashMap。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceGroups 设备分组列表({@code List}) + * @return 设备列表,可能为空 + */ + private Collection getDevicesForReport(UUID siteUuid, List deviceGroups) { List matches = new ArrayList(); matches.add(new Document("siteUuid", siteUuid)); if (deviceGroups != null) { @@ -216,7 +342,19 @@ public class ReportService extends FileService { return devices; } - private List getDataUsages(Collection uuids, boolean wifiUsage, boolean mobileUsage, Date from, Date to) { + /** + * 获取数据Usages。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new ArrayList、new Document、new SortOperation、new ProjectionOperation、aggregate。 + * + * @param uuids UUID 集合({@code Collection}) + * @param wifiUsage 参数 {@code wifiUsage}({@code boolean}) + * @param mobileUsage 参数 {@code mobileUsage}({@code boolean}) + * @param from 起始时间({@code Date}) + * @param to 结束时间({@code Date}) + * @return 数据用量列表,可能为空 + */ + private List getDataUsages(Collection uuids, boolean wifiUsage, boolean mobileUsage, Date from, Date to) { if (!wifiUsage && !mobileUsage) { return new ArrayList(); } else { @@ -252,6 +390,19 @@ public class ReportService extends FileService { } } + /** + * 生成设备报表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;包含异常捕获与降级/回滚分支;包含 41 个条件分支、10 个循环;主要调用:exists、new ArrayList、new ExcelWriter、new XSSFRichTextString、new DateTime、new StringJoiner。 + * + * 框架注解:{@code @Async}。 + * + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @param timeOffset 参数 {@code timeOffset}({@code int}) + * @param mailMe 参数 {@code mailMe}({@code boolean}) + */ @Async public void generateDeviceReport(User user, Site site, DbObject settings, int timeOffset, boolean mailMe) { UUID fileUuid = UUID.randomUUID(); @@ -261,7 +412,8 @@ public class ReportService extends FileService { try { Collection devices = null; String scope; - switch (settings.getString("groupOption", "all")) { + String groupOption = settings.getString("groupOption", "all"); + switch (groupOption) { case "all": devices = this.getDevicesForReport(siteUuid, (List)null); scope = "All devices"; @@ -740,6 +892,17 @@ public class ReportService extends FileService { } + /** + * 设置Generic设备信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DateTime。 + * + * @param writer 参数 {@code writer}({@code ExcelWriter}) + * @param rowNum 参数 {@code rowNum}({@code int}) + * @param cellStyle 参数 {@code cellStyle}({@code CellStyle}) + * @param timeOffset 参数 {@code timeOffset}({@code int}) + * @param device 设备({@code Device}) + */ private void setGenericDeviceInfo(ExcelWriter writer, int rowNum, CellStyle cellStyle, int timeOffset, Device device) { int i = 0; writer.setCell(rowNum, i++, device.getSerialNo(), cellStyle); @@ -759,6 +922,19 @@ public class ReportService extends FileService { writer.setCell(rowNum, i++, Strings.isNullOrEmpty(deviceGroupPath) ? "-" : deviceGroupPath, cellStyle); } + /** + * 生成配置档案报表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;包含异常捕获与降级/回滚分支;包含 40 个条件分支、8 个循环;主要调用:exists、new ExcelWriter、new ArrayList、new HashSet、new HashMap、remove。 + * + * 框架注解:{@code @Async}。 + * + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @param timeOffset 参数 {@code timeOffset}({@code int}) + * @param mailMe 参数 {@code mailMe}({@code boolean}) + */ @Async public void generateProfileReport(User user, Site site, DbObject settings, int timeOffset, boolean mailMe) { String category = "profile"; @@ -1027,8 +1203,7 @@ public class ReportService extends FileService { } if (!dayList.isEmpty()) { - JsonElement var10000 = jProfileObject.get("repeatOption"); - repeatOption = var10000 + " day " + String.join(",", dayList) + " in a month"; + repeatOption = jProfileObject.get("repeatOption") + " day " + String.join(",", dayList) + " in a month"; } else { repeatOption = "Every month but not select yet"; } @@ -1079,6 +1254,20 @@ public class ReportService extends FileService { this.newsMesageSerivce.sendReportMessage(user, site, category, (SiteFile)null, false, mailMe); } + /** + * 生成站点报表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;包含异常捕获与降级/回滚分支;包含 10 个条件分支、5 个循环;主要调用:exists、new ExcelWriter、new DateTime、new ArrayList、findAll、new StringJoiner。 + * + * 框架注解:{@code @Async}。 + * + * @param user 当前用户({@code User}) + * @param userSite 参数 {@code userSite}({@code Site}) + * @param detailSite 参数 {@code detailSite}({@code Site}) + * @param timeOffset 参数 {@code timeOffset}({@code int}) + * @param itemSettings 参数 {@code itemSettings}({@code DbObject}) + * @param mailMe 参数 {@code mailMe}({@code boolean}) + */ @Async public void generateSiteReport(User user, Site userSite, Site detailSite, int timeOffset, DbObject itemSettings, boolean mailMe) { File file = this.getReportTemplate("site.general.xlsx"); @@ -1232,6 +1421,16 @@ public class ReportService extends FileService { } } + /** + * 写入许可证Sheets。 + * + * 实现要点:包含 8 个条件分支、6 个循环;主要调用:find、close、new Date。 + * + * @param writer 参数 {@code writer}({@code ExcelWriter}) + * @param site 站点/企业({@code Site}) + * @param userSite 参数 {@code userSite}({@code Site}) + * @param cellStyle 参数 {@code cellStyle}({@code CellStyle}) + */ private void writeLicenseSheets(ExcelWriter writer, Site site, Site userSite, CellStyle cellStyle) { if (writer.setActive("License orders")) { int rowNum = 13; @@ -1389,7 +1588,16 @@ public class ReportService extends FileService { } - private CloseableIterator queryLicensesFor(Site site, boolean forValid) { + /** + * 查询Licenses用于。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date、new ArrayList、new Criteria。 + * + * @param site 站点/企业({@code Site}) + * @param forValid 参数 {@code forValid}({@code boolean}) + * @return 处理结果 + */ + private CloseableIterator queryLicensesFor(Site site, boolean forValid) { Date now = new Date(); List criterias = new ArrayList(); if (site.isChild()) { @@ -1409,6 +1617,19 @@ public class ReportService extends FileService { return this.mongoTemplate.stream(query, DeviceLicense.class); } + /** + * 保存报表。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new McFile、exists、delete、new FileOutputStream、new File、write。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param user 当前用户({@code User}) + * @param writer 参数 {@code writer}({@code ExcelWriter}) + * @param siteName 参数 {@code siteName}({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param offsetMins 参数 {@code offsetMins}({@code int}) + * @return 处理结果 + */ private SiteFile saveReport(UUID fileUuid, User user, ExcelWriter writer, String siteName, String category, int offsetMins) { try { if (fileUuid == null) { @@ -1459,7 +1680,18 @@ public class ReportService extends FileService { return null; } - private void writeDeviceDistribution(ExcelWriter writer, CellStyle cellStyle, String sheetName, int headerRowIndex, Collection devices) { + /** + * 写入设备Distribution。 + * + * 实现要点:包含 5 个条件分支、2 个循环;主要调用:new HashMap、new DeviceGrouping、new ArrayList。 + * + * @param writer 参数 {@code writer}({@code ExcelWriter}) + * @param cellStyle 参数 {@code cellStyle}({@code CellStyle}) + * @param sheetName 参数 {@code sheetName}({@code String}) + * @param headerRowIndex 参数 {@code headerRowIndex}({@code int}) + * @param devices 参数 {@code devices}({@code Collection}) + */ + private void writeDeviceDistribution(ExcelWriter writer, CellStyle cellStyle, String sheetName, int headerRowIndex, Collection devices) { writer.setActive(sheetName); if (this.hostLicenseService.isStandalone()) { writer.removeColumns(6, 7); @@ -1514,10 +1746,23 @@ public class ReportService extends FileService { writer.setAutoFilter(headerRowIndex); } + /** + * 获取模板文件路径。 + * + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ public String getTemplateFilePath(String fileName) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "report", new Object[]{fileName}); } + /** + * 过期报表。 + * + * 实现要点:由 Spring 调度器按 cron/fixedDelay 触发;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:submit、new Runnable、find、new McFile、exists、delete。 + * + * 框架注解:{@code @Scheduled(cron = "0 10 0 * * *")}。 + */ @Scheduled( cron = "0 10 0 * * *" ) @@ -1549,12 +1794,52 @@ public class ReportService extends FileService { } } + /** + * 【业务服务】{@code DeviceGrouping} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code device}(Device):设备
  • + *
  • {@code hashKey}(String):哈希密钥
  • + *
  • {@code hardwareInfo}(DbObject):硬件信息
  • + *
  • {@code softwareInfo}(DbObject):软件信息
  • + *
+ * + * 协作对象:{@code Device、DbObject}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ private class DeviceGrouping { + /** + * 设备。 + */ private final Device device; + /** + * 哈希密钥。 + */ private final String hashKey; + /** + * 硬件信息。 + */ private final DbObject hardwareInfo; + /** + * 软件信息。 + */ private final DbObject softwareInfo; + /** + * 构造 {@code DeviceGrouping} 实例。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + */ protected DeviceGrouping(Device device) { this.device = device; this.hardwareInfo = device.getProfileCategory(new String[]{"hardware_info"}); @@ -1566,38 +1851,76 @@ public class ReportService extends FileService { } + /** + * 获取 {@code deviceId}。 + * @return 字符串结果 + */ protected String getDeviceId() { return this.device.isEnrolled() ? this.device.getDeviceId() : "unknown"; } + /** + * 获取 {@code productId}。 + * @return 字符串结果 + */ protected String getProductId() { return this.device.isEnrolled() ? this.hardwareInfo.getString("product_id", "-") : "-"; } + /** + * 获取 {@code productModel}。 + * @return 字符串结果 + */ protected String getProductModel() { return this.device.isEnrolled() ? this.hardwareInfo.getString("model", this.getProductId()) : "-"; } + /** + * 获取 {@code osVersion}。 + * @return 字符串结果 + */ protected String getOsVersion() { return this.device.isEnrolled() ? this.softwareInfo.getString("os_version", "-") : "-"; } + /** + * 判断 {@code gmsAvailable}。 + * @return 字段/派生属性 {@code gmsAvailable} 的值 + */ protected boolean isGmsAvailable() { return this.softwareInfo.getBoolean("gms_available", false); } + /** + * 判断 {@code expired}。 + * @return 字段/派生属性 {@code expired} 的值 + */ protected boolean isExpired() { return !ReportService.this.hostLicenseService.isStandalone() && this.device.isLicenseExpired(); } + /** + * 获取 {@code hashKey}。 + * @return 字符串结果 + */ protected String getHashKey() { return this.hashKey; } + /** + * 计算对象哈希值,需与 equals 保持一致。 + * @return 数量/长度 + */ public int hashCode() { return (Integer)ReportService.hashesMap.get(this.hashKey); } + /** + * 比较当前对象与另一个对象是否相等。 + * + * @param obj 参数 {@code obj}({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean equals(Object obj) { return this.hashCode() == ((DeviceGrouping)obj).hashCode(); } diff --git a/src/main/java/com/midm/service/file/package-info.java b/src/main/java/com/midm/service/file/package-info.java new file mode 100644 index 0000000..07587ab --- /dev/null +++ b/src/main/java/com/midm/service/file/package-info.java @@ -0,0 +1,14 @@ +/** + * 文件与报表服务:上传、下载、清理、Excel/PDF 报表生成。 + * + *

本包主要类型: + *

    + *
  • {@link DeviceFilesService}
  • + *
  • {@link FileService}
  • + *
  • {@link ReportService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.file; diff --git a/src/main/java/com/midm/service/log/LogService.java b/src/main/java/com/midm/service/log/LogService.java index f96ae0f..dac9a98 100644 --- a/src/main/java/com/midm/service/log/LogService.java +++ b/src/main/java/com/midm/service/log/LogService.java @@ -131,7 +131,7 @@ public class LogService extends BaseService { /** * 批量直接插入日志集合(常用于历史日志同步或批量导入) */ - public Collection save(Collection logs) { + public Collection save(Collection logs) { return this.mongoTemplate.insert(logs, MidmLog.class); } @@ -153,7 +153,7 @@ public class LogService extends BaseService { * @param direction 升序/降序(默认 desc) * @return 分页结果 */ - public Page findLogs(String filter, Integer page, Integer size, String sortBy, String direction) { + public Page findLogs(String filter, Integer page, Integer size, String sortBy, String direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "loggedAt"; direction = "desc"; @@ -177,7 +177,7 @@ public class LogService extends BaseService { /** * 查询企业租户最近的 License 授权流转动态 */ - public List findLinceseActivities(Site site, int limit, boolean forManagement) { + public List findLinceseActivities(Site site, int limit, boolean forManagement) { Query query = new Query(); Criteria criteria = Criteria.where("forWhat").is(site.getUuid()).and("category").is("license"); if (forManagement) { @@ -193,7 +193,7 @@ public class LogService extends BaseService { /** * 分页查询 License 操作历史日志 */ - public Page findLinceseLogs(Site site, String category, Integer page, Integer size, String sortBy, String direction, boolean forManagement) { + public Page findLinceseLogs(Site site, String category, Integer page, Integer size, String sortBy, String direction, boolean forManagement) { Query query = new Query(); Criteria criteria = Criteria.where("forWhat").is(site.getUuid()).and("category").is("license"); if (forManagement) { @@ -247,7 +247,7 @@ public class LogService extends BaseService { /** * 批量根据主键 ID 物理删除日志 */ - public DeleteResult delete(List uuids) { + public DeleteResult delete(List uuids) { Query query = Query.query(Criteria.where("_id").in(uuids)); return this.mongoTemplate.remove(query, MidmLog.class); } diff --git a/src/main/java/com/midm/service/log/package-info.java b/src/main/java/com/midm/service/log/package-info.java new file mode 100644 index 0000000..eb2f408 --- /dev/null +++ b/src/main/java/com/midm/service/log/package-info.java @@ -0,0 +1,12 @@ +/** + * 审计日志服务:幂等写入、查询、TTL 清理。 + * + *

本包主要类型: + *

    + *
  • {@link LogService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.log; diff --git a/src/main/java/com/midm/service/message/MidmWebSocketSession.java b/src/main/java/com/midm/service/message/MidmWebSocketSession.java index c684570..b6c0d6f 100644 --- a/src/main/java/com/midm/service/message/MidmWebSocketSession.java +++ b/src/main/java/com/midm/service/message/MidmWebSocketSession.java @@ -29,22 +29,94 @@ import org.springframework.web.socket.PongMessage; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; +/** + * 【业务服务】{@code MidmWebSocketSession} + * + * 类职责: + *

    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code pingMessage}(WebSocketMessage):ping消息
  • + *
  • {@code pongMessage}(WebSocketMessage):pong消息
  • + *
  • {@code heartbeatTimeout}(int):字段 heartbeatTimeout
  • + *
  • {@code session}(WebSocketSession):会话
  • + *
  • {@code headers}(HttpHeaders):字段 headers
  • + *
  • {@code jSessionId}(String):j会话ID
  • + *
+ * + * 协作对象:{@code WebSocketMessage、WebSocketSession、HttpHeaders、DateTime、ScheduledExecutorService、ScheduledFuture}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class MidmWebSocketSession { - public static final WebSocketMessage pingMessage = new PingMessage(); - public static final WebSocketMessage pongMessage = new PongMessage(); + /** + * ping消息。 + */ + public static final WebSocketMessage pingMessage = new PingMessage(); + /** + * pong消息。 + */ + public static final WebSocketMessage pongMessage = new PongMessage(); + /** + * 字段 heartbeatTimeout。 + */ private int heartbeatTimeout; + /** + * 会话。 + */ private final WebSocketSession session; + /** + * 字段 headers。 + */ private final HttpHeaders headers; + /** + * j会话ID。 + */ private String jSessionId; + /** + * 字段 holder。 + */ private Object holder; + /** + * pong时间Stamp。 + */ private DateTime pongTimeStamp; + /** + * 数据用量CheckedAt。 + */ private DateTime dataUsageCheckedAt; + /** + * scheduledExecutor服务。 + */ private ScheduledExecutorService scheduledExecutorService; - private ScheduledFuture futureHeartbeatCheckTask; - private ScheduledFuture futurePingCheckTask; + /** + * futureHeartbeat检查任务。 + */ + private ScheduledFuture futureHeartbeatCheckTask; + /** + * futurePing检查任务。 + */ + private ScheduledFuture futurePingCheckTask; + /** + * pong检查任务。 + */ private Runnable pongCheckTask; + /** + * heartbeat检查任务。 + */ private Runnable heartbeatCheckTask; + /** + * 构造 {@code MidmWebSocketSession} 实例。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new Runnable、close。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + */ public MidmWebSocketSession(WebSocketSession session) { this.heartbeatTimeout = 70; this.pongTimeStamp = DateTime.now(); @@ -74,19 +146,40 @@ public class MidmWebSocketSession { } + /** + * 构造 {@code MidmWebSocketSession} 实例。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @param heartbeatInterval 参数 {@code heartbeatInterval}({@code int}) + */ public MidmWebSocketSession(WebSocketSession session, int heartbeatInterval) { this(session); this.setHeartbeatInterval(heartbeatInterval); } + /** + * 设置 {@code heartbeatInterval}。 + * + * @param heartbeatInterval 参数 {@code heartbeatInterval}({@code int}) + */ public void setHeartbeatInterval(int heartbeatInterval) { this.heartbeatTimeout = heartbeatInterval + 10; } + /** + * 获取 {@code jSessionId}。 + * @return 字符串结果 + */ public String getJSessionId() { return this.jSessionId; } + /** + * 获取 {@code siteUuid}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * @return UUID + */ public UUID getSiteUuid() { if (this.holder != null) { return this.isUser() ? this.getUser().getSiteUuid() : this.getDevice().getSiteUuid(); @@ -101,31 +194,63 @@ public class MidmWebSocketSession { } } + /** + * 获取 {@code webSocketSession}。 + * @return 字段/派生属性 {@code webSocketSession} 的值 + */ public WebSocketSession getWebSocketSession() { return this.session; } + /** + * 获取 {@code principal}。 + * @return 字段/派生属性 {@code principal} 的值 + */ public Principal getPrincipal() { return this.session.getPrincipal(); } + /** + * 判断 {@code open}。 + * @return 字段/派生属性 {@code open} 的值 + */ public boolean isOpen() { return this.session.isOpen(); } + /** + * 处理会话ID。 + * @return 字符串结果 + */ public String sessionId() { return this.session.getId(); } + /** + * 判断是否从。 + * + * @param from 起始时间({@code String}) + * @return 字段/派生属性 {@code from} 的值 + */ public boolean isFrom(String from) { return from.equals(this.from()); } + /** + * 处理从。 + * @return 字符串结果 + */ public String from() { List headers = this.getHeaders("from"); return headers != null && !headers.isEmpty() ? (String)headers.get(0) : null; } + /** + * 获取 {@code remoteIpAddress}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getRemoteIpAddress() { String ip = this.getHeader("X-Forwarded-For"); if (!Strings.isNullOrEmpty(ip)) { @@ -140,35 +265,69 @@ public class MidmWebSocketSession { } } + /** + * 获取 {@code ipAddress}。 + * @return 字符串结果 + */ public String getIpAddress() { return this.getHeader("ip_addr"); } + /** + * 处理序列号。 + * @return 字符串结果 + */ public String serialNo() { return this.getHeader("serialNo"); } + /** + * 处理时间Zone。 + * @return 字符串结果 + */ public String timeZone() { return this.getHeader("timeZone"); } + /** + * 加密String。 + * @return 字符串结果 + */ public String encryptString() { return this.getHeader("encryptString"); } + /** + * 处理rtcEnabled。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean rtcEnabled() { return this.headers.containsKey("rtcEnabled"); } + /** + * 判断 {@code siteUuid}。 + * @return 字段/派生属性 {@code siteUuid} 的值 + */ public boolean hasSiteUuid() { return this.headers.containsKey("siteUuid"); } + /** + * 分组UUID。 + * @return UUID + */ public UUID groupUuid() { String value = this.getHeader("groupUuid"); return value == null ? null : UUID.fromString(value); } + /** + * 处理所有者。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String owner() { String value = this.getHeader("owner"); JsonElement json = McJsonUtils.toJsonElement(value); @@ -184,30 +343,61 @@ public class MidmWebSocketSession { } } + /** + * 设置 {@code holder}。 + * + * @param holder 参数 {@code holder}({@code Object}) + */ public void setHolder(Object holder) { this.holder = holder; } + /** + * 获取 {@code device}。 + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device getDevice() { return this.isDevice() ? (Device)this.holder : null; } + /** + * 获取 {@code user}。 + * @return 用户对象;未找到时返回 {@code null} + */ public User getUser() { return this.isUser() ? (User)this.holder : null; } + /** + * 判断 {@code device}。 + * @return 字段/派生属性 {@code device} 的值 + */ public boolean isDevice() { return this.holder instanceof Device; } + /** + * 判断 {@code user}。 + * @return 字段/派生属性 {@code user} 的值 + */ public boolean isUser() { return this.holder instanceof User; } + /** + * 获取 {@code id}。 + * @return 字符串结果 + */ public String getId() { return this.getWebSocketSession().getId(); } + /** + * 获取 {@code uuid}。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * @return UUID + */ public UUID getUuid() { if (this.holder != null) { if (this.holder instanceof Device) { @@ -222,30 +412,56 @@ public class MidmWebSocketSession { return null; } + /** + * 处理selfEnroll。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean selfEnroll() { String value = this.getHeader("selfEnroll"); return value == null ? false : McBooleanUtils.isTrue(value); } + /** + * 处理if存在选项。 + * @return 处理结果 + */ public IF_EXISTS_OPTION ifExistsOption() { String value = this.getHeader("ifExists"); return value == null ? IF_EXISTS_OPTION.skip : IF_EXISTS_OPTION.get(value); } + /** + * 处理许可证ID。 + * @return 字符串结果 + */ public String licenseId() { return this.getHeader("license"); } + /** + * 处理autoRenew。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public Boolean autoRenew() { String value = this.getHeader("renew"); return McBooleanUtils.isTrue(value); } + /** + * 处理renew转换为Same模型。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public Boolean renewToSameModel() { String value = this.getHeader("renewToSameModel"); return McBooleanUtils.isTrue(value); } + /** + * 处理client版本。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 数量/长度 + */ public int clientVersion() { String value = this.getHeader("clientVersion"); @@ -256,16 +472,37 @@ public class MidmWebSocketSession { } } + /** + * 发送请求。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、sendPacket。 + * + * @param code 状态码/业务码({@code int}) + */ public void sendRequest(int code) { MidmPacket packet = new MidmPacket(code); this.sendPacket(packet); } + /** + * 发送请求。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、sendPacket。 + * + * @param request HTTP 请求({@code MIDM_REQUEST}) + */ public void sendRequest(MIDM_REQUEST request) { MidmPacket packet = new MidmPacket(request.getCode()); this.sendPacket(packet); } + /** + * 发送Enroll请求。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、sendPacket。 + * + * @param device 设备({@code Device}) + */ public void sendEnrollRequest(Device device) { MidmPacket packet = new MidmPacket(MIDM_REQUEST.ENROLL); packet.getQuery().setRequest("enroll"); @@ -274,14 +511,21 @@ public class MidmWebSocketSession { this.sendPacket(packet); } + /** + * 发送Client更新请求。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、new JsonObject、sendPacket。 + * + * @param device 设备({@code Device}) + * @param app 参数 {@code app}({@code AppFile}) + */ public void sendClientUpdateRequest(Device device, AppFile app) { MidmPacket packet = new MidmPacket(MIDM_REQUEST.COMMAND); packet.setRecieverUuid(device.getUuid()); packet.getQuery().setRequest("apps"); packet.setParam("command", "install"); JsonObject jParams = new JsonObject(); - UUID var10000 = device.getSiteUuid(); - String url = var10000 + "/file/app/" + app.getFileUuid() + "/" + app.getFileName(); + String url = device.getSiteUuid() + "/file/app/" + app.getFileUuid() + "/" + app.getFileName(); jParams.addProperty("url", url); McJsonUtils.setProperty(jParams, "data", app); jParams.addProperty("remove_after_install", true); @@ -289,25 +533,61 @@ public class MidmWebSocketSession { this.sendPacket(packet); } + /** + * 发送反馈。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:sendFeedback。 + * + * @param code 状态码/业务码({@code int}) + */ public void sendFeedback(int code) { this.sendFeedback(code, "", (Object)null); } + /** + * 发送反馈。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、sendPacket。 + * + * @param code 状态码/业务码({@code int}) + * @param message 消息内容({@code String}) + * @param data 参数 {@code data}({@code Object}) + */ public void sendFeedback(int code, String message, Object data) { MidmPacket packet = new MidmPacket(); packet.setFeedback(code, message, data); this.sendPacket(packet); } + /** + * 发送报文。 + * + * @param packet WebSocket 报文({@code MidmPacket}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean sendPacket(MidmPacket packet) { return this.sendMessage((WebSocketMessage)packet.toBinary()); } + /** + * 发送消息。 + * + * @param packet WebSocket 报文({@code MidmPacket}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean sendMessage(MidmPacket packet) { return this.sendMessage((WebSocketMessage)packet.toMessage()); } - public boolean sendMessage(WebSocketMessage message) { + /** + * 发送消息。 + * + * 实现要点:包含同步块;包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环。 + * + * @param message 消息内容({@code WebSocketMessage}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean sendMessage(WebSocketMessage message) { try { synchronized(this.session) { if (this.session.isOpen()) { @@ -324,12 +604,22 @@ public class MidmWebSocketSession { } } + /** + * 调度TocheckHeartbeat。 + * + * 实现要点:主要调用:schedule。 + */ public void scheduleTocheckHeartbeat() { this.cancelFutureTask(this.futureHeartbeatCheckTask); this.validateScheduleExcutorService(); this.futureHeartbeatCheckTask = this.scheduledExecutorService.schedule(this.heartbeatCheckTask, (long)this.heartbeatTimeout, TimeUnit.SECONDS); } + /** + * 处理ping。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new DateTime、schedule。 + */ public void ping() { if (!(new DateTime()).minusSeconds(this.heartbeatTimeout > 120 ? 120 : this.heartbeatTimeout).isBefore(this.pongTimeStamp)) { this.cancelFutureTask(this.futurePingCheckTask); @@ -340,19 +630,34 @@ public class MidmWebSocketSession { } + /** + * 处理pong。 + */ public void pong() { this.sendMessage(pongMessage); } + /** + * 处理处理Pong。 + */ public void onPong() { this.scheduleTocheckHeartbeat(); } + /** + * 更新Pong时间Stamp。 + */ public void updatePongTimeStamp() { this.pongTimeStamp = DateTime.now(); this.scheduleTocheckHeartbeat(); } + /** + * 处理need转换为更新数据用量。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean needToUpdateDataUsage() { if (this.isDevice() && this.dataUsageCheckedAt.isBefore(this.pongTimeStamp.minusHours(1))) { this.dataUsageCheckedAt = this.pongTimeStamp; @@ -362,6 +667,13 @@ public class MidmWebSocketSession { } } + /** + * 处理关闭。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:close。 + * + * @param reason 参数 {@code reason}({@code CloseStatus}) + */ public void close(CloseStatus reason) { try { this.cancelFutureTask(this.futureHeartbeatCheckTask); @@ -378,14 +690,31 @@ public class MidmWebSocketSession { } - private List getHeaders(String key) { + /** + * 获取Headers。 + * + * @param key 键/配置项({@code String}) + * @return String列表,可能为空 + */ + private List getHeaders(String key) { return this.headers.get(key); } + /** + * 获取Header。 + * + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ private String getHeader(String key) { return this.headers.getFirst(key); } + /** + * 校验调度Excutor服务。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + */ private void validateScheduleExcutorService() { if (this.scheduledExecutorService != null) { this.scheduledExecutorService.shutdownNow(); @@ -394,13 +723,26 @@ public class MidmWebSocketSession { this.scheduledExecutorService = Executors.newScheduledThreadPool(2); } - private void cancelFutureTask(ScheduledFuture futureTask) { + /** + * 取消Future任务。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:cancel。 + * + * @param futureTask 参数 {@code futureTask}({@code ScheduledFuture}) + */ + private void cancelFutureTask(ScheduledFuture futureTask) { if (futureTask != null && !futureTask.isCancelled() && !futureTask.isDone()) { futureTask.cancel(true); } } + /** + * 处理finalize。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @throws Throwable 当 Throwable 条件不满足或底层调用失败时抛出。 + */ protected void finalize() throws Throwable { if (this.scheduledExecutorService != null && !this.scheduledExecutorService.isShutdown()) { this.scheduledExecutorService.shutdownNow(); diff --git a/src/main/java/com/midm/service/message/UserSocketSessions.java b/src/main/java/com/midm/service/message/UserSocketSessions.java index 7e0951b..5278af8 100644 --- a/src/main/java/com/midm/service/message/UserSocketSessions.java +++ b/src/main/java/com/midm/service/message/UserSocketSessions.java @@ -6,31 +6,87 @@ import java.util.Iterator; import java.util.Set; import java.util.UUID; +/** + * 【业务服务】{@code UserSocketSessions} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code jSessionId}(String):j会话ID
  • + *
  • {@code sessions}(Set):会话列表
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class UserSocketSessions { + /** + * j会话ID。 + */ private String jSessionId; - private Set sessions = new HashSet(); + /** + * 会话列表。 + */ + private Set sessions = new HashSet(); + /** + * 构造 {@code UserSocketSessions} 实例。 + * + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ public UserSocketSessions(MidmWebSocketSession session) { this.jSessionId = session.getJSessionId(); this.sessions.add(session); } + /** + * 处理getj会话ID。 + * @return 字符串结果 + */ public String getjSessionId() { return this.jSessionId; } - public Set getSessions() { + /** + * 获取 {@code sessions}。 + * @return MidmWebSocket会话列表,可能为空 + */ + public Set getSessions() { return this.sessions; } + /** + * 处理添加。 + * + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ public void add(MidmWebSocketSession session) { this.sessions.add(session); } + /** + * 处理移除。 + * + * 实现要点:主要调用:remove。 + * + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ public void remove(MidmWebSocketSession session) { this.sessions.remove(session); } + /** + * 发送消息。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param packetFeedback 参数 {@code packetFeedback}({@code MidmPacket}) + */ public void sendMessage(UUID siteUuid, MidmPacket packetFeedback) { Iterator it = this.sessions.iterator(); diff --git a/src/main/java/com/midm/service/message/WebSocketSessionManager.java b/src/main/java/com/midm/service/message/WebSocketSessionManager.java index 0afe9ae..dc59d6a 100644 --- a/src/main/java/com/midm/service/message/WebSocketSessionManager.java +++ b/src/main/java/com/midm/service/message/WebSocketSessionManager.java @@ -76,47 +76,109 @@ import org.springframework.web.socket.WebSocketSession; @Configurable public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListener { /** 全局活跃底层 WebSocket 会话映射表 (SessionId -> MidmWebSocketSession) */ - private Map sessions = new ConcurrentHashMap(); + private Map sessions = new ConcurrentHashMap(); /** 在线 Web 管理用户路由表 (UserUuid -> MidmWebSocketSession) */ - private Map userSessions = new ConcurrentHashMap(); + private Map userSessions = new ConcurrentHashMap(); /** 在线边缘受控设备路由表 (DeviceUuid -> MidmWebSocketSession) */ - private Map deviceSessions = new ConcurrentHashMap(); + private Map deviceSessions = new ConcurrentHashMap(); /** 终端高频重连与滥用探测监控表 (DeviceUuid / SerialNo -> ReconnectMonitor) */ - private Map reconnectMonitors = new ConcurrentHashMap(); + private Map reconnectMonitors = new ConcurrentHashMap(); + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceService deviceService; + /** + * 电池服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private BatteryService batteryService; + /** + * 设备应用列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceAppsService deviceAppsService; + /** + * 设备密钥服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceKeyService deviceKeyService; + /** + * 设备报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceReportService deviceReportService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteService siteService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private LogService logService; + /** + * 任务Scheduler;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired protected TaskScheduler taskScheduler; + /** + * 处理处理Connected。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:register。 + * + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ public void onConnected(MidmWebSocketSession session) { if (this.isValid(session) && this.register(session)) { this.saveDeviceReportAndLog(session); @@ -124,6 +186,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 保存设备报表并日志。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:new Document、save。 + * + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ private void saveDeviceReportAndLog(MidmWebSocketSession session) { UUID deviceUuid = session.getUuid(); String publicIp = session.getRemoteIpAddress(); @@ -144,6 +213,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene this.logService.save((User)null, deviceUuid, "event", log); } + /** + * 处理处理Ping。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + */ public void onPing(MidmWebSocketSession midmSession) { if (this.isValid(midmSession)) { midmSession.pong(); @@ -152,6 +228,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理处理Pong。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + */ public void onPong(MidmWebSocketSession midmSession) { if (this.isValid(midmSession)) { midmSession.onPong(); @@ -159,6 +242,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 判断是否Valid。 + * + * 实现要点:包含 4 个条件分支、0 个循环;主要调用:close。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + * @return 字段/派生属性 {@code valid} 的值 + */ private boolean isValid(MidmWebSocketSession midmSession) { if (this.hostLicenseService.isStandalone()) { if (!this.hostLicenseService.isValid()) { @@ -175,6 +266,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene return true; } + /** + * 处理注册。 + * + * 实现要点:调用持久化方法保存数据;包含 7 个条件分支、0 个循环;主要调用:remove、close、new ReconnectMonitor、new UserSocketSessions、save。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean register(MidmWebSocketSession midmSession) { this.sessions.put(midmSession.sessionId(), midmSession); UUID uuid = midmSession.getUuid(); @@ -224,6 +323,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene return true; } + /** + * 更新设备信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ private void updateDeviceInfo(Device device, MidmWebSocketSession session) { String curTimeZone = session.timeZone(); boolean curRtcEnabled = session.rtcEnabled(); @@ -235,6 +342,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 查询设备信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void queryDeviceInfo(UUID uuid) { if (this.deviceSessions.containsKey(uuid)) { this.queryDeviceInfo(uuid, (MidmWebSocketSession)this.deviceSessions.get(uuid)); @@ -242,6 +356,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 查询设备信息。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:new MidmPacket、new MidmQuery、sendPacket。 + * + * @param uuid 对象 UUID({@code UUID}) + * @param session WebSocket 会话({@code MidmWebSocketSession}) + */ public void queryDeviceInfo(UUID uuid, MidmWebSocketSession session) { if (session != null) { MidmPacket packet = new MidmPacket(); @@ -256,6 +378,15 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 处理请求数据用量。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:new MidmPacket、new MidmQuery、new JsonObject。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param from 起始时间({@code DateTime}) + * @param to 结束时间({@code DateTime}) + */ public void requestDataUsage(UUID deviceUuid, DateTime from, DateTime to) { if (this.isOnline(deviceUuid) && from.compareTo(to) < 0) { MidmPacket packet = new MidmPacket(); @@ -276,6 +407,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理处理Disconnected。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param status 状态({@code CloseStatus}) + */ public void onDisconnected(UUID deviceUuid, CloseStatus status) { if (this.deviceSessions.containsKey(deviceUuid)) { MidmWebSocketSession midmSession = (MidmWebSocketSession)this.deviceSessions.get(deviceUuid); @@ -284,6 +423,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理处理Disconnected。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:remove、close、save。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @param status 状态({@code CloseStatus}) + */ public void onDisconnected(WebSocketSession session, CloseStatus status) { MidmWebSocketSession midmSession = (MidmWebSocketSession)this.sessions.get(session.getId()); if (midmSession != null) { @@ -307,6 +454,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 处理退出。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:close、remove。 + * + * @param user 当前用户({@code User}) + */ public void logout(User user) { if (user != null) { UUID userUuid = user.getUuid(); @@ -328,6 +482,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理关闭。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param uuid 对象 UUID({@code UUID}) + * @param status 状态({@code CloseStatus}) + */ public void close(UUID uuid, CloseStatus status) { if (this.deviceSessions != null && this.deviceSessions.containsKey(uuid)) { ((MidmWebSocketSession)this.deviceSessions.get(uuid)).close(status); @@ -335,10 +497,26 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 通知处理Line状态。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + * @param isOnline 参数 {@code isOnline}({@code boolean}) + */ public void notifyOnLineStatus(MidmWebSocketSession midmSession, boolean isOnline) { this.notifyOnLineStatus(midmSession.isDevice(), midmSession.getSiteUuid(), midmSession.getUuid(), isOnline); } + /** + * 通知处理Line状态。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:new MidmPacket、new MidmResponse、new Document。 + * + * @param isDevice 参数 {@code isDevice}({@code boolean}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param uuid 对象 UUID({@code UUID}) + * @param isOnline 参数 {@code isOnline}({@code boolean}) + */ private void notifyOnLineStatus(boolean isDevice, UUID siteUuid, UUID uuid, boolean isOnline) { if (!isDevice || this.deviceService.updateOnlineStatus(uuid, isOnline).getModifiedCount() != 0L) { MidmPacket packet = new MidmPacket(); @@ -351,6 +529,15 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 更新设备状态。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param packet WebSocket 报文({@code MidmPacket}) + */ public void updateDeviceStatus(UUID siteUuid, UUID deviceUuid, MidmPacket packet) { if (this.deviceService.exists(deviceUuid)) { MidmResponse response = packet.getFeedback(); @@ -362,12 +549,27 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 发送更新反馈。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket。 + * + * @param device 设备({@code Device}) + */ public void sendUpdateFeedback(Device device) { MidmPacket packet = new MidmPacket(); packet.setFeedback(114, "", this.optimizeDeviceInfo(device)); this.sendPacketToOnlineUsers(device.getSiteUuid(), packet); } + /** + * 发送消息转换为Online用户列表。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、new MidmResponse、new JsonObject。 + * + * @param device 设备({@code Device}) + * @param what 参数 {@code what}({@code int}) + */ public void sendMessageToOnlineUsers(Device device, int what) { MidmPacket packetFeedback = new MidmPacket(); MidmResponse feedback = new MidmResponse(); @@ -388,7 +590,15 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene this.sendPacketToOnlineUsers(device.getSiteUuid(), packetFeedback); } - public void sendMessageToOnlineUsers(List devices, int what) { + /** + * 发送消息转换为Online用户列表。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:new MidmPacket、new MidmResponse、new JsonObject。 + * + * @param devices 参数 {@code devices}({@code List}) + * @param what 参数 {@code what}({@code int}) + */ + public void sendMessageToOnlineUsers(List devices, int what) { MidmPacket packetFeedback = new MidmPacket(); MidmResponse feedback = new MidmResponse(); feedback.setCode(what); @@ -407,16 +617,38 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene this.sendPacketToOnlineUsers(((Device)devices.get(0)).getSiteUuid(), packetFeedback); } + /** + * 发送报文转换为Online用户列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param packet WebSocket 报文({@code MidmPacket}) + */ public void sendPacketToOnlineUsers(final UUID siteUuid, MidmPacket packet) { if (siteUuid != null) { this.userSessions.forEach((uuid, sessions) -> sessions.sendMessage(siteUuid, packet)); } } + /** + * 发送消息转换为Online用户列表。 + * + * @param user 当前用户({@code User}) + * @param what 参数 {@code what}({@code int}) + */ public void sendMessageToOnlineUsers(User user, int what) { this.sendMessageToOnlineUsers(user.getUuid(), what); } + /** + * 发送消息转换为Online用户列表。 + * + * 实现要点:主要调用:new MidmPacket、new MidmResponse、new JsonObject。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param what 参数 {@code what}({@code int}) + */ public void sendMessageToOnlineUsers(UUID userUuid, int what) { MidmPacket packetFeedback = new MidmPacket(); MidmResponse feedback = new MidmResponse(); @@ -434,6 +666,7 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene break; case 109: jState.addProperty("message", "Site license ready"); + break; case 110: case 111: case 112: @@ -460,10 +693,24 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene this.sendMessageToOnlineUsers(userUuid, packetFeedback); } + /** + * 发送消息转换为Online用户列表。 + * + * @param user 当前用户({@code User}) + * @param packetFeedback 参数 {@code packetFeedback}({@code MidmPacket}) + */ public void sendMessageToOnlineUsers(User user, MidmPacket packetFeedback) { this.sendMessageToOnlineUsers(user.getUuid(), packetFeedback); } + /** + * 发送消息转换为Online用户列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param packetFeedback 参数 {@code packetFeedback}({@code MidmPacket}) + */ public void sendMessageToOnlineUsers(UUID userUuid, MidmPacket packetFeedback) { if (this.userSessions.containsKey(userUuid)) { ((UserSocketSessions)this.userSessions.get(userUuid)).sendMessage((UUID)null, packetFeedback); @@ -471,6 +718,16 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 发送反馈。 + * + * 实现要点:调用持久化方法保存数据;包含 7 个条件分支、0 个循环;主要调用:new TypeToken、save、new DbObject。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + * @param senderUuid 参数 {@code senderUuid}({@code UUID}) + * @param receiverUuid 参数 {@code receiverUuid}({@code UUID}) + * @param packet WebSocket 报文({@code MidmPacket}) + */ public void sendFeedback(MidmWebSocketSession midmSession, UUID senderUuid, UUID receiverUuid, MidmPacket packet) { int feedbackCode = packet.getFeedback().getCode(); Object feedbackData = packet.getFeedback().getData(); @@ -530,6 +787,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 发送消息。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 4 个条件分支、0 个循环;主要调用:sendPacket、remove。 + * + * @param query 查询对象({@code MidmPacket}) + */ public void sendMessage(MidmPacket query) { UUID receiverUuid = query.getRecieverUuid(); if (receiverUuid != null) { @@ -551,6 +815,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 发送报文转换为Online设备列表。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:sendPacket。 + * + * @param packet WebSocket 报文({@code MidmPacket}) + */ public void sendPacketToOnlineDevices(MidmPacket packet) { for(Map.Entry sessionEntry : this.sessions.entrySet()) { MidmWebSocketSession session = (MidmWebSocketSession)sessionEntry.getValue(); @@ -562,7 +833,16 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } - public boolean sendMessage(WebSocketSession session, WebSocketMessage message) { + /** + * 发送消息。 + * + * 实现要点:包含同步块;包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @param message 消息内容({@code WebSocketMessage}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean sendMessage(WebSocketSession session, WebSocketMessage message) { try { synchronized(session) { if (session.isOpen()) { @@ -577,6 +857,15 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 处理转换为MidmSocket会话。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 37 个条件分支、0 个循环;主要调用:new MidmWebSocketSession、sendFeedback、close、delete、new Device、save。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @param registering 参数 {@code registering}({@code boolean}) + * @return 处理结果 + */ public MidmWebSocketSession toMidmSocketSession(WebSocketSession session, boolean registering) { if (!session.isOpen()) { return null; @@ -768,11 +1057,26 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } } + /** + * 处理处理设备Checked在。 + * + * 实现要点:通过 WebSocket 会话推送消息;主要调用:sendFeedback。 + * + * @param midmSession 参数 {@code midmSession}({@code MidmWebSocketSession}) + */ private void onDeviceCheckedIn(MidmWebSocketSession midmSession) { this.deviceService.updateLastCheckedIn(midmSession.getUuid()); midmSession.sendFeedback(110, "", this.optimizeDeviceInfo(midmSession.getDevice())); } + /** + * 设置设备分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @param groupUuid 分组 UUID({@code UUID}) + */ private void setDeviceGroup(Device device, UUID groupUuid) { if (groupUuid != null) { DeviceGroup deviceGroup = this.deviceService.findDeviceGroup(groupUuid); @@ -781,6 +1085,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 设置设备所有者。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param device 设备({@code Device}) + * @param ownerEmail 参数 {@code ownerEmail}({@code String}) + */ private void setDeviceOwner(Device device, String ownerEmail) { if (!Strings.isNullOrEmpty(ownerEmail)) { User user = this.userService.findUserByEmail(device.getSiteUuid(), ownerEmail); @@ -794,6 +1106,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理optimize设备信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param orgDevice 参数 {@code orgDevice}({@code Device}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device optimizeDeviceInfo(Device orgDevice) { Device device = orgDevice.clone(); device.getProfile().clear(); @@ -818,14 +1138,33 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene return device; } + /** + * 获取Online设备。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device getOnlineDevice(UUID deviceUuid) { return this.deviceSessions.containsKey(deviceUuid) ? ((MidmWebSocketSession)this.deviceSessions.get(deviceUuid)).getDevice() : null; } + /** + * 判断是否Online。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 字段/派生属性 {@code online} 的值 + */ public boolean isOnline(UUID uuid) { return this.deviceSessions.containsKey(uuid) || this.userSessions.containsKey(uuid); } + /** + * 处理ping。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param uuid 对象 UUID({@code UUID}) + */ public void ping(UUID uuid) { if (this.deviceSessions.containsKey(uuid)) { ((MidmWebSocketSession)this.deviceSessions.get(uuid)).ping(); @@ -833,10 +1172,21 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 获取 {@code heartBeatInterval}。 + * @return 数量/长度 + */ private int getHeartBeatInterval() { return this.settingsService != null ? this.settingsService.getInt("websocket.heartbeat.interval", 300) : 300; } + /** + * 更新Installed应用列表。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环;主要调用:new MidmPacket、new MidmQuery、new Document、sendPacket。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + */ public void updateInstalledApps(UUID deviceUuid) { MidmWebSocketSession session = (MidmWebSocketSession)this.deviceSessions.get(deviceUuid); if (session != null) { @@ -860,10 +1210,25 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 更新Installed应用列表。 + * + * 实现要点:主要调用:schedule、new Date。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param delay 参数 {@code delay}({@code int}) + */ public void updateInstalledApps(UUID deviceUuid, int delay) { this.taskScheduler.schedule(() -> this.updateInstalledApps(deviceUuid), new Date((new Date()).getTime() + (long)delay)); } + /** + * 处理block。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ReconnectMonitor。 + * + * @param device 设备({@code Device}) + */ public void block(Device device) { UUID deviceUuid = device.getUuid(); ReconnectMonitor reconnectMonitor = (ReconnectMonitor)this.reconnectMonitors.get(deviceUuid); @@ -875,6 +1240,14 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene reconnectMonitor.block(device); } + /** + * 处理unblock。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param deviceUuid 设备 UUID({@code UUID}) + * @param loggedUser 参数 {@code loggedUser}({@code User}) + */ public void unblock(UUID deviceUuid, User loggedUser) { if (this.reconnectMonitors.containsKey(deviceUuid)) { ((ReconnectMonitor)this.reconnectMonitors.get(deviceUuid)).unblock(loggedUser); @@ -882,6 +1255,13 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理unblock按站点UUID。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void unblockBySiteUuid(UUID siteUuid) { for(ReconnectMonitor reconnectMonitor : this.reconnectMonitors.values()) { Device device = reconnectMonitor.getDevice(); @@ -892,12 +1272,27 @@ public class WebSocketSessionManager implements ReconnectMonitor.OnAbusedListene } + /** + * 处理处理Unblocked。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param monitor 参数 {@code monitor}({@code ReconnectMonitor}) + * @param loggedUser 参数 {@code loggedUser}({@code User}) + */ public void onUnblocked(ReconnectMonitor monitor, User loggedUser) { UUID deviceUuid = monitor.getDeviceUuid(); this.logService.save(loggedUser, deviceUuid, "event", loggedUser == null ? "Unblocked by timeout." : "UnBlocked manually."); this.deviceService.updateBlockState(deviceUuid, (Date)null, (Date)null); } + /** + * 处理处理Abused。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;主要调用:close、save。 + * + * @param monitor 参数 {@code monitor}({@code ReconnectMonitor}) + */ public void onAbused(ReconnectMonitor monitor) { UUID deviceUuid = monitor.getDeviceUuid(); ((MidmWebSocketSession)this.deviceSessions.get(deviceUuid)).sendFeedback(112, "blocked", (Object)null); diff --git a/src/main/java/com/midm/service/message/package-info.java b/src/main/java/com/midm/service/message/package-info.java new file mode 100644 index 0000000..d6ecbe4 --- /dev/null +++ b/src/main/java/com/midm/service/message/package-info.java @@ -0,0 +1,14 @@ +/** + * WebSocket 会话管理:在线会话、重连监控、消息路由。 + * + *

本包主要类型: + *

    + *
  • {@link MidmWebSocketSession}
  • + *
  • {@link UserSocketSessions}
  • + *
  • {@link WebSocketSessionManager}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.message; diff --git a/src/main/java/com/midm/service/news/MessageLogService.java b/src/main/java/com/midm/service/news/MessageLogService.java index 69efd8c..d2b1d33 100644 --- a/src/main/java/com/midm/service/news/MessageLogService.java +++ b/src/main/java/com/midm/service/news/MessageLogService.java @@ -13,8 +13,28 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code MessageLogService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class MessageLogService extends BaseService { + /** + * 查找日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、findOne。 + * + * @param messageUuid 参数 {@code messageUuid}({@code UUID}) + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 处理结果 + */ public MessageLog findLog(UUID messageUuid, UUID userUuid, UUID siteUuid) { Criteria criteria = Criteria.where("message.$id").is(messageUuid).and("reader.$id").is(userUuid).and("siteUuid").is(siteUuid); Query query = new Query(criteria); @@ -22,7 +42,17 @@ public class MessageLogService extends BaseService { return log; } - public List findLog(UUID userUuid, UUID siteUuid, int limit) { + /** + * 查找日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、find。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param limit 数量上限({@code int}) + * @return 消息日志列表,可能为空 + */ + public List findLog(UUID userUuid, UUID siteUuid, int limit) { Criteria criteria = Criteria.where("reader.$id").is(userUuid).orOperator(new Criteria[]{Criteria.where("siteUuid").is(siteUuid), Criteria.where("siteUuid").exists(false)}); Query query = new Query(criteria); query.with(Sort.by(Direction.DESC, new String[]{"notified"})); @@ -35,7 +65,15 @@ public class MessageLogService extends BaseService { return log; } - public List findUnchecked(User user) { + /** + * 查找Unchecked。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param user 当前用户({@code User}) + * @return 消息日志列表,可能为空 + */ + public List findUnchecked(User user) { Criteria criteria = Criteria.where("reader.$id").is(user.getUuid()).and("isCheck").is(false).orOperator(new Criteria[]{Criteria.where("siteUuid").is(user.getSiteUuid()), Criteria.where("siteUuid").exists(false)}); Query query = new Query(criteria); query.with(Sort.by(Direction.DESC, new String[]{"notified"})); @@ -43,34 +81,79 @@ public class MessageLogService extends BaseService { return this.mongoTemplate.find(query, MessageLog.class); } - public List findLogByReadStatus(UUID userUuid, UUID siteUuid, boolean isRead) { + /** + * 查找读取状态的日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param isRead 参数 {@code isRead}({@code boolean}) + * @return 消息日志列表,可能为空 + */ + public List findLogByReadStatus(UUID userUuid, UUID siteUuid, boolean isRead) { Criteria criteria = Criteria.where("reader.$id").is(userUuid).and("siteUuid").is(siteUuid).and("isRead").exists(isRead); Query query = new Query(criteria); List log = this.mongoTemplate.find(query, MessageLog.class); return log; } - public List findLogByCheckStatus(UUID userUuid, UUID siteUuid, boolean isCheck) { + /** + * 查找检查状态的日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param isCheck 参数 {@code isCheck}({@code boolean}) + * @return 消息日志列表,可能为空 + */ + public List findLogByCheckStatus(UUID userUuid, UUID siteUuid, boolean isCheck) { Criteria criteria = Criteria.where("reader.$id").is(userUuid).and("siteUuid").is(siteUuid).and("isCheck").is(isCheck); Query query = new Query(criteria); List log = this.mongoTemplate.find(query, MessageLog.class); return log; } - public List findLogsByMessage(UUID messageUuid) { + /** + * 查找消息的日志列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param messageUuid 参数 {@code messageUuid}({@code UUID}) + * @return 消息日志列表,可能为空 + */ + public List findLogsByMessage(UUID messageUuid) { Criteria criteria = Criteria.where("message.$id").is(messageUuid); Query query = new Query(criteria); List logs = this.mongoTemplate.find(query, MessageLog.class); return logs; } - public List findLogByReader(UUID userUuid, UUID messageUuid) { + /** + * 查找Reader的日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param messageUuid 参数 {@code messageUuid}({@code UUID}) + * @return 消息日志列表,可能为空 + */ + public List findLogByReader(UUID userUuid, UUID messageUuid) { Criteria criteria = Criteria.where("message.$id").is(messageUuid).and("reader.$id").is(userUuid); Query query = new Query(criteria); List log = this.mongoTemplate.find(query, MessageLog.class); return log; } + /** + * 根据新闻消息删除删除Result。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、remove。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteByNewsMessage(NewsMessage newsMessage) { Criteria criteria = Criteria.where("message.$id").is(newsMessage.getUuid()); Query query = new Query(criteria); diff --git a/src/main/java/com/midm/service/news/NewsMessageService.java b/src/main/java/com/midm/service/news/NewsMessageService.java index 3e51979..e09b73d 100644 --- a/src/main/java/com/midm/service/news/NewsMessageService.java +++ b/src/main/java/com/midm/service/news/NewsMessageService.java @@ -71,35 +71,116 @@ import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; +/** + * 【业务服务】{@code NewsMessageService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code emailService}(EmailService):邮件服务
  • + *
  • {@code messageLogService}(MessageLogService):消息日志服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code storeAppService}(StoreAppService):store应用服务
  • + *
  • {@code sessionManager}(WebSocketSessionManager):会话Manager
  • + *
+ * + * 协作对象:{@code FileService、EmailService、MessageLogService、SettingsService、StoreAppService、WebSocketSessionManager}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class NewsMessageService extends BaseService { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 消息日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MessageLogService messageLogService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * store应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private StoreAppService storeAppService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 模板服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private TemplateService templateService; + /** + * string模板Engine;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。 + */ @Autowired @Qualifier("stringTemplateEngine") private TemplateEngine stringTemplateEngine; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteService siteService; + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @return 处理结果 + */ public NewsMessage save(NewsMessage newsMessage) { NewsMessage message = (NewsMessage)this.saveDocument(newsMessage); Date schedule = message.getSendSchedule(); @@ -110,6 +191,14 @@ public class NewsMessageService extends BaseService { return message; } + /** + * 生成新闻消息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new NewsMessage。 + * + * @param device 设备({@code Device}) + * @return 处理结果 + */ public NewsMessage generateNewsMessage(Device device) { NewsMessage newsMessage = null; if (device != null) { @@ -121,41 +210,105 @@ public class NewsMessageService extends BaseService { return newsMessage; } - public NewsMessage setNewsMessage(String title, String content, String summary, String category, Set roles, Device device) { + /** + * 设置新闻消息。 + * + * 实现要点:主要调用:new NewsMessage。 + * + * @param title 参数 {@code title}({@code String}) + * @param content 参数 {@code content}({@code String}) + * @param summary 参数 {@code summary}({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param roles 参数 {@code roles}({@code Set}) + * @param device 设备({@code Device}) + * @return 处理结果 + */ + public NewsMessage setNewsMessage(String title, String content, String summary, String category, Set roles, Device device) { NewsMessage newsMessage = device != null ? new NewsMessage(device, category) : new NewsMessage(); newsMessage.setMessage(title, content, summary); return newsMessage; } + /** + * 处理删除。 + * + * @param messageLog 参数 {@code messageLog}({@code MessageLog}) + */ public void delete(MessageLog messageLog) { this.deleteById(MessageLog.class, messageLog.getUuid()); } + /** + * 处理删除。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void delete(NewsMessage newsMessage) { this.deleteById(NewsMessage.class, newsMessage.getUuid()); this.messageLogService.deleteByNewsMessage(newsMessage); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param newsMessage 参数 {@code newsMessage}({@code List}) + */ public void delete(List newsMessage) { List uuids = (List)newsMessage.stream().map(NewsMessage::getUuid).collect(Collectors.toList()); Query query = Query.query(Criteria.where("_id").in(uuids)); this.mongoTemplate.remove(query, NewsMessage.class); } + /** + * 查找消息。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 处理结果 + */ public NewsMessage findMessage(UUID uuid) { return (NewsMessage)this.findById(NewsMessage.class, uuid); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return 新闻消息列表,可能为空 + */ + public List findAll() { return this.findAll(NewsMessage.class); } - public List findByUser(User user, boolean isUnreadOnly, int size) { + /** + * 根据用户查找列出。 + * + * @param user 当前用户({@code User}) + * @param isUnreadOnly 参数 {@code isUnreadOnly}({@code boolean}) + * @param size 每页数量({@code int}) + * @return 新闻消息列表,可能为空 + */ + public List findByUser(User user, boolean isUnreadOnly, int size) { List newsMessage = null; return newsMessage; } - public Page find(String category, String forWhat, JsonObject jFilter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new Criteria、count、find、new PageImpl。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 分页结果 + */ + public Page find(String category, String forWhat, JsonObject jFilter, String sortBy, Sort.Direction direction, Integer page, Integer size) { Criteria criteria = new Criteria(); if (!Strings.isNullOrEmpty(category)) { criteria.and("category").is(category); @@ -186,7 +339,15 @@ public class NewsMessageService extends BaseService { return pageResult; } - public Collection saveMessageLog(NewsMessage newsMessage) { + /** + * 保存消息日志。 + * + * 实现要点:涉及邮件发送;通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @return 用户邮件列表,可能为空 + */ + public Collection saveMessageLog(NewsMessage newsMessage) { this.setGlobalMessageLog(newsMessage); Collection sendMails = this.getEmailLists(newsMessage.getCategory(), newsMessage.getForWhat(), true); Collection notiMails = this.getEmailLists(newsMessage.getCategory(), newsMessage.getForWhat(), false); @@ -199,11 +360,24 @@ public class NewsMessageService extends BaseService { return sendMails; } + /** + * 通知消息。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ public void notifyMessage(NewsMessage newsMessage) { Collection mails = this.saveMessageLog(newsMessage); this.sendNotification(mails, newsMessage); } + /** + * 发送Notification。 + * + * 实现要点:涉及邮件发送;包含 5 个条件分支、0 个循环;主要调用:sendMail。 + * + * @param mails 参数 {@code mails}({@code Collection}) + * @param message 消息内容({@code NewsMessage}) + */ private void sendNotification(Collection mails, NewsMessage message) { Map recipients = (Map)mails.stream().collect(Collectors.toMap(UserMail::getEmail, (user) -> user.toAddress())); List mailsTo = message.getMailsTo(); @@ -229,6 +403,14 @@ public class NewsMessageService extends BaseService { } } + /** + * 发送邮件。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:send。 + * + * @param sender 参数 {@code sender}({@code McMailSender}) + * @param addresses 参数 {@code addresses}({@code List}) + */ private void sendMail(McMailSender sender, List addresses) { for(List oneList : Lists.partition(addresses, 40)) { sender.clearBcc(); @@ -238,16 +420,42 @@ public class NewsMessageService extends BaseService { } - public List getMessageByCategory(String category) { + /** + * 获取Category的消息。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 新闻消息列表,可能为空 + */ + public List getMessageByCategory(String category) { Query query = Query.query(Criteria.where("category").is(category)); return this.mongoTemplate.find(query, NewsMessage.class); } + /** + * 设置消息日志。 + * + * 实现要点:主要调用:new MessageLog。 + * + * @param message 消息内容({@code NewsMessage}) + * @param reader 参数 {@code reader}({@code User}) + * @param site 站点/企业({@code Site}) + */ public void setMessageLog(NewsMessage message, User reader, Site site) { MessageLog log = new MessageLog(message, reader, site.getUuid()); this.saveMessageLog(log); } + /** + * 设置消息日志。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new MessageLog。 + * + * @param message 消息内容({@code NewsMessage}) + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + */ public void setMessageLog(NewsMessage message, UUID userUuid, UUID siteUuid) { if (message != null && userUuid != null) { MessageLog log = new MessageLog(message, userUuid, siteUuid); @@ -256,23 +464,57 @@ public class NewsMessageService extends BaseService { } + /** + * 保存消息日志。 + * + * @param log 参数 {@code log}({@code MessageLog}) + */ public void saveMessageLog(MessageLog log) { this.saveDocument(log); } + /** + * 删除消息日志。 + * + * @param messages 参数 {@code messages}({@code NewsMessage[]}) + */ public void deleteMessageLog(NewsMessage... messages) { } + /** + * 查找日志。 + * + * @param newsUuid 参数 {@code newsUuid}({@code UUID}) + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 处理结果 + */ public MessageLog findLog(UUID newsUuid, UUID userUuid, UUID siteUuid) { MessageLog log = this.messageLogService.findLog(newsUuid, userUuid, siteUuid); return log; } - public List findLogsByUserAndSite(User user, int limit) { + /** + * 查找用户并站点的日志列表。 + * + * @param user 当前用户({@code User}) + * @param limit 数量上限({@code int}) + * @return 消息日志列表,可能为空 + */ + public List findLogsByUserAndSite(User user, int limit) { List log = this.messageLogService.findLog(user.getUuid(), user.getSiteUuid(), limit); return log; } + /** + * 处理recent消息列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document、new DbObject、aggregate。 + * + * @param user 当前用户({@code User}) + * @param limit 数量上限({@code int}) + * @return MongoDB 文档对象 + */ public Document recentMessages(User user, int limit) { List pipeline = Arrays.asList(new Document("$match", new Document("$and", new Document[]{new Document("$or", Arrays.asList(new Document("siteUuid", user.getSiteUuid()), new Document("siteUuid", new Document("$exists", false)))), new Document("reader.$id", user.getUuid())})), new Document("$group", (new Document("_id", (Object)null)).append("unread", new Document("$sum", new Document("$cond", Arrays.asList("$isRead", 0, 1)))).append("uncheck", new Document("$sum", new Document("$cond", Arrays.asList("$isCheck", 0, 1))))), new DbObject("$project", new Document("_id", 0))); Document result = (Document)this.mongoTemplate.aggregate(Aggregations.from(pipeline), MessageLog.class, Document.class).getUniqueMappedResult(); @@ -282,32 +524,86 @@ public class NewsMessageService extends BaseService { return messages; } - public List findUnchecked(User user) { + /** + * 查找Unchecked。 + * + * @param user 当前用户({@code User}) + * @return 消息日志列表,可能为空 + */ + public List findUnchecked(User user) { return null; } - public List findUnreadLogsByUserAndSite(User user) { + /** + * 查找用户并站点的Unread日志列表。 + * + * @param user 当前用户({@code User}) + * @return 消息日志列表,可能为空 + */ + public List findUnreadLogsByUserAndSite(User user) { List log = this.messageLogService.findLogByReadStatus(user.getUuid(), user.getSiteUuid(), false); return log; } + /** + * 设置 {@code messageAsCheck}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Date。 + * + * @param user 当前用户({@code User}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult setMessageAsCheck(User user) { return this.mongoTemplate.updateMulti(Query.query(Criteria.where("reader.$id").is(user.getUuid()).and("isCheck").is(false)), Update.update("isCheck", true).set("checkDate", new Date()), MessageLog.class); } + /** + * 设置 {@code messageAsCheck}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Date。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult setMessageAsCheck(UUID uuid) { return this.mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(uuid)), Update.update("isCheck", true).set("checkDate", new Date()), MessageLog.class); } + /** + * 处理mark全部消息As读取。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti、new Date。 + * + * @param user 当前用户({@code User}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult markAllMessageAsRead(User user, UUID siteUuid) { return this.mongoTemplate.updateMulti(Query.query(Criteria.where("reader.$id").is(user.getUuid()).and("siteUuid").is(siteUuid).and("readDate").exists(false)), Update.update("readDate", new Date()), MessageLog.class); } + /** + * 统计Unread。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Criteria、count。 + * + * @param user 当前用户({@code User}) + * @return 数量/长度 + */ public long countUnread(User user) { Criteria criteria = (new Criteria()).andOperator(new Criteria[]{Criteria.where("reader.$id").is(user.getUuid()), Criteria.where("siteUuid").is(user.getSiteUuid()), Criteria.where("readDate").exists(false)}); return this.mongoTemplate.count(Query.query(criteria), MessageLog.class); } + /** + * 获取HTML。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Context、process。 + * + * @param message 消息内容({@code NewsMessage}) + * @param newsUuid 参数 {@code newsUuid}({@code UUID}) + * @return 字符串结果 + */ public String getHtml(NewsMessage message, UUID newsUuid) { String template = null; if (message == null) { @@ -317,15 +613,20 @@ public class NewsMessageService extends BaseService { if (message != null) { Context context = new Context(); context.setVariable("message", message); - TemplateService var10000 = this.templateService; - String var10001 = message.getCategory(); - template = var10000.getTemplate("noti." + var10001 + "." + message.getForWhat()); + template = this.templateService.getTemplate("noti." + message.getCategory() + "." + message.getForWhat()); template = this.stringTemplateEngine.process(template, context); } return template; } + /** + * 处理maintain消息列表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;由 Spring 调度器按 cron/fixedDelay 触发;包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @Scheduled(cron = "0 20 0 * * *")}、{@code @Async}。 + */ @Scheduled( cron = "0 20 0 * * *" ) @@ -341,6 +642,11 @@ public class NewsMessageService extends BaseService { } } + /** + * 发送Scheduled消息。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:find。 + */ public void sendScheduledMessage() { Date today = DateTime.now().toLocalDate().toDate(); Query query = Query.query(Criteria.where("sendSchedule").is(today)); @@ -353,6 +659,13 @@ public class NewsMessageService extends BaseService { } + /** + * 移除Expired消息列表。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 0 个条件分支、1 个循环;主要调用:find、delete。 + * + * 框架注解:{@code @Async}。 + */ @Async public void removeExpiredMessages() { Date today = LocalDate.now().toDate(); @@ -364,11 +677,19 @@ public class NewsMessageService extends BaseService { } + /** + * 验证Expiring设备Licenses。 + */ private void verifyExpiringDeviceLicenses() { this.expireTrialLicense(); this.verifyExpiringDate(); } + /** + * 过期Trial许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document、new Date、new LocalDate、updateFirst。 + */ private void expireTrialLicense() { List pipeline = Arrays.asList(new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$licenseModel"), 1)))), new Document("$lookup", (new Document("from", "licenseModel")).append("foreignField", "_id").append("localField", "licenseModel.v").append("as", "licenseModel")), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList("$licenseModel", 0)))), new Document("$match", new Document("licenseModel.name", "Trial")), new Document("$match", new Document("expiry", new Document("$gte", new Date()))), new Document("$lookup", (new Document("from", "device")).append("foreignField", "profile.hardware_info.serial_no").append("localField", "deviceSerial").append("as", "device")), new Document("$addFields", new Document("device", new Document("$arrayElemAt", Arrays.asList("$device", 0)))), new Document("$addFields", new Document("device.license", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$device.license"), 1)))), new Document("$match", new Document("$expr", new Document("$ne", Arrays.asList(new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$device.licenseExpiry")), new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$expiry"))))))); AggregateIterable results = this.getCollection(DeviceLicense.class).aggregate(pipeline); @@ -377,6 +698,11 @@ public class NewsMessageService extends BaseService { results.forEach((result) -> this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(result.get("_id"))), Update.update("expiry", expireDate), DeviceLicense.class)); } + /** + * 验证Expiring日期。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new ArrayList、new Document、new Date、updateFirst。 + */ private void verifyExpiringDate() { List pipeline = new ArrayList(Arrays.asList(new Document("$match", new Document("licenseExpiry", new Document("$exists", true))), new Document("$addFields", new Document("license", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$license"), 1)))), new Document("$lookup", (new Document("from", "deviceLicense")).append("foreignField", "_id").append("localField", "license.v").append("as", "deviceLicense")), new Document("$addFields", new Document("deviceLicense", new Document("$arrayElemAt", Arrays.asList("$deviceLicense", 0)))), new Document("$match", new Document("deviceLicense.expiry", new Document("$gte", new Date()))), new Document("$match", new Document("$expr", new Document("$ne", Arrays.asList(new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$deviceLicense.expiry")), new Document("$dateToString", (new Document("format", "%Y-%m-%d")).append("date", "$licenseExpiry")))))))); AggregateIterable results = this.getCollection(Device.class).aggregate(pipeline); @@ -387,6 +713,11 @@ public class NewsMessageService extends BaseService { }); } + /** + * 处理许可证Expiry发送消息。 + * + * 实现要点:涉及邮件发送;主要调用:new LocalDate、new Document。 + */ public void licenseExpirySendMessage() { this.verifyExpiringDeviceLicenses(); Date today = (new LocalDate()).toDate(); @@ -398,6 +729,13 @@ public class NewsMessageService extends BaseService { results.forEach((result) -> this.saveLicenseMessage(result)); } + /** + * 保存许可证消息。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;通过 WebSocket 会话推送消息;包含 16 个条件分支、1 个循环;主要调用:new NewsMessage、new LocalDate、new DbObject、new StringBuilder、save、new Context。 + * + * @param result 参数 {@code result}({@code Document}) + */ public void saveLicenseMessage(Document result) { Document roles = (Document)result.get("roles"); if (roles != null && !roles.isEmpty()) { @@ -509,6 +847,14 @@ public class NewsMessageService extends BaseService { } } + /** + * 保存或更新Install错误。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:new NewsMessage、new LocalDate、new DbObject、new HashSet、save、new JsonObject。 + * + * @param device 设备({@code Device}) + * @param dbProperty 参数 {@code dbProperty}({@code DbObject}) + */ public void saveOrUpdateInstallError(Device device, DbObject dbProperty) { REPORT_ERROR error = REPORT_ERROR.fromValue(dbProperty.getInteger("reason")); UUID fileUuid = UUID.fromString(dbProperty.getString("fileUuid")); @@ -550,6 +896,18 @@ public class NewsMessageService extends BaseService { } + /** + * 发送报表消息。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;通过 WebSocket 会话推送消息;包含 10 个条件分支、0 个循环;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @param report 参数 {@code report}({@code SiteFile}) + * @param success 参数 {@code success}({@code boolean}) + * @param mailMe 参数 {@code mailMe}({@code boolean}) + */ public void sendReportMessage(User user, Site site, String forWhat, SiteFile report, boolean success, boolean mailMe) { if (success && report != null) { NewsMessage message = new NewsMessage(); @@ -604,12 +962,29 @@ public class NewsMessageService extends BaseService { } } + /** + * 查找Install错误消息。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param errorCode 参数 {@code errorCode}({@code REPORT_ERROR}) + * @return 处理结果 + */ public NewsMessage findInstallErrorMessage(UUID fileUuid, REPORT_ERROR errorCode) { Criteria criteria = Criteria.where("category").is(DeviceService.KEY.install_error.name()).and("reference.fileUuid").is(fileUuid).and("reference.errorCode").is(errorCode.getValue()); Query query = Query.query(criteria); return (NewsMessage)this.mongoTemplate.findOne(query, NewsMessage.class); } + /** + * 保存消息日志。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Criteria、find。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + * @param site 站点/企业({@code Site}) + */ private void saveMessageLog(NewsMessage newsMessage, Site site) { Criteria criteria = new Criteria(); criteria.andOperator(new Criteria[]{Criteria.where("enabled").is(true), Criteria.where("sites.siteUuid").is(site.getUuid()), Criteria.where("sites.enabled").is(true)}); @@ -626,6 +1001,13 @@ public class NewsMessageService extends BaseService { }); } + /** + * 设置 {@code globalMessageLog}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Criteria、find。 + * + * @param newsMessage 参数 {@code newsMessage}({@code NewsMessage}) + */ private void setGlobalMessageLog(NewsMessage newsMessage) { String setting = "settings.noti"; String category = newsMessage.getCategory(); @@ -638,7 +1020,17 @@ public class NewsMessageService extends BaseService { sites.forEach((site) -> this.saveMessageLog(newsMessage, site)); } - private Collection getEmailLists(String category, String forWhat, boolean notifyByMail) { + /** + * 获取邮件Lists。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Document、aggregate、new HashMap。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @param notifyByMail 参数 {@code notifyByMail}({@code boolean}) + * @return 用户邮件列表,可能为空 + */ + private Collection getEmailLists(String category, String forWhat, boolean notifyByMail) { String setting = "settings.noti"; String notiKey = "settings.noti." + category + "." + forWhat; Document matchStage = new Document("$match", new Document("$and", Arrays.asList(new Document("enabled", true), notifyByMail ? new Document("settings.noti.sendEmail", true) : new Document(), new Document(notiKey + ".enabled", true), new Document(notiKey + ".roles", (new Document("$exists", true)).append("$ne", new Document()).append("$not", new Document("$size", 0)))))); @@ -663,7 +1055,16 @@ public class NewsMessageService extends BaseService { return mailMap.values(); } - private Collection getAllExtraReceivers(String category, String forWhat) { + /** + * 获取全部ExtraReceivers。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new HashMap、new ArrayList。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @return InternetAddress列表,可能为空 + */ + private Collection getAllExtraReceivers(String category, String forWhat) { String setting = "settings.noti"; String notiKey = "settings.noti." + category + "." + forWhat + ".enabled"; Query query = Query.query(Criteria.where("settings.noti.sendEmail").is(true).and(notiKey).is(true).and("settings.noti.receivers").exists(true)); @@ -679,6 +1080,13 @@ public class NewsMessageService extends BaseService { return new ArrayList(addresses.values()); } + /** + * 调度转换为通知。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:schedule、new Runnable。 + * + * @param message 消息内容({@code NewsMessage}) + */ private void scheduleToNotify(final NewsMessage message) { if (message.getSendSchedule() != null) { this.schedule(new Runnable() { @@ -690,6 +1098,13 @@ public class NewsMessageService extends BaseService { } + /** + * 调度转换为通知。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Date、find。 + * + * 框架注解:{@code @Async}。 + */ @Async public void scheduleToNotify() { Criteria criteria = Criteria.where("enabled").is(true).and("sendSchedule").gt(new Date()); @@ -697,27 +1112,76 @@ public class NewsMessageService extends BaseService { messages.forEach((message) -> this.scheduleToNotify(message)); } + /** + * 【业务服务】{@code SiteUsers} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code roles}(HashMap):字段 roles
  • + *
  • {@code users}(List):用户列表
  • + *
+ * + * 协作对象:{@code HashMap}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ private class SiteUsers { - private HashMap roles; - private List users; + /** + * 字段 roles。 + */ + private HashMap roles; + /** + * 用户列表。 + */ + private List users; - public HashMap getRoles() { + /** + * 获取 {@code roles}。 + * @return 字段/派生属性 {@code roles} 的值 + */ + public HashMap getRoles() { return this.roles; } - public void setRoles(HashMap roles) { + /** + * 设置 {@code roles}。 + * + * @param roles 参数 {@code roles}({@code HashMap}) + */ + public void setRoles(HashMap roles) { this.roles = roles; } - public List getUsers() { + /** + * 获取 {@code users}。 + * @return 用户邮件列表,可能为空 + */ + public List getUsers() { return this.users; } - public void setUsers(List users) { + /** + * 设置 {@code users}。 + * + * @param users 参数 {@code users}({@code List}) + */ + public void setUsers(List users) { this.users = users; } - public List getEmails() { + /** + * 获取 {@code emails}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList。 + * @return 用户邮件列表,可能为空 + */ + public List getEmails() { List mails = new ArrayList(); this.users.forEach((user) -> { if (user.hasRole(this.roles)) { @@ -729,49 +1193,130 @@ public class NewsMessageService extends BaseService { } } + /** + * 【业务服务】{@code UserMail} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code _id}(String):字段 _id
  • + *
  • {@code email}(String):用户邮箱(登录名,建立索引)
  • + *
  • {@code name}(String):名称
  • + *
  • {@code roles}(String[]):字段 roles
  • + *
+ * + * 协作对象:{@code String[]}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ private static class UserMail { + /** + * 字段 _id。 + */ private String _id; + /** + * 用户邮箱(登录名,建立索引)。 + */ private String email; + /** + * 名称。 + */ private String name; + /** + * 字段 roles。 + */ private String[] roles; + /** + * 获取 {@code uuid}。 + * @return UUID + */ public UUID getUuid() { return UUID.fromString(this._id); } + /** + * 获取 {@code id}。 + * @return 字符串结果 + */ public String getId() { return this._id; } + /** + * 设置 {@code id}。 + * + * @param _id 参数 {@code _id}({@code String}) + */ public void setId(String _id) { this._id = _id; } + /** + * 获取 {@code email}。 + * @return 字符串结果 + */ public String getEmail() { return this.email; } + /** + * 设置 {@code email}。 + * + * @param email 邮箱({@code String}) + */ public void setEmail(String email) { this.email = email; } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.name; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.name = name; } + /** + * 获取 {@code roles}。 + * @return 字段/派生属性 {@code roles} 的值 + */ public String[] getRoles() { return this.roles; } + /** + * 设置 {@code roles}。 + * + * @param roles 参数 {@code roles}({@code String[]}) + */ public void setRoles(String[] roles) { this.roles = roles; } - public boolean hasRole(Map roles) { + /** + * 判断是否Role。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param roles 参数 {@code roles}({@code Map}) + * @return 字段/派生属性 {@code role} 的值 + */ + public boolean hasRole(Map roles) { if (this.roles != null && roles != null) { for(String role : this.roles) { if (roles.containsKey(role) && ((Boolean)roles.get(role)).equals(true)) { @@ -783,6 +1328,12 @@ public class NewsMessageService extends BaseService { return false; } + /** + * 处理转换为Address。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new InternetAddress。 + * @return 处理结果 + */ public InternetAddress toAddress() { try { return new InternetAddress(this.email, this.name); @@ -791,6 +1342,10 @@ public class NewsMessageService extends BaseService { } } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return Strings.isNullOrEmpty(this.getName()) ? this.getEmail() : String.format("%s<%s>", this.getName(), this.getEmail()); } diff --git a/src/main/java/com/midm/service/news/package-info.java b/src/main/java/com/midm/service/news/package-info.java new file mode 100644 index 0000000..da72dfe --- /dev/null +++ b/src/main/java/com/midm/service/news/package-info.java @@ -0,0 +1,13 @@ +/** + * 新闻/通知服务:模板渲染、邮件发送、定时通知。 + * + *

本包主要类型: + *

    + *
  • {@link MessageLogService}
  • + *
  • {@link NewsMessageService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.news; diff --git a/src/main/java/com/midm/service/org/SiteLicenseService.java b/src/main/java/com/midm/service/org/SiteLicenseService.java index 4ceb92e..fd30946 100644 --- a/src/main/java/com/midm/service/org/SiteLicenseService.java +++ b/src/main/java/com/midm/service/org/SiteLicenseService.java @@ -54,27 +54,98 @@ import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.support.PageableExecutionUtils; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code SiteLicenseService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code newsMessageService}(NewsMessageService):新闻消息服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code emailService}(EmailService):邮件服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code sessionManager}(WebSocketSessionManager):会话Manager
  • + *
+ * + * 协作对象:{@code SiteService、NewsMessageService、SettingsService、EmailService、UserService、WebSocketSessionManager}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class SiteLicenseService extends BaseService { + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteService siteService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private NewsMessageService newsMessageService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 处理保存。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + * @return 处理结果 + */ public SiteLicense save(SiteLicense license) { if (license.getSite().isChild()) { license.setChildSite(license.getSite().getReseller()); @@ -99,6 +170,16 @@ public class SiteLicenseService extends BaseService { return (SiteLicense)this.saveDocument(license); } + /** + * 添加日志。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:new MidmLog、new Document、save。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + * @param forChild 参数 {@code forChild}({@code boolean}) + * @param activity 参数 {@code activity}({@code String}) + * @param message 消息内容({@code String}) + */ public void addLog(SiteLicense license, boolean forChild, String activity, String message) { MidmLog addLog = new MidmLog(); if (forChild) { @@ -123,11 +204,27 @@ public class SiteLicenseService extends BaseService { this.logService.save(addLog); } + /** + * 获取站点许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param siteLicenseUuid 参数 {@code siteLicenseUuid}({@code UUID}) + * @return 字段/派生属性 {@code siteLicense} 的值 + */ public SiteLicense getSiteLicense(UUID siteLicenseUuid) { SiteLicense license = (SiteLicense)this.mongoTemplate.findById(siteLicenseUuid, SiteLicense.class); return license; } + /** + * 更新站点许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、updateMulti。 + * + * @param site 站点/企业({@code Site}) + * @param targetPlan 参数 {@code targetPlan}({@code String}) + */ public void updateSiteLicense(Site site, String targetPlan) { String siteType = site.isChild() ? "childSite" : "site"; Query query = Query.query(Criteria.where(siteType).is(site).and("status").in(new Object[]{"PROCESSING", "ORDERED"})); @@ -136,6 +233,13 @@ public class SiteLicenseService extends BaseService { this.mongoTemplate.updateMulti(query, update, SiteLicense.class); } + /** + * 根据站点删除void。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:remove、find、new Date、updateMulti、new Criteria。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void deleteBySite(UUID siteUuid) { Criteria siteCriteria = Criteria.where("site.$id").is(siteUuid); this.mongoTemplate.remove(Query.query(siteCriteria), DeviceLicense.class); @@ -151,6 +255,14 @@ public class SiteLicenseService extends BaseService { this.mongoTemplate.remove(Query.query(criteria), SiteLicense.class); } + /** + * 判断是否站点许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param site 站点/企业({@code Site}) + * @return 字段/派生属性 {@code siteLicense} 的值 + */ public boolean hasSiteLicense(Site site) { String key = site.isChild() ? "childSite" : "site"; key = key + ".$id"; @@ -158,13 +270,29 @@ public class SiteLicenseService extends BaseService { return this.mongoTemplate.count(query, SiteLicense.class) > 0L; } - public List getPlans(Site site) { + /** + * 获取Plans。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param site 站点/企业({@code Site}) + * @return ?列表,可能为空 + */ + public List getPlans(Site site) { String key = site.isChild() ? "childSite" : "site"; key = key + ".$id"; Query query = Query.query(Criteria.where(key).is(site.getUuid())); return this.mongoTemplate.findDistinct(query, "plan", DeviceLicense.class, DeviceLicense.class); } + /** + * 获取Valid许可证统计。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param site 站点/企业({@code Site}) + * @return 数量/长度 + */ public int getValidLicenseCount(Site site) { List licenseModels = this.getLicenseModels(site); int validLicenseCount = 0; @@ -176,7 +304,15 @@ public class SiteLicenseService extends BaseService { return validLicenseCount; } - public List getLicenseModels(Site site) { + /** + * 获取许可证Models。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * @param site 站点/企业({@code Site}) + * @return 许可证模型列表,可能为空 + */ + public List getLicenseModels(Site site) { List licenseModels; if (site.isReseller()) { List plans = this.getPlans(site); @@ -192,7 +328,16 @@ public class SiteLicenseService extends BaseService { return licenseModels; } - public List getLicenseModels(Site site, String plan) { + /** + * 获取许可证Models。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new DateTime、new Date、new DBRef、aggregate、new ArrayList。 + * + * @param site 站点/企业({@code Site}) + * @param plan 参数 {@code plan}({@code String}) + * @return 许可证模型列表,可能为空 + */ + public List getLicenseModels(Site site, String plan) { DateTime today = new DateTime(); Date soon = today.plusDays(10).toDate(); Date now = new Date(); @@ -243,6 +388,18 @@ public class SiteLicenseService extends BaseService { return licenseModels; } + /** + * 统计Cond。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:new ArrayList、new Criteria。 + * + * @param site 站点/企业({@code Site}) + * @param deviceExists 参数 {@code deviceExists}({@code Boolean}) + * @param isActivated 参数 {@code isActivated}({@code Boolean}) + * @param from 起始时间({@code Date}) + * @param to 结束时间({@code Date}) + * @return 处理结果 + */ private ConditionalOperators.Cond countCond(Site site, Boolean deviceExists, Boolean isActivated, Date from, Date to) { List conds = new ArrayList(); if (site.isReseller()) { @@ -279,6 +436,16 @@ public class SiteLicenseService extends BaseService { return ConditionalOperators.when((new Criteria()).andOperator(conds)).then(1).otherwise(0); } + /** + * 处理expiredCond。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new ArrayList、new Criteria。 + * + * @param site 站点/企业({@code Site}) + * @param to 结束时间({@code Date}) + * @param isAutoRenew 参数 {@code isAutoRenew}({@code Boolean}) + * @return 处理结果 + */ private ConditionalOperators.Cond expiredCond(Site site, Date to, Boolean isAutoRenew) { List conds = new ArrayList(); if (site.isReseller()) { @@ -294,7 +461,16 @@ public class SiteLicenseService extends BaseService { return ConditionalOperators.when((new Criteria()).andOperator(conds)).then(1).otherwise(0); } - public List getSiteLicenses(UUID siteUuid, UUID licenseModelUuid) { + /** + * 获取站点Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:new SiteLicense、new ArrayList、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @return 站点许可证列表,可能为空 + */ + public List getSiteLicenses(UUID siteUuid, UUID licenseModelUuid) { LicenseModel licenseModel = this.licenseService.findLicenseModelByUuid(licenseModelUuid); if (licenseModel == null) { return null; @@ -315,10 +491,21 @@ public class SiteLicenseService extends BaseService { } } + /** + * 获取 {@code trialLicense}。 + * @return 字段/派生属性 {@code trialLicense} 的值 + */ public LicenseModel getTrialLicense() { return this.licenseService.getTrialLicenseModel(); } + /** + * 处理unsetNull子站点Reference。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:new Query、find、updateMulti、new Update。 + * + * @param site 站点/企业({@code Site}) + */ public void unsetNullChildSiteReference(Site site) { Query query = new Query(); query.addCriteria(Criteria.where("site.$id").is(site.getUuid()).and("childSite").exists(true)); @@ -331,7 +518,21 @@ public class SiteLicenseService extends BaseService { } - public Page find(Site site, boolean isLicensed, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、1 个循环;主要调用:count、find。 + * + * @param site 站点/企业({@code Site}) + * @param isLicensed 参数 {@code isLicensed}({@code boolean}) + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page find(Site site, boolean isLicensed, JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -366,7 +567,19 @@ public class SiteLicenseService extends BaseService { return pageResult; } - public List find(Site site, boolean isLicensed, JsonObject filter, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、2 个循环;主要调用:find、remove。 + * + * @param site 站点/企业({@code Site}) + * @param isLicensed 参数 {@code isLicensed}({@code boolean}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 站点许可证列表,可能为空 + */ + public List find(Site site, boolean isLicensed, JsonObject filter, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -402,6 +615,13 @@ public class SiteLicenseService extends BaseService { return result; } + /** + * 更新报表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Date、count、new Query。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + */ private void updateReport(SiteLicense license) { long fresh = 0L; long active = 0L; @@ -430,6 +650,14 @@ public class SiteLicenseService extends BaseService { license.setReport("expired", expired); } + /** + * 处理许可证查询。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Query。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + * @return 处理结果 + */ private Query licenseQuery(SiteLicense license) { Query query = new Query(); if (license.isForChildSite()) { @@ -441,6 +669,17 @@ public class SiteLicenseService extends BaseService { return query; } + /** + * 处理许可证统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:count。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + * @param deviceExits 参数 {@code deviceExits}({@code boolean}) + * @param isActivated 参数 {@code isActivated}({@code boolean}) + * @param now 参数 {@code now}({@code Date}) + * @return 数量/长度 + */ private Long licenseCount(SiteLicense license, boolean deviceExits, boolean isActivated, Date now) { Query query = this.licenseQuery(license); query.addCriteria(Criteria.where("deviceUuid").exists(deviceExits).and("activatedAt").exists(isActivated)); @@ -451,12 +690,28 @@ public class SiteLicenseService extends BaseService { return this.mongoTemplate.count(query, DeviceLicense.class); } + /** + * 获取Expiring统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document、new Criteria、aggregate。 + * + * @param siteLicenseUuid 参数 {@code siteLicenseUuid}({@code UUID}) + * @param checkDateTime 参数 {@code checkDateTime}({@code Date}) + * @return MongoDB 文档对象 + */ public Document getExpiringCount(UUID siteLicenseUuid, Date checkDateTime) { Document facedOp = new Document("$facet", (new Document("nearestExpired", Arrays.asList(new Document("$match", new Document("_id.expiry", new Document("$lte", checkDateTime))), new Document("$limit", 1), new Document("$addFields", new Document("_id", "$_id.expiry"))))).append("upcomingExpiration", Arrays.asList(new Document("$match", new Document("_id.expiry", new Document("$gt", checkDateTime))), new Document("$sort", new Document("_id.expiry", 1)), new Document("$limit", 1), new Document("$addFields", new Document("_id", "$_id.expiry"))))); Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{Aggregation.match((new Criteria()).andOperator(new Criteria[]{Criteria.where("childSiteLicense.$id").is(siteLicenseUuid)})), Aggregations.newOperation("{$group: {'_id':{expiry:'$expiry'}, 'count':{$sum:1}}}"), Aggregations.newOperation("{$sort:{'_id.expiry':-1}}"), Aggregations.newOperation(facedOp)}).withOptions(Aggregation.newAggregationOptions().collation(LocaleConst.COLLATION_DEFAULT).build()); return (Document)this.mongoTemplate.aggregate(aggregation, DeviceLicense.class, Document.class).getUniqueMappedResult(); } + /** + * 删除站点许可证。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param license 参数 {@code license}({@code SiteLicense}) + */ public void deleteSiteLicense(SiteLicense license) { if (!this.isLicenseUsed(license.getUuid())) { this.deleteById(SiteLicense.class, license.getUuid()); @@ -464,6 +719,13 @@ public class SiteLicenseService extends BaseService { } + /** + * 删除站点许可证。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param licenseUuid 许可证 UUID({@code UUID}) + */ public void deleteSiteLicense(UUID licenseUuid) { if (!this.isLicenseUsed(licenseUuid)) { this.deleteById(SiteLicense.class, licenseUuid); @@ -471,34 +733,86 @@ public class SiteLicenseService extends BaseService { } + /** + * 判断是否任意站点许可证Used。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param modelUuid 参数 {@code modelUuid}({@code UUID}) + * @return 字段/派生属性 {@code anySiteLicenseUsed} 的值 + */ public boolean isAnySiteLicenseUsed(UUID modelUuid) { Query query = Query.query(Criteria.where("licenseModel.$id").is(modelUuid)); return this.mongoTemplate.exists(query, SiteLicense.class); } + /** + * 判断是否许可证Used。 + * + * @param licenseUuid 许可证 UUID({@code UUID}) + * @return 字段/派生属性 {@code licenseUsed} 的值 + */ public boolean isLicenseUsed(UUID licenseUuid) { return true; } + /** + * 判断是否Normal。 + * + * 实现要点:主要调用:new Date。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + * @return 字段/派生属性 {@code normal} 的值 + */ public boolean isNormal(Date expiry) { return expiry.after(new Date()); } + /** + * 判断是否Trial。 + * + * 实现要点:主要调用:new Date、new DateTime。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + * @return 字段/派生属性 {@code trial} 的值 + */ public boolean isTrial(Date expiry) { Date now = new Date(); return expiry.before(now) && (new DateTime(expiry)).plusDays(45).toDate().after(now); } + /** + * 判断是否Locked。 + * + * 实现要点:主要调用:new Date、new DateTime。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + * @return 字段/派生属性 {@code locked} 的值 + */ public boolean isLocked(Date expiry) { Date now = new Date(); return (new DateTime(expiry)).plusDays(45).toDate().before(now) && (new DateTime(expiry)).plusDays(90).toDate().after(now); } + /** + * 处理need转换为移除。 + * + * 实现要点:主要调用:new Date、new DateTime。 + * + * @param expiry 参数 {@code expiry}({@code Date}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean needToRemove(Date expiry) { Date now = new Date(); return (new DateTime(expiry)).plusDays(90).toDate().before(now); } + /** + * 处理touch子Licenses。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、2 个循环;主要调用:find、new Query、count。 + * @return 数量/长度 + */ public int touchChildLicenses() { Query queryDeviceLicense = Query.query(Criteria.where("childSite").exists(true).and("childSiteLicense").exists(false)); List licenses = this.mongoTemplate.find(queryDeviceLicense, DeviceLicense.class); @@ -526,6 +840,13 @@ public class SiteLicenseService extends BaseService { return licenses.size(); } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 3 个条件分支、1 个循环;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param siteLicense 参数 {@code siteLicense}({@code SiteLicense}) + */ public void sendMessageToRecipients(SiteLicense siteLicense) { Site site = siteLicense.getChildSite() != null ? siteLicense.getChildSite() : siteLicense.getSite(); NewsMessage message = new NewsMessage(); @@ -566,6 +887,17 @@ public class SiteLicenseService extends BaseService { } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环。 + * + * @param email 邮箱({@code String}) + * @param message 消息内容({@code NewsMessage}) + * @param plan 参数 {@code plan}({@code String}) + * @param licenseModel 参数 {@code licenseModel}({@code String}) + * @param amount 参数 {@code amount}({@code long}) + */ public void sendMessageToRecipients(String email, NewsMessage message, String plan, String licenseModel, long amount) { if (email != null) { message.getReference().put("plan", plan); @@ -575,6 +907,13 @@ public class SiteLicenseService extends BaseService { } } + /** + * 发送消息。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param siteLicense 参数 {@code siteLicense}({@code SiteLicense}) + */ public void sendMessage(SiteLicense siteLicense) { Site site = siteLicense.getChildSite() != null ? siteLicense.getChildSite() : siteLicense.getSite(); NewsMessage message = new NewsMessage(); @@ -598,6 +937,18 @@ public class SiteLicenseService extends BaseService { users.forEach((user) -> this.sendMessage(user, message, site, plan, licenseModel, amount)); } + /** + * 发送消息。 + * + * 实现要点:涉及邮件发送;通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + * @param message 消息内容({@code NewsMessage}) + * @param site 站点/企业({@code Site}) + * @param plan 参数 {@code plan}({@code String}) + * @param licenseModel 参数 {@code licenseModel}({@code String}) + * @param amount 参数 {@code amount}({@code long}) + */ public void sendMessage(User user, NewsMessage message, Site site, String plan, String licenseModel, long amount) { if (user.getEnabled()) { this.newsMessageService.setMessageLog(message, user, site); diff --git a/src/main/java/com/midm/service/org/SiteService.java b/src/main/java/com/midm/service/org/SiteService.java index 2128635..b2e5c66 100644 --- a/src/main/java/com/midm/service/org/SiteService.java +++ b/src/main/java/com/midm/service/org/SiteService.java @@ -73,49 +73,154 @@ import org.springframework.data.mongodb.core.query.Update; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code SiteService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
+ * + * 协作对象:{@code DeviceService、UserService、ProfileService、FileService、LogService、SettingsService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class SiteService extends BaseService { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private UserService userService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private ProfileService profileService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService hostLicenseService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private LicenseService licenseService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 站点许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private SiteLicenseService siteLicenseService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private CloudStorageService cloudStorageService; - private static Map sites = new HashMap(); + /** + * 用户可访问的站点列表(多租户)。 + */ + private static Map sites = new HashMap(); + /** + * 判断 {@code site}。 + * + * 实现要点:主要调用:count。 + * @return 字段/派生属性 {@code site} 的值 + */ public boolean hasSite() { return this.count(Site.class) > 0L; } + /** + * 处理保存。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site save(Site site) { if (site == null) { return null; @@ -133,7 +238,15 @@ public class SiteService extends BaseService { } } - public void enableSites(List siteUuids, boolean enabled) { + /** + * 启用站点列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateMulti。 + * + * @param siteUuids 参数 {@code siteUuids}({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ + public void enableSites(List siteUuids, boolean enabled) { Query query = Query.query(Criteria.where("_id").in(siteUuids)); Update update = Update.update("enabled", enabled); this.mongoTemplate.updateMulti(query, update, Site.class); @@ -146,6 +259,15 @@ public class SiteService extends BaseService { }); } + /** + * 更新计划。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param plan 参数 {@code plan}({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updatePlan(UUID siteUuid, String plan) { if (Strings.isNullOrEmpty(plan)) { return null; @@ -164,6 +286,15 @@ public class SiteService extends BaseService { } } + /** + * 设置设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:new Update、updateFirst、new Date、updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult setSetting(UUID siteUuid, DbObject settings) { if (settings != null && !settings.isEmpty()) { Query query = Query.query(Criteria.where("_id").is(siteUuid)); @@ -193,6 +324,15 @@ public class SiteService extends BaseService { } } + /** + * 更新配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profile 设备配置档案({@code DbObject}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateProfile(UUID siteUuid, DbObject profile) { if (profile != null && !profile.isEmpty()) { Query query = Query.query(Criteria.where("_id").is(siteUuid)); @@ -205,6 +345,16 @@ public class SiteService extends BaseService { } } + /** + * 设置设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult setSetting(UUID siteUuid, String key, Object value) { Query query = Query.query(Criteria.where("_id").is(siteUuid)); Update update = Update.update("settings." + key, value); @@ -213,6 +363,14 @@ public class SiteService extends BaseService { return result; } + /** + * 更新站点Map。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param result 参数 {@code result}({@code UpdateResult}) + */ private void updateSiteMap(UUID siteUuid, UpdateResult result) { if (result.getModifiedCount() > 0L) { Site site = (Site)this.findById(Site.class, siteUuid); @@ -223,6 +381,16 @@ public class SiteService extends BaseService { } + /** + * 处理查找。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site find(User user, UUID siteUuid, String siteId) { Site site = null; if (siteUuid != null) { @@ -240,6 +408,14 @@ public class SiteService extends BaseService { return site; } + /** + * 根据ID名称查找站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param idName 参数 {@code idName}({@code String}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site findByIdName(String idName) { Query query = Query.query(Criteria.where("idName").is(idName)); Site site = (Site)this.mongoTemplate.findOne(query, Site.class); @@ -250,6 +426,14 @@ public class SiteService extends BaseService { return site; } + /** + * 根据Credential查找站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param credentail 参数 {@code credentail}({@code String}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site findByCredential(String credentail) { Query query = Query.query(Criteria.where("settings.credential.credential").is(credentail)); Site site = (Site)this.mongoTemplate.findOne(query, Site.class); @@ -260,10 +444,25 @@ public class SiteService extends BaseService { return site; } + /** + * 更新Credential。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param credential 参数 {@code credential}({@code DbObject}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateCredential(UUID siteUuid, DbObject credential) { return this.setSetting(siteUuid, "credential", credential); } + /** + * 根据UUID查找站点。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site findByUuid(UUID siteUuid) { Site site = null; if (siteUuid != null) { @@ -280,6 +479,16 @@ public class SiteService extends BaseService { return site; } + /** + * 处理reorganize。 + * + * 实现要点:调用持久化方法保存数据;包含 7 个条件分支、0 个循环;主要调用:save、remove。 + * + * @param id 参数 {@code id}({@code String}) + * @param resellerId 参数 {@code resellerId}({@code String}) + * @param reorganize 参数 {@code reorganize}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean reorganize(String id, String resellerId, String reorganize) { Site site = Strings.isNullOrEmpty(id) ? null : this.findByIdName(id); if (site == null) { @@ -314,6 +523,15 @@ public class SiteService extends BaseService { } } + /** + * 根据模型并用户查找站点。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param model 参数 {@code model}({@code String}) + * @param user 当前用户({@code User}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site findByModelAndUser(String model, User user) { if (!Strings.isNullOrEmpty(model) && user != null) { for(SiteInfo siteInfo : user.getSites()) { @@ -329,6 +547,14 @@ public class SiteService extends BaseService { } } + /** + * 获取Title。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new StringBuilder。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ public String getTitle(UUID siteUuid) { Site site = this.findByUuid(siteUuid); if (site == null) { @@ -345,24 +571,64 @@ public class SiteService extends BaseService { } } + /** + * 处理存在。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(UUID siteUuid) { return sites.containsKey(siteUuid) || this.existsById(Site.class, siteUuid); } + /** + * 处理存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param siteId 参数 {@code siteId}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(String siteId) { return this.mongoTemplate.exists(Query.query(Criteria.where("idName").regex(String.format("^%s$", siteId), "i")), Site.class); } - public List getByPlan(String plan) { + /** + * 根据计划获取列出。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param plan 参数 {@code plan}({@code String}) + * @return 站点列表,可能为空 + */ + public List getByPlan(String plan) { return this.mongoTemplate.find(Query.query(Criteria.where("profile.plan.plan").regex(String.format("^%s$", plan), "i")), Site.class); } + /** + * 判断是否电池计划。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字段/派生属性 {@code batteryPlan} 的值 + */ public boolean hasBatteryPlan(UUID siteUuid) { Site site = this.findByUuid(siteUuid); return site != null ? site.isStandardWithBatteryPro() : false; } - public Page findAdminState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Admin状态。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findAdminState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -402,15 +668,44 @@ public class SiteService extends BaseService { return pageResult; } + /** + * 获取子站点统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 数量/长度 + */ public long getChildSiteCount(UUID siteUuid) { return this.mongoTemplate.count(Query.query(Criteria.where("reseller.$id").is(siteUuid)), Site.class); } - public List getChildSite(UUID siteUuid) { + /** + * 获取子站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 站点列表,可能为空 + */ + public List getChildSite(UUID siteUuid) { return this.mongoTemplate.find(Query.query(Criteria.where("reseller.$id").is(siteUuid)), Site.class); } - public PageImpl findchildState(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { + /** + * 处理findchild状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count、find、new PageImpl。 + * + * @param entityClass 参数 {@code entityClass}({@code Class}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 分页结果 + */ + public PageImpl findchildState(Class entityClass, JsonObject filter, String sortBy, Sort.Direction direction, Integer page, Integer size) { Query query = McMongoUtils.toQuery(filter, sortBy, direction); query.addCriteria(Criteria.where("reseller").exists(true)).with(Sort.by(new String[]{"reseller.$id"})); query.collation(LocaleConst.COLLATION_DEFAULT); @@ -420,7 +715,19 @@ public class SiteService extends BaseService { return new PageImpl(result, pageable, total); } - public Page childState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 处理子状态。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page childState(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { Page pageResult = this.findchildState(Site.class, filter, sortBy, direction, page, size); for(Site childSite : pageResult) { @@ -435,6 +742,12 @@ public class SiteService extends BaseService { return pageResult; } + /** + * 处理总数状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Document、count。 + * @return MongoDB 文档对象 + */ public Document totalState() { Document stateCollection = new Document(); long siteRegister = this.mongoTemplate.count(Query.query(Criteria.where("reseller").exists(false)), Site.class); @@ -455,7 +768,13 @@ public class SiteService extends BaseService { return stateCollection; } - public List getTotalLicenseCount() { + /** + * 获取 {@code totalLicenseCount}。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new Document、new ArrayList。 + * @return Document列表,可能为空 + */ + public List getTotalLicenseCount() { LicenseModel triaLicenseModel = this.licenseService.findLicenseModelByIdName("trial"); List pipeline = Arrays.asList(new Document("$match", new Document("licenseModel.$id", new Document("$ne", triaLicenseModel.getUuid()))), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList(new Document("$objectToArray", "$licenseModel"), 1)))), new Document("$lookup", (new Document("from", "licenseModel")).append("foreignField", "_id").append("localField", "licenseModel.v").append("as", "licenseModel")), new Document("$addFields", new Document("licenseModel", new Document("$arrayElemAt", Arrays.asList("$licenseModel", 0)))), new Document("$group", (new Document("_id", "$licenseModel._id")).append("name", new Document("$first", "$licenseModel.name")).append("idName", new Document("$first", "$licenseModel.idName")).append("count", new Document("$sum", 1)))); List licenseCounts = new ArrayList(); @@ -470,12 +789,30 @@ public class SiteService extends BaseService { return licenseCounts; } + /** + * 判断是否Valid。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字段/派生属性 {@code valid} 的值 + */ public boolean isValid(UUID siteUuid) { Site site = this.findByUuid(siteUuid); return site != null && site.getEnabled(); } - public List findAll(Site site, String model, String plan, String sortBy, boolean updateReport) { + /** + * 查找全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、1 个循环;主要调用:new Criteria、find。 + * + * @param site 站点/企业({@code Site}) + * @param model 参数 {@code model}({@code String}) + * @param plan 参数 {@code plan}({@code String}) + * @param sortBy 排序字段({@code String}) + * @param updateReport 参数 {@code updateReport}({@code boolean}) + * @return 站点列表,可能为空 + */ + public List findAll(Site site, String model, String plan, String sortBy, boolean updateReport) { Criteria criteria = new Criteria(); if (site == null) { criteria.and("reseller").exists(false); @@ -508,11 +845,26 @@ public class SiteService extends BaseService { return sites; } - public List findAllChilds(Site parentSite) { + /** + * 查找全部Childs。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param parentSite 参数 {@code parentSite}({@code Site}) + * @return 站点列表,可能为空 + */ + public List findAllChilds(Site parentSite) { Query query = Query.query(Criteria.where("reseller.$id").is(parentSite.getUuid())); return this.mongoTemplate.find(query, Site.class); } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 3 个条件分支、1 个循环;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param site 站点/企业({@code Site}) + */ public void sendMessageToRecipients(Site site) { NewsMessage message = new NewsMessage(); message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); @@ -552,6 +904,17 @@ public class SiteService extends BaseService { } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环。 + * + * @param email 邮箱({@code String}) + * @param message 消息内容({@code NewsMessage}) + * @param plan 参数 {@code plan}({@code String}) + * @param targetPlan 参数 {@code targetPlan}({@code String}) + * @param requestDate 参数 {@code requestDate}({@code Date}) + */ public void sendMessageToRecipients(String email, NewsMessage message, String plan, String targetPlan, Date requestDate) { if (email != null) { message.getReference().put("plan", plan); @@ -561,6 +924,14 @@ public class SiteService extends BaseService { } } + /** + * 发送消息。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param site 站点/企业({@code Site}) + * @param targetPlan 参数 {@code targetPlan}({@code String}) + */ public void sendMessage(Site site, String targetPlan) { NewsMessage message = new NewsMessage(); message.setExpiry((new DateTime()).plusDays(7).toLocalDate().toDate()); @@ -580,6 +951,17 @@ public class SiteService extends BaseService { users.forEach((user) -> this.sendMessage(user, message, site, site.getShowPlanName(site.getPlanName()), site.getShowPlanName(targetPlan))); } + /** + * 发送消息。 + * + * 实现要点:涉及邮件发送;通过 WebSocket 会话推送消息;包含 2 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + * @param message 消息内容({@code NewsMessage}) + * @param site 站点/企业({@code Site}) + * @param plan 参数 {@code plan}({@code String}) + * @param targetPlan 参数 {@code targetPlan}({@code String}) + */ public void sendMessage(User user, NewsMessage message, Site site, String plan, String targetPlan) { if (user.getEnabled()) { this.newsMessageService.setMessageLog(message, user, site); @@ -593,7 +975,15 @@ public class SiteService extends BaseService { } } - public List getUserSites(User user) { + /** + * 获取用户站点列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、1 个循环;主要调用:new ArrayList、find。 + * + * @param user 当前用户({@code User}) + * @return 站点列表,可能为空 + */ + public List getUserSites(User user) { List siteInfos = user.getSites(); if (siteInfos.size() > 0) { List siteUuids = new ArrayList(); @@ -616,6 +1006,13 @@ public class SiteService extends BaseService { return new ArrayList(); } + /** + * 更新最新Visit。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + */ public void updateLatestVisit(Site site) { Date latestVisit = site.getUpdated(); Device device = this.deviceService.findLastestVisit(site.getUuid()); @@ -626,7 +1023,19 @@ public class SiteService extends BaseService { site.setLatestVisit(latestVisit); } - public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -648,6 +1057,14 @@ public class SiteService extends BaseService { return pageResult; } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:submit、new Runnable、save。 + * + * @param site 站点/企业({@code Site}) + * @param logUser 参数 {@code logUser}({@code User}) + */ public void delete(final Site site, final User logUser) { this.taskExecutor.submit(new Runnable() { public void run() { @@ -663,6 +1080,14 @@ public class SiteService extends BaseService { }); } + /** + * 删除异步。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:remove、delete、new McFile。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param logUser 参数 {@code logUser}({@code User}) + */ public void deleteAsync(UUID siteUuid, User logUser) { this.deleteById(Site.class, siteUuid); sites.remove(siteUuid); @@ -693,10 +1118,27 @@ public class SiteService extends BaseService { } - public boolean canManageRole(Site site, User user, Set roles) { + /** + * 判断是否ManageRole。 + * + * @param site 站点/企业({@code Site}) + * @param user 当前用户({@code User}) + * @param roles 参数 {@code roles}({@code Set}) + * @return 字段/派生属性 {@code manageRole} 的值 + */ + public boolean canManageRole(Site site, User user, Set roles) { return roles.contains("SUPERVISOR") ? this.canManageSupervisor(site, user) : this.canManageUsers(site, user); } + /** + * 判断是否ManageSupervisor。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + * @param user 当前用户({@code User}) + * @return 字段/派生属性 {@code manageSupervisor} 的值 + */ public boolean canManageSupervisor(Site site, User user) { if (site == null) { return false; @@ -713,6 +1155,15 @@ public class SiteService extends BaseService { } } + /** + * 判断是否Manage用户列表。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + * @param user 当前用户({@code User}) + * @return 字段/派生属性 {@code manageUsers} 的值 + */ public boolean canManageUsers(Site site, User user) { if (site == null) { return false; @@ -730,6 +1181,13 @@ public class SiteService extends BaseService { } } + /** + * 更新许可证报表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne、new DateTime。 + * + * @param site 站点/企业({@code Site}) + */ public void updateLicenseReport(Site site) { Criteria criteria = Criteria.where("site.$id").is(site.isChild() ? site.getReseller().getUuid() : site.getUuid()); if (site.isChild()) { @@ -746,6 +1204,13 @@ public class SiteService extends BaseService { site.addReport("hasLicense", licenseModels.size() > 0); } + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date、save。 + * + * @param request HTTP 请求({@code SiteRequest}) + */ public void save(SiteRequest request) { if (request.getUuid() == null) { request.setUuid(UUID.randomUUID()); @@ -758,12 +1223,28 @@ public class SiteService extends BaseService { this.mongoTemplate.save(request); } - public List findUserByRole(Site site, Set roles) { + /** + * 查找Role的用户。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param site 站点/企业({@code Site}) + * @param roles 参数 {@code roles}({@code Set}) + * @return 用户列表,可能为空 + */ + public List findUserByRole(Site site, Set roles) { Criteria criteria = Criteria.where("enabled").is(true).and("sites").elemMatch(Criteria.where("siteUuid").is(site.getUuid()).and("roles").in(roles)); Query query = new Query(criteria); return this.mongoTemplate.find(query, User.class); } + /** + * 清理Orphans。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、2 个循环;主要调用:aggregate、delete、remove。 + * + * 框架注解:{@code @Async}。 + */ @Async public void clearOrphans() { if (!this.hostLicenseService.isStandalone()) { @@ -784,7 +1265,7 @@ public class SiteService extends BaseService { MatchOperation matchOp = Aggregation.match(Criteria.where("sites").size(0)); GroupOperation groupOp = Aggregation.group(new String[]{"$siteUuid"}); Aggregation aggregation = Aggregation.newAggregation(new AggregationOperation[]{lookupOp, matchOp, groupOp}); - Class[] collections = new Class[]{AppFile.class, OtaFile.class, BaseFile.class}; + Class[] collections = new Class[]{AppFile.class, OtaFile.class, BaseFile.class}; for(Class classType : collections) { this.mongoTemplate.remove(Query.query(Criteria.where("siteUuid").exists(false)), classType); diff --git a/src/main/java/com/midm/service/org/UserSecurityService.java b/src/main/java/com/midm/service/org/UserSecurityService.java index 95f30c2..4d7e838 100644 --- a/src/main/java/com/midm/service/org/UserSecurityService.java +++ b/src/main/java/com/midm/service/org/UserSecurityService.java @@ -8,9 +8,39 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; +/** + * 【业务服务】{@code UserSecurityService} + * + * 类职责: + *
    + *
  • 封装可复用的业务逻辑,供 Controller/WebService 调用。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code UserService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ public class UserSecurityService implements UserDetailsService { + /** + * 用户服务。 + */ private UserService userService; + /** + * 加载用户按Username。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList、new SimpleGrantedAuthority、new User、new UsernameNotFoundException。 + * + * @param userName 参数 {@code userName}({@code String}) + * @return 处理结果 + * @throws UsernameNotFoundException 当 UsernameNotFoundException 条件不满足或底层调用失败时抛出。 + */ public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { User user = this.userService.findUserByEmail(userName); if (user != null && user.isAvailable()) { diff --git a/src/main/java/com/midm/service/org/UserService.java b/src/main/java/com/midm/service/org/UserService.java index ead894c..19db59a 100644 --- a/src/main/java/com/midm/service/org/UserService.java +++ b/src/main/java/com/midm/service/org/UserService.java @@ -55,23 +55,85 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code UserService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code passwordEncoder}(PasswordEncoder):字段 passwordEncoder
  • + *
  • {@code emailService}(EmailService):邮件服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
+ * + * 协作对象:{@code SiteService、PasswordEncoder、EmailService、SettingsService、LogService、DeviceService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class UserService extends BaseService { + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 字段 passwordEncoder;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private PasswordEncoder passwordEncoder; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private EmailService emailService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 判断是否存在用户。 + */ private static boolean hasUser = false; + /** + * 判断 {@code user}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:count。 + * @return 字段/派生属性 {@code user} 的值 + */ public boolean hasUser() { if (!hasUser) { hasUser = this.count(User.class) > 0L; @@ -80,6 +142,14 @@ public class UserService extends BaseService { return hasUser; } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + * @return 用户对象;未找到时返回 {@code null} + */ public User save(User user) { if (user != null && !Strings.isNullOrEmpty(user.getEmail())) { user.setUpdated(); @@ -90,12 +160,29 @@ public class UserService extends BaseService { } } - public void enableUsers(UUID siteUuid, List userUuids, boolean enabled) { + /** + * 启用用户列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param userUuids 参数 {@code userUuids}({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + */ + public void enableUsers(UUID siteUuid, List userUuids, boolean enabled) { Query query = Query.query(Criteria.where("_id").in(userUuids).and("sites.siteUuid").is(siteUuid)); Update update = Update.update("sites.$.enabled", enabled); this.mongoTemplate.updateMulti(query, update, User.class); } + /** + * 保存用户列表。 + * + * 实现要点:调用持久化方法保存数据;包含 0 个条件分支、1 个循环;主要调用:new ArrayList、save。 + * + * @param users 参数 {@code users}({@code List}) + * @return 用户列表,可能为空 + */ public List saveUsers(List users) { List savedUsers = new ArrayList(); @@ -107,6 +194,15 @@ public class UserService extends BaseService { return savedUsers; } + /** + * 处理changePassword。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Date、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param newPassword 参数 {@code newPassword}({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult changePassword(User user, String newPassword) { user.setPassword(this.passwordEncoder.encode(newPassword)); Update update = Update.update("password", user.getPassword()).set("updated", new Date()); @@ -115,6 +211,16 @@ public class UserService extends BaseService { return result; } + /** + * 处理注册。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;包含 1 个条件分支、0 个循环;主要调用:count、save、new Date。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param user 当前用户({@code User}) + * @return 用户对象;未找到时返回 {@code null} + */ public User register(HttpServletRequest request, HttpServletResponse response, User user) { String password = user.getPassword(); user.init(); @@ -129,27 +235,70 @@ public class UserService extends BaseService { return user; } + /** + * 处理请求重置Password。 + * + * 实现要点:涉及邮件发送;主要调用:new UserToken。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param user 当前用户({@code User}) + */ public void requestResetPassword(HttpServletRequest request, HttpServletResponse response, User user) { UserToken token = new UserToken(user, 'P', 1800000L); token = (UserToken)this.saveDocument(token); this.emailService.sendPasswordResetRequest(request, response, user, token.getTokenUuid()); } + /** + * 处理存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param account 参数 {@code account}({@code User}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(User account) { Query query = Query.query(Criteria.where("email").is(account.getEmail())); return this.mongoTemplate.count(query, User.class) > 0L; } + /** + * 保存站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult saveSite(User user) { Update update = Update.update("sites", user.getSites()); return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); } + /** + * 添加站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param siteInfo 参数 {@code siteInfo}({@code SiteInfo}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult addSite(User user, SiteInfo siteInfo) { Update update = (new Update()).push("sites", siteInfo); return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); } + /** + * 删除站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Criteria、new Update、new Document、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult deleteSite(User user, UUID siteUuid) { if (siteUuid == null) { return null; @@ -165,6 +314,16 @@ public class UserService extends BaseService { } } + /** + * 处理激活。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param base64Token 参数 {@code base64Token}({@code String}) + * @return 用户对象;未找到时返回 {@code null} + */ public User activate(HttpServletRequest request, HttpServletResponse response, String base64Token) { User user = null; UUID tokenUuid = McUuidUtils.toUuidFromBase64(base64Token); @@ -180,16 +339,42 @@ public class UserService extends BaseService { return user; } + /** + * 处理激活。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Date、updateFirst。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean activate(UUID userUuid) { Update update = Update.update("activated", new Date()).set("enabled", true); return this.mongoTemplate.updateFirst(this.queryById(userUuid), update, User.class).getModifiedCount() > 0L; } + /** + * 处理启用。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param enable 参数 {@code enable}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean enable(UUID userUuid, boolean enable) { Update update = Update.update("enabled", enable); return this.mongoTemplate.updateFirst(this.queryById(userUuid), update, User.class).getModifiedCount() > 0L; } + /** + * 处理switch站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateFirst。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean switchSite(UUID userUuid, UUID siteUuid) { Update update = new Update(); if (siteUuid == null) { @@ -202,7 +387,17 @@ public class UserService extends BaseService { return result.getModifiedCount() > 0L; } - public long changeGroupByUuid(UUID siteUuid, UUID groupUuid, Collection users) { + /** + * 处理change分组按UUID。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param users 参数 {@code users}({@code Collection}) + * @return 数量/长度 + */ + public long changeGroupByUuid(UUID siteUuid, UUID groupUuid, Collection users) { Criteria criteria = Criteria.where("sites.siteUuid").is(siteUuid).and("_id").in(users); Query query = Query.query(criteria); Update update = new Update(); @@ -215,7 +410,17 @@ public class UserService extends BaseService { return this.mongoTemplate.updateMulti(query, update, User.class).getModifiedCount(); } - public long changeGroupByEmail(UUID siteUuid, UUID groupUuid, Collection emails) { + /** + * 处理change分组按邮件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateMulti。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param emails 参数 {@code emails}({@code Collection}) + * @return 数量/长度 + */ + public long changeGroupByEmail(UUID siteUuid, UUID groupUuid, Collection emails) { Criteria criteria = Criteria.where("sites.siteUuid").is(siteUuid).and("email").in(emails); Query query = Query.query(criteria); Update update = new Update(); @@ -228,6 +433,15 @@ public class UserService extends BaseService { return this.mongoTemplate.updateMulti(query, update, User.class).getModifiedCount(); } + /** + * 处理change语言区域。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Date、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param locale 参数 {@code locale}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean changeLocale(User user, String locale) { if (user.isSameLocale(locale)) { return true; @@ -243,12 +457,31 @@ public class UserService extends BaseService { } } + /** + * 设置设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult setSetting(User user, String key, String value) { Update update = Update.update("settings." + key, value); UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); return result; } + /** + * 设置最后分页。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:new Date、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param lastPage 参数 {@code lastPage}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setLastPage(User user, String lastPage) { Criteria criteria = Criteria.where("_id").is(user.getUuid()); Update update = Update.update("updated", new Date()); @@ -274,6 +507,16 @@ public class UserService extends BaseService { return result.getModifiedCount() > 0L; } + /** + * 设置站点设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Date、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSiteSetting(User user, String key, Object value) { Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(user.getSiteUuid()); Update update = Update.update("sites.$.settings." + key, value).set("updated", new Date()); @@ -281,18 +524,50 @@ public class UserService extends BaseService { return result.getModifiedCount() > 0L; } + /** + * 设置分页设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @param url 参数 {@code url}({@code String}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setPageSetting(User user, String url, DbObject settings) { Update update = Update.update("settings.page." + url, settings); UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); return result.getModifiedCount() > 0L; } + /** + * 设置分页设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @param url 参数 {@code url}({@code String}) + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setPageSetting(User user, String url, String key, String value) { Update update = Update.update("settings.page." + url + "." + key, value); UpdateResult result = this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); return result.getModifiedCount() > 0L; } + /** + * 设置站点分页设置。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param url 参数 {@code url}({@code String}) + * @param settings 参数 {@code settings}({@code Document}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSitePageSetting(User user, UUID siteUuid, String url, Document settings) { Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(siteUuid); Update update = Update.update("sites.$.settings.page." + url, settings); @@ -306,25 +581,64 @@ public class UserService extends BaseService { return result.getModifiedCount() > 0L; } + /** + * 查找用户UUID的用户。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUserByUserUuid(UUID userUuid) { return userUuid == null ? null : (User)this.findById(User.class, userUuid); } + /** + * 查找用户UUID的用户配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUserProfileByUserUuid(UUID userUuid) { Query query = this.queryById(userUuid); query.fields().include("email").include("profile"); return (User)this.mongoTemplate.findOne(query, User.class); } + /** + * 存在按邮件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param email 邮箱({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean existsByEmail(String email) { Query query = Query.query(Criteria.where("email").regex(email, "i")); return this.mongoTemplate.exists(query, User.class); } + /** + * 查找邮件的用户。 + * + * @param email 邮箱({@code String}) + * @param fields 参数 {@code fields}({@code String[]}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUserByEmail(String email, String... fields) { return this.findUserByEmail((UUID)null, email, fields); } + /** + * 查找邮件的用户。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 9 个条件分支、2 个循环;主要调用:findOne、exists、remove、save。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @param fields 参数 {@code fields}({@code String[]}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUserByEmail(UUID siteUuid, String email, String... fields) { Criteria criteria = Criteria.where("email").is(email); if (siteUuid != null) { @@ -377,6 +691,14 @@ public class UserService extends BaseService { return user; } + /** + * 查找LastestVisitor。 + * + * 实现要点:主要调用:new JsonObject、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findLastestVisitor(UUID siteUuid) { JsonObject jFilter = new JsonObject(); jFilter.addProperty("sites.siteUuid", siteUuid.toString()); @@ -385,6 +707,15 @@ public class UserService extends BaseService { return users.isEmpty() ? null : (User)users.get(0); } + /** + * 处理matchPassword。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + * @param password 密码({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean matchPassword(User user, String password) { if (!Strings.isNullOrEmpty(user.getPassword()) && !Strings.isNullOrEmpty(password)) { return this.passwordEncoder.matches(password, user.getPassword()) || user.getPassword().equals(password); @@ -393,10 +724,24 @@ public class UserService extends BaseService { } } + /** + * 编码Password。 + * + * @param user 当前用户({@code User}) + */ public void encodePassword(User user) { user.encodePassword(this.passwordEncoder); } + /** + * 查找用户。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @return 用户对象;未找到时返回 {@code null} + */ public User findUser(UUID userUuid, String email) { User user = null; if (userUuid != null) { @@ -410,7 +755,20 @@ public class UserService extends BaseService { return user; } - public Page findUsers(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { + /** + * 查找用户列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、1 个循环;主要调用:new JsonObject、new Query、count、find、new PageImpl。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @return 分页结果 + */ + public Page findUsers(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = "asc"; @@ -440,7 +798,17 @@ public class UserService extends BaseService { return pageResult; } - public UpdateResult updateSystemRoles(String command, String role, List uuids) { + /** + * 更新系统Roles。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateMulti。 + * + * @param command 参数 {@code command}({@code String}) + * @param role 参数 {@code role}({@code String}) + * @param uuids UUID 集合({@code List}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult updateSystemRoles(String command, String role, List uuids) { Criteria criteria = Criteria.where("_id").in(uuids); Update update = new Update(); if (command.equals("remove")) { @@ -454,7 +822,18 @@ public class UserService extends BaseService { return this.mongoTemplate.updateMulti(Query.query(criteria), update, User.class); } - public UpdateResult updateRoles(User user, UUID siteUuid, Set roles, Boolean apiOnly) { + /** + * 更新Roles。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param roles 参数 {@code roles}({@code Set}) + * @param apiOnly 参数 {@code apiOnly}({@code Boolean}) + * @return MongoDB 更新结果(匹配数/修改数) + */ + public UpdateResult updateRoles(User user, UUID siteUuid, Set roles, Boolean apiOnly) { Criteria criteria = Criteria.where("_id").is(user.getUuid()).and("sites.siteUuid").is(siteUuid); Update update = Update.update("sites.$.roles", roles).unset("sites.$.settings.lastPage"); if (apiOnly != null) { @@ -464,24 +843,61 @@ public class UserService extends BaseService { return this.mongoTemplate.updateFirst(Query.query(criteria), update, User.class); } - public List findUsersBySite(UUID siteUuid) { + /** + * 查找站点的用户列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户列表,可能为空 + */ + public List findUsersBySite(UUID siteUuid) { Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); return this.mongoTemplate.find(query, User.class); } - public List findSupervisors(UUID siteUuid) { + /** + * 查找Supervisors。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户列表,可能为空 + */ + public List findSupervisors(UUID siteUuid) { Query query = new Query(); query.addCriteria(Criteria.where("sites").elemMatch(Criteria.where("siteUuid").is(siteUuid).and("roles").is("SUPERVISOR"))); return this.mongoTemplate.find(query, User.class); } + /** + * 统计Supervisor。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 数量/长度 + */ public long countSupervisor(UUID siteUuid) { Query query = new Query(); query.addCriteria(Criteria.where("sites").elemMatch(Criteria.where("siteUuid").is(siteUuid).and("roles").is("SUPERVISOR"))); return this.mongoTemplate.count(query, User.class); } - public Page findSupervisors(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { + /** + * 查找Supervisors。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:new Query、count、find、new PageImpl。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @return 分页结果 + */ + public Page findSupervisors(UUID siteUuid, String filter, Integer page, Integer size, String sortBy, String direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = "asc"; @@ -506,22 +922,52 @@ public class UserService extends BaseService { return pageResult; } - public List findSystemAdmin() { + /** + * 查找系统Admin。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、find。 + * @return 用户列表,可能为空 + */ + public List findSystemAdmin() { Criteria criteria = Criteria.where("systemRoles").is("SYSTEM_ADMIN").and("isEnabled").is(true); Query query = new Query(criteria); return this.mongoTemplate.find(query, User.class); } + /** + * 获取用户统计。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 数量/长度 + */ public long getUserCount(UUID siteUuid) { Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); return this.mongoTemplate.count(query, User.class); } - public List findUser(UUID siteUuid) { + /** + * 查找用户。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户列表,可能为空 + */ + public List findUser(UUID siteUuid) { Query query = Query.query(Criteria.where("sites.siteUuid").is(siteUuid)); return this.mongoTemplate.find(query, User.class); } + /** + * 更新登录Attempt。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateFirst。 + * + * @param user 当前用户({@code User}) + * @param succeed 参数 {@code succeed}({@code boolean}) + */ public void updateLoginAttempt(User user, boolean succeed) { Criteria criteria = Criteria.where("_id").is(user.getUuid()); Update update; @@ -536,6 +982,13 @@ public class UserService extends BaseService { this.mongoTemplate.updateFirst(Query.query(criteria), update, user.getClass()); } + /** + * 删除用户。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。 + * + * @param userUuid 用户 UUID({@code UUID}) + */ public void deleteUser(UUID userUuid) { if (userUuid != null) { this.deleteTokenByUser(userUuid); @@ -547,12 +1000,26 @@ public class UserService extends BaseService { } } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param user 当前用户({@code User}) + */ public void delete(User user) { if (user != null && user.getUuid() != null) { this.deleteUser(user.getUuid()); } } + /** + * 删除邮件的用户。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param email 邮箱({@code String}) + */ public void deleteUserByEmail(String email) { User user = this.findUserByEmail(email); if (user != null) { @@ -561,16 +1028,38 @@ public class UserService extends BaseService { } + /** + * 处理更新。 + * + * @param user 当前用户({@code User}) + * @return 用户对象;未找到时返回 {@code null} + */ public User update(User user) { User existingUser = (User)this.findById(User.class, user.getUuid()); return existingUser == null ? null : (User)this.saveDocument(user); } + /** + * 更新配置档案。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:updateFirst。 + * + * @param user 当前用户({@code User}) + * @return MongoDB 更新结果(匹配数/修改数) + */ public UpdateResult updateProfile(User user) { Update update = Update.update("profile", user.getProfile()); return this.mongoTemplate.updateFirst(this.queryById(user.getUuid()), update, User.class); } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param token 令牌({@code UserToken}) + * @return 处理结果 + */ public UserToken save(UserToken token) { if (token.getTokenType() != 'D') { this.deleteTokenByType(token); @@ -581,12 +1070,29 @@ public class UserService extends BaseService { return (UserToken)this.saveDocument(token); } + /** + * 处理renew。 + * + * 实现要点:主要调用:delete。 + * + * @param token 令牌({@code UserToken}) + * @return 处理结果 + */ public UserToken renew(UserToken token) { this.delete(token); token.renew(); return (UserToken)this.saveDocument(token); } + /** + * 查找令牌。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param user 当前用户({@code User}) + * @param tokenType 参数 {@code tokenType}({@code Character}) + * @return 处理结果 + */ public UserToken findToken(User user, Character tokenType) { if (user != null && user.getUuid() != null && tokenType != null) { Query query = Query.query(Criteria.where("userUuid").is(user.getUuid()).and("tokenType").is(tokenType)); @@ -596,6 +1102,14 @@ public class UserService extends BaseService { } } + /** + * 查找令牌。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * @param tokenUuid 参数 {@code tokenUuid}({@code UUID}) + * @return 处理结果 + */ public UserToken findToken(UUID tokenUuid) { UserToken token = tokenUuid == null ? null : (UserToken)this.findById(UserToken.class, tokenUuid); if (token != null && token.isExpired()) { @@ -606,11 +1120,24 @@ public class UserService extends BaseService { return token; } + /** + * 查找令牌。 + * + * @param tokenBase64 参数 {@code tokenBase64}({@code String}) + * @return 处理结果 + */ public UserToken findToken(String tokenBase64) { UUID tokenUuid = McUuidUtils.toUuidFromBase64(tokenBase64); return tokenUuid == null ? null : (UserToken)this.findById(UserToken.class, tokenUuid); } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param token 令牌({@code UserToken}) + */ public void delete(UserToken token) { if (token != null) { this.deleteById(UserToken.class, token.getTokenUuid()); @@ -618,33 +1145,79 @@ public class UserService extends BaseService { } + /** + * 删除类型的令牌。 + * + * @param token 令牌({@code UserToken}) + */ public void deleteTokenByType(UserToken token) { this.deleteToken(token.getUserUuid(), token.getTokenType()); } + /** + * 删除用户的令牌。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param userUuid 用户 UUID({@code UUID}) + */ public void deleteTokenByUser(UUID userUuid) { Query query = Query.query(Criteria.where("userUuid").is(userUuid)); this.mongoTemplate.remove(query, UserToken.class); } + /** + * 删除登录令牌。 + * + * @param user 当前用户({@code User}) + */ public void deleteLoginToken(User user) { this.deleteToken(user, 'L'); } + /** + * 删除令牌。 + * + * @param user 当前用户({@code User}) + * @param tokenType 参数 {@code tokenType}({@code char}) + */ public void deleteToken(User user, char tokenType) { this.deleteToken(user.getUuid(), tokenType); } + /** + * 删除令牌。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param userUuid 用户 UUID({@code UUID}) + * @param tokenType 参数 {@code tokenType}({@code char}) + */ public void deleteToken(UUID userUuid, char tokenType) { Query query = Query.query(Criteria.where("userUuid").is(userUuid).and("tokenType").is(tokenType)); this.mongoTemplate.remove(query, UserToken.class); } + /** + * 删除设备Access令牌。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param token 令牌({@code UserToken}) + */ public void deleteDeviceAccessToken(UserToken token) { Query query = Query.query(Criteria.where("reference.deviceUuid").is(token.getDeviceUuid()).and("tokenType").is(token.getTokenType())); this.mongoTemplate.remove(query, UserToken.class); } + /** + * 授权登录。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:new UserToken、new UsernamePasswordAuthenticationToken、new UserPrincipal、save。 + * + * @param user 当前用户({@code User}) + * @return 处理结果 + */ public Authentication authorizeLogin(User user) { UserToken token = new UserToken(user, 'L', 604800000L); token.encryptToken(); @@ -661,6 +1234,14 @@ public class UserService extends BaseService { return authentication; } + /** + * 更新Authorized用户。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new UsernamePasswordAuthenticationToken、new UserPrincipal。 + * + * @param user 当前用户({@code User}) + * @return 处理结果 + */ public Authentication updateAuthorizedUser(User user) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserToken token = this.findToken(user, 'L'); @@ -673,6 +1254,14 @@ public class UserService extends BaseService { } } + /** + * 授权登录。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * @param tokenUuid 参数 {@code tokenUuid}({@code UUID}) + * @return 处理结果 + */ public Authentication authorizeLogin(UUID tokenUuid) { UserToken token = this.findToken(tokenUuid); if (token == null) { @@ -687,6 +1276,15 @@ public class UserService extends BaseService { } } + /** + * 处理authorized用户。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:delete。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 用户对象;未找到时返回 {@code null} + */ public User authorizedUser(Authentication authentication, String accessToken) { User user = UserPrincipal.getUser(authentication); if (user == null && !Strings.isNullOrEmpty(accessToken) && accessToken.startsWith("Bearer")) { @@ -707,6 +1305,14 @@ public class UserService extends BaseService { return user; } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param group 分组对象({@code UserGroup}) + * @return 处理结果 + */ public UserGroup save(UserGroup group) { if (group.getUuid() == null) { group.init(); @@ -715,10 +1321,25 @@ public class UserService extends BaseService { return (UserGroup)this.saveDocument(group); } + /** + * 查找用户分组。 + * + * @param groupUuid 分组 UUID({@code UUID}) + * @return 处理结果 + */ public UserGroup findUserGroup(UUID groupUuid) { return groupUuid == null ? null : (UserGroup)this.findById(UserGroup.class, groupUuid); } + /** + * 查找用户分组。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save、new UserGroup。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param path 参数 {@code path}({@code String}) + * @return 处理结果 + */ public UserGroup findUserGroup(UUID siteUuid, String path) { if (McStringUtils.isNullOrEmpty(path)) { return null; @@ -739,7 +1360,16 @@ public class UserService extends BaseService { } } - public List findUserGroupByName(UUID siteUuid, String name) { + /** + * 查找名称的用户分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @return 用户分组列表,可能为空 + */ + public List findUserGroupByName(UUID siteUuid, String name) { if (siteUuid == null) { return null; } else { @@ -751,6 +1381,16 @@ public class UserService extends BaseService { } } + /** + * 查找用户分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param parent 参数 {@code parent}({@code UserGroup}) + * @param childName 参数 {@code childName}({@code String}) + * @return 处理结果 + */ private UserGroup findUserGroup(UUID siteUuid, UserGroup parent, String childName) { if (siteUuid == null) { return null; @@ -766,7 +1406,15 @@ public class UserService extends BaseService { } } - public List findAllUserGroups(UUID siteUuid) { + /** + * 查找全部用户分组列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:find、count。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户分组列表,可能为空 + */ + public List findAllUserGroups(UUID siteUuid) { Sort sort = Sort.by(new String[]{"parentUuid"}).and(Sort.by(new String[]{"order"})).and(Sort.by(new String[]{"profile.name"})); Query queryBySite = Query.query(Criteria.where("siteUuid").is(siteUuid)); queryBySite.with(sort); @@ -784,7 +1432,19 @@ public class UserService extends BaseService { return groups; } - public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找用户分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findUserGroup(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "profile.name"; direction = Direction.ASC; @@ -794,6 +1454,13 @@ public class UserService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:find、delete、new Update、updateMulti。 + * + * @param group 分组对象({@code UserGroup}) + */ public void delete(UserGroup group) { if (group != null && group.getUuid() != null) { Query queryByParent = Query.query(Criteria.where("parentUuid").is(group.getUuid())); @@ -809,16 +1476,38 @@ public class UserService extends BaseService { } } + /** + * 删除站点UUID的用户分组。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return MongoDB 删除结果(删除数) + */ public DeleteResult deleteUserGroupBySiteUuid(UUID siteUuid) { Query query = Query.query(Criteria.where("siteUuid").is(siteUuid)); return this.mongoTemplate.remove(query, UserGroup.class); } + /** + * 清理ExpiredTokens。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove、new Date。 + * + * 框架注解:{@code @Async}。 + */ @Async public void clearExpiredTokens() { this.mongoTemplate.remove(Query.query(Criteria.where("expired").lt(new Date())), UserToken.class); } + /** + * 更新用户名称If非存在。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、1 个循环;主要调用:find、updateFirst、remove。 + * + * 框架注解:{@code @Async}。 + */ @Async public void updateUserNameIfNotExists() { Query query = Query.query(Criteria.where("profile.name").exists(false)); diff --git a/src/main/java/com/midm/service/org/package-info.java b/src/main/java/com/midm/service/org/package-info.java new file mode 100644 index 0000000..a01b973 --- /dev/null +++ b/src/main/java/com/midm/service/org/package-info.java @@ -0,0 +1,15 @@ +/** + * 组织架构服务:站点、用户、用户组、License。 + * + *

本包主要类型: + *

    + *
  • {@link SiteLicenseService}
  • + *
  • {@link SiteService}
  • + *
  • {@link UserSecurityService}
  • + *
  • {@link UserService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.org; diff --git a/src/main/java/com/midm/service/package-info.java b/src/main/java/com/midm/service/package-info.java new file mode 100644 index 0000000..951366c --- /dev/null +++ b/src/main/java/com/midm/service/package-info.java @@ -0,0 +1,18 @@ +/** + * 业务服务根包:Mongo 通用 CRUD、聚合、异步任务基类。 + * + *

本包主要类型: + *

    + *
  • {@link Aggregations}
  • + *
  • {@link BaseService}
  • + *
  • {@link EmailService}
  • + *
  • {@link EmailTemplateResolver}
  • + *
  • {@link ExternalApiService}
  • + *
  • {@link GeneralService}
  • + *
  • {@link ScheduledTaskService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service; diff --git a/src/main/java/com/midm/service/store/KeyStoreService.java b/src/main/java/com/midm/service/store/KeyStoreService.java index a0733de..05f4d33 100644 --- a/src/main/java/com/midm/service/store/KeyStoreService.java +++ b/src/main/java/com/midm/service/store/KeyStoreService.java @@ -17,12 +17,47 @@ import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code KeyStoreService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
+ * + * 协作对象:{@code SettingsService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class KeyStoreService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; - public Page findKeys(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Keys。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findKeys(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "id"; direction = Direction.ASC; @@ -32,24 +67,55 @@ public class KeyStoreService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理保存。 + * + * @param key 键/配置项({@code KeyStore}) + * @return 处理结果 + */ public KeyStore save(KeyStore key) { return (KeyStore)this.saveDocument(key); } + /** + * 处理查找。 + * + * @param id 参数 {@code id}({@code String}) + * @return 处理结果 + */ public KeyStore find(String id) { return (KeyStore)this.findById(KeyStore.class, id); } + /** + * 处理删除。 + * + * 实现要点:主要调用:new McFile。 + * + * @param id 参数 {@code id}({@code String}) + */ public void delete(String id) { this.deleteById(KeyStore.class, id); String targetFilePath = this.getFilePath(id); (new McFile(targetFilePath)).delete(); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return 密钥Store列表,可能为空 + */ + public List findAll() { return this.findAll(KeyStore.class); } + /** + * 获取文件路径。 + * + * @param id 参数 {@code id}({@code String}) + * @return 字符串结果 + */ public String getFilePath(String id) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "keyStore", new Object[]{id}); } diff --git a/src/main/java/com/midm/service/store/StoreAppService.java b/src/main/java/com/midm/service/store/StoreAppService.java index a88cc3f..db69902 100644 --- a/src/main/java/com/midm/service/store/StoreAppService.java +++ b/src/main/java/com/midm/service/store/StoreAppService.java @@ -44,17 +44,61 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code StoreAppService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code SettingsService、FileService、CloudStorageService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class StoreAppService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理保存。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find、new Date。 + * + * @param app 参数 {@code app}({@code StoreApp}) + * @param oldPackageName 参数 {@code oldPackageName}({@code String}) + * @return 处理结果 + */ public StoreApp save(StoreApp app, String oldPackageName) { if (oldPackageName != null) { this.deleteById(StoreApp.class, oldPackageName); @@ -70,21 +114,51 @@ public class StoreAppService extends BaseService { return (StoreApp)this.saveDocument(app); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return Store应用列表,可能为空 + */ + public List findAll() { return this.findAll(StoreApp.class); } - public List findAll(int minSdkVersion) { + /** + * 查找全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document、aggregate。 + * + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @return 应用信息列表,可能为空 + */ + public List findAll(int minSdkVersion) { List pipeline = Arrays.asList(new Document("$match", new Document("appInfo.minSdkVersion", new Document("$lte", minSdkVersion))), new Document("$sort", new Document("appInfo.versionCode", 1)), new Document("$group", (new Document("_id", "$appInfo.packageName")).append("appInfo", new Document("$last", "$appInfo"))), new Document("$project", (new Document("_id", 0)).append("packageName", "$appInfo.packageName").append("label", "$appInfo.label").append("minSdkVersion", "$appInfo.minSdkVersion").append("versionCode", "$appInfo.versionCode").append("versionName", "$appInfo.versionName"))); List apps = this.mongoTemplate.aggregate(Aggregations.from(pipeline), StoreAppFile.class, AppInfo.class).getMappedResults(); return apps; } - public List getSdkVersions(String packageName) { + /** + * 获取SDKVersions。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return Integer列表,可能为空 + */ + public List getSdkVersions(String packageName) { Query query = Query.query(Criteria.where("_id.packageName").is(packageName)); return this.mongoTemplate.findDistinct(query, "minSdkVersion", AppReleaseNote.class, Integer.class); } + /** + * 处理查找。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return 处理结果 + */ public StoreApp find(String packageName) { StoreApp app = (StoreApp)this.findById(StoreApp.class, packageName); if (app != null) { @@ -94,10 +168,27 @@ public class StoreAppService extends BaseService { return app; } + /** + * 查找应用文件。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 处理结果 + */ public StoreAppFile findAppFile(UUID fileUuid) { return (StoreAppFile)this.findById(StoreAppFile.class, fileUuid); } + /** + * 查找最新应用文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:findOne。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param sdkVersion 参数 {@code sdkVersion}({@code int}) + * @param certMd5 参数 {@code certMd5}({@code String}) + * @return 处理结果 + */ public StoreAppFile findLatestAppFile(String packageName, int versionCode, int sdkVersion, String certMd5) { Criteria criteria = Criteria.where("appInfo.packageName").is(packageName); if (sdkVersion > 0) { @@ -117,6 +208,16 @@ public class StoreAppService extends BaseService { return (StoreAppFile)this.mongoTemplate.findOne(query, StoreAppFile.class); } + /** + * 查找应用文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code long}) + * @param certMd5 参数 {@code certMd5}({@code String}) + * @return 处理结果 + */ public StoreAppFile findAppFile(String packageName, long versionCode, String certMd5) { Criteria criteria = Criteria.where("appInfo.packageName").is(packageName).and("appInfo.certMd5").is(certMd5); Query query = Query.query(criteria); @@ -129,10 +230,23 @@ public class StoreAppService extends BaseService { return (StoreAppFile)this.mongoTemplate.findOne(query, StoreAppFile.class); } + /** + * 查找应用文件。 + * + * @param file 文件({@code StoreAppFile}) + * @return 处理结果 + */ public StoreAppFile findAppFile(StoreAppFile file) { return this.findAppFile(file.getPackageName(), file.getVersionCode(), file.getCertMd5()); } + /** + * 删除应用文件。 + * + * 实现要点:主要调用:new McFile、delete。 + * + * @param fileUuid 文件 UUID({@code UUID}) + */ public void deleteAppFile(UUID fileUuid) { StoreAppFile appFile = this.findAppFile(fileUuid); String targetFilePath = this.getStoreAppPath(appFile.getPackageName(), appFile.getVersionCode(), fileUuid); @@ -141,6 +255,15 @@ public class StoreAppService extends BaseService { this.deleteById(StoreAppFile.class, fileUuid); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 6 个条件分支、0 个循环;主要调用:remove、new McFile、delete。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param filesOnly 参数 {@code filesOnly}({@code boolean}) + */ public void delete(String packageName, int versionCode, boolean filesOnly) { if (versionCode <= 0) { this.deleteById(StoreApp.class, packageName); @@ -175,11 +298,26 @@ public class StoreAppService extends BaseService { } - public List findApps(String packageName) { + /** + * 查找应用列表。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return Store应用文件列表,可能为空 + */ + public List findApps(String packageName) { return this.findAppFiles(packageName, -1); } - public List findAppFiles(String packageName, int versionCode) { + /** + * 查找应用文件列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @return Store应用文件列表,可能为空 + */ + public List findAppFiles(String packageName, int versionCode) { Criteria criteria = Criteria.where("appInfo.packageName").is(packageName); if (versionCode > 0) { criteria = criteria.and("appInfo.versionCode").is(versionCode); @@ -190,7 +328,19 @@ public class StoreAppService extends BaseService { return storeAppFiles; } - public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找应用列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findApps(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "title.en-US"; direction = Direction.ASC; @@ -208,47 +358,124 @@ public class StoreAppService extends BaseService { return pageResult; } + /** + * 处理保存。 + * + * @param app 参数 {@code app}({@code StoreAppFile}) + */ public void save(StoreAppFile app) { this.saveDocument(app); } + /** + * 获取Temp文件路径。 + * + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getTempFilePath(String fileType, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", fileType, fileUuid}); } + /** + * 获取Store文件路径。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param fileType 参数 {@code fileType}({@code String}) + * @return 字符串结果 + */ public String getStoreFilePath(String packageName, String fileType) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, packageName}); } + /** + * 获取Store应用路径。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code long}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreAppPath(String packageName, long versionCode, UUID fileUuid) { return Joiner.on('/').join(this.getStoreFilePath(packageName, "app"), versionCode, new Object[]{fileUuid}); } + /** + * 获取StoreIcon路径。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字符串结果 + */ public String getStoreIconPath(String packageName) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"app", packageName, "icon.png"}); } + /** + * 添加Release备注。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new AppReleaseNote、save。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @return 处理结果 + */ public AppReleaseNote addReleaseNote(String packageName, int versionCode, String versionName, int minSdkVersion) { AppReleaseNote releaseNote = new AppReleaseNote(packageName, versionCode, versionName, minSdkVersion); return this.save(releaseNote); } + /** + * 添加Release备注。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new AppReleaseNote、save。 + * + * @param appFile 参数 {@code appFile}({@code StoreAppFile}) + */ public void addReleaseNote(StoreAppFile appFile) { AppReleaseNote releaseNote = new AppReleaseNote(appFile); this.save(releaseNote); } + /** + * 查找Release备注。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @return 处理结果 + */ public AppReleaseNote findReleaseNote(String packageName, int versionCode) { Criteria criteria = Criteria.where("_id.packageName").is(packageName).and("_id.versionCode").is(versionCode); AppReleaseNote releaseNote = (AppReleaseNote)this.mongoTemplate.findOne(Query.query(criteria), AppReleaseNote.class); return releaseNote; } - public List findReleaseNote(String packageName, Boolean isFormal) { + /** + * 查找Release备注。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param isFormal 参数 {@code isFormal}({@code Boolean}) + * @return 应用Release备注列表,可能为空 + */ + public List findReleaseNote(String packageName, Boolean isFormal) { return this.findReleaseNotes(packageName, -1, isFormal); } - public List findReleaseNotes(String packageName, int sdkVersion, Boolean isFormal) { + /** + * 查找ReleaseNotes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param sdkVersion 参数 {@code sdkVersion}({@code int}) + * @param isFormal 参数 {@code isFormal}({@code Boolean}) + * @return 应用Release备注列表,可能为空 + */ + public List findReleaseNotes(String packageName, int sdkVersion, Boolean isFormal) { Criteria criteria = Criteria.where("_id.packageName").is(packageName); if (sdkVersion > 0) { criteria.and("minSdkVersion").is(sdkVersion); @@ -263,12 +490,33 @@ public class StoreAppService extends BaseService { return releaseNotes; } + /** + * 处理release备注存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean releaseNoteExists(String packageName, int versionCode) { Criteria criteria = Criteria.where("_id.packageName").is(packageName).and("_id.versionCode").is(versionCode); return this.mongoTemplate.exists(Query.query(criteria), AppReleaseNote.class); } - public Page findReleaseNotes(String packageName, int sdkVersion, String certMd5, int page, int size) { + /** + * 查找ReleaseNotes。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:new Query、count、new PageImpl、new ArrayList、new DbObject、aggregate。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param sdkVersion 参数 {@code sdkVersion}({@code int}) + * @param certMd5 参数 {@code certMd5}({@code String}) + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @return 分页结果 + */ + public Page findReleaseNotes(String packageName, int sdkVersion, String certMd5, int page, int size) { Query query = new Query(); query.addCriteria(Criteria.where("_id.packageName").is(packageName)); if (sdkVersion > 0) { @@ -304,11 +552,31 @@ public class StoreAppService extends BaseService { } } + /** + * 处理保存。 + * + * @param releaseNote 参数 {@code releaseNote}({@code AppReleaseNote}) + * @return 处理结果 + */ public AppReleaseNote save(AppReleaseNote releaseNote) { releaseNote.setFiles((List)null); return (AppReleaseNote)this.saveDocument(releaseNote); } + /** + * 更新备注。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 4 个条件分支、2 个循环;主要调用:new NoteId、new AppReleaseNote、save、new ArrayList。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @param notes 参数 {@code notes}({@code String[]}) + * @param noteNewFunctions 参数 {@code noteNewFunctions}({@code String[]}) + * @param releasedAt 参数 {@code releasedAt}({@code Date}) + * @return 处理结果 + */ public AppReleaseNote updateNote(String packageName, int versionCode, String versionName, int minSdkVersion, String[] notes, String[] noteNewFunctions, Date releasedAt) { AppReleaseNote releaseNote = (AppReleaseNote)this.findById(AppReleaseNote.class, new AppReleaseNote.NoteId(packageName, versionCode)); if (releaseNote == null) { @@ -345,6 +613,16 @@ public class StoreAppService extends BaseService { } } + /** + * 更新备注判断是否Formal。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new NoteId、save。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 处理结果 + */ public AppReleaseNote updateNoteIsFormal(String packageName, int versionCode, boolean isFormal) { AppReleaseNote releaseNote = (AppReleaseNote)this.findById(AppReleaseNote.class, new AppReleaseNote.NoteId(packageName, versionCode)); if (releaseNote != null) { @@ -355,6 +633,15 @@ public class StoreAppService extends BaseService { return releaseNote; } + /** + * 处理签名。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:exists、new McApkFile、close、findAll、new McFile、sign。 + * + * @param user 当前用户({@code User}) + * @param file 文件({@code McFile}) + * @param originalFileName 原始文件名({@code String}) + */ public void sign(User user, McFile file, String originalFileName) { if (file.exists()) { McApkFile apkFile = null; @@ -390,6 +677,23 @@ public class StoreAppService extends BaseService { } } + /** + * 处理签名。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new ProcessBuilder、new McFile、new StoreAppFile、save、upload。 + * + * @param inputApkPath 参数 {@code inputApkPath}({@code String}) + * @param outputApkPath 参数 {@code outputApkPath}({@code String}) + * @param keyStoreFilePath 参数 {@code keyStoreFilePath}({@code String}) + * @param keyStoreAlias 参数 {@code keyStoreAlias}({@code String}) + * @param keyPassword 参数 {@code keyPassword}({@code String}) + * @param storePassword 参数 {@code storePassword}({@code String}) + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param keyID 参数 {@code keyID}({@code String}) + * @return 字符串结果 + */ public String sign(String inputApkPath, String outputApkPath, String keyStoreFilePath, String keyStoreAlias, String keyPassword, String storePassword, User user, UUID fileUuid, String packageName, String keyID) { McFile apkSigner = this.fileService.getResourceFile("apksigner/apksigner.jar", false); diff --git a/src/main/java/com/midm/service/store/StoreOtaService.java b/src/main/java/com/midm/service/store/StoreOtaService.java index b1cae85..c70b491 100644 --- a/src/main/java/com/midm/service/store/StoreOtaService.java +++ b/src/main/java/com/midm/service/store/StoreOtaService.java @@ -32,18 +32,65 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code StoreOtaService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code SettingsService、CloudStorageService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class StoreOtaService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理保存。 + * + * @param ota 参数 {@code ota}({@code StoreOta}) + * @return 处理结果 + */ public StoreOta save(StoreOta ota) { return (StoreOta)this.saveDocument(ota); } - public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Otas。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findOtas(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "productId"; direction = Direction.ASC; @@ -53,16 +100,40 @@ public class StoreOtaService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return StoreOTA 固件列表,可能为空 + */ + public List findAll() { return this.findAll(StoreOta.class); } - public List findOtaFiles(String productId) { + /** + * 查找OTA 固件文件列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * + * @param productId 参数 {@code productId}({@code String}) + * @return StoreOTA 固件文件列表,可能为空 + */ + public List findOtaFiles(String productId) { Query query = Query.query(Criteria.where("otaInfo.productId").is(productId)); return this.mongoTemplate.find(query, StoreOtaFile.class); } - public Page findOtaFiles(String productId, int page, int size) { + /** + * 查找OTA 固件文件列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new Query、count、new ArrayList、new Document、aggregate、new PageImpl。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @return 分页结果 + */ + public Page findOtaFiles(String productId, int page, int size) { Query query = new Query(); query.addCriteria(Criteria.where("otaInfo.productId").is(productId)); query.collation(LocaleConst.COLLATION_DEFAULT); @@ -84,15 +155,38 @@ public class StoreOtaService extends BaseService { } } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Criteria、findOne。 + * + * @param productId 参数 {@code productId}({@code String}) + * @return 处理结果 + */ public StoreOta find(String productId) { Criteria criteria = (new Criteria()).orOperator(new Criteria[]{Criteria.where("_id").is(productId), Criteria.where("deviceId").is(productId)}); return (StoreOta)this.mongoTemplate.findOne(Query.query(criteria), StoreOta.class); } + /** + * 查找OTA 固件文件。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 处理结果 + */ public StoreOtaFile findOtaFile(UUID fileUuid) { return (StoreOtaFile)this.findById(StoreOtaFile.class, fileUuid); } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + * @return 处理结果 + */ public StoreOtaFile find(String productId, long buildDate) { Criteria criteria = Criteria.where("otaInfo.productId").is(productId); if (buildDate > 0L) { @@ -104,6 +198,16 @@ public class StoreOtaService extends BaseService { return otaFile; } + /** + * 查找最新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:new ArrayList、new Criteria、findOne。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + * @return 处理结果 + */ public StoreOtaFile findLatest(String productId, String skuId, long buildDate) { List andSet = new ArrayList(); andSet.add((new Criteria()).orOperator(new Criteria[]{Criteria.where("otaInfo.productId").is(productId), Criteria.where("otaInfo.deviceId").is(productId)})); @@ -122,26 +226,64 @@ public class StoreOtaService extends BaseService { return otaFile; } + /** + * 处理保存。 + * + * @param ota 参数 {@code ota}({@code StoreOtaFile}) + * @return 处理结果 + */ public StoreOtaFile save(StoreOtaFile ota) { return (StoreOtaFile)this.saveDocument(ota); } + /** + * 处理移除。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void remove(String productId) { this.deleteById(StoreOta.class, productId); } + /** + * 获取Store文件路径。 + * + * @param productId 参数 {@code productId}({@code String}) + * @return 字符串结果 + */ public String getStoreFilePath(String productId) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"ota", productId}); } + /** + * 获取StoreOTA 固件文件路径。 + * + * @param productId 参数 {@code productId}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreOtaFilePath(String productId, UUID fileUuid) { return Joiner.on('/').join(this.getStoreFilePath(productId), fileUuid, new Object[0]); } + /** + * 获取Temp文件路径。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getTempFilePath(UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", "ota", fileUuid}); } + /** + * 删除Single文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove、new McFile、delete。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param productId 参数 {@code productId}({@code String}) + */ public void deleteSingleFile(UUID fileUuid, String productId) { Criteria criteria = Criteria.where("fileUuid").is(fileUuid); this.mongoTemplate.remove(Query.query(criteria), StoreOtaFile.class); @@ -150,6 +292,13 @@ public class StoreOtaService extends BaseService { this.cloudStorageService.delete("store", "ota", productId, fileUuid); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove、new McFile、delete。 + * + * @param productId 参数 {@code productId}({@code String}) + */ public void delete(String productId) { this.deleteById(StoreOta.class, productId); Criteria criteria = Criteria.where("otaInfo.productId").is(productId); @@ -159,6 +308,15 @@ public class StoreOtaService extends BaseService { this.cloudStorageService.delete("store", "ota", productId); } + /** + * 更新备注。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new ArrayList、save。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param notes 参数 {@code notes}({@code String[]}) + * @return 处理结果 + */ public StoreOtaFile updateNote(UUID fileUuid, String[] notes) { StoreOtaFile otaFile = this.findOtaFile(fileUuid); if (otaFile == null) { diff --git a/src/main/java/com/midm/service/store/StoreOtherService.java b/src/main/java/com/midm/service/store/StoreOtherService.java index fb908b3..c3ec2bd 100644 --- a/src/main/java/com/midm/service/store/StoreOtherService.java +++ b/src/main/java/com/midm/service/store/StoreOtherService.java @@ -21,20 +21,68 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code StoreOtherService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code SettingsService、CloudStorageService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class StoreOtherService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 删除文件。 + * + * 实现要点:主要调用:new McFile、delete。 + * + * @param fileUuid 文件 UUID({@code UUID}) + */ public void deleteFile(UUID fileUuid) { this.deleteById(StoreOtherFile.class, fileUuid); (new McFile(this.getStoreFilePath("other", fileUuid))).delete(); this.cloudStorageService.delete("store", "other", fileUuid); } - public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page find(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "name"; direction = Direction.ASC; @@ -44,22 +92,59 @@ public class StoreOtherService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理保存。 + * + * @param file 文件({@code StoreOtherFile}) + */ public void save(StoreOtherFile file) { this.saveDocument(file); } + /** + * 根据UUID查找StoreOther文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 处理结果 + */ public StoreOtherFile findByUuid(UUID fileUuid) { return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(fileUuid)), StoreOtherFile.class); } + /** + * 根据名称查找StoreOther文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param name 参数 {@code name}({@code String}) + * @return 处理结果 + */ public StoreOtherFile findByName(String name) { return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("fileInfo.fileName").is(name)), StoreOtherFile.class); } + /** + * 根据Alias查找StoreOther文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param alias 参数 {@code alias}({@code String}) + * @return 处理结果 + */ public StoreOtherFile findByAlias(String alias) { return (StoreOtherFile)this.mongoTemplate.findOne(Query.query(Criteria.where("alias").is(alias)), StoreOtherFile.class); } + /** + * 获取新Alias。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param file 文件({@code McFile}) + * @return 字符串结果 + */ public String getNewAlias(McFile file) { String alias = file.getNameWithoutExtension(); if (!this.existsByAlias(alias)) { @@ -80,10 +165,26 @@ public class StoreOtherService extends BaseService { } } + /** + * 存在按Alias。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param alias 参数 {@code alias}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean existsByAlias(String alias) { return this.mongoTemplate.exists(Query.query(Criteria.where("alias").is(alias)), StoreOtherFile.class); } + /** + * 根据UUID或名称或Alias查找StoreOther文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param uuriOrNameOrAlias 参数 {@code uuriOrNameOrAlias}({@code String}) + * @return 处理结果 + */ public StoreOtherFile findByUuidOrNameOrAlias(String uuriOrNameOrAlias) { StoreOtherFile file = null; @@ -100,6 +201,16 @@ public class StoreOtherService extends BaseService { return file; } + /** + * 处理文件名称存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean fileNameExists(UUID fileUuid, String name, UUID siteUuid) { Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); Query query = Query.query(criteria); @@ -107,20 +218,51 @@ public class StoreOtherService extends BaseService { return file != null && !file.getFileUuid().equals(fileUuid); } + /** + * 移除Same文件。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + */ public void removeSameFile(UUID fileUuid, String name, UUID siteUuid) { Criteria criteria = Criteria.where("name").is(name).and("siteUuid").is(siteUuid); Query query = Query.query(criteria); this.mongoTemplate.remove(query, StoreOtherFile.class); } + /** + * 获取Store文件路径。 + * + * @param fileType 参数 {@code fileType}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreFilePath(String fileType, UUID fileUuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, fileUuid}); } + /** + * 获取Store文件路径。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param fileType 参数 {@code fileType}({@code String}) + * @return 字符串结果 + */ public String getStoreFilePath(String packageName, String fileType) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{fileType, packageName}); } + /** + * 获取Store应用路径。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code long}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreAppPath(String packageName, long versionCode, UUID fileUuid) { return Joiner.on('/').join(this.getStoreFilePath(packageName, "app"), versionCode, new Object[]{fileUuid}); } diff --git a/src/main/java/com/midm/service/store/StoreWebAppService.java b/src/main/java/com/midm/service/store/StoreWebAppService.java index 7ac4502..6cf3b77 100644 --- a/src/main/java/com/midm/service/store/StoreWebAppService.java +++ b/src/main/java/com/midm/service/store/StoreWebAppService.java @@ -31,23 +31,77 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code StoreWebAppService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code SettingsService、CloudStorageService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class StoreWebAppService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:save。 + * + * @param appFile 参数 {@code appFile}({@code StoreWebApp}) + */ public void save(StoreWebApp appFile) { this.mongoTemplate.save(appFile); } + /** + * 处理存在。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:exists。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(UUID fileUuid) { Query query = Query.query(Criteria.where("_id").is(fileUuid)); return this.mongoTemplate.exists(query, StoreWebApp.class); } - public boolean updateNote(UUID appFileUuid, List notes, List notesNewFunction) { + /** + * 更新备注。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含异常捕获与降级/回滚分支;包含 4 个条件分支、2 个循环;主要调用:new ArrayList、new Update、updateFirst。 + * + * @param appFileUuid 参数 {@code appFileUuid}({@code UUID}) + * @param notes 参数 {@code notes}({@code List}) + * @param notesNewFunction 参数 {@code notesNewFunction}({@code List}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean updateNote(UUID appFileUuid, List notes, List notesNewFunction) { List newNotes = new ArrayList(); if (notes != null) { for(String note : notes) { @@ -85,6 +139,15 @@ public class StoreWebAppService extends BaseService { return this.mongoTemplate.updateFirst(query, update, StoreWebApp.class).getModifiedCount() > 0L; } + /** + * 设置转换为Formal。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Update、updateFirst。 + * + * @param appFileUuid 参数 {@code appFileUuid}({@code UUID}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setToFormal(UUID appFileUuid, boolean isFormal) { Query query = Query.query(Criteria.where("_id").is(appFileUuid)); Update update = new Update(); @@ -97,7 +160,13 @@ public class StoreWebAppService extends BaseService { return this.mongoTemplate.updateFirst(query, update, StoreWebApp.class).getModifiedCount() > 0L; } - public List getArtifacts() { + /** + * 获取 {@code artifacts}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new ArrayList、new Document、aggregate。 + * @return Document列表,可能为空 + */ + public List getArtifacts() { List pipeline = new ArrayList(Arrays.asList(new Document("$group", (new Document("_id", "$appInfo.artifactId")).append("name", new Document("$first", "$name"))))); List artifacts = new ArrayList(); Aggregation aggregation = Aggregations.from(pipeline); @@ -106,11 +175,29 @@ public class StoreWebAppService extends BaseService { return artifacts; } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @return 处理结果 + */ public StoreWebApp find(UUID fileUuid) { Query query = Query.query(Criteria.where("_id").is(fileUuid)); return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); } + /** + * 查找最新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 处理结果 + */ public StoreWebApp findLatest(String groupId, String artifactId, boolean isFormal) { Criteria criteria = Criteria.where("appInfo.groupId").is(groupId).and("appInfo.artifactId").is(artifactId).and("fileInfo").exists(true); if (isFormal) { @@ -122,6 +209,16 @@ public class StoreWebAppService extends BaseService { return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、0 个循环;主要调用:new Criteria、findOne。 + * + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param version 参数 {@code version}({@code String}) + * @return 处理结果 + */ public StoreWebApp find(String groupId, String artifactId, String version) { Criteria criteria = new Criteria(); if (!Strings.isNullOrEmpty(groupId)) { @@ -141,7 +238,18 @@ public class StoreWebAppService extends BaseService { return (StoreWebApp)this.mongoTemplate.findOne(query, StoreWebApp.class); } - public List findAll(String groupId, String artifactId, String version, int limit) { + /** + * 查找全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 4 个条件分支、0 个循环;主要调用:new Criteria、find。 + * + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param version 参数 {@code version}({@code String}) + * @param limit 数量上限({@code int}) + * @return StoreWeb应用列表,可能为空 + */ + public List findAll(String groupId, String artifactId, String version, int limit) { Criteria criteria = new Criteria(); if (!Strings.isNullOrEmpty(groupId)) { criteria.and("appInfo.groupId").is(groupId); @@ -164,7 +272,18 @@ public class StoreWebAppService extends BaseService { return this.mongoTemplate.find(query, StoreWebApp.class); } - public Page find(String groupId, String artifactId, Integer page, Integer size) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count、find、new PageImpl。 + * + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 分页结果 + */ + public Page find(String groupId, String artifactId, Integer page, Integer size) { Query query = Query.query(Criteria.where("appInfo.groupId").is(groupId).and("appInfo.artifactId").is(artifactId)); query.collation(LocaleConst.COLLATION_DEFAULT); long total = this.mongoTemplate.count(query, StoreWebApp.class); @@ -174,6 +293,15 @@ public class StoreWebAppService extends BaseService { return new PageImpl(result, pageable, total); } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new McFile、delete、remove、updateFirst、new Update。 + * + * @param fileUuid 文件 UUID({@code UUID}) + * @param fileOnly 参数 {@code fileOnly}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean delete(UUID fileUuid, boolean fileOnly) { McFile file = new McFile(this.getStoreFilePath(fileUuid)); file.delete(); @@ -187,10 +315,22 @@ public class StoreWebAppService extends BaseService { } } + /** + * 获取Store文件路径。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreFilePath(UUID uuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"webapp", uuid.toString()}); } + /** + * 获取StoreTemp文件路径。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ public String getStoreTempFilePath(UUID uuid) { return Joiner.on('/').join(this.settingsService.getFilesRootPath(), "store", new Object[]{"temp", "webapp", uuid.toString()}); } diff --git a/src/main/java/com/midm/service/store/package-info.java b/src/main/java/com/midm/service/store/package-info.java new file mode 100644 index 0000000..20656c7 --- /dev/null +++ b/src/main/java/com/midm/service/store/package-info.java @@ -0,0 +1,16 @@ +/** + * 应用商店服务:APK 解析、签名、版本管理、OTA 发布。 + * + *

本包主要类型: + *

    + *
  • {@link KeyStoreService}
  • + *
  • {@link StoreAppService}
  • + *
  • {@link StoreOtaService}
  • + *
  • {@link StoreOtherService}
  • + *
  • {@link StoreWebAppService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.store; diff --git a/src/main/java/com/midm/service/system/HelpMessageService.java b/src/main/java/com/midm/service/system/HelpMessageService.java index f52d70b..15e8770 100644 --- a/src/main/java/com/midm/service/system/HelpMessageService.java +++ b/src/main/java/com/midm/service/system/HelpMessageService.java @@ -35,20 +35,70 @@ import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; +/** + * 【业务服务】{@code HelpMessageService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code stringTemplateEngine}(TemplateEngine):string模板Engine
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code messageMap}(Map):消息Map
  • + *
  • {@code helpTemplate}(String):帮助模板
  • + *
+ * + * 协作对象:{@code ServletContext、TemplateEngine、FileService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class HelpMessageService extends BaseService { + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired ServletContext servletContext; + /** + * string模板Engine;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Qualifier("stringTemplateEngine")}。 + */ @Autowired @Qualifier("stringTemplateEngine") private TemplateEngine stringTemplateEngine; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; - private final Map messageMap = new HashMap(); + /** + * 消息Map。 + */ + private final Map messageMap = new HashMap(); + /** + * 帮助模板。 + */ private String helpTemplate; + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:save。 + * + * @param message 消息内容({@code HelpMessage}) + */ public void save(HelpMessage message) { if (message != null && !Strings.isNullOrEmpty(message.getCode())) { this.mongoTemplate.save(message, "helpMessage"); @@ -57,7 +107,19 @@ public class HelpMessageService extends BaseService { } - public Page findMessages(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找消息列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findMessages(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "code"; direction = Direction.ASC; @@ -67,6 +129,13 @@ public class HelpMessageService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、1 个循环;主要调用:save。 + * + * @param messages 参数 {@code messages}({@code HelpMessage[]}) + */ public void save(HelpMessage[] messages) { if (messages != null && messages.length > 0) { for(HelpMessage message : messages) { @@ -76,6 +145,17 @@ public class HelpMessageService extends BaseService { } + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param title 参数 {@code title}({@code String}) + * @param message 消息内容({@code String}) + * @return 数量/长度 + */ public long save(String code, String locale, String title, String message) { if (Strings.isNullOrEmpty(code)) { return 0L; @@ -87,12 +167,31 @@ public class HelpMessageService extends BaseService { } } + /** + * 处理删除。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param code 状态码/业务码({@code String}) + * @return 数量/长度 + */ public long delete(String code) { Query query = Query.query(Criteria.where("_id").is(code)); DeleteResult result = this.mongoTemplate.remove(query, HelpMessage.class); return result.getDeletedCount(); } + /** + * 保存选项。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合)。 + * + * @param code 状态码/业务码({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @return 数量/长度 + */ public long saveOption(String code, String category, String key, String desc) { Query query = Query.query(Criteria.where("_id").is(code)); Update update = Update.update(String.format("options.%s.%s", category, key), desc); @@ -100,6 +199,16 @@ public class HelpMessageService extends BaseService { return result.getModifiedCount(); } + /** + * 删除选项。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update。 + * + * @param code 状态码/业务码({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @return 数量/长度 + */ public long deleteOption(String code, String category, String key) { Query query = Query.query(Criteria.where("_id").is(code)); Update update = (new Update()).unset(String.format("%s.%s", category, key)); @@ -107,24 +216,58 @@ public class HelpMessageService extends BaseService { return result.getModifiedCount(); } + /** + * 处理获取。 + * + * @param code 状态码/业务码({@code String}) + * @return 处理结果 + */ public HelpMessage get(String code) { return (HelpMessage)this.messageMap.get(code); } + /** + * 获取Title。 + * + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ public String getTitle(String code) { return this.getTitle(code, "en-US"); } + /** + * 获取Title。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getTitle(String code, String locale) { HelpMessage message = this.get(code); return message == null ? null : message.getTitle(locale); } + /** + * 获取选项列表AsMap。 + * + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ public String getOptionsAsMap(String code) { HelpMessage message = this.get(code); return McJsonUtils.toJson(message.getOptions(), true); } + /** + * 获取HTMLContent。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save、new HelpMessage、new Context、process。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ public String getHtmlContent(String code, String locale) { HelpMessage message = this.get(code); if (message == null) { @@ -140,7 +283,13 @@ public class HelpMessageService extends BaseService { } } - public List getOptionCategories() { + /** + * 获取 {@code optionCategories}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:aggregate、new ArrayList。 + * @return String列表,可能为空 + */ + public List getOptionCategories() { AggregationOperation optionProjectOp = Aggregations.newOperation("{$project: {options: {$objectToArray: '$options'}}}"); AggregationOperation categoryProjectOp = Aggregations.newOperation("{$project: {category: '$options.k'}}"); AggregationOperation unwindOp = Aggregation.unwind("category"); @@ -149,6 +298,14 @@ public class HelpMessageService extends BaseService { return (List)(result == null ? new ArrayList() : (List)result.get("categories")); } + /** + * 处理存在。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new HelpMessage、save。 + * + * @param code 状态码/业务码({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(String code) { HelpMessage message = this.get(code); if (message == null) { @@ -159,6 +316,11 @@ public class HelpMessageService extends BaseService { return !message.getMessage().isEmpty(); } + /** + * 加载消息列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findAll。 + */ public void loadMessages() { List messages = this.mongoTemplate.findAll(HelpMessage.class); this.messageMap.clear(); diff --git a/src/main/java/com/midm/service/system/HostLicenseService.java b/src/main/java/com/midm/service/system/HostLicenseService.java index dd04812..eb977a8 100644 --- a/src/main/java/com/midm/service/system/HostLicenseService.java +++ b/src/main/java/com/midm/service/system/HostLicenseService.java @@ -40,33 +40,118 @@ import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code HostLicenseService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_IS_PRIMARY}(String):字段 KEY_IS_PRIMARY
  • + *
  • {@code KEY_LICENSE_KEY}(String):字段 KEY_LICENSE_KEY
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code newsMessageService}(NewsMessageService):新闻消息服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code deviceLicenseService}(LicenseService):设备许可证服务
  • + *
+ * + * 协作对象:{@code UserService、NewsMessageService、SettingsService、LicenseService、WebSocketSessionManager、EmailService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class HostLicenseService extends BaseService { + /** + * 字段 KEY_IS_PRIMARY。 + */ public static final String KEY_IS_PRIMARY = "isPrimary"; + /** + * 字段 KEY_LICENSE_KEY。 + */ public static final String KEY_LICENSE_KEY = "licenseKey"; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private UserService userService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 设备许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService deviceLicenseService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 系统哈希;从配置注入。 + * + * 注解:{@code @Value("${system.hash:#{null}}")}。 + */ @Value("${system.hash:#{null}}") private String systemHash; + /** + * primary许可证。 + */ private HostLicense primaryLicense = null; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new HostLicense、save。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param licenseKey 参数 {@code licenseKey}({@code String}) + * @param isPrimary 参数 {@code isPrimary}({@code boolean}) + * @return 处理结果 + */ public HostLicense save(String systemHash, String licenseKey, boolean isPrimary) { HostLicense license = new HostLicense(this.settingsService.hostId(), systemHash, licenseKey); license.setPrimary(isPrimary); return license.isValidKey() ? this.save(license) : null; } + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:count。 + * + * @param license 参数 {@code license}({@code HostLicense}) + * @return 处理结果 + */ public HostLicense save(HostLicense license) { if (license != null) { if (Strings.isNullOrEmpty(this.systemHash)) { @@ -93,14 +178,36 @@ public class HostLicenseService extends BaseService { } } + /** + * 获取Current站点。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @return 站点对象;未找到时返回 {@code null} + */ public Site getCurrentSite(UUID siteUuid) { return (Site)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(siteUuid)), Site.class); } + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:save。 + * + * @param standaSettings 参数 {@code standaSettings}({@code StandaloneLicense}) + */ public void save(StandaloneLicense standaSettings) { this.mongoTemplate.save(standaSettings); } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、1 个循环;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param standaSettings 参数 {@code standaSettings}({@code StandaloneLicense}) + */ public void sendMessageToRecipients(StandaloneLicense standaSettings) { Site site = standaSettings.getSite(); NewsMessage message = new NewsMessage(); @@ -131,6 +238,19 @@ public class HostLicenseService extends BaseService { } + /** + * 发送消息转换为Recipients。 + * + * 实现要点:涉及邮件发送;包含 2 个条件分支、0 个循环;主要调用:new SimpleDateFormat、new Date。 + * + * @param email 邮箱({@code String}) + * @param message 消息内容({@code NewsMessage}) + * @param site 站点/企业({@code Site}) + * @param licenseType 参数 {@code licenseType}({@code String}) + * @param deviceLimit 参数 {@code deviceLimit}({@code int}) + * @param validTo 参数 {@code validTo}({@code long}) + * @param period 参数 {@code period}({@code int}) + */ public void sendMessageToRecipients(String email, NewsMessage message, Site site, String licenseType, int deviceLimit, long validTo, int period) { if (email != null) { DateFormat dateFormat = new SimpleDateFormat("EE-MM-dd-yyyy"); @@ -147,6 +267,13 @@ public class HostLicenseService extends BaseService { } } + /** + * 发送消息。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new NewsMessage、new DateTime、new SimpleDateFormat、save。 + * + * @param standaSettings 参数 {@code standaSettings}({@code StandaloneLicense}) + */ public void sendMessage(StandaloneLicense standaSettings) { Site site = standaSettings.getSite(); NewsMessage message = new NewsMessage(); @@ -170,6 +297,18 @@ public class HostLicenseService extends BaseService { users.forEach((user) -> this.sendMessage(user, message, site, licenseType, deviceLimit, validTo)); } + /** + * 发送消息。 + * + * 实现要点:涉及邮件发送;通过 WebSocket 会话推送消息;包含 3 个条件分支、0 个循环;主要调用:new SimpleDateFormat、new Date。 + * + * @param user 当前用户({@code User}) + * @param message 消息内容({@code NewsMessage}) + * @param site 站点/企业({@code Site}) + * @param licenseType 参数 {@code licenseType}({@code String}) + * @param deviceLimit 参数 {@code deviceLimit}({@code int}) + * @param validTo 参数 {@code validTo}({@code long}) + */ public void sendMessage(User user, NewsMessage message, Site site, String licenseType, int deviceLimit, long validTo) { if (user.getEnabled()) { this.newsMessageService.setMessageLog(message, user, site); @@ -190,6 +329,14 @@ public class HostLicenseService extends BaseService { } } + /** + * 设置 {@code asPrimary}。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new DateTime、save。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 处理结果 + */ public HostLicense setAsPrimary(String systemHash) { HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); if (license != null && !license.isPrimary()) { @@ -209,42 +356,97 @@ public class HostLicenseService extends BaseService { } } + /** + * 判断 {@code standalone}。 + * @return 字段/派生属性 {@code standalone} 的值 + */ public boolean isStandalone() { return this.getPrimaryLicense().isStandalone(); } + /** + * 获取 {@code deviceLimit}。 + * @return 数量/长度 + */ public int getDeviceLimit() { return this.getPrimaryLicense().getDeviceLimit(); } + /** + * 处理设备Left。 + * + * 实现要点:主要调用:count。 + * @return 数量/长度 + */ public long deviceLeft() { return (long)this.getDeviceLimit() - this.count(Device.class); } + /** + * 处理valid转换为。 + * @return 数量/长度 + */ public Long validTo() { return this.getPrimaryLicense().getValidTo(); } + /** + * 判断 {@code valid}。 + * @return 字段/派生属性 {@code valid} 的值 + */ public boolean isValid() { return this.getPrimaryLicense().isValid(); } + /** + * 获取 {@code systemHash}。 + * @return 字符串结果 + */ public String getSystemHash() { return HostLicense.generateSystemHash(this.systemHash); } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 处理结果 + */ public HostLicense find(String systemHash) { return (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(systemHash)), HostLicense.class); } + /** + * 查找最新。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param uuid 对象 UUID({@code UUID}) + * @return 处理结果 + */ public StandaloneLicense findLatest(UUID uuid) { return (StandaloneLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("site.$id").is(uuid)), StandaloneLicense.class); } + /** + * 删除Standalone许可证。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:remove。 + * + * @param siteUuid 站点 UUID({@code UUID}) + */ public void deleteStandaloneLicense(UUID siteUuid) { this.mongoTemplate.remove(Query.query(Criteria.where("site.$id").is(siteUuid)), StandaloneLicense.class); } + /** + * 获取 {@code primaryLicense}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 5 个条件分支、0 个循环;主要调用:findOne、updateFirst、new Query、save。 + * @return 字段/派生属性 {@code primaryLicense} 的值 + */ public HostLicense getPrimaryLicense() { if (this.primaryLicense == null) { HostLicense license = (HostLicense)this.mongoTemplate.findOne(Query.query(Criteria.where("isPrimary").is(true)), HostLicense.class); @@ -275,6 +477,14 @@ public class HostLicenseService extends BaseService { return this.primaryLicense; } + /** + * 生成Trial许可证。 + * + * 实现要点:主要调用:new HostLicense。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 处理结果 + */ private HostLicense generateTrialLicense(String systemHash) { HostLicense license = new HostLicense(this.settingsService.hostId(), systemHash); license.setValidFrom(this.settingsService.startedFrom()); @@ -283,6 +493,14 @@ public class HostLicenseService extends BaseService { return license; } + /** + * 处理校验。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:new HostLicense、count、new DateTime、save。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 处理结果 + */ private HostLicense validate(String systemHash) { HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); if (license == null) { @@ -308,10 +526,23 @@ public class HostLicenseService extends BaseService { return this.save(license); } - public List findAll() { + /** + * 查找全部。 + * + * 实现要点:主要调用:findAll。 + * @return Host许可证列表,可能为空 + */ + public List findAll() { return this.findAll(HostLicense.class); } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + */ public void delete(String systemHash) { HostLicense license = (HostLicense)this.findById(HostLicense.class, systemHash); if (license != null && !license.isPrimary()) { @@ -320,22 +551,49 @@ public class HostLicenseService extends BaseService { } + /** + * 处理unsetPrimary。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Update、updateMulti。 + * + * @param systemHash 参数 {@code systemHash}({@code String}) + */ private void unsetPrimary(String systemHash) { Criteria criteria = Criteria.where("_id").ne(systemHash); Update update = (new Update()).unset("licenseKey").set("isPrimary", false); this.mongoTemplate.updateMulti(Query.query(criteria), update, HostLicense.class); } + /** + * 判断 {@code primaryServer}。 + * @return 字段/派生属性 {@code primaryServer} 的值 + */ public boolean isPrimaryServer() { HostLicense license = (HostLicense)this.findById(HostLicense.class, HostLicense.generateSystemHash(this.systemHash)); return license != null && license.isPrimary(); } + /** + * 判断 {@code exceedDeviceLimit}。 + * + * 实现要点:主要调用:count。 + * @return 字段/派生属性 {@code exceedDeviceLimit} 的值 + */ public boolean isExceedDeviceLimit() { int limit = this.getPrimaryLicense().getDeviceLimit(); return limit != -1 && (long)limit <= this.count(Device.class); } + /** + * 校验许可证。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HostLicense。 + * + * @param hostId 参数 {@code hostId}({@code String}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param licenseKey 参数 {@code licenseKey}({@code String}) + * @return 处理结果 + */ public HostLicense validateLicense(String hostId, String systemHash, String licenseKey) { if (Strings.isNullOrEmpty(hostId)) { hostId = this.settingsService.hostId(); @@ -346,6 +604,11 @@ public class HostLicenseService extends BaseService { return license; } + /** + * 校验许可证。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + */ public void validateLicense() { if (this.primaryLicense == null) { this.getPrimaryLicense(); @@ -358,6 +621,11 @@ public class HostLicenseService extends BaseService { this.validate(HostLicense.generateSystemHash(this.systemHash)); } + /** + * 通知IfExpiring。 + * + * 实现要点:涉及邮件发送;包含 4 个条件分支、1 个循环;主要调用:new DateTime。 + */ public void notifyIfExpiring() { HostLicense license = this.getPrimaryLicense(); if (license.getSystemHash().equals(HostLicense.generateSystemHash((String)null))) { @@ -380,7 +648,20 @@ public class HostLicenseService extends BaseService { } } - public Page find(JsonObject filter, Integer page, UUID siteUuid, Integer size, String sortBy, Sort.Direction direction) { + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:find、count。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page find(JsonObject filter, Integer page, UUID siteUuid, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "site.idName"; direction = Direction.ASC; @@ -400,6 +681,13 @@ public class HostLicenseService extends BaseService { return pageResult; } + /** + * 调度Maintenance。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;由 Spring 调度器按 cron/fixedDelay 触发。 + * + * 框架注解:{@code @Scheduled(cron = "0 0 0 * * *")}、{@code @Async}。 + */ @Scheduled( cron = "0 0 0 * * *" ) @@ -409,6 +697,13 @@ public class HostLicenseService extends BaseService { this.notifyIfExpiring(); } + /** + * 调度转换为ForceGC。 + * + * 实现要点:异步执行,调用方不阻塞等待结果;由 Spring 调度器按 cron/fixedDelay 触发。 + * + * 框架注解:{@code @Scheduled(cron = "0 15,45 * * * *")}、{@code @Async}。 + */ @Scheduled( cron = "0 15,45 * * * *" ) diff --git a/src/main/java/com/midm/service/system/LicenseService.java b/src/main/java/com/midm/service/system/LicenseService.java index bb2d9d7..8a959f6 100644 --- a/src/main/java/com/midm/service/system/LicenseService.java +++ b/src/main/java/com/midm/service/system/LicenseService.java @@ -24,14 +24,53 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code LicenseService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code licenseModels}(List):许可证Models
  • + *
  • {@code modelsByUuid}(Map):models按UUID
  • + *
  • {@code modelsByIdName}(Map):models按ID名称
  • + *
  • {@code trialLicenseModel}(LicenseModel):trial许可证模型
  • + *
+ * + * 协作对象:{@code LicenseModel}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class LicenseService extends BaseService { - private List licenseModels = null; - Map modelsByUuid = new HashMap(); - Map modelsByIdName = new HashMap(); + /** + * 许可证Models。 + */ + private List licenseModels = null; + /** + * models按UUID。 + */ + Map modelsByUuid = new HashMap(); + /** + * models按ID名称。 + */ + Map modelsByIdName = new HashMap(); + /** + * trial许可证模型。 + */ private LicenseModel trialLicenseModel = null; - public List getFullFeatures() { + /** + * 获取 {@code fullFeatures}。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * @return Category列表,可能为空 + */ + public List getFullFeatures() { List categories = this.getCategories(); for(Category category : categories) { @@ -42,24 +81,55 @@ public class LicenseService extends BaseService { return categories; } - public List getCategories() { + /** + * 获取 {@code categories}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:find。 + * @return Category列表,可能为空 + */ + public List getCategories() { Query query = Query.query(Criteria.where("categoryId.use").is("licenseFeature")); query.with(Sort.by(Direction.ASC, new String[]{"order"})); return this.mongoTemplate.find(query, Category.class); } + /** + * 处理保存。 + * + * @param category 分类(app/ota/other/report 等)({@code Category}) + * @return 处理结果 + */ public Category save(Category category) { return (Category)this.saveDocument(category); } + /** + * 处理删除。 + * + * 实现要点:主要调用:delete。 + * + * @param category 分类(app/ota/other/report 等)({@code Category}) + */ public void delete(Category category) { this.delete(category.id); } + /** + * 处理删除。 + * + * @param categoryId 参数 {@code categoryId}({@code CategoryId}) + */ public void delete(CategoryId categoryId) { this.deleteById(Category.class, categoryId); } + /** + * 删除Category。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new CategoryId、remove、delete。 + * + * @param categoryId 参数 {@code categoryId}({@code String}) + */ public void deleteCategory(String categoryId) { CategoryId id = new CategoryId("licenseFeature", categoryId); Query query = Query.query(Criteria.where("categoryId").is(id)); @@ -67,28 +137,65 @@ public class LicenseService extends BaseService { this.delete(id); } - public List getFeatures(String categoryId) { + /** + * 获取Features。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new CategoryId、find。 + * + * @param categoryId 参数 {@code categoryId}({@code String}) + * @return 许可证Feature列表,可能为空 + */ + public List getFeatures(String categoryId) { CategoryId id = new CategoryId("licenseFeature", categoryId); Query query = Query.query(Criteria.where("categoryId").is(id)); return this.mongoTemplate.find(query, LicenseFeature.class); } + /** + * 处理保存。 + * + * @param feature 参数 {@code feature}({@code LicenseFeature}) + * @return 处理结果 + */ public LicenseFeature save(LicenseFeature feature) { return (LicenseFeature)this.saveDocument(feature); } + /** + * 删除Feature。 + * + * @param featureCode 参数 {@code featureCode}({@code String}) + */ public void deleteFeature(String featureCode) { this.deleteById(LicenseFeature.class, featureCode); } + /** + * 查找UUID的许可证模型。 + * + * @param modelUuid 参数 {@code modelUuid}({@code UUID}) + * @return 处理结果 + */ public LicenseModel findLicenseModelByUuid(UUID modelUuid) { return modelUuid != null ? (LicenseModel)this.modelsByUuid.get(modelUuid) : this.getTrialLicenseModel(); } + /** + * 查找ID名称的许可证模型。 + * + * @param idName 参数 {@code idName}({@code String}) + * @return 处理结果 + */ public LicenseModel findLicenseModelByIdName(String idName) { return !Strings.isNullOrEmpty(idName) ? (LicenseModel)this.modelsByIdName.get(idName) : null; } + /** + * 获取 {@code trialLicenseModel}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:findOne。 + * @return 字段/派生属性 {@code trialLicenseModel} 的值 + */ public LicenseModel getTrialLicenseModel() { if (this.trialLicenseModel == null) { this.trialLicenseModel = this.findLicenseModelByIdName("trial"); @@ -101,7 +208,13 @@ public class LicenseService extends BaseService { return this.trialLicenseModel; } - public List getAllModels() { + /** + * 获取 {@code allModels}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:findAll。 + * @return 许可证模型列表,可能为空 + */ + public List getAllModels() { if (this.licenseModels == null) { this.licenseModels = this.findAll(LicenseModel.class); this.modelsByUuid.clear(); @@ -115,7 +228,19 @@ public class LicenseService extends BaseService { return this.licenseModels; } - public Page findModels(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Models。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:count、find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findModels(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "name"; direction = Direction.ASC; @@ -130,6 +255,14 @@ public class LicenseService extends BaseService { return pageResult; } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param model 参数 {@code model}({@code LicenseModel}) + * @return 处理结果 + */ public LicenseModel save(LicenseModel model) { if (model.getUuid() == null) { model.initUuid(); @@ -141,10 +274,20 @@ public class LicenseService extends BaseService { return model; } + /** + * 处理删除。 + * + * @param model 参数 {@code model}({@code LicenseModel}) + */ public void delete(LicenseModel model) { this.deleteModel(model.getUuid()); } + /** + * 删除模型。 + * + * @param modelUuid 参数 {@code modelUuid}({@code UUID}) + */ public void deleteModel(UUID modelUuid) { this.deleteById(LicenseModel.class, modelUuid); this.licenseModels = null; diff --git a/src/main/java/com/midm/service/system/LocaleService.java b/src/main/java/com/midm/service/system/LocaleService.java index 35592b6..56fe321 100644 --- a/src/main/java/com/midm/service/system/LocaleService.java +++ b/src/main/java/com/midm/service/system/LocaleService.java @@ -24,24 +24,72 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code LocaleService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code messageMap}(Map):消息Map
  • + *
  • {@code localeMap}(Map):语言区域Map
  • + *
  • {@code enabledLocaleTags}(Set):enabled语言区域Tags
  • + *
  • {@code enabledLocales}(List):Resource语言区域集合
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class LocaleService extends BaseService { - private Map messageMap; - private Map localeMap; - private Set enabledLocaleTags = new HashSet(); - private List enabledLocales; + /** + * 消息Map。 + */ + private Map messageMap; + /** + * 语言区域Map。 + */ + private Map localeMap; + /** + * enabled语言区域Tags。 + */ + private Set enabledLocaleTags = new HashSet(); + /** + * Resource语言区域集合。 + */ + private List enabledLocales; + /** + * 处理保存。 + * + * @param locale 参数 {@code locale}({@code ResourceLocale}) + */ public void save(ResourceLocale locale) { this.saveDocument(locale); this.addIndex("resourceMessage", new String[]{"messages." + locale.getLocale()}); this.enabledLocales = null; } - public List findAllLocales() { + /** + * 查找全部Locales。 + * + * 实现要点:主要调用:findAll。 + * @return Resource语言区域列表,可能为空 + */ + public List findAllLocales() { return this.findAll(ResourceLocale.class); } - public List findEnabledLocales() { + /** + * 查找EnabledLocales。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:find。 + * @return Resource语言区域列表,可能为空 + */ + public List findEnabledLocales() { if (this.enabledLocales == null || this.enabledLocales.isEmpty()) { Sort sort = Sort.by(Direction.ASC, new String[]{"order"}).and(Sort.by(Direction.ASC, new String[]{"locale"})); Query query = Query.query(Criteria.where("enabled").is(true)); @@ -54,15 +102,40 @@ public class LocaleService extends BaseService { return this.enabledLocales; } + /** + * 判断是否语言区域Enabled。 + * + * @param localeTag 参数 {@code localeTag}({@code String}) + * @return 字段/派生属性 {@code localeEnabled} 的值 + */ private boolean isLocaleEnabled(String localeTag) { return this.enabledLocaleTags.contains(localeTag); } - public Page findLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找Locales。 + * + * 实现要点:主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { List result = this.find(ResourceLocale.class, filter, sortBy, direction); return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理删除。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param locale 参数 {@code locale}({@code ResourceLocale}) + */ public void delete(ResourceLocale locale) { this.deleteById(ResourceLocale.class, locale.getLocale()); @@ -74,15 +147,34 @@ public class LocaleService extends BaseService { this.enabledLocales = null; } + /** + * 处理保存。 + * + * @param altLocale 参数 {@code altLocale}({@code AltLocale}) + */ public void save(AltLocale altLocale) { this.localeMap.put(altLocale.getLocale(), altLocale); this.saveDocument(altLocale); } + /** + * 查找Alt语言区域。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @return 处理结果 + */ public Locale findAltLocale(Locale locale) { return this.findAltLocale(locale.toLanguageTag()); } + /** + * 查找Alt语言区域。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param localeTag 参数 {@code localeTag}({@code String}) + * @return 处理结果 + */ public Locale findAltLocale(String localeTag) { if (this.isLocaleEnabled(localeTag)) { return Locale.forLanguageTag(localeTag); @@ -94,11 +186,29 @@ public class LocaleService extends BaseService { } } - public List findAllAltLocales() { + /** + * 查找全部AltLocales。 + * + * 实现要点:主要调用:findAll。 + * @return Alt语言区域列表,可能为空 + */ + public List findAllAltLocales() { return this.findAll(AltLocale.class); } - public Page findAltLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { + /** + * 查找AltLocales。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find、new PageImpl。 + * + * @param filter 过滤条件({@code JsonObject}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 分页结果 + */ + public Page findAltLocales(JsonObject filter, Integer page, Integer size, String sortBy, Sort.Direction direction) { if (McStringUtils.isNullOrEmpty(sortBy)) { sortBy = "locale"; direction = Direction.ASC; @@ -112,16 +222,36 @@ public class LocaleService extends BaseService { return new PageImpl(result.subList(McDbUtils.from(page, size), McDbUtils.to(page, size, result.size())), PageRequest.of(page, size), (long)result.size()); } + /** + * 处理删除。 + * + * 实现要点:主要调用:remove。 + * + * @param altLocale 参数 {@code altLocale}({@code AltLocale}) + */ public void delete(AltLocale altLocale) { this.localeMap.remove(altLocale.getLocale()); this.deleteById(AltLocale.class, altLocale.getLocale()); } + /** + * 加载语言区域并Resources。 + */ public void loadLocaleAndResources() { this.localeMap = (Map)this.findAllAltLocales().stream().collect(Collectors.toMap(AltLocale::getLocale, (locale) -> locale)); this.messageMap = (Map)this.findAllMessages().stream().collect(Collectors.toMap(ResourceMessage::getCode, (value) -> value)); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new ResourceMessage、save。 + * + * @param code 状态码/业务码({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param message 消息内容({@code String}) + * @return 处理结果 + */ public ResourceMessage save(String code, String locale, String message) { ResourceMessage resourceMessage = (ResourceMessage)this.findById(ResourceMessage.class, code); if (resourceMessage == null) { @@ -132,6 +262,14 @@ public class LocaleService extends BaseService { return this.save(resourceMessage); } + /** + * 处理保存。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param message 消息内容({@code ResourceMessage}) + * @return 处理结果 + */ public ResourceMessage save(ResourceMessage message) { if (Strings.isNullOrEmpty(message.getCode())) { return null; @@ -142,14 +280,36 @@ public class LocaleService extends BaseService { } } + /** + * 获取消息。 + * + * @param code 状态码/业务码({@code String}) + * @return 字段/派生属性 {@code message} 的值 + */ public ResourceMessage getMessage(String code) { return (ResourceMessage)this.messageMap.get(code); } + /** + * 获取消息。 + * + * @param locale 参数 {@code locale}({@code Locale}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ public String getMessage(Locale locale, String code) { return this.getMessage(locale.toLanguageTag(), code); } + /** + * 获取消息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ResourceMessage。 + * + * @param locale 参数 {@code locale}({@code String}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ public String getMessage(String locale, String code) { ResourceMessage resourceMessage = (ResourceMessage)this.messageMap.get(code); if (resourceMessage == null) { @@ -159,15 +319,34 @@ public class LocaleService extends BaseService { return resourceMessage.getMessage(locale); } - public List findAllMessages() { + /** + * 查找全部消息列表。 + * + * 实现要点:主要调用:findAll。 + * @return Resource消息列表,可能为空 + */ + public List findAllMessages() { return this.findAll(ResourceMessage.class); } + /** + * 处理删除。 + * + * 实现要点:主要调用:remove。 + * + * @param message 消息内容({@code ResourceMessage}) + */ public void delete(ResourceMessage message) { this.messageMap.remove(message.getCode()); this.deleteById(ResourceMessage.class, message.getCode()); } + /** + * 根据ID查找Resource消息。 + * + * @param code 状态码/业务码({@code String}) + * @return 处理结果 + */ public ResourceMessage findById(String code) { return (ResourceMessage)this.findById(ResourceMessage.class, code); } diff --git a/src/main/java/com/midm/service/system/PolicyAgreementService.java b/src/main/java/com/midm/service/system/PolicyAgreementService.java index c571357..d5df37a 100644 --- a/src/main/java/com/midm/service/system/PolicyAgreementService.java +++ b/src/main/java/com/midm/service/system/PolicyAgreementService.java @@ -15,23 +15,66 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code PolicyAgreementService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
+ * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class PolicyAgreementService extends BaseService { + /** + * 判断是否Eula。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:count。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 字段/派生属性 {@code eula} 的值 + */ public boolean hasEula(String category) { Criteria criteria = Criteria.where("category").is(category); return this.mongoTemplate.count(Query.query(criteria), PolicyAgreement.class) > 0L; } + /** + * 处理保存。 + * + * @param agreement 参数 {@code agreement}({@code PolicyAgreement}) + * @return 处理结果 + */ public PolicyAgreement save(PolicyAgreement agreement) { return (PolicyAgreement)this.saveDocument(agreement); } + /** + * 查找Exist协议。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param version 参数 {@code version}({@code String}) + * @return 处理结果 + */ public PolicyAgreement findExistAgreement(String category, String version) { Query query = Query.query(Criteria.where("category").is(category).and("version").is(version)); return (PolicyAgreement)this.mongoTemplate.findOne(query, PolicyAgreement.class); } - public Page findAll(String filter, Integer page, Integer size) { + /** + * 查找全部。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、count、find、new PageImpl。 + * + * @param filter 过滤条件({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 分页结果 + */ + public Page findAll(String filter, Integer page, Integer size) { Query query = new Query(); query.collation(LocaleConst.COLLATION_DEFAULT); Long total = this.mongoTemplate.count(query, PolicyAgreement.class); @@ -50,6 +93,14 @@ public class PolicyAgreementService extends BaseService { return pageResult; } + /** + * 处理findlatest。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:new Query、findOne。 + * + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 处理结果 + */ public PolicyAgreement findlatest(String category) { Criteria criteria = Criteria.where("category").is(category); Query query = new Query(criteria); @@ -64,6 +115,11 @@ public class PolicyAgreementService extends BaseService { return result; } + /** + * 处理删除。 + * + * @param agreement 参数 {@code agreement}({@code PolicyAgreement}) + */ public void delete(PolicyAgreement agreement) { this.deleteById(PolicyAgreement.class, agreement.getUuid()); } diff --git a/src/main/java/com/midm/service/system/RestoreService.java b/src/main/java/com/midm/service/system/RestoreService.java index 9f9d43f..38ce7a1 100644 --- a/src/main/java/com/midm/service/system/RestoreService.java +++ b/src/main/java/com/midm/service/system/RestoreService.java @@ -31,15 +31,57 @@ import org.bson.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code RestoreService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
  • {@code helpMessageService}(HelpMessageService):帮助消息服务
  • + *
+ * + * 协作对象:{@code SettingsService、LocaleService、HelpMessageService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class RestoreService extends BaseService { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 帮助消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HelpMessageService helpMessageService; + /** + * 处理restore。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、1 个循环;主要调用:exists、new BufferedInputStream、close、new ZipInputStream、new GZIPInputStream、new FilenameFilter。 + * + * @param source 参数 {@code source}({@code McFile}) + */ public void restore(McFile source) { if (source != null && source.exists()) { if (source.isFile()) { @@ -81,6 +123,13 @@ public class RestoreService extends BaseService { } + /** + * 处理restore。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new URIBuilder、execute、new HttpGet。 + * + * @param syncServer 参数 {@code syncServer}({@code String}) + */ public void restore(String syncServer) { try { if (Strings.isNullOrEmpty(syncServer)) { @@ -108,6 +157,13 @@ public class RestoreService extends BaseService { } + /** + * 处理restore。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ZipInputStream、close。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ public void restore(InputStream input) { ZipInputStream zipInput = new ZipInputStream(input); this.restore(zipInput); @@ -121,6 +177,13 @@ public class RestoreService extends BaseService { this.reloadResources(); } + /** + * 处理restore。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环。 + * + * @param input 参数 {@code input}({@code ZipInputStream}) + */ public void restore(ZipInputStream input) { ZipEntry entry; try { @@ -141,6 +204,15 @@ public class RestoreService extends BaseService { } + /** + * 处理restore。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new BasicBSONDecoder、new ArrayList、new Document。 + * + * @param input 参数 {@code input}({@code InputStream}) + * @param collectionName 参数 {@code collectionName}({@code String}) + * @return 数量/长度 + */ public int restore(InputStream input, String collectionName) { int count = 0; @@ -169,9 +241,15 @@ public class RestoreService extends BaseService { return count; } + /** + * 处理backup。 + */ public void backup() { } + /** + * 处理reloadResources。 + */ public void reloadResources() { this.localeService.loadLocaleAndResources(); this.helpMessageService.loadMessages(); diff --git a/src/main/java/com/midm/service/system/SettingsService.java b/src/main/java/com/midm/service/system/SettingsService.java index d15ae85..e286a84 100644 --- a/src/main/java/com/midm/service/system/SettingsService.java +++ b/src/main/java/com/midm/service/system/SettingsService.java @@ -28,41 +28,146 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code SettingsService} + * + * 类职责: + *
    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DEFAULT_SYNC_SERVER}(String):字段 DEFAULT_SYNC_SERVER
  • + *
  • {@code KEY_HOST_ID}(String):字段 KEY_HOST_ID
  • + *
  • {@code KEY_MIDM_LICENSE}(String):字段 KEY_MIDM_LICENSE
  • + *
  • {@code KEY_DB_INDEXED}(String):字段 KEY_DB_INDEXED
  • + *
  • {@code KEY_DB_SCHEME}(String):字段 KEY_DB_SCHEME
  • + *
  • {@code KEY_DB_SYNC_SERVER}(String):字段 KEY_DB_SYNC_SERVER
  • + *
+ * + * 协作对象:{@code PolicyAgreementService、DeviceService、HostLicenseService、CloudStorageService、EmailService、RestoreService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class SettingsService extends BaseService { + /** + * 字段 DEFAULT_SYNC_SERVER。 + */ private static final String DEFAULT_SYNC_SERVER = "https://midmtest.mic.com.tw"; + /** + * 字段 KEY_HOST_ID。 + */ private static final String KEY_HOST_ID = "host.id"; + /** + * 字段 KEY_MIDM_LICENSE。 + */ private static final String KEY_MIDM_LICENSE = "midm.license"; + /** + * 字段 KEY_DB_INDEXED。 + */ public static final String KEY_DB_INDEXED = "db.indexed"; + /** + * 字段 KEY_DB_SCHEME。 + */ public static final String KEY_DB_SCHEME = "db.scheme"; + /** + * 字段 KEY_DB_SYNC_SERVER。 + */ public static final String KEY_DB_SYNC_SERVER = "db.sync.server"; + /** + * 字段 KEY_DB_SYNC_ON_STARTS。 + */ public static final String KEY_DB_SYNC_ON_STARTS = "db.sync.onStarts"; + /** + * 字段 KEY_DB_SYNC_UPDATED。 + */ public static final String KEY_DB_SYNC_UPDATED = "db.sync.updated"; + /** + * 字段 KEY_RTC_AWS_ARN。 + */ public static final String KEY_RTC_AWS_ARN = "rtc.aws.arn"; + /** + * 字段 KEY_URL_VALIDATE_RSA。 + */ public static final String KEY_URL_VALIDATE_RSA = "url.validate.rsa"; + /** + * 文件列表RootDefault;从配置注入。 + * + * 注解:{@code @Value("${files.root:/MiDM/files}")}。 + */ @Value("${files.root:/MiDM/files}") private String filesRootDefault; + /** + * 策略协议服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private PolicyAgreementService policyAgreementService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private DeviceService deviceService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private HostLicenseService licenseService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private CloudStorageService cloudStorageService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private EmailService emailService; + /** + * restore服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy}。 + */ @Autowired @Lazy private RestoreService restoreService; + /** + * hostID。 + */ private String hostId; + /** + * websocketBuffer数量。 + */ private int websocketBufferSize = 65536; - private Map settingsMap = new HashMap(); + /** + * 设置列表Map。 + */ + private Map settingsMap = new HashMap(); + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;包含 8 个条件分支、1 个循环;主要调用:save。 + * + * @param settings 参数 {@code settings}({@code SystemSetting[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean save(SystemSetting... settings) { boolean isSucceed = true; @@ -97,27 +202,77 @@ public class SettingsService extends BaseService { return isSucceed; } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save、new SystemSetting。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @return 处理结果 + */ public SystemSetting save(String key, String value) { return this.save(new SystemSetting(key, value)); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Number}) + * @return 处理结果 + */ public SystemSetting save(String key, Number value) { return this.save(key, value.toString()); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code boolean}) + * @return 处理结果 + */ public SystemSetting save(String key, boolean value) { return this.save(key, String.valueOf(value)); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Date}) + * @return 处理结果 + */ public SystemSetting save(String key, Date value) { return this.save(key, (Number)value.getTime()); } + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:save。 + * + * @param setting 参数 {@code setting}({@code SystemSetting}) + * @return 处理结果 + */ public SystemSetting save(SystemSetting setting) { this.settingsMap.put(setting.getKey(), setting.getValue()); return (SystemSetting)this.mongoTemplate.save(setting); } + /** + * 处理hostID。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * @return 字符串结果 + */ public String hostId() { if (Strings.isNullOrEmpty(this.hostId)) { this.hostId = this.get("host.id"); @@ -131,6 +286,12 @@ public class SettingsService extends BaseService { return this.hostId; } + /** + * 处理started从。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * @return 数量/长度 + */ public long startedFrom() { long from = this.getLong("midm.startsFrom", -1L); if (from <= 0L) { @@ -141,6 +302,12 @@ public class SettingsService extends BaseService { return from; } + /** + * 获取 {@code firstUserCreated}。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Query、findOne、new Date。 + * @return 数量/长度 + */ private Long getFirstUserCreated() { Query query = new Query(Criteria.where("created").exists(true)); query.fields().include("created"); @@ -149,73 +316,148 @@ public class SettingsService extends BaseService { return user != null ? user.getCreated().getTime() : (new Date()).getTime(); } + /** + * 处理valid转换为。 + * @return 数量/长度 + */ public Long validTo() { return this.licenseService.validTo(); } + /** + * 获取 {@code deviceLimit}。 + * @return 数量/长度 + */ public int getDeviceLimit() { return this.licenseService.getDeviceLimit(); } + /** + * 处理设备Left。 + * @return 数量/长度 + */ public long deviceLeft() { return this.licenseService.deviceLeft(); } + /** + * 判断 {@code exceedDeviceLimit}。 + * @return 字段/派生属性 {@code exceedDeviceLimit} 的值 + */ public boolean isExceedDeviceLimit() { return this.deviceService.isExceedDeviceLimit(); } + /** + * 处理aboutExceed设备Limit。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean aboutExceedDeviceLimit() { long deviceLimit = (long)this.getDeviceLimit(); long deviceLeft = this.deviceLeft(); return deviceLimit != -1L && deviceLeft <= 30L && deviceLeft > 0L; } + /** + * 判断 {@code deviceLimit}。 + * @return 字段/派生属性 {@code deviceLimit} 的值 + */ public boolean hasDeviceLimit() { return this.isStandalone() && this.getDeviceLimit() > 0; } + /** + * 判断 {@code hostLicenseValid}。 + * @return 字段/派生属性 {@code hostLicenseValid} 的值 + */ public boolean isHostLicenseValid() { return this.licenseService.isValid(); } + /** + * 判断 {@code standalone}。 + * @return 字段/派生属性 {@code standalone} 的值 + */ public boolean isStandalone() { return this.licenseService.isStandalone(); } + /** + * 获取 {@code systemHash}。 + * @return 字符串结果 + */ public String getSystemHash() { return this.licenseService.getSystemHash(); } + /** + * 处理eulaEnabled。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean eulaEnabled() { return this.getBoolean("eulaEnabled"); } + /** + * 处理RSAEnabled。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean rsaEnabled() { return this.getBoolean("rsaEnabled", false); } + /** + * 处理willExpired。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean willExpired() { Long validTo = this.validTo(); return validTo != null && validTo > 0L; } + /** + * 处理webSocketBuffer数量。 + * @return 数量/长度 + */ public int webSocketBufferSize() { return this.websocketBufferSize; } + /** + * 处理存在。 + * + * @param key 键/配置项({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(String key) { return Strings.isNullOrEmpty(key) ? false : this.settingsMap.containsKey(key); } + /** + * 处理数据库Scheme。 + * @return 数量/长度 + */ public long dbScheme() { return this.getLong("db.scheme", -1L); } + /** + * 设置 {@code dbScheme}。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param scheme 参数 {@code scheme}({@code long}) + */ public void setDbScheme(long scheme) { this.save("db.scheme", (Number)scheme); } + /** + * 处理站点请求Recipients。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:parse。 + * @return 处理结果 + */ public InternetAddress[] siteRequestRecipients() { String receipients = this.get("recipients.siteRequest"); @@ -226,6 +468,14 @@ public class SettingsService extends BaseService { } } + /** + * 处理判断是否存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean has(String key) { if (this.settingsMap.containsKey(key)) { return !Strings.isNullOrEmpty((String)this.settingsMap.get(key)); @@ -234,6 +484,14 @@ public class SettingsService extends BaseService { } } + /** + * 处理获取。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、0 个循环;主要调用:save。 + * + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ public String get(String key) { if (Strings.isNullOrEmpty(key)) { return ""; @@ -254,19 +512,34 @@ public class SettingsService extends BaseService { this.settingsMap.put(key, setting.getValue()); return setting.getValue(); } else { - this.settingsMap.put(key, (Object)null); + this.settingsMap.put(key, null); return ""; } } } } + /** + * 处理获取。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code String}) + * @return 字符串结果 + */ public String get(String key, String defaultValue) { String value = (String)this.settingsMap.get(key); return Strings.isNullOrEmpty(value) ? defaultValue : value; } - public Iterable get(String[] keys) { + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:new ArrayList、new SystemSetting。 + * + * @param keys 参数 {@code keys}({@code String[]}) + * @return 结果集合,可能为空 + */ + public Iterable get(String[] keys) { ArrayList settings = new ArrayList(); for(String key : keys) { @@ -279,26 +552,67 @@ public class SettingsService extends BaseService { return settings; } + /** + * 获取Boolean。 + * + * @param key 键/配置项({@code String}) + * @return 字段/派生属性 {@code boolean} 的值 + */ public boolean getBoolean(String key) { return this.getBoolean(key, false); } + /** + * 获取Boolean。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code boolean}) + * @return 字段/派生属性 {@code boolean} 的值 + */ public boolean getBoolean(String key, boolean defaultValue) { return this.settingsMap.containsKey(key) ? Boolean.parseBoolean(this.get(key)) : defaultValue; } + /** + * 获取Int。 + * + * @param key 键/配置项({@code String}) + * @return 数量/长度 + */ public Integer getInt(String key) { return McNumberUtils.toInt(this.get(key), -1); } + /** + * 获取Int。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code int}) + * @return 数量/长度 + */ public Integer getInt(String key, int defaultValue) { return this.settingsMap.containsKey(key) ? McNumberUtils.toInt(this.get(key), -1) : defaultValue; } + /** + * 获取Long。 + * + * @param key 键/配置项({@code String}) + * @return 数量/长度 + */ public Long getLong(String key) { return this.getLong(key, -1L); } + /** + * 获取Long。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code long}) + * @return 数量/长度 + */ public Long getLong(String key, long defaultValue) { if (this.settingsMap.containsKey(key)) { String value = (String)this.settingsMap.get(key); @@ -311,42 +625,79 @@ public class SettingsService extends BaseService { return defaultValue; } + /** + * 处理重建索引。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:dropIndex、createIndex、new Document。 + * + * @param collection 参数 {@code collection}({@code String}) + */ public void reindex(String collection) { switch (collection) { - case "deviceReport": + case "deviceReport": { Long expiry = this.getLong("db.deviceReport.expireAfter", -1L); McMongoUtils.dropIndex(this.mongoTemplate, "deviceReport", new String[]{"reportedAt"}); McMongoUtils.createIndex(this.mongoTemplate, "deviceReport", new Document("reportedAt", 1), "reportedAt", (Boolean)null, expiry > 0L ? expiry : null); break; - case "midmLog": + } + case "midmLog": { Long expiry = this.getLong("db.midmLog.expireAfter", -1L); McMongoUtils.dropIndex(this.mongoTemplate, "midmLog", new String[]{"loggedAt"}); McMongoUtils.createIndex(this.mongoTemplate, "midmLog", new Document("loggedAt", 1), "loggedAt", (Boolean)null, expiry > 0L ? expiry : null); + } } } + /** + * 获取 {@code filesRootPath}。 + * @return 字符串结果 + */ public String getFilesRootPath() { String path = this.get("files.root"); return Strings.isNullOrEmpty(path) ? this.filesRootDefault : path; } + /** + * 获取 {@code syncServer}。 + * @return 字符串结果 + */ public String getSyncServer() { return this.get("db.sync.server"); } + /** + * 同步处理Starts。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean syncOnStarts() { return this.getBoolean("db.sync.onStarts"); } + /** + * 设置 {@code dbUpdated}。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param updatedAt 参数 {@code updatedAt}({@code long}) + */ public void setDbUpdated(long updatedAt) { this.save("db.sync.updated", (Number)updatedAt); } + /** + * 处理resource数据库Updated。 + * @return 数量/长度 + */ public long resourceDbUpdated() { return this.getLong("db.sync.updated", -1L); } + /** + * 加载设置列表。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 1 个条件分支、0 个循环;主要调用:findAll。 + */ public void loadSettings() { MapUtils.populateMap(this.settingsMap, this.mongoTemplate.findAll(SystemSetting.class), SystemSetting::getKey, SystemSetting::getValue); if (this.getBoolean("eulaEnabled") && !this.policyAgreementService.hasEula("service")) { diff --git a/src/main/java/com/midm/service/system/package-info.java b/src/main/java/com/midm/service/system/package-info.java new file mode 100644 index 0000000..c022e94 --- /dev/null +++ b/src/main/java/com/midm/service/system/package-info.java @@ -0,0 +1,18 @@ +/** + * 系统服务:设置、语言、License、备份恢复、帮助消息。 + * + *

本包主要类型: + *

    + *
  • {@link HelpMessageService}
  • + *
  • {@link HostLicenseService}
  • + *
  • {@link LicenseService}
  • + *
  • {@link LocaleService}
  • + *
  • {@link PolicyAgreementService}
  • + *
  • {@link RestoreService}
  • + *
  • {@link SettingsService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.system; diff --git a/src/main/java/com/midm/service/template/TemplateService.java b/src/main/java/com/midm/service/template/TemplateService.java index c0bb797..46bc902 100644 --- a/src/main/java/com/midm/service/template/TemplateService.java +++ b/src/main/java/com/midm/service/template/TemplateService.java @@ -11,13 +11,44 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Service; +/** + * 【业务服务】{@code TemplateService} + * + * 类职责: + *

    + *
  • 实现核心业务规则,协调 Repository/MongoTemplate、缓存、邮件与 WebSocket。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code FileService}。 + * + * 学习提示:先看 public 方法的入参/出参,再看 mongoTemplate 查询、事务边界和异常分支。 + */ @Service public class TemplateService extends BaseService { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired @Lazy @Qualifier("fileService")}。 + */ @Autowired @Lazy @Qualifier("fileService") private FileService fileService; + /** + * 处理保存。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 2 个条件分支、0 个循环;主要调用:save。 + * + * @param template 参数 {@code template}({@code MailTemplate}) + * @return 处理结果 + */ public MailTemplate save(MailTemplate template) { if (template != null && !Strings.isNullOrEmpty(template.getIdName())) { if (template.getCreated() == null) { @@ -30,10 +61,26 @@ public class TemplateService extends BaseService { return template; } + /** + * 处理查找。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:findOne。 + * + * @param idName 参数 {@code idName}({@code String}) + * @return 处理结果 + */ public MailTemplate find(String idName) { return (MailTemplate)this.mongoTemplate.findOne(Query.query(Criteria.where("_id").is(idName)), MailTemplate.class); } + /** + * 获取模板。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find。 + * + * @param idName 参数 {@code idName}({@code String}) + * @return 字符串结果 + */ public String getTemplate(String idName) { MailTemplate template = this.find(idName); if (template != null) { diff --git a/src/main/java/com/midm/service/template/package-info.java b/src/main/java/com/midm/service/template/package-info.java new file mode 100644 index 0000000..882f050 --- /dev/null +++ b/src/main/java/com/midm/service/template/package-info.java @@ -0,0 +1,12 @@ +/** + * 模板服务:从数据库加载邮件/消息模板。 + * + *

本包主要类型: + *

    + *
  • {@link TemplateService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.service.template; diff --git a/src/main/java/com/midm/webservice/battery/BatteryApi.java b/src/main/java/com/midm/webservice/battery/BatteryApi.java index f8c8b14..4b882fb 100644 --- a/src/main/java/com/midm/webservice/battery/BatteryApi.java +++ b/src/main/java/com/midm/webservice/battery/BatteryApi.java @@ -35,16 +35,62 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code BatteryApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code batteryService}(BatteryService):电池服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code BatteryService、DeviceService、UserService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/battery"}) public class BatteryApi { + /** + * 电池服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private BatteryService batteryService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 保存电池。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new TypeToken。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -62,6 +108,17 @@ public class BatteryApi { } } + /** + * 处理报表。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new TypeToken。 + * + * 框架注解:{@code @RequestMapping(value = {"/report"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @return 字符串结果 + */ @RequestMapping( value = {"/report"}, method = {RequestMethod.POST}, @@ -79,13 +136,27 @@ public class BatteryApi { } } + /** + * 设置注册状态。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/setRegisterState"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param batteryUuids 参数 {@code batteryUuids}({@code List}) + * @param registerState 参数 {@code registerState}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setRegisterState"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String setRegisterState(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam List batteryUuids, @RequestParam String registerState) { + public String setRegisterState(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam List batteryUuids, @RequestParam String registerState) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -95,6 +166,23 @@ public class BatteryApi { } } + /** + * 查找Batteries。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -127,6 +215,21 @@ public class BatteryApi { } } + /** + * 查找电池按。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBy"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param batteryUuid 参数 {@code batteryUuid}({@code UUID}) + * @param batterySerial 参数 {@code batterySerial}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBy"}, method = {RequestMethod.GET}, @@ -147,6 +250,21 @@ public class BatteryApi { } } + /** + * 查找电池日志。 + * + * 实现要点:包含 4 个条件分支、0 个循环;主要调用:new DateTime。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBatteryLog"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @param deviceSerial 参数 {@code deviceSerial}({@code String}) + * @param minOffset 参数 {@code minOffset}({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBatteryLog"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/battery/package-info.java b/src/main/java/com/midm/webservice/battery/package-info.java new file mode 100644 index 0000000..0ad7ddc --- /dev/null +++ b/src/main/java/com/midm/webservice/battery/package-info.java @@ -0,0 +1,12 @@ +/** + * 电池数据 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link BatteryApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.battery; diff --git a/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java b/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java index 7345fb7..d946789 100644 --- a/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java +++ b/src/main/java/com/midm/webservice/cloud/CloudStorageApi.java @@ -34,17 +34,66 @@ import software.amazon.awssdk.services.kinesisvideosignaling.model.GetIceServerC import software.amazon.awssdk.services.kinesisvideosignaling.model.GetIceServerConfigResponse; import software.amazon.awssdk.services.kinesisvideosignaling.model.IceServer; +/** + * 【Web 控制器】{@code CloudStorageApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code AWS_STUN}(String):字段 AWS_STUN
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
+ * + * 协作对象:{@code UserService、FileService、SettingsService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/cloud"}) public class CloudStorageApi { + /** + * 字段 AWS_STUN。 + */ private static final String AWS_STUN = "stun:stun.kinesisvideo.%s.amazonaws.com:443"; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 处理查找。 + * + * 框架注解:{@code @RequestMapping(value = {"/awsS3/regions"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/awsS3/regions"}, method = {RequestMethod.GET}, @@ -55,6 +104,18 @@ public class CloudStorageApi { return MidmResponse.getSucceedResponse((Object)AwsS3.getRegions()); } + /** + * 更新Meta信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateMetaInfo"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateMetaInfo"}, method = {RequestMethod.GET}, @@ -71,6 +132,18 @@ public class CloudStorageApi { } } + /** + * 获取AwsIceServer。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getAwsIceServer"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getAwsIceServer"}, method = {RequestMethod.GET}, @@ -98,7 +171,16 @@ public class CloudStorageApi { } } - private Pair getIceList(String arn, String region) { + /** + * 获取Ice列出。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、2 个循环;主要调用:new StringJoiner。 + * + * @param arn 参数 {@code arn}({@code String}) + * @param region 参数 {@code region}({@code String}) + * @return 字段/派生属性 {@code iceList} 的值 + */ + private Pair getIceList(String arn, String region) { try { KinesisVideoClient kinesisVideoClient = (KinesisVideoClient)((KinesisVideoClientBuilder)((KinesisVideoClientBuilder)KinesisVideoClient.builder().credentialsProvider(InstanceProfileCredentialsProvider.create())).region(Region.of(region))).build(); GetSignalingChannelEndpointRequest endPointRequest = (GetSignalingChannelEndpointRequest)GetSignalingChannelEndpointRequest.builder().channelARN(arn).singleMasterChannelEndpointConfiguration((SingleMasterChannelEndpointConfiguration)SingleMasterChannelEndpointConfiguration.builder().protocols(new ChannelProtocol[]{ChannelProtocol.HTTPS, ChannelProtocol.WSS}).role(ChannelRole.VIEWER).build()).build(); diff --git a/src/main/java/com/midm/webservice/cloud/package-info.java b/src/main/java/com/midm/webservice/cloud/package-info.java new file mode 100644 index 0000000..2cd7637 --- /dev/null +++ b/src/main/java/com/midm/webservice/cloud/package-info.java @@ -0,0 +1,12 @@ +/** + * 云存储配置 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link CloudStorageApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.cloud; diff --git a/src/main/java/com/midm/webservice/device/DeviceApi.java b/src/main/java/com/midm/webservice/device/DeviceApi.java index bfa7124..08ae0f5 100644 --- a/src/main/java/com/midm/webservice/device/DeviceApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceApi.java @@ -75,36 +75,134 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.socket.CloseStatus; +/** + * 【Web 控制器】{@code DeviceApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code deviceReportService}(DeviceReportService):设备报表服务
  • + *
  • {@code deviceAppsService}(DeviceAppsService):设备应用列表服务
  • + *
  • {@code deviceKeyService}(DeviceKeyService):设备密钥服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code hostLicenseService}(HostLicenseService):host许可证服务
  • + *
+ * + * 协作对象:{@code DeviceService、DeviceReportService、DeviceAppsService、DeviceKeyService、UserService、HostLicenseService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device"}) public class DeviceApi { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 设备报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceReportService deviceReportService; + /** + * 设备应用列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceAppsService deviceAppsService; + /** + * 设备密钥服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceKeyService deviceKeyService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * 检查Out。 + * + * 框架注解:{@code @RequestMapping(value = {"/checkIn"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param locale 参数 {@code locale}({@code Locale}) + * @param model 参数 {@code model}({@code Model}) + * @return 字符串结果 + */ @RequestMapping( value = {"/checkIn"}, method = {RequestMethod.POST}, @@ -115,6 +213,15 @@ public class DeviceApi { return null; } + /** + * 检查Out。 + * + * 框架注解:{@code @RequestMapping(value = {"/checkOut"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/checkOut"}, method = {RequestMethod.GET}, @@ -126,6 +233,18 @@ public class DeviceApi { return MidmResponse.getSucceedResponse(); } + /** + * 获取RemoteURL。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:new UserToken、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/remoteUrl/{serialNo}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param serialNo 设备序列号({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/remoteUrl/{serialNo}"}, method = {RequestMethod.GET}, @@ -151,6 +270,23 @@ public class DeviceApi { } } + /** + * 处理更新。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 15 个条件分支、1 个循环;主要调用:new TypeToken。 + * + * 框架注解:{@code @RequestMapping(value = {"/save", "/register"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save", "/register"}, method = {RequestMethod.POST}, @@ -239,6 +375,18 @@ public class DeviceApi { } } + /** + * 处理upsert设备。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 19 个条件分支、0 个循环;主要调用:save。 + * + * @param user 当前用户({@code User}) + * @param device 设备({@code Device}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @return 数量/长度 + */ private int upsertDevice(User user, Device device, UUID licenseModelUuid, boolean autoRenew, boolean renewToSameModel) { String serialNo = device.getSerialNo(); if (!Strings.isNullOrEmpty(serialNo)) { @@ -333,6 +481,21 @@ public class DeviceApi { } } + /** + * 处理change所有者。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、1 个循环;主要调用:new ArrayList、new MidmLog、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/changeOwner"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuids 设备 UUID 数组({@code String[]}) + * @param owner 参数 {@code owner}({@code User}) + * @param ownerUuid 所有者用户 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/changeOwner"}, method = {RequestMethod.POST}, @@ -375,6 +538,20 @@ public class DeviceApi { } } + /** + * 处理change设备分组。 + * + * 实现要点:调用持久化方法保存数据;包含 5 个条件分支、1 个循环;主要调用:new ArrayList、new MidmLog、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/changeGroup"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuids 设备 UUID 数组({@code String[]}) + * @param groupUuid 分组 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/changeGroup"}, method = {RequestMethod.POST}, @@ -415,6 +592,19 @@ public class DeviceApi { } } + /** + * 更新设备配置档案。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new MidmLog、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/update/{deviceUuid}/{key}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/update/{deviceUuid}/{key}"}, method = {RequestMethod.POST}, @@ -434,6 +624,18 @@ public class DeviceApi { return result.getModifiedCount() > 0L ? MidmResponse.getSucceedResponse() : MidmResponse.getFailedResponse(); } + /** + * 处理upsertRSAPrivate密钥。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:delete、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/upsertRsa"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upsertRsa"}, method = {RequestMethod.POST}, @@ -465,6 +667,17 @@ public class DeviceApi { } } + /** + * 处理报表。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 21 个条件分支、2 个循环;主要调用:new TypeToken、new ArrayList、remove、new MidmLog、exists、new MidmPacket。 + * + * 框架注解:{@code @RequestMapping(value = {"/report"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/report"}, method = {RequestMethod.POST}, @@ -601,6 +814,22 @@ public class DeviceApi { } } + /** + * 处理位置。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/location"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param from 起始时间({@code Long}) + * @param to 结束时间({@code Long}) + * @return 字符串结果 + */ @RequestMapping( value = {"/location"}, method = {RequestMethod.GET}, @@ -632,6 +861,26 @@ public class DeviceApi { } } + /** + * 处理数据用量。 + * + * 实现要点:包含 7 个条件分支、0 个循环;主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/dataUsage"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param networkType 参数 {@code networkType}({@code String}) + * @param from 起始时间({@code Date}) + * @param to 结束时间({@code Date}) + * @param frequency 参数 {@code frequency}({@code McDateTimeUtils.FREQUENCY}) + * @param separate 参数 {@code separate}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dataUsage"}, method = {RequestMethod.GET}, @@ -674,6 +923,20 @@ public class DeviceApi { } } + /** + * 处理最新位置。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/latestLocation"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latestLocation"}, method = {RequestMethod.GET}, @@ -701,6 +964,22 @@ public class DeviceApi { } } + /** + * 查找设备UUID的报表。 + * + * 实现要点:包含 4 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/reports"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param key 键/配置项({@code String}) + * @param limit 数量上限({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/reports"}, method = {RequestMethod.GET}, @@ -730,6 +1009,21 @@ public class DeviceApi { } } + /** + * 获取Progress。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/profile/progress"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/profile/progress"}, method = {RequestMethod.GET}, @@ -745,6 +1039,20 @@ public class DeviceApi { } } + /** + * 获取ProgressHTML。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/profile/progress/{deviceUuid}/{profileUuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/profile/progress/{deviceUuid}/{profileUuid}"}, method = {RequestMethod.GET}, @@ -765,6 +1073,22 @@ public class DeviceApi { } } + /** + * 根据UUID查找String。 + * + * 实现要点:调用持久化方法保存数据;包含 12 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBy"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param minify 参数 {@code minify}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBy"}, method = {RequestMethod.GET}, @@ -826,6 +1150,27 @@ public class DeviceApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 9 个条件分支、1 个循环;主要调用:find、new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param deviceScope 参数 {@code deviceScope}({@code boolean}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param blocked 参数 {@code blocked}({@code boolean}) + * @param licenseFilter 参数 {@code licenseFilter}({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -881,6 +1226,18 @@ public class DeviceApi { } } + /** + * 处理统计。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/count"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/count"}, method = {RequestMethod.GET}, @@ -899,6 +1256,18 @@ public class DeviceApi { } } + /** + * 判断是否Alive。 + * + * 实现要点:通过 WebSocket 会话推送消息。 + * + * 框架注解:{@code @RequestMapping(value = {"/isAlive/{deviceUuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/isAlive/{deviceUuid}"}, method = {RequestMethod.GET}, @@ -910,6 +1279,19 @@ public class DeviceApi { return MidmResponse.getSucceedResponse((Object)isOnline); } + /** + * 判断是否Alive。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/isAlive/{serialNo}/{androidId}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param serialNo 设备序列号({@code String}) + * @param androidId 参数 {@code androidId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/isAlive/{serialNo}/{androidId}"}, method = {RequestMethod.GET}, @@ -933,6 +1315,15 @@ public class DeviceApi { return MidmResponse.getResponse(200, (String)null, isOnline); } + /** + * 清理非Existing分组。 + * + * 框架注解:{@code @RequestMapping(value = {"/clearNotExisting"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/clearNotExisting"}, method = {RequestMethod.GET}, @@ -944,6 +1335,21 @@ public class DeviceApi { return MidmResponse.getSucceedResponse((Object)count); } + /** + * 处理enabledDisabled按分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/enableByGroup"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + * @param filter 过滤条件({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enableByGroup"}, method = {RequestMethod.POST}, @@ -960,13 +1366,30 @@ public class DeviceApi { } } + /** + * 处理enabledDisabled按Single。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 6 个条件分支、2 个循环;主要调用:new ArrayList、new MidmLog、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param uuids UUID 集合({@code List}) + * @param devices 参数 {@code devices}({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String enabledDisabledBySingle(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,name = "uuid") List uuids, @RequestBody(required = false) List devices) { + public String enabledDisabledBySingle(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(required = false) UUID deviceUuid, @RequestParam(required = false,name = "uuid") List uuids, @RequestBody(required = false) List devices) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -1000,6 +1423,21 @@ public class DeviceApi { } } + /** + * 处理unblock。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 6 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/unblock"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/unblock"}, method = {RequestMethod.POST}, @@ -1033,13 +1471,29 @@ public class DeviceApi { } } + /** + * 处理删除。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、1 个循环;主要调用:new ArrayList、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param ids ID 集合({@code List}) + * @param device 设备({@code Device}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false,name = "uuids") List ids, @RequestBody(required = false) Device device) { + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false,name = "uuids") List ids, @RequestBody(required = false) Device device) { if (this.hostLicenseService.getDeviceLimit() > 0) { return MidmResponse.getResponse(421, "Not authorized."); } else { @@ -1084,13 +1538,28 @@ public class DeviceApi { } } + /** + * 处理retire。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/retire"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param uuids UUID 集合({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/retire"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String retire(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) List uuids) { + public String retire(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) List uuids) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -1107,6 +1576,21 @@ public class DeviceApi { } } + /** + * 处理存在。 + * + * 实现要点:主要调用:exists。 + * + * 框架注解:{@code @RequestMapping(value = {"/exists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/exists"}, method = {RequestMethod.GET}, @@ -1117,6 +1601,21 @@ public class DeviceApi { return MidmResponse.getSucceedResponse((Object)this.deviceService.exists(siteUuid, serialNo)); } + /** + * 处理renew。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/renew"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/renew"}, method = {RequestMethod.GET}, @@ -1141,6 +1640,25 @@ public class DeviceApi { } } + /** + * 应用许可证。 + * + * 实现要点:包含 9 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/apply"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param deviceUuids 设备 UUID 数组({@code UUID[]}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param keepModel 参数 {@code keepModel}({@code boolean}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/apply"}, method = {RequestMethod.POST}, @@ -1181,9 +1699,9 @@ public class DeviceApi { return MidmResponse.getResponse(433, "No permission."); } - DeviceLicense license = this.deviceService.setLicense(device, licenseModelUuid, keepModel, autoRenew, renewToSameModel); - if (license != null) { - licenes.add(license); + DeviceLicense deviceLicense = this.deviceService.setLicense(device, licenseModelUuid, keepModel, autoRenew, renewToSameModel); + if (deviceLicense != null) { + licenes.add(deviceLicense); ++var16; continue; } @@ -1197,6 +1715,20 @@ public class DeviceApi { } } + /** + * 移除许可证。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/remove"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/remove"}, method = {RequestMethod.POST}, @@ -1225,6 +1757,21 @@ public class DeviceApi { } } + /** + * 处理transfer许可证。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/transfer"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/transfer"}, method = {RequestMethod.POST}, @@ -1253,6 +1800,21 @@ public class DeviceApi { } } + /** + * 判断是否Transfer。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/canTransfer"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/canTransfer"}, method = {RequestMethod.GET}, @@ -1275,6 +1837,20 @@ public class DeviceApi { } } + /** + * 重置许可证。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/reset"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param serialNo 设备序列号({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/reset"}, method = {RequestMethod.POST}, @@ -1296,6 +1872,22 @@ public class DeviceApi { } } + /** + * 处理reactivate。 + * + * 实现要点:包含 11 个条件分支、0 个循环;主要调用:addLicenseLog。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/extend"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param serialNo 设备序列号({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param licenseUuid 许可证 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/extend"}, method = {RequestMethod.POST}, @@ -1331,9 +1923,7 @@ public class DeviceApi { if (device != null) { this.deviceService.updateLicenseExpiry(device, expiry); User user = this.userService.authorizedUser(authentication, accessToken); - DeviceService var10000 = this.deviceService; - String var10005 = user.getEmail(); - var10000.addLicenseLog(license, device, (Device)null, "reactivated", "License extended by " + var10005 + ", extension count = " + license.getReactivated().size()); + this.deviceService.addLicenseLog(license, device, (Device)null, "reactivated", "License extended by " + user.getEmail() + ", extension count = " + license.getReactivated().size()); } if (license != null) { @@ -1346,6 +1936,16 @@ public class DeviceApi { } } + /** + * 处理qr代码。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:encrypt、new String。 + * + * 框架注解:{@code @RequestMapping(value = {"/enroll/qr"}, method = {RequestMethod.GET})}。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param params 参数 {@code params}({@code String}) + */ @RequestMapping( value = {"/enroll/qr"}, method = {RequestMethod.GET} @@ -1362,6 +1962,18 @@ public class DeviceApi { } + /** + * 处理qr注册。 + * + * 框架注解:{@code @RequestMapping(value = {"/qrTemplate"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @param print 参数 {@code print}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/qrTemplate"}, method = {RequestMethod.GET} @@ -1372,6 +1984,20 @@ public class DeviceApi { return loggedUser == null ? MidmResponse.getResponse(415, "Not authorized.") : this.deviceService.qrTemplate(loggedUser, code, print); } + /** + * 查找分组。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/group"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param path 参数 {@code path}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/group"}, method = {RequestMethod.GET}, @@ -1388,6 +2014,26 @@ public class DeviceApi { } } + /** + * 处理配置档案列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、1 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/profiles"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param userAgent 参数 {@code userAgent}({@code UserAgent}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param clientVersion 参数 {@code clientVersion}({@code long}) + * @param withRef 参数 {@code withRef}({@code boolean}) + * @param minify 参数 {@code minify}({@code boolean}) + * @return 字符串结果 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ @RequestMapping( value = {"/profiles"}, method = {RequestMethod.GET}, @@ -1428,6 +2074,20 @@ public class DeviceApi { } } + /** + * 上传Screen。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new McFile、write。 + * + * 框架注解:{@code @RequestMapping(value = {"upload/screen"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param file 文件({@code MultipartFile}) + * @return 字符串结果 + */ @RequestMapping( value = {"upload/screen"}, method = {RequestMethod.POST}, @@ -1449,6 +2109,20 @@ public class DeviceApi { } } + /** + * 上传文件。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new McFile、write。 + * + * 框架注解:{@code @RequestMapping(value = {"upload/file"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param file 文件({@code MultipartFile}) + * @return 字符串结果 + */ @RequestMapping( value = {"upload/file"}, method = {RequestMethod.POST}, @@ -1472,6 +2146,19 @@ public class DeviceApi { return MidmResponse.getSucceedResponse(); } + /** + * 上传设备列出。 + * + * 实现要点:主要调用:new DevicesParser。 + * + * 框架注解:{@code @RequestMapping(value = {"upload/list"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"upload/list"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/DeviceAppApi.java b/src/main/java/com/midm/webservice/device/DeviceAppApi.java index 19d5724..af2bd9f 100644 --- a/src/main/java/com/midm/webservice/device/DeviceAppApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceAppApi.java @@ -32,20 +32,81 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code DeviceAppApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code deviceAppsService}(DeviceAppsService):设备应用列表服务
  • + *
  • {@code websocketSessionManager}(WebSocketSessionManager):websocket会话Manager
  • + *
+ * + * 协作对象:{@code UserService、FileService、DeviceService、DeviceAppsService、WebSocketSessionManager}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/app"}) public class DeviceAppApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 设备应用列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceAppsService deviceAppsService; + /** + * websocket会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager websocketSessionManager; + /** + * 处理install。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write、new AppFile、new MidmPacket。 + * + * 框架注解:{@code @RequestMapping(value = {"install"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @return 字符串结果 + */ @RequestMapping( value = {"install"}, method = {RequestMethod.POST}, @@ -99,6 +160,20 @@ public class DeviceAppApi { } } + /** + * 处理移除。 + * + * 实现要点:主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"remove/userfile/{userUuid}/{fileUuid}/{fileName}", "forgetNetwork/userfile/{userUuid}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param userUuid 用户 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"remove/userfile/{userUuid}/{fileUuid}/{fileName}", "forgetNetwork/userfile/{userUuid}/{fileUuid}/{fileName}"}, method = {RequestMethod.GET} @@ -110,6 +185,21 @@ public class DeviceAppApi { return MidmResponse.getSucceedResponse(); } + /** + * 获取Installed。 + * + * 实现要点:包含 7 个条件分支、0 个循环;主要调用:new DeviceApps。 + * + * 框架注解:{@code @RequestMapping(value = {"installed"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param uuid 对象 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"installed"}, method = {RequestMethod.GET}, @@ -151,6 +241,25 @@ public class DeviceAppApi { } } + /** + * 判断是否Installed。 + * + * 实现要点:包含 7 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"isInstalled"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param uuid 对象 UUID({@code UUID}) + * @param serialNo 设备序列号({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdk 参数 {@code minSdk}({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"isInstalled"}, method = {RequestMethod.GET}, @@ -192,6 +301,16 @@ public class DeviceAppApi { } } + /** + * 获取Clients。 + * + * 框架注解:{@code @RequestMapping(value = {"clients"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"clients"}, method = {RequestMethod.GET}, @@ -202,6 +321,17 @@ public class DeviceAppApi { return MidmResponse.getSucceedResponse(this.deviceService.getClients()); } + /** + * 更新Installed。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"installed/update"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"installed/update"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/DeviceFilesApi.java b/src/main/java/com/midm/webservice/device/DeviceFilesApi.java index 3203cd0..4cff945 100644 --- a/src/main/java/com/midm/webservice/device/DeviceFilesApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceFilesApi.java @@ -31,18 +31,75 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code DeviceFilesApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code deviceFilesService}(DeviceFilesService):设备文件列表服务
  • + *
  • {@code websocketSessionManager}(WebSocketSessionManager):websocket会话Manager
  • + *
+ * + * 协作对象:{@code FileService、UserService、DeviceFilesService、WebSocketSessionManager}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/files"}) public class DeviceFilesApi { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 设备文件列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceFilesService deviceFilesService; + /** + * websocket会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager websocketSessionManager; + /** + * 处理推送。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write、new BaseFile、new MidmPacket。 + * + * 框架注解:{@code @RequestMapping(value = {"push"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param path 参数 {@code path}({@code String}) + * @param extract 参数 {@code extract}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"push"}, method = {RequestMethod.POST}, @@ -93,6 +150,23 @@ public class DeviceFilesApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -113,6 +187,20 @@ public class DeviceFilesApi { } } + /** + * 处理findone。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findone"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findone"}, method = {RequestMethod.GET}, @@ -129,6 +217,18 @@ public class DeviceFilesApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/DeviceGroupApi.java b/src/main/java/com/midm/webservice/device/DeviceGroupApi.java index 9411eaf..2a96c69 100644 --- a/src/main/java/com/midm/webservice/device/DeviceGroupApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceGroupApi.java @@ -23,16 +23,63 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code DeviceGroupApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
+ * + * 协作对象:{@code DeviceService、UserService、LogService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/group"}) public class DeviceGroupApi { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:new Date、save、new MidmLog。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -70,6 +117,19 @@ public class DeviceGroupApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param count 参数 {@code count}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -88,6 +148,19 @@ public class DeviceGroupApi { } } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:new MidmLog、save、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java b/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java index 3159ec0..572bd6a 100644 --- a/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceLicenseApi.java @@ -25,18 +25,80 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code DeviceLicenseApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code licenseService}(LicenseService):许可证服务
  • + *
+ * + * 协作对象:{@code DeviceService、UserService、SiteService、LicenseService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/licenses"}) public class DeviceLicenseApi { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param modelUuid 参数 {@code modelUuid}({@code UUID}) + * @param filter 过滤条件({@code JsonObject}) + * @param plan 参数 {@code plan}({@code String}) + * @param licensed 参数 {@code licensed}({@code boolean}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param licenseFilter 参数 {@code licenseFilter}({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -60,6 +122,19 @@ public class DeviceLicenseApi { } } + /** + * 处理日志。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/device/DeviceNoteApi.java b/src/main/java/com/midm/webservice/device/DeviceNoteApi.java index 27935a2..76f3b7b 100644 --- a/src/main/java/com/midm/webservice/device/DeviceNoteApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceNoteApi.java @@ -19,14 +19,55 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code DeviceNoteApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code DeviceService、UserService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/note"}) public class DeviceNoteApi { + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -53,6 +94,19 @@ public class DeviceNoteApi { } } + /** + * 根据UUID查找String。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/recent"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/recent"}, method = {RequestMethod.GET}, @@ -69,6 +123,21 @@ public class DeviceNoteApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/list"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param pageNum 参数 {@code pageNum}({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/list"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/device/DeviceProfileApi.java b/src/main/java/com/midm/webservice/device/DeviceProfileApi.java index 66211e3..a87aba7 100644 --- a/src/main/java/com/midm/webservice/device/DeviceProfileApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceProfileApi.java @@ -52,26 +52,101 @@ import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.HandlerMapping; +/** + * 【Web 控制器】{@code DeviceProfileApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code profileAdvisor}(ProfileAdvisor):配置档案Advisor
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code mustProfileService}(MustProfileService):must配置档案服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
+ * + * 协作对象:{@code ProfileService、ProfileAdvisor、DeviceService、MustProfileService、FileService、LogService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/profile"}) public class DeviceProfileApi { + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 配置档案Advisor;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileAdvisor profileAdvisor; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * must配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MustProfileService mustProfileService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * scheduled任务服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ScheduledTaskService scheduledTaskService; + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 8 个条件分支、0 个循环;主要调用:new DateTime、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -126,13 +201,28 @@ public class DeviceProfileApi { } } + /** + * 处理enabledDisabled配置档案列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param enabled 参数 {@code enabled}({@code boolean}) + * @param uuids UUID 集合({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String enabledDisabledProfiles(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(name = "uuid") List uuids) { + public String enabledDisabledProfiles(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) boolean enabled, @RequestParam(name = "uuid") List uuids) { User loggeduser = this.userService.authorizedUser(authentication, accessToken); if (loggeduser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -142,13 +232,28 @@ public class DeviceProfileApi { } } + /** + * 设置Sequence。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/sequence/set"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuids UUID 集合({@code List}) + * @param rmUuids 参数 {@code rmUuids}({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sequence/set"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String setSequence(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "sequence") List uuids, @RequestParam(name = "rmSequence",defaultValue = "") List rmUuids) { + public String setSequence(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "sequence") List uuids, @RequestParam(name = "rmSequence",defaultValue = "") List rmUuids) { User loggeduser = this.userService.authorizedUser(authentication, accessToken); if (loggeduser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -162,6 +267,20 @@ public class DeviceProfileApi { } } + /** + * 处理unsetSequence。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/sequence/unset"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sequence/unset"}, method = {RequestMethod.POST}, @@ -178,6 +297,18 @@ public class DeviceProfileApi { } } + /** + * 处理must模型更新。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 10 个条件分支、1 个循环;主要调用:new McFile、exists、save。 + * + * 框架注解:{@code @RequestMapping(value = {"must/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"must/save"}, method = {RequestMethod.POST}, @@ -242,6 +373,24 @@ public class DeviceProfileApi { } } + /** + * 处理查找。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -274,6 +423,25 @@ public class DeviceProfileApi { } } + /** + * 查找设备列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/devices"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/devices"}, method = {RequestMethod.GET}, @@ -290,6 +458,20 @@ public class DeviceProfileApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -306,6 +488,26 @@ public class DeviceProfileApi { } } + /** + * 处理查找。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/{profileUuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param withRef 参数 {@code withRef}({@code boolean}) + * @param clientVersion 参数 {@code clientVersion}({@code long}) + * @param updated 参数 {@code updated}({@code long}) + * @param minify 参数 {@code minify}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{profileUuid}"}, method = {RequestMethod.GET}, @@ -340,6 +542,23 @@ public class DeviceProfileApi { } } + /** + * 查找模型配置档案。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"{modelSite}/{profileUuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param modelSite 参数 {@code modelSite}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param minify 参数 {@code minify}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"{modelSite}/{profileUuid}"}, method = {RequestMethod.GET}, @@ -364,6 +583,23 @@ public class DeviceProfileApi { } } + /** + * 获取路径。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"{modelSite}/{profileUuid}/**"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param modelSite 参数 {@code modelSite}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @param minify 参数 {@code minify}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"{modelSite}/{profileUuid}/**"}, method = {RequestMethod.GET}, @@ -387,6 +623,21 @@ public class DeviceProfileApi { } } + /** + * 添加Folder。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/addFolder/{modelSite}/{profileUuid}/**"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param newFolder 参数 {@code newFolder}({@code String}) + * @param modelSite 参数 {@code modelSite}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/addFolder/{modelSite}/{profileUuid}/**"}, method = {RequestMethod.POST}, @@ -414,6 +665,22 @@ public class DeviceProfileApi { } } + /** + * 删除文件列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/deleteFiles/{modelSite}/{profileUuid}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filePath 参数 {@code filePath}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param modelSite 参数 {@code modelSite}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/deleteFiles/{modelSite}/{profileUuid}"}, method = {RequestMethod.POST}, @@ -435,6 +702,23 @@ public class DeviceProfileApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 9 个条件分支、0 个循环;主要调用:find、new Date、new McFile、exists、delete、write。 + * + * 框架注解:{@code @RequestMapping(value = {"{modelSite}/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code Long}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param currentPath 参数 {@code currentPath}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"{modelSite}/upload"}, method = {RequestMethod.POST}, @@ -495,6 +779,19 @@ public class DeviceProfileApi { } } + /** + * 根据模型查找String。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:findOne。 + * + * 框架注解:{@code @RequestMapping(value = {"/b2c"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/b2c"}, method = {RequestMethod.GET}, @@ -511,6 +808,19 @@ public class DeviceProfileApi { } } + /** + * 应用按设备。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/applyByDevice"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/applyByDevice"}, method = {RequestMethod.POST}, @@ -537,6 +847,22 @@ public class DeviceProfileApi { } } + /** + * 处理应用。 + * + * 实现要点:调用持久化方法保存数据;包含 21 个条件分支、1 个循环;主要调用:find、remove、new Date、new DateTime、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/apply"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return 字符串结果 + */ @RequestMapping( value = {"/apply"}, method = {RequestMethod.POST}, @@ -650,6 +976,15 @@ public class DeviceProfileApi { } } + /** + * 通知转换为应用。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save、new Document。 + * + * @param user 当前用户({@code User}) + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + * @return MongoDB 文档对象 + */ private Document notifyToApply(User user, DeviceProfile deviceProfile) { this.scheduledTaskService.cancelSchedule(deviceProfile.getUuid()); if (this.profileService.notifyUpdate(deviceProfile, true)) { @@ -661,6 +996,13 @@ public class DeviceProfileApi { return (new Document("uuid", deviceProfile.getUuid())).append("name", deviceProfile.getName()).append("updated", deviceProfile.getUpdated().getTime()); } + /** + * 更新Scoped设备列表。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 10 个条件分支、2 个循环;主要调用:new ArrayList、new Device、save。 + * + * @param deviceProfile 参数 {@code deviceProfile}({@code DeviceProfile}) + */ private void updateScopedDevices(DeviceProfile deviceProfile) { if (deviceProfile.isGlobal()) { deviceProfile.setScope((ProfileScope)null); @@ -724,6 +1066,19 @@ public class DeviceProfileApi { } } + /** + * 应用全部。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/applyAll"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profile 设备配置档案({@code DeviceProfile}) + * @return 字符串结果 + */ @RequestMapping( value = {"/applyAll"}, method = {RequestMethod.POST}, @@ -751,12 +1106,28 @@ public class DeviceProfileApi { } } + /** + * 处理设备分组Removed。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/sync"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param code 状态码/业务码({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sync"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody + @SuppressWarnings("fallthrough") public String deviceGroupRemoved(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam("profile") UUID profileUuid, @RequestParam("group") UUID groupUuid, @RequestParam("status") int code) { User user = this.userService.authorizedUser(authentication, accessToken); if (user == null) { @@ -772,6 +1143,7 @@ public class DeviceProfileApi { switch (code) { case 136: command = "remove_profile"; + // fall through: case 136 still needs the default device-notification loop below default: for(Device device : this.deviceService.findAllDevicesInGroup(groupUuid, (JsonObject)null)) { this.profileService.notifyToSync(device, profileUuid, command, code); @@ -783,13 +1155,27 @@ public class DeviceProfileApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new ArrayList、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuids UUID 集合({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "uuid",required = false) List uuids) { + public String delete(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(name = "uuid",required = false) List uuids) { User user = this.userService.authorizedUser(authentication, accessToken); if (user == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -813,6 +1199,19 @@ public class DeviceProfileApi { } } + /** + * 处理must配置档案删除。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:exists、delete、new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"must/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"must/delete"}, method = {RequestMethod.POST}, @@ -838,6 +1237,20 @@ public class DeviceProfileApi { } } + /** + * 生成文件。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:exists。 + * + * 框架注解:{@code @RequestMapping(value = {"must/generate"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"must/generate"}, method = {RequestMethod.POST}, @@ -861,6 +1274,21 @@ public class DeviceProfileApi { } } + /** + * 下载文件。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"must/download"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param file 文件({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"must/download"}, method = {RequestMethod.GET}, @@ -881,13 +1309,30 @@ public class DeviceProfileApi { return MidmResponse.getSucceedResponse(); } + /** + * 更新范围。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 11 个条件分支、0 个循环;主要调用:new HashSet、new Device、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/{profileUuid}/scope/{command}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profileUuid 配置档案 UUID({@code UUID}) + * @param command 参数 {@code command}({@code String}) + * @param registerIfNotExists 参数 {@code registerIfNotExists}({@code boolean}) + * @param devices 参数 {@code devices}({@code Set}) + * @param groups 参数 {@code groups}({@code Set}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{profileUuid}/scope/{command}"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String updateScope(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID profileUuid, @PathVariable String command, @RequestParam(required = false,defaultValue = "false") boolean registerIfNotExists, @RequestParam(name = "device",required = false,defaultValue = "") Set devices, @RequestParam(name = "group",required = false,defaultValue = "") Set groups) { + public String updateScope(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable UUID profileUuid, @PathVariable String command, @RequestParam(required = false,defaultValue = "false") boolean registerIfNotExists, @RequestParam(name = "device",required = false,defaultValue = "") Set devices, @RequestParam(name = "group",required = false,defaultValue = "") Set groups) { if (!command.equals("add") && !command.equals("remove")) { return MidmResponse.getResponse(422, "Unknown command. only allowed to be 'add | remove'."); } else { @@ -958,6 +1403,18 @@ public class DeviceProfileApi { } } + /** + * 处理统计。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/count"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/count"}, method = {RequestMethod.GET}, @@ -976,6 +1433,17 @@ public class DeviceProfileApi { } } + /** + * 处理advice。 + * + * 框架注解:{@code @RequestMapping(value = {"/advice"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/advice"}, method = {RequestMethod.GET}, @@ -987,6 +1455,21 @@ public class DeviceProfileApi { return MidmResponse.getSucceedResponse((Object)conflicts); } + /** + * 上传配置档案。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环;主要调用:new DeviceProfile、new DateTime、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/import"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param file 文件({@code MultipartFile}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param groupUuid 分组 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/import"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java b/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java index 1a834eb..f21a323 100644 --- a/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java +++ b/src/main/java/com/midm/webservice/device/DeviceProfileGroupApi.java @@ -22,16 +22,63 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code DeviceProfileGroupApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
+ * + * 协作对象:{@code ProfileService、UserService、LogService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/device/profile/group"}) public class DeviceProfileGroupApi { + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:new Date、save、new MidmLog。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -69,6 +116,18 @@ public class DeviceProfileGroupApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -87,6 +146,19 @@ public class DeviceProfileGroupApi { } } + /** + * 处理删除。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:new MidmLog、save、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/device/package-info.java b/src/main/java/com/midm/webservice/device/package-info.java new file mode 100644 index 0000000..4ad3443 --- /dev/null +++ b/src/main/java/com/midm/webservice/device/package-info.java @@ -0,0 +1,19 @@ +/** + * 设备管理 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link DeviceApi}
  • + *
  • {@link DeviceAppApi}
  • + *
  • {@link DeviceFilesApi}
  • + *
  • {@link DeviceGroupApi}
  • + *
  • {@link DeviceLicenseApi}
  • + *
  • {@link DeviceNoteApi}
  • + *
  • {@link DeviceProfileApi}
  • + *
  • {@link DeviceProfileGroupApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.device; diff --git a/src/main/java/com/midm/webservice/files/AppsApi.java b/src/main/java/com/midm/webservice/files/AppsApi.java index 0a04359..02d9390 100644 --- a/src/main/java/com/midm/webservice/files/AppsApi.java +++ b/src/main/java/com/midm/webservice/files/AppsApi.java @@ -41,18 +41,77 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code AppsApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code FileService、ProfileService、UserService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/apps"}) public class AppsApi { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理查找。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:new JsonObject。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -87,6 +146,22 @@ public class AppsApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -113,6 +188,19 @@ public class AppsApi { } } + /** + * 处理设备配置档案列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/profiles/{uuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/profiles/{uuid}"}, method = {RequestMethod.GET}, @@ -129,6 +217,20 @@ public class AppsApi { } } + /** + * 处理信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new JsonObject、new MidmResponse。 + * + * 框架注解:{@code @RequestMapping(value = {"/info/{uuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @param versionCode 参数 {@code versionCode}({@code long}) + * @param minify 参数 {@code minify}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info/{uuid}"}, method = {RequestMethod.GET}, @@ -147,13 +249,28 @@ public class AppsApi { } } + /** + * 处理信息。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new HashMap、new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuids UUID 集合({@code List}) + * @param expiries 参数 {@code expiries}({@code List}) + * @param checksums 参数 {@code checksums}({@code List}) + * @param minify 参数 {@code minify}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"} ) @ResponseBody - public String info(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam(required = false) List expiries, @RequestParam(required = false) List checksums, @RequestParam(required = false,defaultValue = "false") Boolean minify) { + public String info(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam(required = false) List expiries, @RequestParam(required = false) List checksums, @RequestParam(required = false,defaultValue = "false") Boolean minify) { Map results = new HashMap(); for(int i = 0; i < uuids.size(); ++i) { @@ -173,6 +290,18 @@ public class AppsApi { return MidmResponse.getSucceedResponse((Object)results); } + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -194,6 +323,19 @@ public class AppsApi { } } + /** + * 更新Extras。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateExtras"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateExtras"}, method = {RequestMethod.POST}, @@ -212,6 +354,20 @@ public class AppsApi { } } + /** + * 处理重命名。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/rename"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/rename"}, method = {RequestMethod.POST}, @@ -228,6 +384,19 @@ public class AppsApi { } } + /** + * 处理名称存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/nameExists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/nameExists"}, method = {RequestMethod.GET}, @@ -244,6 +413,18 @@ public class AppsApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -265,6 +446,22 @@ public class AppsApi { } } + /** + * 添加Link。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 7 个条件分支、0 个循环;主要调用:new JsonObject。 + * + * 框架注解:{@code @RequestMapping(value = {"/addLink"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param url 参数 {@code url}({@code URL}) + * @param keepInHost 参数 {@code keepInHost}({@code Boolean}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/addLink"}, method = {RequestMethod.POST}, @@ -320,6 +517,22 @@ public class AppsApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param file 文件({@code MultipartFile}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -345,13 +558,27 @@ public class AppsApi { try { return this.writeFile(user, appFile, file.getInputStream(), originalFileName, lastModified, (String)null, notifyToUpdate, request.getParameterMap()); } catch (Exception e) { - String var10001 = e.getMessage(); - return MidmResponse.getResponse(400, var10001 + " -> " + originalFileName); + return MidmResponse.getResponse(400, e.getMessage() + " -> " + originalFileName); } } } - private String writeFile(User user, AppFile orgAppFile, InputStream input, String fileName, long lastModified, String url, boolean notifyToUpdate, Map params) { + /** + * 写入文件。 + * + * 实现要点:调用持久化方法保存数据;包含 8 个条件分支、0 个循环;主要调用:new McFile、write、new AppFile、delete、save、upload。 + * + * @param user 当前用户({@code User}) + * @param orgAppFile 参数 {@code orgAppFile}({@code AppFile}) + * @param input 参数 {@code input}({@code InputStream}) + * @param fileName 文件名({@code String}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param url 参数 {@code url}({@code String}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code boolean}) + * @param params 参数 {@code params}({@code Map}) + * @return 字符串结果 + */ + private String writeFile(User user, AppFile orgAppFile, InputStream input, String fileName, long lastModified, String url, boolean notifyToUpdate, Map params) { UUID fileUuid = UUID.randomUUID(); String filePath = this.fileService.getFilePath(user.getSiteUuid(), "app", fileUuid); McFile targetFile = new McFile(filePath); @@ -413,6 +640,16 @@ public class AppsApi { } } + /** + * 查找名称。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param label 参数 {@code label}({@code String}) + * @return 字符串结果 + */ private String findName(UUID siteUuid, UUID fileUuid, String label) { String name = label; @@ -422,6 +659,13 @@ public class AppsApi { return name; } + /** + * 删除应用。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:delete。 + * + * @param appFile 参数 {@code appFile}({@code McFile}) + */ private void deleteApp(McFile appFile) { McFile parentFile = appFile.getParentFile(); FilenameFilter filenameFilter = (dir, name) -> name.startsWith(appFile.getName()); @@ -433,6 +677,14 @@ public class AppsApi { } + /** + * 通知更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save。 + * + * @param uuid 对象 UUID({@code UUID}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + */ private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { List profiles = this.profileService.findAllByApp(uuid); if (profiles != null && !profiles.isEmpty()) { diff --git a/src/main/java/com/midm/webservice/files/FilesApi.java b/src/main/java/com/midm/webservice/files/FilesApi.java index fe134f7..a7bb6d5 100644 --- a/src/main/java/com/midm/webservice/files/FilesApi.java +++ b/src/main/java/com/midm/webservice/files/FilesApi.java @@ -38,18 +38,77 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code FilesApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code FileService、ProfileService、UserService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/files"}) public class FilesApi { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理查找。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:new JsonObject。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -84,6 +143,22 @@ public class FilesApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -110,6 +185,21 @@ public class FilesApi { } } + /** + * 处理信息。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new JsonObject、new MidmResponse。 + * + * 框架注解:{@code @RequestMapping(value = {"/info/{uuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @param checksum 参数 {@code checksum}({@code long}) + * @param expiry 参数 {@code expiry}({@code long}) + * @param minify 参数 {@code minify}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info/{uuid}"}, method = {RequestMethod.GET}, @@ -132,6 +222,18 @@ public class FilesApi { } } + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -153,6 +255,19 @@ public class FilesApi { } } + /** + * 更新Extras。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateExtras"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateExtras"}, method = {RequestMethod.POST}, @@ -171,6 +286,18 @@ public class FilesApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -192,6 +319,16 @@ public class FilesApi { } } + /** + * 处理清理。 + * + * 框架注解:{@code @RequestMapping(value = {"/sync"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sync"}, method = {RequestMethod.GET}, @@ -203,6 +340,20 @@ public class FilesApi { return user != null && user.hasSystemRole("SYSTEM_ADMIN") ? MidmResponse.getSucceedResponse((Object)this.fileService.sync()) : MidmResponse.getResponse(415, "Not authorized."); } + /** + * 处理重命名。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/rename"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/rename"}, method = {RequestMethod.POST}, @@ -219,6 +370,19 @@ public class FilesApi { } } + /** + * 处理名称存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/nameExists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/nameExists"}, method = {RequestMethod.GET}, @@ -235,6 +399,21 @@ public class FilesApi { } } + /** + * 添加Link。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/addLink"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param url 参数 {@code url}({@code URL}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/addLink"}, method = {RequestMethod.POST}, @@ -287,6 +466,22 @@ public class FilesApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -320,7 +515,25 @@ public class FilesApi { } } - private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, String contentType, long lastModified, String url, boolean notifyToUpdate, Map params) { + /** + * 写入文件。 + * + * 实现要点:调用持久化方法保存数据;包含 10 个条件分支、0 个循环;主要调用:exists、delete、write、new BaseFile、save、upload。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param input 参数 {@code input}({@code InputStream}) + * @param targetFile 参数 {@code targetFile}({@code McFile}) + * @param fileName 文件名({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param contentType Content-Type({@code String}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param url 参数 {@code url}({@code String}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code boolean}) + * @param params 参数 {@code params}({@code Map}) + * @return 字符串结果 + */ + private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, String contentType, long lastModified, String url, boolean notifyToUpdate, Map params) { if (targetFile.exists()) { targetFile.delete(); } @@ -374,6 +587,16 @@ public class FilesApi { } } + /** + * 查找名称。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param label 参数 {@code label}({@code String}) + * @return 字符串结果 + */ private String findName(UUID siteUuid, UUID fileUuid, String label) { String name = label; @@ -383,6 +606,14 @@ public class FilesApi { return name; } + /** + * 通知更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save。 + * + * @param uuid 对象 UUID({@code UUID}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + */ private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { List profiles = this.profileService.findAllByFile(uuid); if (profiles != null && !profiles.isEmpty()) { diff --git a/src/main/java/com/midm/webservice/files/GooglePlayApi.java b/src/main/java/com/midm/webservice/files/GooglePlayApi.java index 37a2d9e..86394d7 100644 --- a/src/main/java/com/midm/webservice/files/GooglePlayApi.java +++ b/src/main/java/com/midm/webservice/files/GooglePlayApi.java @@ -17,12 +17,48 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code GooglePlayApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code UserService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/play"}) public class GooglePlayApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 获取APK信息。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/app/{packageName}"}, method = {RequestMethod.GET}, headers = {"Accept=*/*"}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/app/{packageName}"}, method = {RequestMethod.GET}, @@ -40,6 +76,19 @@ public class GooglePlayApi { } } + /** + * 处理搜索。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/search"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param key 键/配置项({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/search"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/files/OtasApi.java b/src/main/java/com/midm/webservice/files/OtasApi.java index e502170..0c82de9 100644 --- a/src/main/java/com/midm/webservice/files/OtasApi.java +++ b/src/main/java/com/midm/webservice/files/OtasApi.java @@ -40,18 +40,77 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code OtasApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code FileService、ProfileService、UserService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/otas"}) public class OtasApi { + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理查找。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:new JsonObject。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -86,6 +145,22 @@ public class OtasApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -112,6 +187,20 @@ public class OtasApi { } } + /** + * 处理信息。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/info/{uuid}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @param fingerPrint 参数 {@code fingerPrint}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code long}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info/{uuid}"}, method = {RequestMethod.GET}, @@ -129,13 +218,35 @@ public class OtasApi { } } + /** + * 处理infos。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuids UUID 集合({@code List}) + * @param deviceId 参数 {@code deviceId}({@code String}) + * @param fingerPrint 参数 {@code fingerPrint}({@code String}) + * @param partialFirst 参数 {@code partialFirst}({@code Boolean}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @param customerId 参数 {@code customerId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param scriptVersion 参数 {@code scriptVersion}({@code String}) + * @param regionBuildDate 参数 {@code regionBuildDate}({@code long}) + * @param ignorePartNo 参数 {@code ignorePartNo}({@code boolean}) + * @param checkBuildDate 参数 {@code checkBuildDate}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"} ) @ResponseBody - public String infos(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam String deviceId, @RequestParam(required = false) String fingerPrint, @RequestParam(required = false,defaultValue = "true") Boolean partialFirst, @RequestParam(required = false,defaultValue = "-1") Long buildDate, @RequestParam(required = false) String customerId, @RequestParam(required = false) String skuId, @RequestParam(required = false) String scriptVersion, @RequestParam(required = false,defaultValue = "-1") long regionBuildDate, @RequestParam(required = false,defaultValue = "false") boolean ignorePartNo, @RequestParam(required = false,defaultValue = "false") boolean checkBuildDate) { + public String infos(HttpServletRequest request, Authentication authentication, @RequestParam List uuids, @RequestParam String deviceId, @RequestParam(required = false) String fingerPrint, @RequestParam(required = false,defaultValue = "true") Boolean partialFirst, @RequestParam(required = false,defaultValue = "-1") Long buildDate, @RequestParam(required = false) String customerId, @RequestParam(required = false) String skuId, @RequestParam(required = false) String scriptVersion, @RequestParam(required = false,defaultValue = "-1") long regionBuildDate, @RequestParam(required = false,defaultValue = "false") boolean ignorePartNo, @RequestParam(required = false,defaultValue = "false") boolean checkBuildDate) { if (!Strings.isNullOrEmpty(fingerPrint)) { fingerPrint = URLDecoder.decode(fingerPrint, Charset.defaultCharset()); } @@ -144,6 +255,20 @@ public class OtasApi { return otaFile != null ? MidmResponse.getSucceedResponse((Object)otaFile) : MidmResponse.getResponse(404, "No OTA image found to update."); } + /** + * 处理重命名。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/rename"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/rename"}, method = {RequestMethod.POST}, @@ -160,6 +285,19 @@ public class OtasApi { } } + /** + * 处理名称存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/nameExists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/nameExists"}, method = {RequestMethod.GET}, @@ -176,6 +314,18 @@ public class OtasApi { } } + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -197,6 +347,19 @@ public class OtasApi { } } + /** + * 更新Extras。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateExtras"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateExtras"}, method = {RequestMethod.POST}, @@ -215,6 +378,18 @@ public class OtasApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -236,6 +411,22 @@ public class OtasApi { } } + /** + * 添加Link。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环;主要调用:new JsonObject、new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/addLink"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param url 参数 {@code url}({@code URL}) + * @param keepInHost 参数 {@code keepInHost}({@code Boolean}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/addLink"}, method = {RequestMethod.POST}, @@ -303,6 +494,22 @@ public class OtasApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param file 文件({@code MultipartFile}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -344,7 +551,24 @@ public class OtasApi { } } - private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, long lastModified, String url, boolean notifyToUpdate, Map params) { + /** + * 写入文件。 + * + * 实现要点:调用持久化方法保存数据;包含 18 个条件分支、0 个循环;主要调用:exists、delete、write、new OtaFile、save、upload。 + * + * @param user 当前用户({@code User}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param input 参数 {@code input}({@code InputStream}) + * @param targetFile 参数 {@code targetFile}({@code McFile}) + * @param fileName 文件名({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param url 参数 {@code url}({@code String}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code boolean}) + * @param params 参数 {@code params}({@code Map}) + * @return 字符串结果 + */ + private String writeFile(User user, UUID fileUuid, InputStream input, McFile targetFile, String fileName, String name, long lastModified, String url, boolean notifyToUpdate, Map params) { if (targetFile.exists()) { targetFile.delete(); } @@ -425,6 +649,16 @@ public class OtasApi { return MidmResponse.getResponse(441, "Invalid system image."); } + /** + * 查找名称。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param label 参数 {@code label}({@code String}) + * @return 字符串结果 + */ private String findName(UUID siteUuid, UUID fileUuid, String label) { String name = label; @@ -434,6 +668,14 @@ public class OtasApi { return name; } + /** + * 通知更新。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save。 + * + * @param uuid 对象 UUID({@code UUID}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + */ private void notifyUpdate(UUID uuid, Boolean notifyToUpdate) { List profiles = this.profileService.findAllByOta(uuid); if (profiles != null && !profiles.isEmpty()) { diff --git a/src/main/java/com/midm/webservice/files/ReportApi.java b/src/main/java/com/midm/webservice/files/ReportApi.java index c77ef9c..1c5563e 100644 --- a/src/main/java/com/midm/webservice/files/ReportApi.java +++ b/src/main/java/com/midm/webservice/files/ReportApi.java @@ -36,16 +36,68 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code ReportApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code reportService}(ReportService):报表服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code SiteService、ReportService、UserService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/report"}) public class ReportApi { + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 报表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ReportService reportService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -66,13 +118,33 @@ public class ReportApi { } } + /** + * 处理更新。 + * + * 实现要点:包含 14 个条件分支、2 个循环;主要调用:new DbObject、new ArrayList。 + * + * 框架注解:{@code @RequestMapping(value = {"/request/{category}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param sites 参数 {@code sites}({@code Set}) + * @param keep 参数 {@code keep}({@code boolean}) + * @param mailMe 参数 {@code mailMe}({@code boolean}) + * @param minOffset 参数 {@code minOffset}({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/request/{category}"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String category, @RequestBody(required = false) DbObject settings, @CookieValue(required = false) TimeZone timeZone, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) Set sites, @RequestParam(required = false,defaultValue = "true") boolean keep, @RequestParam(required = false,defaultValue = "false") boolean mailMe, @RequestParam(name = "timeOffset",required = false) Integer minOffset) { + public String update(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String category, @RequestBody(required = false) DbObject settings, @CookieValue(required = false) TimeZone timeZone, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) Set sites, @RequestParam(required = false,defaultValue = "true") boolean keep, @RequestParam(required = false,defaultValue = "false") boolean mailMe, @RequestParam(name = "timeOffset",required = false) Integer minOffset) { User user = this.userService.authorizedUser(authentication, accessToken); if (user == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -161,6 +233,20 @@ public class ReportApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write。 + * + * 框架注解:{@code @RequestMapping(value = {"template/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"template/upload"}, method = {RequestMethod.POST}, @@ -191,6 +277,19 @@ public class ReportApi { } } + /** + * 获取Installed。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/installedApps"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/installedApps"}, method = {RequestMethod.GET}, @@ -219,6 +318,18 @@ public class ReportApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -241,6 +352,20 @@ public class ReportApi { } } + /** + * 处理findone。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findone"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findone"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/files/package-info.java b/src/main/java/com/midm/webservice/files/package-info.java new file mode 100644 index 0000000..691a168 --- /dev/null +++ b/src/main/java/com/midm/webservice/files/package-info.java @@ -0,0 +1,16 @@ +/** + * 文件/报表/OTA REST API。 + * + *

本包主要类型: + *

    + *
  • {@link AppsApi}
  • + *
  • {@link FilesApi}
  • + *
  • {@link GooglePlayApi}
  • + *
  • {@link OtasApi}
  • + *
  • {@link ReportApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.files; diff --git a/src/main/java/com/midm/webservice/log/LogsApi.java b/src/main/java/com/midm/webservice/log/LogsApi.java index a3c6ca0..6ef1da0 100644 --- a/src/main/java/com/midm/webservice/log/LogsApi.java +++ b/src/main/java/com/midm/webservice/log/LogsApi.java @@ -20,14 +20,60 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code LogsApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code logService}(LogService):日志服务
  • + *
+ * + * 协作对象:{@code UserService、LogService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/logs"}) public class LogsApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code String}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -52,13 +98,25 @@ public class LogsApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param uuids UUID 集合({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String delete(HttpServletRequest request, Principal principal, @RequestParam(required = false) List uuids) { + public String delete(HttpServletRequest request, Principal principal, @RequestParam(required = false) List uuids) { if (uuids == null) { MidmLog log = (MidmLog)McJsonUtils.toObject(request, MidmLog.class); return MidmResponse.getSucceedResponse((Object)this.logService.delete(log)); @@ -67,6 +125,16 @@ public class LogsApi { } } + /** + * 清理全部日志列表。 + * + * 框架注解:{@code @RequestMapping(value = {"/clear"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/clear"}, method = {RequestMethod.POST}, @@ -78,6 +146,16 @@ public class LogsApi { return MidmResponse.getSucceedResponse(); } + /** + * 清理全部设备日志列表。 + * + * 框架注解:{@code @RequestMapping(value = {"/clear/device"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param deviceUuid 设备 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/clear/device"}, method = {RequestMethod.POST}, @@ -89,6 +167,16 @@ public class LogsApi { return MidmResponse.getSucceedResponse(); } + /** + * 清理全部用户日志列表。 + * + * 框架注解:{@code @RequestMapping(value = {"/clear/user"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param userUuid 用户 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/clear/user"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/log/package-info.java b/src/main/java/com/midm/webservice/log/package-info.java new file mode 100644 index 0000000..081439d --- /dev/null +++ b/src/main/java/com/midm/webservice/log/package-info.java @@ -0,0 +1,12 @@ +/** + * 审计日志 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link LogsApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.log; diff --git a/src/main/java/com/midm/webservice/news/NewsMessageApi.java b/src/main/java/com/midm/webservice/news/NewsMessageApi.java index 652fcec..ec23140 100644 --- a/src/main/java/com/midm/webservice/news/NewsMessageApi.java +++ b/src/main/java/com/midm/webservice/news/NewsMessageApi.java @@ -28,16 +28,68 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code NewsMessageApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code newsMessageService}(NewsMessageService):新闻消息服务
  • + *
  • {@code messageLogService}(MessageLogService):消息日志服务
  • + *
+ * + * 协作对象:{@code UserService、NewsMessageService、MessageLogService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/news"}) public class NewsMessageApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 新闻消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private NewsMessageService newsMessageService; + /** + * 消息日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MessageLogService messageLogService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param sendNow 参数 {@code sendNow}({@code Boolean}) + * @param device 设备({@code Device}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -62,6 +114,20 @@ public class NewsMessageApi { } } + /** + * 保存日志。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/saveLog"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/saveLog"}, method = {RequestMethod.POST}, @@ -80,6 +146,19 @@ public class NewsMessageApi { } } + /** + * 删除从站点。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/deleteFromSite"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/deleteFromSite"}, method = {RequestMethod.POST}, @@ -97,6 +176,20 @@ public class NewsMessageApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAllFromSite"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param limit 数量上限({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAllFromSite"}, method = {RequestMethod.GET}, @@ -113,6 +206,26 @@ public class NewsMessageApi { } } + /** + * 查找全部新闻消息。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param forWhat 参数 {@code forWhat}({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param filter 过滤条件({@code JsonObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -129,6 +242,19 @@ public class NewsMessageApi { } } + /** + * 删除从Admin。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/deleteFromAdmin"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/deleteFromAdmin"}, method = {RequestMethod.POST}, @@ -146,6 +272,20 @@ public class NewsMessageApi { } } + /** + * 处理markAs读取。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/markAsRead"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/markAsRead"}, method = {RequestMethod.POST}, @@ -162,6 +302,20 @@ public class NewsMessageApi { } } + /** + * 处理recent消息列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/recents"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param limit 数量上限({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/recents"}, method = {RequestMethod.GET}, @@ -178,6 +332,20 @@ public class NewsMessageApi { } } + /** + * 处理unchecked。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/unchecked"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param limit 数量上限({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/unchecked"}, method = {RequestMethod.GET}, @@ -194,6 +362,19 @@ public class NewsMessageApi { } } + /** + * 统计Unread。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/count"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/count"}, method = {RequestMethod.GET}, @@ -210,6 +391,19 @@ public class NewsMessageApi { } } + /** + * 设置消息Ascheck。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/setAsCheck"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setAsCheck"}, method = {RequestMethod.POST}, @@ -226,6 +420,20 @@ public class NewsMessageApi { } } + /** + * 设置One消息As检查。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/setOneAsChecked"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param messageLogUuid 参数 {@code messageLogUuid}({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setOneAsChecked"}, method = {RequestMethod.POST}, @@ -242,6 +450,12 @@ public class NewsMessageApi { } } + /** + * 发送许可证Expiring消息。 + * + * 框架注解:{@code @RequestMapping(value = {"/sendExpiring"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * @return 字符串结果 + */ @RequestMapping( value = {"/sendExpiring"}, method = {RequestMethod.GET}, @@ -253,6 +467,20 @@ public class NewsMessageApi { return MidmResponse.getSucceedResponse(); } + /** + * 获取PopUp模板。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getPopUpTemplate"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param newsUuid 参数 {@code newsUuid}({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getPopUpTemplate"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/news/package-info.java b/src/main/java/com/midm/webservice/news/package-info.java new file mode 100644 index 0000000..b264f5e --- /dev/null +++ b/src/main/java/com/midm/webservice/news/package-info.java @@ -0,0 +1,12 @@ +/** + * 新闻/通知 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link NewsMessageApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.news; diff --git a/src/main/java/com/midm/webservice/org/SiteApi.java b/src/main/java/com/midm/webservice/org/SiteApi.java index d8e9a48..e16cccf 100644 --- a/src/main/java/com/midm/webservice/org/SiteApi.java +++ b/src/main/java/com/midm/webservice/org/SiteApi.java @@ -50,28 +50,110 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code SiteApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code hostLicenseService}(HostLicenseService):host许可证服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code ServletContext、UserService、SiteService、DeviceService、HostLicenseService、FileService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/site"}) public class SiteApi { + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ServletContext servletContext; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理注册。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param site 站点/企业({@code Site}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -109,6 +191,21 @@ public class SiteApi { } } + /** + * 设置设置。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/setSettings"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param settings 参数 {@code settings}({@code DbObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setSettings"}, method = {RequestMethod.POST}, @@ -137,6 +234,21 @@ public class SiteApi { } } + /** + * 更新配置档案。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateProfile"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param profile 设备配置档案({@code DbObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateProfile"}, method = {RequestMethod.POST}, @@ -165,6 +277,21 @@ public class SiteApi { } } + /** + * 获取设置。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/setting/{key}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setting/{key}"}, method = {RequestMethod.GET}, @@ -196,6 +323,20 @@ public class SiteApi { } } + /** + * 获取Credential。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getCredential"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getCredential"}, method = {RequestMethod.GET}, @@ -227,6 +368,21 @@ public class SiteApi { } } + /** + * 更新Credential。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateCredential"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param credential 参数 {@code credential}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateCredential"}, method = {RequestMethod.POST}, @@ -255,6 +411,19 @@ public class SiteApi { } } + /** + * 启用设置。 + * + * 框架注解:{@code @RequestMapping(value = {"/enableSetting"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param key 键/配置项({@code String}) + * @param value 值({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enableSetting"}, method = {RequestMethod.POST}, @@ -266,13 +435,28 @@ public class SiteApi { return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)this.siteService.setSetting(user.getSiteUuid(), key, value).getModifiedCount()); } + /** + * 启用站点列表。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuids UUID 集合({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String enableSites(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,name = "uuid") List uuids, @RequestParam(required = false) boolean enabled) { + public String enableSites(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false,name = "uuid") List uuids, @RequestParam(required = false) boolean enabled) { User loggeduser = this.userService.authorizedUser(authentication, accessToken); if (loggeduser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -283,6 +467,23 @@ public class SiteApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param model 参数 {@code model}({@code String}) + * @param plan 参数 {@code plan}({@code String}) + * @param sortBy 排序字段({@code String}) + * @param updateReport 参数 {@code updateReport}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -301,6 +502,24 @@ public class SiteApi { } } + /** + * 处理查找。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -319,6 +538,20 @@ public class SiteApi { } } + /** + * 处理存在。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * 框架注解:{@code @RequestMapping(value = {"/exists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param idName 参数 {@code idName}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/exists"}, method = {RequestMethod.GET}, @@ -335,6 +568,20 @@ public class SiteApi { } } + /** + * 获取Standalone。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getStandalone"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param plan 参数 {@code plan}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getStandalone"}, method = {RequestMethod.GET}, @@ -351,6 +598,21 @@ public class SiteApi { } } + /** + * 查找按。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBy"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param id 参数 {@code id}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBy"}, method = {RequestMethod.GET}, @@ -375,6 +637,20 @@ public class SiteApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -409,13 +685,32 @@ public class SiteApi { } } + /** + * 添加用户。 + * + * 实现要点:包含 8 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/addUser"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param userUuid 用户 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param groupPath 参数 {@code groupPath}({@code String}) + * @param roles 参数 {@code roles}({@code Set}) + * @return 字符串结果 + */ @RequestMapping( value = {"/addUser"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String addUser(HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath, @RequestParam(required = false,defaultValue = "") Set roles) { + public String addUser(HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath, @RequestParam(required = false,defaultValue = "") Set roles) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); Site site = this.siteService.find(loggedUser, siteUuid, siteId); if (site == null) { @@ -456,6 +751,17 @@ public class SiteApi { } } + /** + * 处理background镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:getUrl、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}) + */ @RequestMapping( value = {"/background"}, method = {RequestMethod.GET} @@ -487,6 +793,17 @@ public class SiteApi { } + /** + * 处理headerLogo。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环;主要调用:getUrl、new McFile、exists。 + * + * 框架注解:{@code @RequestMapping(value = {"/titleLogo"}, method = {RequestMethod.GET})}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + */ @RequestMapping( value = {"/titleLogo"}, method = {RequestMethod.GET} @@ -522,6 +839,18 @@ public class SiteApi { } } + /** + * 删除Logo。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save、new McFile、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/{type}/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param type 类型({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{type}/delete"}, method = {RequestMethod.POST}, @@ -547,6 +876,17 @@ public class SiteApi { } } + /** + * 处理请求Trial。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/requestTrial"}, method = {RequestMethod.POST})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @return 字符串结果 + */ @RequestMapping( value = {"/requestTrial"}, method = {RequestMethod.POST} @@ -561,6 +901,21 @@ public class SiteApi { return MidmResponse.getSucceedResponse(); } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 11 个条件分支、0 个循环;主要调用:new McFile、exists、delete、save、write、upload。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param file 文件({@code MultipartFile}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param type 类型({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -625,6 +980,20 @@ public class SiteApi { } } + /** + * 处理reorganize。 + * + * 框架注解:{@code @RequestMapping(value = {"/reorganize"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param resellerId 参数 {@code resellerId}({@code String}) + * @param id 参数 {@code id}({@code String}) + * @param organize 参数 {@code organize}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/reorganize"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/org/UserApi.java b/src/main/java/com/midm/webservice/org/UserApi.java index 9b6e7ec..397ead7 100644 --- a/src/main/java/com/midm/webservice/org/UserApi.java +++ b/src/main/java/com/midm/webservice/org/UserApi.java @@ -83,36 +83,146 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code UserApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code policyAgreementService}(PolicyAgreementService):策略协议服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
+ * + * 协作对象:{@code UserService、PolicyAgreementService、FileService、DeviceService、SiteService、ProfileService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/user"}) public class UserApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 策略协议服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private PolicyAgreementService policyAgreementService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 会话Manager;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private WebSocketSessionManager sessionManager; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 字段 passwordEncoder;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private PasswordEncoder passwordEncoder; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; - private Map columns = null; + /** + * 映射表。 + */ + private Map columns = null; + /** + * 邮件ColumnIndex。 + */ private int emailColumnIndex; + /** + * 处理登录。 + * + * 实现要点:调用持久化方法保存数据;涉及邮件发送;通过 WebSocket 会话推送消息;包含异常捕获与降级/回滚分支;包含 39 个条件分支、1 个循环;主要调用:new DateTime、new ArrayList、remove、new Cookie、save、new MidmLog。 + * + * 框架注解:{@code @RequestMapping(value = {"/login"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + * @param sessionId 参数 {@code sessionId}({@code String}) + * @param userAgent 参数 {@code userAgent}({@code UserAgent}) + * @param email 邮箱({@code String}) + * @param password 密码({@code String}) + * @param forceToLogout 参数 {@code forceToLogout}({@code Boolean}) + * @param bypassEula 参数 {@code bypassEula}({@code Boolean}) + * @param keepSignIn 参数 {@code keepSignIn}({@code Boolean}) + * @param eulaUuid 参数 {@code eulaUuid}({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/login"}, method = {RequestMethod.POST}, @@ -318,6 +428,19 @@ public class UserApi { } } + /** + * 处理退出。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/logout"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/logout"}, method = {RequestMethod.GET}, @@ -338,13 +461,30 @@ public class UserApi { } } + /** + * 处理注册。 + * + * 实现要点:调用持久化方法保存数据;包含 20 个条件分支、0 个循环;主要调用:find、register、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/register"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param roles 参数 {@code roles}({@code Set}) + * @param user 当前用户({@code User}) + * @return 字符串结果 + */ @RequestMapping( value = {"/register"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String register(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set roles, @RequestBody User user) { + public String register(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set roles, @RequestBody User user) { String email = user.getEmail(); User existingUser = this.userService.findUserByEmail(email); String password = user.getPassword(); @@ -437,6 +577,20 @@ public class UserApi { } } + /** + * 更新配置档案。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/updateProfile"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param profile 设备配置档案({@code DbObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/updateProfile"}, method = {RequestMethod.POST}, @@ -454,6 +608,19 @@ public class UserApi { } } + /** + * 注册转换为模型站点。 + * + * 实现要点:调用持久化方法保存数据;包含 8 个条件分支、0 个循环;主要调用:new Site、new DbObject、save、new DeviceProfile、new DateTime、register。 + * + * 框架注解:{@code @RequestMapping(value = {"{siteModel}/register"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param siteModel 参数 {@code siteModel}({@code String}) + * @param user 当前用户({@code User}) + * @return 字符串结果 + */ @RequestMapping( value = {"{siteModel}/register"}, method = {RequestMethod.POST}, @@ -540,13 +707,29 @@ public class UserApi { } } + /** + * 启用用户列表。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 5 个条件分支、1 个循环;主要调用:remove。 + * + * 框架注解:{@code @RequestMapping(value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param uuids UUID 集合({@code List}) + * @param enabled 参数 {@code enabled}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enable"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String enableUsers(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(name = "uuid") List uuids, @RequestParam boolean enabled) { + public String enableUsers(HttpServletRequest request, Principal principal, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(name = "uuid") List uuids, @RequestParam boolean enabled) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -578,13 +761,32 @@ public class UserApi { } } + /** + * 处理change分组。 + * + * 实现要点:包含 8 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/changeGroup"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param userUuids 参数 {@code userUuids}({@code Set}) + * @param emails 参数 {@code emails}({@code Set}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param groupPath 参数 {@code groupPath}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/changeGroup"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String changeGroup(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set userUuids, @RequestParam(required = false,defaultValue = "") Set emails, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath) { + public String changeGroup(HttpServletRequest request, HttpServletResponse response, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false,defaultValue = "") Set userUuids, @RequestParam(required = false,defaultValue = "") Set emails, @RequestParam(required = false) UUID groupUuid, @RequestParam(required = false) String groupPath) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -623,6 +825,19 @@ public class UserApi { } } + /** + * 处理激活。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/activate"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/activate"}, method = {RequestMethod.POST}, @@ -651,6 +866,21 @@ public class UserApi { } } + /** + * 处理agreeEula。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/eula/agree"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param eula 参数 {@code eula}({@code String}) + * @param email 邮箱({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/eula/agree"}, method = {RequestMethod.POST}, @@ -664,6 +894,19 @@ public class UserApi { return MidmResponse.getSucceedResponse((Object)loggedUser); } + /** + * 设置Dashboard。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/dashboardSettings"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dashboardSettings"}, method = {RequestMethod.POST}, @@ -682,6 +925,20 @@ public class UserApi { } } + /** + * 处理passwordConfirm。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/passwordConfirm"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param password 密码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/passwordConfirm"}, method = {RequestMethod.GET}, @@ -697,6 +954,17 @@ public class UserApi { } } + /** + * 获取Dashboard。 + * + * 框架注解:{@code @RequestMapping(value = {"/getDashboardSettings"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getDashboardSettings"}, method = {RequestMethod.GET}, @@ -708,6 +976,17 @@ public class UserApi { return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse(user.getDashboardSettings()); } + /** + * 处理激活。 + * + * 框架注解:{@code @RequestMapping(value = {"/activate/{token}"}, method = {RequestMethod.GET}, produces = {"application/json"})}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param model 参数 {@code model}({@code Model}) + * @param tokenString 参数 {@code tokenString}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/activate/{token}"}, method = {RequestMethod.GET}, @@ -718,6 +997,18 @@ public class UserApi { return "redirect:/?" + (user != null ? "activation_done" : "activation_failed"); } + /** + * 处理请求重置Password。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new User。 + * + * 框架注解:{@code @RequestMapping(value = {"/requestResetPassword"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param email 邮箱({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/requestResetPassword"}, method = {RequestMethod.POST}, @@ -739,6 +1030,21 @@ public class UserApi { } } + /** + * 处理changePassword。 + * + * 实现要点:调用持久化方法保存数据;通过 WebSocket 会话推送消息;包含 10 个条件分支、0 个循环;主要调用:delete、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/changePassword"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param userUuid 用户 UUID({@code UUID}) + * @param tokenUuid 参数 {@code tokenUuid}({@code UUID}) + * @param params 参数 {@code params}({@code DbObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/changePassword"}, method = {RequestMethod.POST}, @@ -803,6 +1109,19 @@ public class UserApi { } } + /** + * 保存最后分页。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/saveLastPage"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param curPage 参数 {@code curPage}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/saveLastPage"}, method = {RequestMethod.POST}, @@ -819,6 +1138,20 @@ public class UserApi { } } + /** + * 处理change语言区域。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/changeLocale"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/changeLocale"}, method = {RequestMethod.POST}, @@ -836,6 +1169,20 @@ public class UserApi { } } + /** + * 处理change设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/settings"}, method = {RequestMethod.POST}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/settings"}, method = {RequestMethod.POST}, @@ -857,6 +1204,19 @@ public class UserApi { } } + /** + * 获取设置列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/settings/get"}, method = {RequestMethod.GET}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param key 键/配置项({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/settings/get"}, method = {RequestMethod.GET}, @@ -873,6 +1233,19 @@ public class UserApi { } } + /** + * 获取分页设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/settings/get/page"}, method = {RequestMethod.GET}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/settings/get/page"}, method = {RequestMethod.GET}, @@ -893,6 +1266,19 @@ public class UserApi { } } + /** + * 获取站点分页设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/page/settings"}, method = {RequestMethod.GET}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/page/settings"}, method = {RequestMethod.GET}, @@ -914,6 +1300,21 @@ public class UserApi { } } + /** + * 设置分页设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/settings/set/page"}, method = {RequestMethod.POST}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param pageUrl 参数 {@code pageUrl}({@code String}) + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/settings/set/page"}, method = {RequestMethod.POST}, @@ -935,6 +1336,19 @@ public class UserApi { } } + /** + * 处理存在。 + * + * 实现要点:调用持久化方法保存数据;包含 5 个条件分支、1 个循环;主要调用:remove、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/exists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteModel 参数 {@code siteModel}({@code String}) + * @param email 邮箱({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/exists"}, method = {RequestMethod.GET}, @@ -970,6 +1384,19 @@ public class UserApi { } } + /** + * 处理验证。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/verify"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param email 邮箱({@code String}) + * @param password 密码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/verify"}, method = {RequestMethod.GET}, @@ -985,6 +1412,21 @@ public class UserApi { } } + /** + * 查找站点列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * 框架注解:{@code @RequestMapping(value = {"/sites"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param email 邮箱({@code String}) + * @param password 密码({@code String}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sites"}, method = {RequestMethod.GET}, @@ -1030,6 +1472,20 @@ public class UserApi { } } + /** + * 处理change站点设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/settings"}, method = {RequestMethod.POST}, produces = {"text/plain"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param key 键/配置项({@code String}) + * @param value 值({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/settings"}, method = {RequestMethod.POST}, @@ -1050,6 +1506,19 @@ public class UserApi { } } + /** + * 获取站点设置列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/settings/get"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param key 键/配置项({@code String}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/settings/get"}, method = {RequestMethod.GET}, @@ -1071,6 +1540,22 @@ public class UserApi { } } + /** + * 查找按。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBy"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @param password 密码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBy"}, method = {RequestMethod.GET}, @@ -1107,6 +1592,17 @@ public class UserApi { } } + /** + * 根据Access令牌查找String。 + * + * 框架注解:{@code @RequestMapping(value = {"/findByAccessToken"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findByAccessToken"}, method = {RequestMethod.GET}, @@ -1118,6 +1614,22 @@ public class UserApi { return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)user); } + /** + * 根据邮件查找String。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findByEmail"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @param fields 参数 {@code fields}({@code String[]}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findByEmail"}, method = {RequestMethod.GET}, @@ -1148,6 +1660,25 @@ public class UserApi { } } + /** + * 处理查找。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -1166,6 +1697,25 @@ public class UserApi { } } + /** + * 查找Supervisors。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/supervisors"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/supervisors"}, method = {RequestMethod.GET}, @@ -1193,6 +1743,16 @@ public class UserApi { } } + /** + * 处理统计。 + * + * 框架注解:{@code @RequestMapping(value = {"/count"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/count"}, method = {RequestMethod.GET}, @@ -1204,13 +1764,28 @@ public class UserApi { return user == null ? MidmResponse.getResponse(415, "Not authorized.") : MidmResponse.getSucceedResponse((Object)this.userService.getUserCount(user.getSiteUuid())); } + /** + * 添加或删除系统Role。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/systemRoles/{command}/{role}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param command 参数 {@code command}({@code String}) + * @param role 参数 {@code role}({@code String}) + * @param uuids UUID 集合({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/systemRoles/{command}/{role}"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String addOrDeleteSystemRole(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String command, @PathVariable String role, @RequestParam(name = "uuid",defaultValue = "") List uuids) { + public String addOrDeleteSystemRole(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @PathVariable String command, @PathVariable String role, @RequestParam(name = "uuid",defaultValue = "") List uuids) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser != null && loggedUser.hasSystemRole("SYSTEM_ADMIN")) { UpdateResult result = this.userService.updateSystemRoles(command, role, uuids); @@ -1220,13 +1795,31 @@ public class UserApi { } } + /** + * 保存Roles。 + * + * 实现要点:通过 WebSocket 会话推送消息;包含 17 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/saveRoles", "/updateRoles"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param userUuid 用户 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @param roles 参数 {@code roles}({@code Set}) + * @param apiOnly 参数 {@code apiOnly}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/saveRoles", "/updateRoles"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String saveRoles(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false,defaultValue = "") Set roles, @RequestParam(required = false) Boolean apiOnly) { + public String saveRoles(HttpServletRequest request, Authentication authentication, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam(required = false) UUID siteUuid, @RequestParam(required = false) String siteId, @RequestParam(required = false) UUID userUuid, @RequestParam(required = false) String email, @RequestParam(required = false,defaultValue = "") Set roles, @RequestParam(required = false) Boolean apiOnly) { User loggedUser = this.userService.authorizedUser(authentication, accessToken); if (loggedUser == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -1303,6 +1896,21 @@ public class UserApi { } } + /** + * 处理switch站点。 + * + * 实现要点:包含 8 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/switchSite"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param curPage 参数 {@code curPage}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/switchSite"}, method = {RequestMethod.POST}, @@ -1355,6 +1963,17 @@ public class UserApi { } } + /** + * 登录响应。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new JsonObject。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param includeExtra 参数 {@code includeExtra}({@code boolean}) + * @return 字符串结果 + */ private String loginResponse(Authentication authentication, User user, Site site, boolean includeExtra) { UserToken token = (UserToken)authentication.getCredentials(); JsonObject jData = new JsonObject(); @@ -1367,6 +1986,22 @@ public class UserApi { return MidmResponse.getSucceedResponse((Object)jData); } + /** + * 删除站点。 + * + * 实现要点:包含 6 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param userUuid 用户 UUID({@code UUID}) + * @param email 邮箱({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -1400,6 +2035,16 @@ public class UserApi { } } + /** + * 处理用户信息。 + * + * 框架注解:{@code @RequestMapping(value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info"}, method = {RequestMethod.GET}, @@ -1411,6 +2056,18 @@ public class UserApi { return user != null ? MidmResponse.getSucceedResponse((Object)user) : MidmResponse.getResponse(415, "Not authorized."); } + /** + * 处理renew令牌。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/token/renew"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/token/renew"}, method = {RequestMethod.GET}, @@ -1431,6 +2088,23 @@ public class UserApi { return MidmResponse.getResponse(415, "Not authorized."); } + /** + * 处理设备列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/devices"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/devices"}, method = {RequestMethod.GET}, @@ -1447,6 +2121,20 @@ public class UserApi { } } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write。 + * + * 框架注解:{@code @RequestMapping(value = {"/profile/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param file 文件({@code MultipartFile}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param userUuid 用户 UUID({@code UUID}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/profile/upload"}, method = {RequestMethod.POST}, @@ -1488,6 +2176,19 @@ public class UserApi { } } + /** + * 上传用户列出。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"upload/list"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"upload/list"}, method = {RequestMethod.POST}, @@ -1513,7 +2214,7 @@ public class UserApi { } if (returnValues != null && returnValues.get(0) instanceof User) { - this.userService.saveUsers(returnValues); + this.userService.saveUsers((List)returnValues); return MidmResponse.getSucceedResponse(returnValues); } else { return MidmResponse.getResponse(404, "Parsing error", returnValues); @@ -1525,6 +2226,17 @@ public class UserApi { } } + /** + * 解析Row。 + * + * 实现要点:包含 27 个条件分支、3 个循环;主要调用:new HashMap、new User。 + * + * @param loggedUser 参数 {@code loggedUser}({@code User}) + * @param row 参数 {@code row}({@code Row}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 用户对象;未找到时返回 {@code null} + * @throws MidmParseException 当 MidmParseException 条件不满足或底层调用失败时抛出。 + */ private User parseRow(User loggedUser, Row row, UUID siteUuid) throws MidmParseException { String sheetName = row.getSheet().getSheetName(); Iterator cells = row.cellIterator(); @@ -1670,7 +2382,17 @@ public class UserApi { } } - private List parseSheets(User loggedUser, Iterator sheets, UUID siteUuid) { + /** + * 解析Sheets。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、3 个循环;主要调用:new ArrayList。 + * + * @param loggedUser 参数 {@code loggedUser}({@code User}) + * @param sheets 参数 {@code sheets}({@code Iterator}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return ?列表,可能为空 + */ + private List parseSheets(User loggedUser, Iterator sheets, UUID siteUuid) { List users = new ArrayList(); List exceptions = new ArrayList(); @@ -1714,7 +2436,17 @@ public class UserApi { } } - private List parseXls(User loggedUser, InputStream is, UUID siteUuid) { + /** + * 解析Excel。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new HSSFWorkbook、close。 + * + * @param loggedUser 参数 {@code loggedUser}({@code User}) + * @param is 参数 {@code is}({@code InputStream}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return ?列表,可能为空 + */ + private List parseXls(User loggedUser, InputStream is, UUID siteUuid) { List returnValues = null; try { @@ -1729,7 +2461,17 @@ public class UserApi { return returnValues; } - private List parseXlsx(User loggedUser, InputStream is, UUID siteUuid) { + /** + * 解析Xlsx。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new XSSFWorkbook、close。 + * + * @param loggedUser 参数 {@code loggedUser}({@code User}) + * @param is 参数 {@code is}({@code InputStream}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return ?列表,可能为空 + */ + private List parseXlsx(User loggedUser, InputStream is, UUID siteUuid) { List returnValues = null; try { @@ -1744,13 +2486,49 @@ public class UserApi { return returnValues; } + /** + * 【REST API】{@code MidmParseException} + * + * 类职责: + *
    + *
  • 暴露 REST 接口,完成协议转换与权限校验。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
+ * + * 学习提示:先看类注释和 public 方法,再结合调用方理解它在整体流程中的位置。 + */ private static class MidmParseException extends Exception { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = 1L; + /** + * 构造 {@code MidmParseException} 实例。 + * + * @param code 状态码/业务码({@code int}) + * @param message 消息内容({@code String}) + */ public MidmParseException(int code, String message) { super(message); } + /** + * 处理gen异常。 + * + * 实现要点:主要调用:new MidmParseException。 + * + * @param code 状态码/业务码({@code int}) + * @param sheetName 参数 {@code sheetName}({@code String}) + * @param rowNum 参数 {@code rowNum}({@code int}) + * @param reason 参数 {@code reason}({@code String}) + * @return 处理结果 + */ public static MidmParseException genException(int code, String sheetName, int rowNum, String reason) { String message = String.format("%s:%04d %s", sheetName, rowNum, reason); return new MidmParseException(code, message); diff --git a/src/main/java/com/midm/webservice/org/UserGroupApi.java b/src/main/java/com/midm/webservice/org/UserGroupApi.java index 3c39951..e04e696 100644 --- a/src/main/java/com/midm/webservice/org/UserGroupApi.java +++ b/src/main/java/com/midm/webservice/org/UserGroupApi.java @@ -22,14 +22,58 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code UserGroupApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
+ * + * 协作对象:{@code UserService、SiteService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/user/group"}) public class UserGroupApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 5 个条件分支、0 个循环;主要调用:find、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param group 分组对象({@code UserGroup}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -63,6 +107,20 @@ public class UserGroupApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -85,6 +143,23 @@ public class UserGroupApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 5 个条件分支、0 个循环;主要调用:find、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param siteId 参数 {@code siteId}({@code String}) + * @param groupUuid 分组 UUID({@code UUID}) + * @param groupPath 参数 {@code groupPath}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/org/package-info.java b/src/main/java/com/midm/webservice/org/package-info.java new file mode 100644 index 0000000..296c40a --- /dev/null +++ b/src/main/java/com/midm/webservice/org/package-info.java @@ -0,0 +1,14 @@ +/** + * 组织/用户/站点 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link SiteApi}
  • + *
  • {@link UserApi}
  • + *
  • {@link UserGroupApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.org; diff --git a/src/main/java/com/midm/webservice/ota/OtaService.java b/src/main/java/com/midm/webservice/ota/OtaService.java index 30754a5..9962bdf 100644 --- a/src/main/java/com/midm/webservice/ota/OtaService.java +++ b/src/main/java/com/midm/webservice/ota/OtaService.java @@ -24,14 +24,63 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code OtaService} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code BASIC_AUTH}(String):字段 BASIC_AUTH
  • + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code ServletContext、FileService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller public class OtaService { + /** + * 字段 BASIC_AUTH。 + */ private static final String BASIC_AUTH = "Basic"; + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ServletContext servletContext; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/otas"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param credentials 参数 {@code credentials}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @param deviceId 参数 {@code deviceId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/otas"}, method = {RequestMethod.GET}, @@ -54,6 +103,19 @@ public class OtaService { } } + /** + * 获取文件。 + * + * 实现要点:包含 5 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/otas/{fileUuid}/{fileName}"}, method = {RequestMethod.GET})}。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param credentials 参数 {@code credentials}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param fileName 文件名({@code String}) + */ @RequestMapping( value = {"/otas/{fileUuid}/{fileName}"}, method = {RequestMethod.GET} diff --git a/src/main/java/com/midm/webservice/ota/package-info.java b/src/main/java/com/midm/webservice/ota/package-info.java new file mode 100644 index 0000000..7df8721 --- /dev/null +++ b/src/main/java/com/midm/webservice/ota/package-info.java @@ -0,0 +1,12 @@ +/** + * OTA 发布 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link OtaService}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.ota; diff --git a/src/main/java/com/midm/webservice/stat/StatApi.java b/src/main/java/com/midm/webservice/stat/StatApi.java index 9c83354..48e3666 100644 --- a/src/main/java/com/midm/webservice/stat/StatApi.java +++ b/src/main/java/com/midm/webservice/stat/StatApi.java @@ -32,22 +32,93 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code StatApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code licenseService}(LicenseService):许可证服务
  • + *
  • {@code siteLicenseService}(SiteLicenseService):站点许可证服务
  • + *
  • {@code profileService}(ProfileService):配置档案服务
  • + *
  • {@code hostLicenseService}(HostLicenseService):host许可证服务
  • + *
+ * + * 协作对象:{@code SiteService、DeviceService、LicenseService、SiteLicenseService、ProfileService、HostLicenseService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/stat"}) public class StatApi { + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 站点许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteLicenseService siteLicenseService; + /** + * 配置档案服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ProfileService profileService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/dbquery"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param db 参数 {@code db}({@code String}) + * @param fields 参数 {@code fields}({@code String[]}) + * @param filter 过滤条件({@code String}) + * @param uuids UUID 集合({@code UUID[]}) + * @param uuid 对象 UUID({@code UUID}) + * @param profile 设备配置档案({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dbquery"}, method = {RequestMethod.GET}, @@ -80,6 +151,20 @@ public class StatApi { } } + /** + * 获取配置档案。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getProfile"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @param filter 过滤条件({@code JsonObject}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getProfile"}, method = {RequestMethod.GET}, @@ -96,6 +181,24 @@ public class StatApi { } } + /** + * 处理站点查询。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/siteQuery"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/siteQuery"}, method = {RequestMethod.GET}, @@ -114,6 +217,19 @@ public class StatApi { } } + /** + * 处理总数状态。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/totalState"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/totalState"}, method = {RequestMethod.GET}, @@ -129,6 +245,19 @@ public class StatApi { } } + /** + * 处理总数许可证Amount。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/totalLicenseAmount"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/totalLicenseAmount"}, method = {RequestMethod.GET}, @@ -144,6 +273,24 @@ public class StatApi { } } + /** + * 处理子状态。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/childState"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/childState"}, method = {RequestMethod.GET}, @@ -162,6 +309,16 @@ public class StatApi { } } + /** + * 获取设备统计。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new JsonObject。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param fields 参数 {@code fields}({@code String[]}) + * @param filter 过滤条件({@code String}) + * @return 字段/派生属性 {@code deviceStat} 的值 + */ private JsonObject getDeviceStat(UUID siteUuid, String[] fields, String filter) { JsonObject jResult = new JsonObject(); long total = this.deviceService.getDeviceTotal(siteUuid, filter); @@ -198,7 +355,16 @@ public class StatApi { return jResult.size() > 0 ? jResult : null; } - private List getLicenseStat(Site site, UUID siteUuid) { + /** + * 获取许可证统计。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * @param site 站点/企业({@code Site}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 许可证模型列表,可能为空 + */ + private List getLicenseStat(Site site, UUID siteUuid) { if (this.hostLicenseService.isStandalone()) { return null; } else { @@ -216,11 +382,28 @@ public class StatApi { } } - private List getSiteStat(Site site) { + /** + * 获取站点统计。 + * + * 实现要点:主要调用:findAll。 + * + * @param site 站点/企业({@code Site}) + * @return 站点列表,可能为空 + */ + private List getSiteStat(Site site) { List siteList = this.siteService.findAll(site, "midm", (String)null, (String)null, true); return siteList; } + /** + * 获取配置档案统计。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:find、new JsonArray。 + * + * @param siteUuid 站点 UUID({@code UUID}) + * @param profile 设备配置档案({@code String}) + * @return 字段/派生属性 {@code profileStat} 的值 + */ private JsonArray getProfileStat(UUID siteUuid, String profile) { DeviceProfile deviceProfile; try { diff --git a/src/main/java/com/midm/webservice/stat/package-info.java b/src/main/java/com/midm/webservice/stat/package-info.java new file mode 100644 index 0000000..5576c2a --- /dev/null +++ b/src/main/java/com/midm/webservice/stat/package-info.java @@ -0,0 +1,12 @@ +/** + * 统计看板 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link StatApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.stat; diff --git a/src/main/java/com/midm/webservice/store/KeyStoreApi.java b/src/main/java/com/midm/webservice/store/KeyStoreApi.java index 650374c..97a2868 100644 --- a/src/main/java/com/midm/webservice/store/KeyStoreApi.java +++ b/src/main/java/com/midm/webservice/store/KeyStoreApi.java @@ -28,16 +28,65 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code KeyStoreApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code keyStoreService}(KeyStoreService):密钥Store服务
  • + *
  • {@code servletContext}(ServletContext):字段 servletContext
  • + *
+ * + * 协作对象:{@code UserService、KeyStoreService、ServletContext}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/store/key"}) public class KeyStoreApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 密钥Store服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private KeyStoreService keyStoreService; + /** + * 字段 servletContext;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private ServletContext servletContext; + /** + * 保存OTA 固件。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param keyStore 参数 {@code keyStore}({@code KeyStore}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -56,6 +105,23 @@ public class KeyStoreApi { } } + /** + * 处理查找。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -74,6 +140,18 @@ public class KeyStoreApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -92,6 +170,20 @@ public class KeyStoreApi { } } + /** + * 删除OTA 固件。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete/{id}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param id 参数 {@code id}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete/{id}"}, method = {RequestMethod.POST}, @@ -110,6 +202,20 @@ public class KeyStoreApi { } } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 6 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param keyStore 参数 {@code keyStore}({@code KeyStore}) + * @param file 文件({@code MultipartFile}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -145,8 +251,7 @@ public class KeyStoreApi { } } catch (IOException e) { tempFile.delete(); - String var10001 = e.getMessage(); - return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + return MidmResponse.getResponse(400, e.getMessage() + " -> " + tempFile.getPath()); } return MidmResponse.getFailedResponse(); @@ -154,6 +259,19 @@ public class KeyStoreApi { } } + /** + * 获取文件。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"file/{id}/{fileName}"}, method = {RequestMethod.GET})}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param id 参数 {@code id}({@code String}) + * @param fileName 文件名({@code String}) + */ @RequestMapping( value = {"file/{id}/{fileName}"}, method = {RequestMethod.GET} diff --git a/src/main/java/com/midm/webservice/store/StoreAppsApi.java b/src/main/java/com/midm/webservice/store/StoreAppsApi.java index 3f59ce5..68708c8 100644 --- a/src/main/java/com/midm/webservice/store/StoreAppsApi.java +++ b/src/main/java/com/midm/webservice/store/StoreAppsApi.java @@ -30,14 +30,57 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code StoreAppsApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code storeAppService}(StoreAppService):store应用服务
  • + *
+ * + * 协作对象:{@code UserService、StoreAppService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/store/apps"}) public class StoreAppsApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * store应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreAppService storeAppService; + /** + * 保存应用。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param oldPackageName 参数 {@code oldPackageName}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -57,6 +100,23 @@ public class StoreAppsApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -75,6 +135,20 @@ public class StoreAppsApi { } } + /** + * 获取Packages。 + * + * 实现要点:主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/packages"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @param packages 参数 {@code packages}({@code String[]}) + * @return 字符串结果 + */ @RequestMapping( value = {"/packages"}, method = {RequestMethod.GET}, @@ -85,6 +159,20 @@ public class StoreAppsApi { return MidmResponse.getSucceedResponse(this.storeAppService.findAll(minSdkVersion)); } + /** + * 获取应用Details。 + * + * 实现要点:主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/about/{packageName}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/about/{packageName}"}, method = {RequestMethod.GET}, @@ -96,6 +184,21 @@ public class StoreAppsApi { return app != null ? MidmResponse.getSucceedResponse((Object)app) : MidmResponse.getResponse(421, "Package not found."); } + /** + * 获取应用文件列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/files/{packageName}/{versionCode}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/files/{packageName}/{versionCode}"}, method = {RequestMethod.GET}, @@ -114,6 +217,21 @@ public class StoreAppsApi { } } + /** + * 获取最新应用Details。 + * + * 框架注解:{@code @RequestMapping(value = {"/latest/{packageName}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param certMd5 参数 {@code certMd5}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param sdkVersion 参数 {@code sdkVersion}({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latest/{packageName}"}, method = {RequestMethod.GET}, @@ -125,6 +243,20 @@ public class StoreAppsApi { return file != null ? MidmResponse.getSucceedResponse((Object)file) : MidmResponse.getResponse(421, "No update needed."); } + /** + * 删除应用。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -145,6 +277,22 @@ public class StoreAppsApi { } } + /** + * 删除全部应用。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete/{packageName}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param filesOnly 参数 {@code filesOnly}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete/{packageName}"}, method = {RequestMethod.POST}, @@ -165,6 +313,26 @@ public class StoreAppsApi { } } + /** + * 保存Release备注。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/releaseNote/add"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param notes 参数 {@code notes}({@code String[]}) + * @param noteNewFunctions 参数 {@code noteNewFunctions}({@code String[]}) + * @param releasedAt 参数 {@code releasedAt}({@code Date}) + * @param versionName 参数 {@code versionName}({@code String}) + * @param minSdkVersion 参数 {@code minSdkVersion}({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/releaseNote/add"}, method = {RequestMethod.POST}, @@ -183,6 +351,23 @@ public class StoreAppsApi { } } + /** + * 查找ReleaseNotes。 + * + * 框架注解:{@code @RequestMapping(value = {"/releaseNote/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @param sdkVersion 参数 {@code sdkVersion}({@code int}) + * @param certMd5 参数 {@code certMd5}({@code String}) + * @param includeFiles 参数 {@code includeFiles}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/releaseNote/find"}, method = {RequestMethod.GET}, @@ -194,6 +379,22 @@ public class StoreAppsApi { return MidmResponse.getSucceedResponse(releaseNote); } + /** + * 处理更新。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/releaseNote/setToFormal"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @param versionCode 参数 {@code versionCode}({@code int}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/releaseNote/setToFormal"}, method = {RequestMethod.POST}, @@ -212,6 +413,18 @@ public class StoreAppsApi { } } + /** + * 获取SDKVersions。 + * + * 框架注解:{@code @RequestMapping(value = {"/getSdk"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getSdk"}, method = {RequestMethod.GET}, @@ -223,6 +436,21 @@ public class StoreAppsApi { return MidmResponse.getSucceedResponse(sdkVersions); } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环;主要调用:new McFile、write、new StoreAppFile、delete、find、new StoreApp。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param multiPartFile 参数 {@code multiPartFile}({@code MultipartFile}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -282,8 +510,7 @@ public class StoreAppsApi { } } catch (IOException e) { tempFile.delete(); - String var10001 = e.getMessage(); - return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + return MidmResponse.getResponse(400, e.getMessage() + " -> " + tempFile.getPath()); } } } else { diff --git a/src/main/java/com/midm/webservice/store/StoreOtasApi.java b/src/main/java/com/midm/webservice/store/StoreOtasApi.java index 38c6e1b..ae449da 100644 --- a/src/main/java/com/midm/webservice/store/StoreOtasApi.java +++ b/src/main/java/com/midm/webservice/store/StoreOtasApi.java @@ -32,16 +32,64 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code StoreOtasApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code storeOtaService}(StoreOtaService):storeOTA 固件服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code UserService、StoreOtaService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/store/otas"}) public class StoreOtasApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * storeOTA 固件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtaService storeOtaService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 保存OTA 固件。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -61,6 +109,23 @@ public class StoreOtasApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -79,6 +144,19 @@ public class StoreOtasApi { } } + /** + * 查找全部Otas。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -97,6 +175,22 @@ public class StoreOtasApi { } } + /** + * 查找OTA 固件文件列表。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findOtaFiles"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findOtaFiles"}, method = {RequestMethod.GET}, @@ -115,6 +209,21 @@ public class StoreOtasApi { } } + /** + * 保存Release备注。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/releaseNote/add"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param notes 参数 {@code notes}({@code String[]}) + * @return 字符串结果 + */ @RequestMapping( value = {"/releaseNote/add"}, method = {RequestMethod.POST}, @@ -133,6 +242,20 @@ public class StoreOtasApi { } } + /** + * 获取OTA 固件Details。 + * + * 实现要点:主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/details/{productId}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/details/{productId}"}, method = {RequestMethod.GET}, @@ -144,6 +267,18 @@ public class StoreOtasApi { return ota == null ? MidmResponse.getResponse(421, "System image not found") : MidmResponse.getSucceedResponse((Object)ota); } + /** + * 获取最新Dummy。 + * + * 框架注解:{@code @RequestMapping(value = {"/latest"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latest"}, method = {RequestMethod.GET}, @@ -154,6 +289,20 @@ public class StoreOtasApi { return MidmResponse.getResponse(421, "No product ID is defined."); } + /** + * 获取最新。 + * + * 框架注解:{@code @RequestMapping(value = {"/latest/{productId}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latest/{productId}"}, method = {RequestMethod.GET}, @@ -165,6 +314,20 @@ public class StoreOtasApi { return otaFile == null ? MidmResponse.getResponse(421, "No System image update available.") : MidmResponse.getSucceedResponse((Object)otaFile); } + /** + * 获取SkuID的最新。 + * + * 框架注解:{@code @RequestMapping(value = {"/latest/{productId}/{skuId}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @param skuId 参数 {@code skuId}({@code String}) + * @param buildDate 参数 {@code buildDate}({@code Long}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latest/{productId}/{skuId}"}, method = {RequestMethod.GET}, @@ -176,6 +339,21 @@ public class StoreOtasApi { return otaFile == null ? MidmResponse.getResponse(421, "No System image update available.") : MidmResponse.getSucceedResponse((Object)otaFile); } + /** + * 获取最新OTA 固件。 + * + * 实现要点:主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/download/{productId}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @param cert 参数 {@code cert}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/download/{productId}"}, method = {RequestMethod.GET}, @@ -187,6 +365,20 @@ public class StoreOtasApi { return MidmResponse.getSucceedResponse((Object)ota); } + /** + * 删除OTA 固件。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete/{productId}"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param productId 参数 {@code productId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete/{productId}"}, method = {RequestMethod.POST}, @@ -205,6 +397,21 @@ public class StoreOtasApi { } } + /** + * 删除OTA 固件文件。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param productId 参数 {@code productId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -223,6 +430,20 @@ public class StoreOtasApi { } } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 20 个条件分支、0 个循环;主要调用:new McFile、write、new StoreOtaFile、delete、find、new StoreOta。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -329,8 +550,7 @@ public class StoreOtasApi { } } catch (IOException e) { tempFile.delete(); - String var10001 = e.getMessage(); - return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + return MidmResponse.getResponse(400, e.getMessage() + " -> " + tempFile.getPath()); } return MidmResponse.getFailedResponse(); diff --git a/src/main/java/com/midm/webservice/store/StoreOtherApi.java b/src/main/java/com/midm/webservice/store/StoreOtherApi.java index c05c059..b4ee5bb 100644 --- a/src/main/java/com/midm/webservice/store/StoreOtherApi.java +++ b/src/main/java/com/midm/webservice/store/StoreOtherApi.java @@ -28,16 +28,64 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code StoreOtherApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code storeOtherService}(StoreOtherService):storeOther服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code UserService、StoreOtherService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/store/others"}) public class StoreOtherApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * storeOther服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreOtherService storeOtherService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 保存应用。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -61,6 +109,19 @@ public class StoreOtherApi { } } + /** + * 查找按。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/findBy"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @param alias 参数 {@code alias}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findBy"}, method = {RequestMethod.GET}, @@ -78,6 +139,23 @@ public class StoreOtherApi { return otherFile == null ? MidmResponse.getResponse(421, "No records.") : MidmResponse.getSucceedResponse((Object)otherFile); } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -96,6 +174,20 @@ public class StoreOtherApi { } } + /** + * 删除应用。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -116,6 +208,22 @@ public class StoreOtherApi { } } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 10 个条件分支、0 个循环;主要调用:new Date、new McFile、write、new StoreOtherFile、upload、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @param lastModified 参数 {@code lastModified}({@code Long}) + * @param notifyToUpdate 参数 {@code notifyToUpdate}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/store/StoreWebAppApi.java b/src/main/java/com/midm/webservice/store/StoreWebAppApi.java index d3449f8..5f72a77 100644 --- a/src/main/java/com/midm/webservice/store/StoreWebAppApi.java +++ b/src/main/java/com/midm/webservice/store/StoreWebAppApi.java @@ -27,16 +27,65 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code StoreWebAppApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code storeWebAppService}(StoreWebAppService):storeWeb应用服务
  • + *
  • {@code cloudStorageService}(CloudStorageService):cloud存储服务
  • + *
+ * + * 协作对象:{@code UserService、StoreWebAppService、CloudStorageService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/store/webapp"}) public class StoreWebAppApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * storeWeb应用服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private StoreWebAppService storeWebAppService; + /** + * cloud存储服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private CloudStorageService cloudStorageService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、0 个循环;主要调用:new StoreWebApp、new Date、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param fileUuid 文件 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -68,13 +117,29 @@ public class StoreWebAppApi { } } + /** + * 保存Release备注。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/saveNotes"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param notes 参数 {@code notes}({@code List}) + * @param notesNewFunction 参数 {@code notesNewFunction}({@code List}) + * @return 字符串结果 + */ @RequestMapping( value = {"/saveNotes"}, method = {RequestMethod.POST}, produces = {"application/json"} ) @ResponseBody - public String saveReleaseNote(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid, @RequestParam(required = false) List notes, @RequestParam(required = false) List notesNewFunction) { + public String saveReleaseNote(HttpServletRequest request, Authentication authentication, HttpServletResponse response, @RequestHeader(value = "Authorization",required = false) String accessToken, @RequestParam UUID uuid, @RequestParam(required = false) List notes, @RequestParam(required = false) List notesNewFunction) { User user = this.userService.authorizedUser(authentication, accessToken); if (user == null) { return MidmResponse.getResponse(415, "Not authorized."); @@ -86,6 +151,21 @@ public class StoreWebAppApi { } } + /** + * 设置转换为Formal。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/setToFormal"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/setToFormal"}, method = {RequestMethod.POST}, @@ -104,6 +184,21 @@ public class StoreWebAppApi { } } + /** + * 查找最新。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/latest"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param isFormal 参数 {@code isFormal}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/latest"}, method = {RequestMethod.GET}, @@ -122,6 +217,18 @@ public class StoreWebAppApi { } } + /** + * 获取ArtifactID。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/getArtifacts"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getArtifacts"}, method = {RequestMethod.GET}, @@ -140,6 +247,22 @@ public class StoreWebAppApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param groupId 参数 {@code groupId}({@code String}) + * @param artifactId 参数 {@code artifactId}({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -158,6 +281,21 @@ public class StoreWebAppApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @param fileOnly 参数 {@code fileOnly}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -178,6 +316,20 @@ public class StoreWebAppApi { } } + /** + * 处理上传。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 7 个条件分支、0 个循环;主要调用:new McFile、write、new StoreWebApp、find、upload、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param file 文件({@code MultipartFile}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -228,8 +380,7 @@ public class StoreWebAppApi { } } catch (IOException e) { tempFile.delete(); - String var10001 = e.getMessage(); - return MidmResponse.getResponse(400, var10001 + " -> " + tempFile.getPath()); + return MidmResponse.getResponse(400, e.getMessage() + " -> " + tempFile.getPath()); } } } diff --git a/src/main/java/com/midm/webservice/store/package-info.java b/src/main/java/com/midm/webservice/store/package-info.java new file mode 100644 index 0000000..c9f9b32 --- /dev/null +++ b/src/main/java/com/midm/webservice/store/package-info.java @@ -0,0 +1,16 @@ +/** + * 应用商店 REST API。 + * + *

本包主要类型: + *

    + *
  • {@link KeyStoreApi}
  • + *
  • {@link StoreAppsApi}
  • + *
  • {@link StoreOtasApi}
  • + *
  • {@link StoreOtherApi}
  • + *
  • {@link StoreWebAppApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.store; diff --git a/src/main/java/com/midm/webservice/system/AltLocaleApi.java b/src/main/java/com/midm/webservice/system/AltLocaleApi.java index 7e4b266..e63c834 100644 --- a/src/main/java/com/midm/webservice/system/AltLocaleApi.java +++ b/src/main/java/com/midm/webservice/system/AltLocaleApi.java @@ -16,12 +16,46 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code AltLocaleApi} + * + * 类职责: + *

    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
+ * + * 协作对象:{@code LocaleService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/altLocale"}) public class AltLocaleApi { + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -34,6 +68,15 @@ public class AltLocaleApi { return MidmResponse.getSucceedResponse((Object)locale); } + /** + * 获取全部。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -44,6 +87,20 @@ public class AltLocaleApi { return MidmResponse.getSucceedResponse(this.localeService.findAllAltLocales()); } + /** + * 查找全部。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -55,6 +112,17 @@ public class AltLocaleApi { return MidmResponse.getSucceedResponse(pageResult); } + /** + * 处理删除。 + * + * 实现要点:主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/system/HelpMessageApi.java b/src/main/java/com/midm/webservice/system/HelpMessageApi.java index 3dcae21..db3a28e 100644 --- a/src/main/java/com/midm/webservice/system/HelpMessageApi.java +++ b/src/main/java/com/midm/webservice/system/HelpMessageApi.java @@ -26,14 +26,58 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code HelpMessageApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code helpMessageService}(HelpMessageService):帮助消息服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
+ * + * 协作对象:{@code HelpMessageService、UserService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"api/help"}) public class HelpMessageApi { + /** + * 帮助消息服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HelpMessageService helpMessageService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 处理查找。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -45,6 +89,15 @@ public class HelpMessageApi { return MidmResponse.getSucceedResponse(pageResult); } + /** + * 查找选项Categories。 + * + * 框架注解:{@code @RequestMapping(value = {"/findCategories"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findCategories"}, method = {RequestMethod.GET}, @@ -56,6 +109,22 @@ public class HelpMessageApi { return MidmResponse.getSucceedResponse(categories); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param code 状态码/业务码({@code String}) + * @param title 参数 {@code title}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -93,6 +162,19 @@ public class HelpMessageApi { } } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -110,6 +192,22 @@ public class HelpMessageApi { } } + /** + * 保存选项。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/option/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/option/save"}, method = {RequestMethod.POST}, @@ -126,6 +224,21 @@ public class HelpMessageApi { } } + /** + * 删除选项。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/option/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/option/delete"}, method = {RequestMethod.POST}, @@ -142,6 +255,17 @@ public class HelpMessageApi { } } + /** + * 获取帮助。 + * + * 框架注解:{@code @RequestMapping(value = {"/{code}/html"}, method = {RequestMethod.GET}, produces = {"text/html"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{code}/html"}, method = {RequestMethod.GET}, @@ -154,6 +278,19 @@ public class HelpMessageApi { return this.helpMessageService.getHtmlContent(code, locale); } + /** + * 处理存在。 + * + * 实现要点:主要调用:exists。 + * + * 框架注解:{@code @RequestMapping(value = {"/{code}/exists"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{code}/exists"}, method = {RequestMethod.GET}, @@ -164,6 +301,18 @@ public class HelpMessageApi { return MidmResponse.getSucceedResponse((Object)this.helpMessageService.exists(code)); } + /** + * 处理reload。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/reload"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/reload"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/system/HostLicenseApi.java b/src/main/java/com/midm/webservice/system/HostLicenseApi.java index 5375dc3..281b609 100644 --- a/src/main/java/com/midm/webservice/system/HostLicenseApi.java +++ b/src/main/java/com/midm/webservice/system/HostLicenseApi.java @@ -40,22 +40,86 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code HostLicenseApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code buildProperties}(BuildProperties):构建Properties
  • + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code licenseService}(HostLicenseService):许可证服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code mongoTemplate}(MongoTemplate):MongoDB模板
  • + *
+ * + * 协作对象:{@code BuildProperties、SettingsService、HostLicenseService、DeviceService、UserService、MongoTemplate}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/host"}) public class HostLicenseApi { + /** + * 构建Properties;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private BuildProperties buildProperties; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService licenseService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * MongoDB模板;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private MongoTemplate mongoTemplate; + /** + * 构建版本。 + * + * 实现要点:主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/buildInfo"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/buildInfo"}, method = {RequestMethod.GET}, @@ -67,6 +131,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)buildInfo); } + /** + * 处理server信息。 + * + * 实现要点:主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/server"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/server"}, method = {RequestMethod.GET}, @@ -78,6 +153,19 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)serverInfo); } + /** + * 处理许可证密钥。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、0 个循环;主要调用:new HostLicense、new Date、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/license"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param standaloneLicense 参数 {@code standaloneLicense}({@code StandaloneLicense}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license"}, method = {RequestMethod.POST}, @@ -127,6 +215,16 @@ public class HostLicenseApi { } } + /** + * 获取最新Standalone许可证。 + * + * 框架注解:{@code @RequestMapping(value = {"/getLatestLicense"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/getLatestLicense"}, method = {RequestMethod.GET}, @@ -138,6 +236,17 @@ public class HostLicenseApi { return license == null ? MidmResponse.getResponse(421, "No license.") : MidmResponse.getSucceedResponse((Object)license); } + /** + * 处理许可证密钥。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/licenses"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/licenses"}, method = {RequestMethod.GET}, @@ -158,6 +267,20 @@ public class HostLicenseApi { } } + /** + * 保存密钥。 + * + * 实现要点:调用持久化方法保存数据;包含 6 个条件分支、0 个循环;主要调用:find、new HostLicense、count、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param licenseKey 参数 {@code licenseKey}({@code String}) + * @param hostId 参数 {@code hostId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/save"}, method = {RequestMethod.POST}, @@ -199,6 +322,20 @@ public class HostLicenseApi { } } + /** + * 处理校验。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/validate"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param licenseKey 参数 {@code licenseKey}({@code String}) + * @param hostId 参数 {@code hostId}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/validate"}, method = {RequestMethod.POST}, @@ -215,6 +352,18 @@ public class HostLicenseApi { } } + /** + * 处理switchPrimary。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/switch"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/switch"}, method = {RequestMethod.POST}, @@ -231,6 +380,18 @@ public class HostLicenseApi { } } + /** + * 移除许可证。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find、delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/remove"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/remove"}, method = {RequestMethod.POST}, @@ -252,6 +413,20 @@ public class HostLicenseApi { } } + /** + * 处理许可证信息。 + * + * 实现要点:主要调用:new HostLicense。 + * + * 框架注解:{@code @RequestMapping(value = {"/license/info"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param hostId 参数 {@code hostId}({@code String}) + * @param systemHash 参数 {@code systemHash}({@code String}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/license/info"}, method = {RequestMethod.GET}, @@ -263,6 +438,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)hostLicense); } + /** + * 处理信息。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McSystemInfo、new JsonArray。 + * + * 框架注解:{@code @RequestMapping(value = {"/info"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/info"}, method = {RequestMethod.GET}, @@ -286,6 +472,15 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)jInfo); } + /** + * 处理ip。 + * + * 框架注解:{@code @RequestMapping(value = {"/ip"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/ip"}, method = {RequestMethod.GET}, @@ -296,6 +491,15 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)McNetUtils.getIpAddress()); } + /** + * 处理myIp。 + * + * 框架注解:{@code @RequestMapping(value = {"/myip"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/myip"}, method = {RequestMethod.GET}, @@ -306,6 +510,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)request.getRemoteAddr()); } + /** + * 处理数据库信息。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/dbInfo"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dbInfo"}, method = {RequestMethod.GET}, @@ -317,6 +532,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)result); } + /** + * 处理数据库Server状态。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/dbServerStatus"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dbServerStatus"}, method = {RequestMethod.GET}, @@ -328,6 +554,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)result); } + /** + * 处理数据库Stats。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);主要调用:new Document。 + * + * 框架注解:{@code @RequestMapping(value = {"/dbStats"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/dbStats"}, method = {RequestMethod.GET}, @@ -339,6 +576,16 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)result); } + /** + * 处理哈希。 + * + * 框架注解:{@code @RequestMapping(value = {"/hash"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param forPrimary 参数 {@code forPrimary}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/hash"}, method = {RequestMethod.GET}, @@ -349,6 +596,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)HostLicense.generateSystemHash(forPrimary ? this.licenseService.getPrimaryLicense().getSystemHash() : this.licenseService.getSystemHash())); } + /** + * 处理cur许可证信息。 + * + * 实现要点:主要调用:new Date。 + * + * 框架注解:{@code @RequestMapping(value = {"/startedFrom"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/startedFrom"}, method = {RequestMethod.GET}, @@ -360,6 +618,17 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse(startedFrom == null ? "Not defined" : new Date(startedFrom)); } + /** + * 处理用户Dir。 + * + * 实现要点:主要调用:new JsonObject、new File。 + * + * 框架注解:{@code @RequestMapping(value = {"/userDir"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/userDir"}, method = {RequestMethod.GET}, @@ -374,6 +643,15 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)jObject); } + /** + * 获取设备NumerLimit。 + * + * 框架注解:{@code @RequestMapping(value = {"/isExceedDeviceLimit"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/isExceedDeviceLimit"}, method = {RequestMethod.GET}, @@ -384,6 +662,25 @@ public class HostLicenseApi { return MidmResponse.getSucceedResponse((Object)this.deviceService.isExceedDeviceLimit()); } + /** + * 处理查找。 + * + * 实现要点:主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, diff --git a/src/main/java/com/midm/webservice/system/LicenseApi.java b/src/main/java/com/midm/webservice/system/LicenseApi.java index bb10d9f..814584a 100644 --- a/src/main/java/com/midm/webservice/system/LicenseApi.java +++ b/src/main/java/com/midm/webservice/system/LicenseApi.java @@ -35,24 +35,100 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code LicenseApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code licenseService}(LicenseService):许可证服务
  • + *
  • {@code siteLicenseService}(SiteLicenseService):站点许可证服务
  • + *
  • {@code siteService}(SiteService):站点服务
  • + *
  • {@code deviceService}(DeviceService):设备服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code hostLicenseService}(HostLicenseService):host许可证服务
  • + *
+ * + * 协作对象:{@code LicenseService、SiteLicenseService、SiteService、DeviceService、UserService、HostLicenseService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/license"}) public class LicenseApi { + /** + * 许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LicenseService licenseService; + /** + * 站点许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteLicenseService siteLicenseService; + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 设备服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceService deviceService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * host许可证服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private HostLicenseService hostLicenseService; + /** + * 日志服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LogService logService; + /** + * 获取Models。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/models"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/models"}, method = {RequestMethod.GET}, @@ -71,6 +147,21 @@ public class LicenseApi { } } + /** + * 获取全部Models。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/allModels"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param plan 参数 {@code plan}({@code String}) + * @param requested 参数 {@code requested}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/allModels"}, method = {RequestMethod.GET}, @@ -94,6 +185,19 @@ public class LicenseApi { } } + /** + * 更新模型。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/model/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/model/save"}, method = {RequestMethod.POST}, @@ -113,6 +217,20 @@ public class LicenseApi { } } + /** + * 删除模型。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/model/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param modelUuid 参数 {@code modelUuid}({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/model/delete"}, method = {RequestMethod.POST}, @@ -133,6 +251,26 @@ public class LicenseApi { } } + /** + * 获取站点Licenses。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:find。 + * + * 框架注解:{@code @RequestMapping(value = {"/site"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param licensed 参数 {@code licensed}({@code Boolean}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site"}, method = {RequestMethod.GET}, @@ -154,6 +292,20 @@ public class LicenseApi { } } + /** + * 获取站点许可证Models。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/models"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/models"}, method = {RequestMethod.GET}, @@ -179,6 +331,30 @@ public class LicenseApi { } } + /** + * 处理exchange站点许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 12 个条件分支、4 个循环;主要调用:new SiteLicense、save、new Date、new ArrayList、new DeviceLicense。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/upgrade"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param plan 参数 {@code plan}({@code String}) + * @param amount 参数 {@code amount}({@code Integer}) + * @param po 参数 {@code po}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @param applyAll 参数 {@code applyAll}({@code boolean}) + * @param exchangeAlive 参数 {@code exchangeAlive}({@code boolean}) + * @param includeDisabled 参数 {@code includeDisabled}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/upgrade"}, method = {RequestMethod.POST}, @@ -272,6 +448,31 @@ public class LicenseApi { } } + /** + * 更新站点许可证。 + * + * 实现要点:调用持久化方法保存数据;包含 13 个条件分支、3 个循环;主要调用:new SiteLicense、save、new Date、new ArrayList、new DeviceLicense。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param licenseModelUuid 许可证型号 UUID({@code UUID}) + * @param siteLicenseUuid 参数 {@code siteLicenseUuid}({@code UUID}) + * @param plan 参数 {@code plan}({@code String}) + * @param amount 参数 {@code amount}({@code int}) + * @param po 参数 {@code po}({@code String}) + * @param desc 参数 {@code desc}({@code String}) + * @param status 状态({@code SiteLicense.STATUS}) + * @param applyNow 参数 {@code applyNow}({@code Boolean}) + * @param autoRenew 参数 {@code autoRenew}({@code Boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code Boolean}) + * @param includeDisabled 参数 {@code includeDisabled}({@code Boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/save"}, method = {RequestMethod.POST}, @@ -369,6 +570,16 @@ public class LicenseApi { } } + /** + * 删除站点许可证。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param licenseUuid 许可证 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/delete"}, method = {RequestMethod.POST}, @@ -380,6 +591,20 @@ public class LicenseApi { return MidmResponse.getSucceedResponse(); } + /** + * 获取站点Activities。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/activities"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param limit 数量上限({@code int}) + * @param forManagement 参数 {@code forManagement}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/activities"}, method = {RequestMethod.GET}, @@ -396,6 +621,24 @@ public class LicenseApi { } } + /** + * 获取站点日志列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/logs"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @param forManagement 参数 {@code forManagement}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/logs"}, method = {RequestMethod.GET}, @@ -412,6 +655,20 @@ public class LicenseApi { } } + /** + * 清理站点日志列表。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/site/logs/clear"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @param forManagement 参数 {@code forManagement}({@code boolean}) + * @return 字符串结果 + */ @RequestMapping( value = {"/site/logs/clear"}, method = {RequestMethod.POST}, @@ -428,6 +685,17 @@ public class LicenseApi { } } + /** + * 同步Expiry。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/syncExpiry"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/syncExpiry"}, method = {RequestMethod.GET}, @@ -449,6 +717,17 @@ public class LicenseApi { return MidmResponse.getSucceedResponse(); } + /** + * 处理touch许可证的设备。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、1 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/touchDevice"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/touchDevice"}, method = {RequestMethod.GET}, @@ -478,12 +757,32 @@ public class LicenseApi { return MidmResponse.getSucceedResponse((Object)count); } + /** + * 更新站点计划。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * @param user 当前用户({@code User}) + * @param site 站点/企业({@code Site}) + * @param targetPlan 参数 {@code targetPlan}({@code String}) + */ private void updateSitePlan(User user, Site site, String targetPlan) { this.siteLicenseService.updateSiteLicense(site, targetPlan); this.siteService.sendMessage(site, targetPlan); this.logService.save(user, site.getUuid(), "siteLicense_upgrade_success", String.format("SiteLicense upgrade success from (%s) to (%s)", site.getPlanName(), targetPlan)); } + /** + * 设置设备许可证。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save、addLicenseLog。 + * + * @param device 设备({@code Device}) + * @param license 参数 {@code license}({@code DeviceLicense}) + * @param autoRenew 参数 {@code autoRenew}({@code boolean}) + * @param renewToSameModel 参数 {@code renewToSameModel}({@code boolean}) + * @param licensed 参数 {@code licensed}({@code Date}) + */ private void setDeviceLicense(Device device, DeviceLicense license, boolean autoRenew, boolean renewToSameModel, Date licensed) { license.setDevice(device); license.setAutoRenew(autoRenew); diff --git a/src/main/java/com/midm/webservice/system/LocaleApi.java b/src/main/java/com/midm/webservice/system/LocaleApi.java index 2789ec8..bbc7a4f 100644 --- a/src/main/java/com/midm/webservice/system/LocaleApi.java +++ b/src/main/java/com/midm/webservice/system/LocaleApi.java @@ -19,12 +19,46 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code LocaleApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
+ * + * 协作对象:{@code LocaleService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/locale"}) public class LocaleApi { + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -37,6 +71,17 @@ public class LocaleApi { return MidmResponse.getSucceedResponse((Object)locale); } + /** + * 获取Availables。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new HashMap。 + * + * 框架注解:{@code @RequestMapping(value = {"/availables"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/availables"}, method = {RequestMethod.GET}, @@ -54,6 +99,15 @@ public class LocaleApi { return MidmResponse.getSucceedResponse((Object)localeMap); } + /** + * 获取全部。 + * + * 框架注解:{@code @RequestMapping(value = {"/all"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/all"}, method = {RequestMethod.GET}, @@ -64,6 +118,15 @@ public class LocaleApi { return MidmResponse.getSucceedResponse(this.localeService.findAllLocales()); } + /** + * 获取全部Enabled。 + * + * 框架注解:{@code @RequestMapping(value = {"/enabled"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/enabled"}, method = {RequestMethod.GET}, @@ -74,6 +137,20 @@ public class LocaleApi { return MidmResponse.getSucceedResponse(this.localeService.findEnabledLocales()); } + /** + * 查找全部。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -85,6 +162,17 @@ public class LocaleApi { return MidmResponse.getSucceedResponse(pageResult); } + /** + * 处理删除。 + * + * 实现要点:主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java b/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java index b77aeac..d983c31 100644 --- a/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java +++ b/src/main/java/com/midm/webservice/system/PolicyAgreementApi.java @@ -20,14 +20,58 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +/** + * 【Web 控制器】{@code PolicyAgreementApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code policyAgreementService}(PolicyAgreementService):策略协议服务
  • + *
+ * + * 协作对象:{@code UserService、PolicyAgreementService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/agreement"}) public class PolicyAgreementApi { + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 策略协议服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private PolicyAgreementService policyAgreementService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -54,6 +98,23 @@ public class PolicyAgreementApi { } } + /** + * 查找全部。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:findAll。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param filter 过滤条件({@code String}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -70,6 +131,19 @@ public class PolicyAgreementApi { } } + /** + * 查找NewestEula。 + * + * 框架注解:{@code @RequestMapping(value = {"/findLatest"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param siteUuid 站点 UUID({@code UUID}) + * @param category 分类(app/ota/other/report 等)({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findLatest"}, method = {RequestMethod.GET}, @@ -81,6 +155,19 @@ public class PolicyAgreementApi { return MidmResponse.getSucceedResponse((Object)agreement); } + /** + * 处理删除。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/system/ResourceMessageApi.java b/src/main/java/com/midm/webservice/system/ResourceMessageApi.java index c087077..b87e93d 100644 --- a/src/main/java/com/midm/webservice/system/ResourceMessageApi.java +++ b/src/main/java/com/midm/webservice/system/ResourceMessageApi.java @@ -29,16 +29,67 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code ResourceMessageApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code localeService}(LocaleService):语言区域服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code restoreService}(RestoreService):restore服务
  • + *
+ * + * 协作对象:{@code LocaleService、UserService、RestoreService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/message"}) public class ResourceMessageApi { + /** + * 语言区域服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private LocaleService localeService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * restore服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private RestoreService restoreService; + /** + * 处理添加。 + * + * 实现要点:调用持久化方法保存数据;包含 3 个条件分支、0 个循环;主要调用:new ResourceMessage、save。 + * + * 框架注解:{@code @RequestMapping(value = {"/insert"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @param code 状态码/业务码({@code String}) + * @param message 消息内容({@code String}) + * @param comment 参数 {@code comment}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/insert"}, method = {RequestMethod.POST}, @@ -65,6 +116,18 @@ public class ResourceMessageApi { } } + /** + * 处理更新。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -82,6 +145,19 @@ public class ResourceMessageApi { } } + /** + * 处理同步。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/sync"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param syncServer 参数 {@code syncServer}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/sync"}, method = {RequestMethod.POST}, @@ -98,6 +174,15 @@ public class ResourceMessageApi { } } + /** + * 查找全部。 + * + * 框架注解:{@code @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/findAll"}, method = {RequestMethod.GET}, @@ -109,6 +194,18 @@ public class ResourceMessageApi { return MidmResponse.getSucceedResponse(messages); } + /** + * 处理reload。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/reload"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/reload"}, method = {RequestMethod.GET}, @@ -125,6 +222,20 @@ public class ResourceMessageApi { } } + /** + * 处理查找。 + * + * 框架注解:{@code @RequestMapping(value = {"/find"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param filter 过滤条件({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @param page 页码(从 0 开始)({@code Integer}) + * @param size 每页数量({@code Integer}) + * @return 字符串结果 + */ @RequestMapping( value = {"/find"}, method = {RequestMethod.GET}, @@ -136,6 +247,18 @@ public class ResourceMessageApi { return MidmResponse.getSucceedResponse(pageResult); } + /** + * 处理删除。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:delete。 + * + * 框架注解:{@code @RequestMapping(value = {"/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/delete"}, method = {RequestMethod.POST}, @@ -153,6 +276,17 @@ public class ResourceMessageApi { } } + /** + * 获取消息。 + * + * 框架注解:{@code @RequestMapping(value = {"/{code}/{locale}"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param locale 参数 {@code locale}({@code String}) + * @param code 状态码/业务码({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/{code}/{locale}"}, method = {RequestMethod.GET}, @@ -164,6 +298,19 @@ public class ResourceMessageApi { return MidmResponse.getSucceedResponse((Object)message); } + /** + * 处理上传。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @param file 文件({@code MultipartFile}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -193,6 +340,13 @@ public class ResourceMessageApi { } } + /** + * 处理restoreCSV。 + * + * 实现要点:调用持久化方法保存数据;包含 4 个条件分支、1 个循环;主要调用:new CsvReader、new ResourceMessage、save。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ private void restoreCsv(InputStream input) { CsvReader reader = new CsvReader(input) { String[] locales = null; diff --git a/src/main/java/com/midm/webservice/system/SystemSettingsApi.java b/src/main/java/com/midm/webservice/system/SystemSettingsApi.java index 297880d..5718354 100644 --- a/src/main/java/com/midm/webservice/system/SystemSettingsApi.java +++ b/src/main/java/com/midm/webservice/system/SystemSettingsApi.java @@ -27,18 +27,71 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; +/** + * 【Web 控制器】{@code SystemSettingsApi} + * + * 类职责: + *
    + *
  • 接收 HTTP 请求、做参数绑定/鉴权,并把业务委托给 Service。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code settingsService}(SettingsService):设置列表服务
  • + *
  • {@code emailService}(EmailService):邮件服务
  • + *
  • {@code userService}(UserService):用户服务
  • + *
  • {@code fileService}(FileService):文件服务
  • + *
+ * + * 协作对象:{@code SettingsService、EmailService、UserService、FileService}。 + * + * 学习提示:先看类上的 @RequestMapping 路径,再沿 public 方法里的 service 调用链阅读。 + */ @Controller @RequestMapping({"/api/settings"}) public class SystemSettingsApi { + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; + /** + * 邮件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private EmailService emailService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:save。 + * + * 框架注解:{@code @RequestMapping(value = {"/save"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param settings 参数 {@code settings}({@code SystemSetting[]}) + * @return 字符串结果 + */ @RequestMapping( value = {"/save"}, method = {RequestMethod.POST}, @@ -49,6 +102,16 @@ public class SystemSettingsApi { return this.settingsService.save(settings) ? MidmResponse.getSucceedResponse((Object)settings) : MidmResponse.getResponse(400, "Device Number has exceeded limitation"); } + /** + * 处理查找。 + * + * 框架注解:{@code @RequestMapping(value = {"/get"}, method = {RequestMethod.GET}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @param keys 参数 {@code keys}({@code String[]}) + * @return 字符串结果 + */ @RequestMapping( value = {"/get"}, method = {RequestMethod.GET}, @@ -60,6 +123,17 @@ public class SystemSettingsApi { return MidmResponse.getSucceedResponse((Object)settings); } + /** + * 测试邮件。 + * + * 实现要点:涉及邮件发送;包含 1 个条件分支、0 个循环。 + * + * 框架注解:{@code @RequestMapping(value = {"/mail/test"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param principal 参数 {@code principal}({@code Principal}) + * @return 字符串结果 + */ @RequestMapping( value = {"/mail/test"}, method = {RequestMethod.POST}, @@ -76,6 +150,19 @@ public class SystemSettingsApi { return MidmResponse.getSucceedResponse(); } + /** + * 上传Background。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new McFile、exists、delete、write。 + * + * 框架注解:{@code @RequestMapping(value = {"/upload"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param file 文件({@code MultipartFile}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @param accessToken 参数 {@code accessToken}({@code String}) + * @return 字符串结果 + */ @RequestMapping( value = {"/upload"}, method = {RequestMethod.POST}, @@ -114,6 +201,17 @@ public class SystemSettingsApi { } } + /** + * 删除Logo。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new McFile。 + * + * 框架注解:{@code @RequestMapping(value = {"/background/delete"}, method = {RequestMethod.POST}, produces = {"application/json"})}、{@code @ResponseBody}。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 字符串结果 + */ @RequestMapping( value = {"/background/delete"}, method = {RequestMethod.POST}, diff --git a/src/main/java/com/midm/webservice/system/package-info.java b/src/main/java/com/midm/webservice/system/package-info.java new file mode 100644 index 0000000..9a554a8 --- /dev/null +++ b/src/main/java/com/midm/webservice/system/package-info.java @@ -0,0 +1,19 @@ +/** + * 系统设置/License REST API。 + * + *

本包主要类型: + *

    + *
  • {@link AltLocaleApi}
  • + *
  • {@link HelpMessageApi}
  • + *
  • {@link HostLicenseApi}
  • + *
  • {@link LicenseApi}
  • + *
  • {@link LocaleApi}
  • + *
  • {@link PolicyAgreementApi}
  • + *
  • {@link ResourceMessageApi}
  • + *
  • {@link SystemSettingsApi}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.webservice.system; diff --git a/src/main/java/com/midm/websocket/message/QueryHandler.java b/src/main/java/com/midm/websocket/message/QueryHandler.java index 64c3e57..199515c 100644 --- a/src/main/java/com/midm/websocket/message/QueryHandler.java +++ b/src/main/java/com/midm/websocket/message/QueryHandler.java @@ -70,9 +70,19 @@ import org.springframework.web.socket.WebSocketSession; @Component public class QueryHandler implements WebSocketHandler { + /** + * 站点服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SiteService siteService; + /** + * 设备文件列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private DeviceFilesService deviceFilesService; @@ -89,9 +99,19 @@ public class QueryHandler implements WebSocketHandler { @Lazy private DeviceReportService deviceReportService; + /** + * 用户服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private UserService userService; + /** + * 文件服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private FileService fileService; @@ -103,6 +123,11 @@ public class QueryHandler implements WebSocketHandler { @Autowired private LogService logService; + /** + * 设置列表服务;Spring 自动注入的依赖。 + * + * 注解:{@code @Autowired}。 + */ @Autowired private SettingsService settingsService; @@ -161,7 +186,7 @@ public class QueryHandler implements WebSocketHandler { * @param message 抽象 WebSocket 消息载荷 */ @Override - public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception { + public void handleMessage(WebSocketSession session, WebSocketMessage message) throws Exception { MidmWebSocketSession midmSession = this.sessionManager.toMidmSocketSession(session, false); if (midmSession != null) { // 1. 刷新活跃时间戳(Heartbeat Timestamp) @@ -249,6 +274,15 @@ public class QueryHandler implements WebSocketHandler { this.sessionManager.onPong(session); } + /** + * 处理Transport错误。 + * + * 框架注解:{@code @Override}。 + * + * @param session WebSocket 会话({@code WebSocketSession}) + * @param exception 参数 {@code exception}({@code Throwable}) + * @throws Exception 当 Exception 条件不满足或底层调用失败时抛出。 + */ @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { } @@ -394,6 +428,7 @@ public class QueryHandler implements WebSocketHandler { } } } + break; case CHECKIN: default: break; @@ -518,8 +553,10 @@ public class QueryHandler implements WebSocketHandler { case "data_usage": // 记录移动数据用量统计 this.deviceReportService.saveDataUsage(device, feedback.getDataAsDbObject()); + break; } } + break; default: } } @@ -585,6 +622,15 @@ public class QueryHandler implements WebSocketHandler { } } + /** + * 是否支持 WebSocket 分片消息。 + * + *

MiDM 的报文由客户端一次性发送,服务端不启用 Spring 的 partial message 聚合, + * 因此固定返回 {@code false},避免额外缓存分片。 + * + * 框架注解:{@code @Override}。 + * @return 固定返回 {@code false} + */ @Override public boolean supportsPartialMessages() { return false; diff --git a/src/main/java/com/midm/websocket/message/package-info.java b/src/main/java/com/midm/websocket/message/package-info.java new file mode 100644 index 0000000..2491d3a --- /dev/null +++ b/src/main/java/com/midm/websocket/message/package-info.java @@ -0,0 +1,12 @@ +/** + * WebSocket 消息处理器:按 MIDM_REQUEST 分支处理设备上报。 + * + *

本包主要类型: + *

    + *
  • {@link QueryHandler}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.midm.websocket.message; diff --git a/src/main/java/com/mitac/cell/barcode/QrCode.java b/src/main/java/com/mitac/cell/barcode/QrCode.java index 3df9c7f..d22d6bc 100644 --- a/src/main/java/com/mitac/cell/barcode/QrCode.java +++ b/src/main/java/com/mitac/cell/barcode/QrCode.java @@ -17,53 +17,143 @@ import java.util.EnumMap; import java.util.Map; import javax.imageio.ImageIO; +/** + * 【通用基础库】{@code QrCode} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DEFAULT_WIDTH}(int):字段 DEFAULT_WIDTH
  • + *
  • {@code DEFAULT_MARGIN}(int):字段 DEFAULT_MARGIN
  • + *
  • {@code code}(String):代码
  • + *
  • {@code width}(int):字段 width
  • + *
  • {@code margin}(int):字段 margin
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class QrCode { + /** + * 字段 DEFAULT_WIDTH。 + */ private static final int DEFAULT_WIDTH = 220; + /** + * 字段 DEFAULT_MARGIN。 + */ private static final int DEFAULT_MARGIN = 1; + /** + * 代码。 + */ private String code; + /** + * 字段 width。 + */ private int width = 220; + /** + * 字段 margin。 + */ private int margin = 1; + /** + * 构造 {@code QrCode} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public QrCode() { } + /** + * 构造 {@code QrCode} 实例。 + * + * @param code 状态码/业务码({@code String}) + * @param width 参数 {@code width}({@code int}) + */ public QrCode(String code, int width) { this.setCode(code); this.setWidth(width); } + /** + * 获取 {@code code}。 + * @return 字符串结果 + */ public String getCode() { return this.code; } + /** + * 设置 {@code code}。 + * + * @param code 状态码/业务码({@code String}) + */ public void setCode(String code) { this.code = code; } + /** + * 获取 {@code wdith}。 + * @return 数量/长度 + */ public int getWdith() { return this.width; } + /** + * 设置 {@code width}。 + * + * @param width 参数 {@code width}({@code int}) + */ public void setWidth(int width) { this.width = width; } + /** + * 获取 {@code margin}。 + * @return 数量/长度 + */ public int getMargin() { return this.margin; } + /** + * 设置 {@code margin}。 + * + * @param margin 参数 {@code margin}({@code int}) + */ public void setMargin(int margin) { this.margin = margin; } + /** + * 处理转换为镜像。 + * @return 处理结果 + */ public BufferedImage toImage() { return toImage(this.code, this.width, this.margin); } + /** + * 处理转换为Bytes。 + * + * @param fileFormat 参数 {@code fileFormat}({@code String}) + * @return 处理结果 + */ public byte[] toBytes(String fileFormat) { return toBytes(this.toImage(), fileFormat); } + /** + * 保存As。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @return 处理结果 + */ public File saveAs(String filePath) { if (Strings.isNullOrEmpty(filePath)) { return null; @@ -73,6 +163,15 @@ public class QrCode { } } + /** + * 保存As。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new File、write。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @param fileFormat 参数 {@code fileFormat}({@code String}) + * @return 处理结果 + */ public File saveAs(String filePath, String fileFormat) { if (Strings.isNullOrEmpty(fileFormat)) { fileFormat = "png"; @@ -88,6 +187,15 @@ public class QrCode { } } + /** + * 处理转换为Bytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ByteArrayOutputStream、write。 + * + * @param image 参数 {@code image}({@code BufferedImage}) + * @param fileFormat 参数 {@code fileFormat}({@code String}) + * @return 处理结果 + */ public static byte[] toBytes(BufferedImage image, String fileFormat) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -100,6 +208,16 @@ public class QrCode { } } + /** + * 处理转换为镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new EnumMap、new QRCodeWriter。 + * + * @param code 状态码/业务码({@code String}) + * @param size 每页数量({@code Integer}) + * @param margin 参数 {@code margin}({@code Integer}) + * @return 处理结果 + */ public static BufferedImage toImage(String code, Integer size, Integer margin) { if (Strings.isNullOrEmpty(code)) { return null; diff --git a/src/main/java/com/mitac/cell/barcode/package-info.java b/src/main/java/com/mitac/cell/barcode/package-info.java new file mode 100644 index 0000000..91ea72c --- /dev/null +++ b/src/main/java/com/mitac/cell/barcode/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.barcode}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link QrCode}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.barcode; diff --git a/src/main/java/com/mitac/cell/constant/DateTimeConst.java b/src/main/java/com/mitac/cell/constant/DateTimeConst.java index 98675aa..9265f94 100644 --- a/src/main/java/com/mitac/cell/constant/DateTimeConst.java +++ b/src/main/java/com/mitac/cell/constant/DateTimeConst.java @@ -1,13 +1,61 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code DateTimeConst} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code FORMAT_DATE_4_DIGIT_PASSWORD}(String):字段 FORMAT_DATE_4_DIGIT_PASSWORD
  • + *
  • {@code FORMAT_DATE_6_DIGIT_PASSWORD}(String):字段 FORMAT_DATE_6_DIGIT_PASSWORD
  • + *
  • {@code FORMAT_DATE_8_DIGIT_PASSWORD}(String):字段 FORMAT_DATE_8_DIGIT_PASSWORD
  • + *
  • {@code ONE_MINUTES}(long):字段 ONE_MINUTES
  • + *
  • {@code ONE_HOUR}(long):字段 ONE_HOUR
  • + *
  • {@code HALF_HOUR}(long):字段 HALF_HOUR
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class DateTimeConst { + /** + * 字段 FORMAT_DATE_4_DIGIT_PASSWORD。 + */ public static final String FORMAT_DATE_4_DIGIT_PASSWORD = "MMdd"; + /** + * 字段 FORMAT_DATE_6_DIGIT_PASSWORD。 + */ public static final String FORMAT_DATE_6_DIGIT_PASSWORD = "yyMMdd"; + /** + * 字段 FORMAT_DATE_8_DIGIT_PASSWORD。 + */ public static final String FORMAT_DATE_8_DIGIT_PASSWORD = "yyyyMMdd"; + /** + * 字段 ONE_MINUTES。 + */ public static final long ONE_MINUTES = 60000L; + /** + * 字段 ONE_HOUR。 + */ public static final long ONE_HOUR = 3600000L; + /** + * 字段 HALF_HOUR。 + */ public static final long HALF_HOUR = 1800000L; + /** + * 字段 QUATER_HOUR。 + */ public static final long QUATER_HOUR = 900000L; + /** + * 字段 ONE_DAY。 + */ public static final long ONE_DAY = 86400000L; + /** + * 字段 ONE_WEEK。 + */ public static final long ONE_WEEK = 604800000L; } diff --git a/src/main/java/com/mitac/cell/constant/GeneralConst.java b/src/main/java/com/mitac/cell/constant/GeneralConst.java index 1539761..a63d779 100644 --- a/src/main/java/com/mitac/cell/constant/GeneralConst.java +++ b/src/main/java/com/mitac/cell/constant/GeneralConst.java @@ -1,13 +1,61 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code GeneralConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_KEY}(String):字段 KEY_KEY
  • + *
  • {@code KEY_AUTH_KEY}(String):字段 KEY_AUTH_KEY
  • + *
  • {@code KEY_ID}(String):字段 KEY_ID
  • + *
  • {@code KEY_NAME}(String):字段 KEY_NAME
  • + *
  • {@code KEY_THEME}(String):字段 KEY_THEME
  • + *
  • {@code VALUE_DEFAULT}(String):字段 VALUE_DEFAULT
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class GeneralConst { + /** + * 字段 KEY_KEY。 + */ public static final String KEY_KEY = "key"; + /** + * 字段 KEY_AUTH_KEY。 + */ public static final String KEY_AUTH_KEY = "auth_key"; + /** + * 字段 KEY_ID。 + */ public static final String KEY_ID = "id"; + /** + * 字段 KEY_NAME。 + */ public static final String KEY_NAME = "name"; + /** + * 字段 KEY_THEME。 + */ public static final String KEY_THEME = "theme"; + /** + * 字段 VALUE_DEFAULT。 + */ public static final String VALUE_DEFAULT = "default"; + /** + * 字段 CATEGORY_APP。 + */ public static final String CATEGORY_APP = "app"; + /** + * 字段 DEFAULT_TOKEN_LIFE_CYCLE。 + */ public static final long DEFAULT_TOKEN_LIFE_CYCLE = 86400000L; + /** + * 字段 KEY_LANGUAGE。 + */ public static final String KEY_LANGUAGE = "language"; } diff --git a/src/main/java/com/mitac/cell/constant/LocaleConst.java b/src/main/java/com/mitac/cell/constant/LocaleConst.java index e21681d..ed6f935 100644 --- a/src/main/java/com/mitac/cell/constant/LocaleConst.java +++ b/src/main/java/com/mitac/cell/constant/LocaleConst.java @@ -2,7 +2,28 @@ package com.mitac.cell.constant; import java.util.Locale; +/** + * 【常量定义】{@code LocaleConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DEFAULT_LOCALE}(Locale):字段 DEFAULT_LOCALE
  • + *
+ * + * 协作对象:{@code Locale}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class LocaleConst { + /** + * 字段 DEFAULT_LOCALE。 + */ public static final Locale DEFAULT_LOCALE; static { diff --git a/src/main/java/com/mitac/cell/constant/LocationConst.java b/src/main/java/com/mitac/cell/constant/LocationConst.java index 9f5ba6e..309b3a6 100644 --- a/src/main/java/com/mitac/cell/constant/LocationConst.java +++ b/src/main/java/com/mitac/cell/constant/LocationConst.java @@ -1,8 +1,39 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code LocationConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_LAT}(String):字段 KEY_LAT
  • + *
  • {@code KEY_LATITUDE}(String):字段 KEY_LATITUDE
  • + *
  • {@code KEY_LON}(String):字段 KEY_LON
  • + *
  • {@code KEY_LONGITUDE}(String):字段 KEY_LONGITUDE
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class LocationConst { + /** + * 字段 KEY_LAT。 + */ public static String KEY_LAT = "lat"; + /** + * 字段 KEY_LATITUDE。 + */ public static String KEY_LATITUDE = "latitude"; + /** + * 字段 KEY_LON。 + */ public static String KEY_LON = "lon"; + /** + * 字段 KEY_LONGITUDE。 + */ public static String KEY_LONGITUDE = "longitude"; } diff --git a/src/main/java/com/mitac/cell/constant/MessageConst.java b/src/main/java/com/mitac/cell/constant/MessageConst.java index 08ad6db..e4e8940 100644 --- a/src/main/java/com/mitac/cell/constant/MessageConst.java +++ b/src/main/java/com/mitac/cell/constant/MessageConst.java @@ -1,21 +1,93 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code MessageConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code ID}(String):字段 ID
  • + *
  • {@code FROM}(String):字段 FROM
  • + *
  • {@code REPLY_TO}(String):字段 REPLY_TO
  • + *
  • {@code TO}(String):字段 TO
  • + *
  • {@code CC}(String):字段 CC
  • + *
  • {@code BCC}(String):字段 BCC
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class MessageConst { + /** + * 字段 ID。 + */ public static final String ID = "id"; + /** + * 字段 FROM。 + */ public static final String FROM = "from"; + /** + * 字段 REPLY_TO。 + */ public static final String REPLY_TO = "replyto"; + /** + * 字段 TO。 + */ public static final String TO = "to"; + /** + * 字段 CC。 + */ public static final String CC = "cc"; + /** + * 字段 BCC。 + */ public static final String BCC = "bcc"; + /** + * 字段 TAG。 + */ public static final String TAG = "tag"; + /** + * 字段 TYPE。 + */ public static final String TYPE = "type"; + /** + * 字段 WEB_URL。 + */ public static final String WEB_URL = "web_url"; + /** + * 字段 HEADERS。 + */ public static final String HEADERS = "headers"; + /** + * 字段 SUBJECT。 + */ public static final String SUBJECT = "subject"; + /** + * 字段 TEXT。 + */ public static final String TEXT = "text"; + /** + * 字段 HTML。 + */ public static final String HTML = "html"; + /** + * 字段 ATTR。 + */ public static final String ATTR = "attr"; + /** + * 字段 ATTACHMENT。 + */ public static final String ATTACHMENT = "attachment"; + /** + * 字段 ATTACHMENT_URL。 + */ public static final String ATTACHMENT_URL = "attachment_url"; + /** + * 字段 INLINE_IMAGE。 + */ public static final String INLINE_IMAGE = "inline_image"; } diff --git a/src/main/java/com/mitac/cell/constant/PropertyConst.java b/src/main/java/com/mitac/cell/constant/PropertyConst.java index 7d0a003..bf6d455 100644 --- a/src/main/java/com/mitac/cell/constant/PropertyConst.java +++ b/src/main/java/com/mitac/cell/constant/PropertyConst.java @@ -1,63 +1,261 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code PropertyConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code ROLE}(String):字段 ROLE
  • + *
  • {@code ADMIN}(String):字段 ADMIN
  • + *
  • {@code ADMINISTRATOR}(String):字段 ADMINISTRATOR
  • + *
  • {@code NAME}(String):字段 NAME
  • + *
  • {@code FILE_NAME}(String):字段 FILE_NAME
  • + *
  • {@code CONTENT_TYPE}(String):字段 CONTENT_TYPE
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class PropertyConst { + /** + * 字段 ROLE。 + */ public static final String ROLE = "role"; + /** + * 字段 ADMIN。 + */ public static final String ADMIN = "admin"; + /** + * 字段 ADMINISTRATOR。 + */ public static final String ADMINISTRATOR = "Administrator"; + /** + * 字段 NAME。 + */ public static final String NAME = "name"; + /** + * 字段 FILE_NAME。 + */ public static final String FILE_NAME = "fileName"; + /** + * 字段 CONTENT_TYPE。 + */ public static final String CONTENT_TYPE = "contentType"; + /** + * 字段 FILE_URL。 + */ public static final String FILE_URL = "fileUrl"; + /** + * 字段 ICON_NAME。 + */ public static final String ICON_NAME = "iconName"; + /** + * 字段 ICON_URL。 + */ public static final String ICON_URL = "iconUrl"; + /** + * 字段 ICON_ID。 + */ public static final String ICON_ID = "iconId"; + /** + * 字段 DEVELOPER。 + */ public static final String DEVELOPER = "developer"; + /** + * 字段 DESC。 + */ public static final String DESC = "desc"; + /** + * 字段 LENGTH。 + */ public static final String LENGTH = "length"; + /** + * 字段 CHECKSUM。 + */ public static final String CHECKSUM = "checksum"; + /** + * 字段 LAST_MODIFIED。 + */ public static final String LAST_MODIFIED = "lastModified"; + /** + * 字段 TYPE。 + */ public static final String TYPE = "type"; + /** + * 字段 AB_UPDATE。 + */ public static final String AB_UPDATE = "abUpdate"; + /** + * 字段 BUILD_DATE。 + */ public static final String BUILD_DATE = "buildDate"; + /** + * 字段 BUILD_TIME。 + */ public static final String BUILD_TIME = "buildTime"; + /** + * 字段 POST_BUILD_DATE。 + */ public static final String POST_BUILD_DATE = "postBuildDate"; + /** + * 字段 PRODUCT_ID。 + */ public static final String PRODUCT_ID = "productId"; + /** + * 字段 TARGET_PRODUCT。 + */ public static final String TARGET_PRODUCT = "targetProduct"; + /** + * 字段 DEVICE_ID。 + */ public static final String DEVICE_ID = "deviceId"; + /** + * 字段 SKU_ID。 + */ public static final String SKU_ID = "skuId"; + /** + * 字段 COMPATIBLE_SKU_IDS。 + */ public static final String COMPATIBLE_SKU_IDS = "compatibleSkuIds"; + /** + * 字段 DISPLAY_ID。 + */ public static final String DISPLAY_ID = "displayId"; + /** + * 字段 PRODUCT_DISPLAY_ID。 + */ public static final String PRODUCT_DISPLAY_ID = "productDisplayId"; + /** + * 字段 PRE_DISPLAY_ID。 + */ public static final String PRE_DISPLAY_ID = "preDisplayId"; + /** + * 字段 BUILD_TYPE。 + */ public static final String BUILD_TYPE = "buildType"; + /** + * 字段 BUILD_TAGS。 + */ public static final String BUILD_TAGS = "buildTags"; + /** + * 字段 OTA_CERT。 + */ public static final String OTA_CERT = "otaCert"; + /** + * 字段 BRAND。 + */ public static final String BRAND = "brand"; + /** + * 字段 CUSTOMER。 + */ public static final String CUSTOMER = "customer"; + /** + * 字段 CUSTOMER_ID。 + */ public static final String CUSTOMER_ID = "customerId"; + /** + * 字段 PART_NO。 + */ public static final String PART_NO = "partNo"; + /** + * 字段 OS_VERSION。 + */ public static final String OS_VERSION = "osVersion"; + /** + * 字段 SCRIPT_VERSION。 + */ public static final String SCRIPT_VERSION = "scriptVersion"; + /** + * 字段 RELEASE_VERSION。 + */ public static final String RELEASE_VERSION = "releaseVersion"; + /** + * 字段 MARKET_NAME_1。 + */ public static final String MARKET_NAME_1 = "marketName1"; + /** + * 字段 MARKET_NAME_2。 + */ public static final String MARKET_NAME_2 = "marketName2"; + /** + * 字段 SDK。 + */ public static final String SDK = "sdk"; + /** + * 字段 SECURITY_PATCH。 + */ public static final String SECURITY_PATCH = "securityPatch"; + /** + * 字段 MODEM_SKU。 + */ public static final String MODEM_SKU = "modemSku"; + /** + * 字段 MODEM_FIRMWARE_VERSION。 + */ public static final String MODEM_FIRMWARE_VERSION = "modemFirmwareVersion"; + /** + * 字段 MODEM_FIRMWARE_LONG_VERSION。 + */ public static final String MODEM_FIRMWARE_LONG_VERSION = "modemFirmwareLongVersion"; + /** + * 字段 PRE_BUILD。 + */ public static final String PRE_BUILD = "preBuild"; + /** + * 字段 POST_BUILD。 + */ public static final String POST_BUILD = "postBuild"; + /** + * 字段 PACKAGE。 + */ public static final String PACKAGE = "package"; + /** + * 字段 PACKAGE_NAME。 + */ public static final String PACKAGE_NAME = "packageName"; + /** + * 字段 SHARED_UID。 + */ public static final String SHARED_UID = "sharedUid"; + /** + * 字段 LABEL。 + */ public static final String LABEL = "label"; + /** + * 字段 VERSION。 + */ public static final String VERSION = "version"; + /** + * 字段 VERSION_CODE。 + */ public static final String VERSION_CODE = "versionCode"; + /** + * 字段 VERSION_NAME。 + */ public static final String VERSION_NAME = "versionName"; + /** + * 字段 MIN_SDK_VERSION。 + */ public static final String MIN_SDK_VERSION = "minSdkVersion"; + /** + * 字段 MAX_SDK_VERSION。 + */ public static final String MAX_SDK_VERSION = "maxSdkVersion"; + /** + * 字段 TARGET_SDK_VERSION。 + */ public static final String TARGET_SDK_VERSION = "targetSdkVersion"; + /** + * 字段 USER_PERMISSION。 + */ public static final String USER_PERMISSION = "userPermission"; + /** + * 字段 CERT_MD5。 + */ public static final String CERT_MD5 = "certMd5"; } diff --git a/src/main/java/com/mitac/cell/constant/SizeConst.java b/src/main/java/com/mitac/cell/constant/SizeConst.java index dfa1291..ff5a28f 100644 --- a/src/main/java/com/mitac/cell/constant/SizeConst.java +++ b/src/main/java/com/mitac/cell/constant/SizeConst.java @@ -1,9 +1,40 @@ package com.mitac.cell.constant; +/** + * 【常量定义】{@code SizeConst} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code SIZE_1K}(long):字段 SIZE_1K
  • + *
  • {@code SIZE_1M}(long):字段 SIZE_1M
  • + *
  • {@code SIZE_1G}(long):字段 SIZE_1G
  • + *
  • {@code SIZE_1T}(long):字段 SIZE_1T
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class SizeConst { + /** + * 字段 SIZE_1K。 + */ public static long SIZE_1K = 1024L; + /** + * 字段 SIZE_1M。 + */ public static long SIZE_1M; + /** + * 字段 SIZE_1G。 + */ public static long SIZE_1G; + /** + * 字段 SIZE_1T。 + */ public static long SIZE_1T; static { diff --git a/src/main/java/com/mitac/cell/constant/package-info.java b/src/main/java/com/mitac/cell/constant/package-info.java new file mode 100644 index 0000000..27a907a --- /dev/null +++ b/src/main/java/com/mitac/cell/constant/package-info.java @@ -0,0 +1,18 @@ +/** + * 包 {@code com.mitac.cell.constant}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link DateTimeConst}
  • + *
  • {@link GeneralConst}
  • + *
  • {@link LocaleConst}
  • + *
  • {@link LocationConst}
  • + *
  • {@link MessageConst}
  • + *
  • {@link PropertyConst}
  • + *
  • {@link SizeConst}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.constant; diff --git a/src/main/java/com/mitac/cell/data/McCompress.java b/src/main/java/com/mitac/cell/data/McCompress.java index 25fc777..bb0afb0 100644 --- a/src/main/java/com/mitac/cell/data/McCompress.java +++ b/src/main/java/com/mitac/cell/data/McCompress.java @@ -4,30 +4,82 @@ import com.google.common.base.Charsets; import java.io.ByteArrayOutputStream; import java.util.zip.Deflater; +/** + * 【通用基础库】{@code McCompress} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code BUF_SIZE}(int):字段 BUF_SIZE
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McCompress extends Deflater { + /** + * 字段 BUF_SIZE。 + */ private static int BUF_SIZE = 1024; + /** + * 构造 {@code McCompress} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public McCompress() { } + /** + * 构造 {@code McCompress} 实例。 + * + * @param source 参数 {@code source}({@code byte[]}) + */ public McCompress(byte[] source) { this.setInput(source); } + /** + * 构造 {@code McCompress} 实例。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @param level 参数 {@code level}({@code int}) + */ public McCompress(byte[] source, int level) { super(level); this.setInput(source); } + /** + * 构造 {@code McCompress} 实例。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @param level 参数 {@code level}({@code int}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + */ public McCompress(byte[] source, int level, boolean noHeader) { super(level, noHeader); this.setInput(source); } + /** + * 设置 {@code source}。 + * + * @param source 参数 {@code source}({@code byte[]}) + */ public void setSource(byte[] source) { this.setInput(source); } + /** + * 处理转换为ByteArray。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new ByteArrayOutputStream、write。 + * @return 处理结果 + */ public byte[] toByteArray() { this.finish(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -47,14 +99,36 @@ public class McCompress extends Deflater { return baos.toByteArray(); } + /** + * 处理compress。 + * + * 实现要点:主要调用:new McCompress。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @param level 参数 {@code level}({@code int}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + * @return 处理结果 + */ public static byte[] compress(byte[] source, int level, boolean noHeader) { return (new McCompress(source, level, noHeader)).toByteArray(); } + /** + * 处理compress。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @return 处理结果 + */ public static byte[] compress(byte[] source) { return compress(source, 9, true); } + /** + * 处理compress。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + */ public static byte[] compress(String source) { return compress(source.getBytes(Charsets.UTF_8), 9, true); } diff --git a/src/main/java/com/mitac/cell/data/McDecompress.java b/src/main/java/com/mitac/cell/data/McDecompress.java index 709cc62..ef0fd8b 100644 --- a/src/main/java/com/mitac/cell/data/McDecompress.java +++ b/src/main/java/com/mitac/cell/data/McDecompress.java @@ -5,40 +5,101 @@ import java.nio.ByteBuffer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; +/** + * 【通用基础库】{@code McDecompress} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code BUF_SIZE}(int):字段 BUF_SIZE
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McDecompress extends Inflater { + /** + * 字段 BUF_SIZE。 + */ private static int BUF_SIZE = 1024; + /** + * 构造 {@code McDecompress} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public McDecompress() { } + /** + * 构造 {@code McDecompress} 实例。 + * + * @param source 参数 {@code source}({@code byte[]}) + */ public McDecompress(byte[] source) { this.setInput(source); } + /** + * 构造 {@code McDecompress} 实例。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + */ public McDecompress(byte[] source, boolean noHeader) { super(noHeader); this.setInput(source); } + /** + * 构造 {@code McDecompress} 实例。 + * + * @param source 参数 {@code source}({@code ByteBuffer}) + */ public McDecompress(ByteBuffer source) { this.setSource(source); } + /** + * 构造 {@code McDecompress} 实例。 + * + * @param source 参数 {@code source}({@code ByteBuffer}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + */ public McDecompress(ByteBuffer source, boolean noHeader) { super(noHeader); this.setSource(source); } + /** + * 设置 {@code source}。 + * + * @param source 参数 {@code source}({@code ByteBuffer}) + */ public void setSource(ByteBuffer source) { byte[] bytes = new byte[source.remaining()]; source.get(bytes, 0, bytes.length); this.setInput(bytes); } + /** + * 设置 {@code source}。 + * + * @param source 参数 {@code source}({@code byte[]}) + */ public void setSource(byte[] source) { this.setInput(source); } + /** + * 处理转换为ByteArray。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new ByteArrayOutputStream、write。 + * @return 处理结果 + */ public byte[] toByteArray() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUF_SIZE]; @@ -56,18 +117,48 @@ public class McDecompress extends Inflater { return baos.toByteArray(); } + /** + * 处理decompress。 + * + * 实现要点:主要调用:new McDecompress。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + * @return 处理结果 + */ public static byte[] decompress(byte[] source, boolean noHeader) { return (new McDecompress(source, noHeader)).toByteArray(); } + /** + * 处理decompress。 + * + * @param source 参数 {@code source}({@code byte[]}) + * @return 处理结果 + */ public static byte[] decompress(byte[] source) { return decompress(source, true); } + /** + * 处理decompress。 + * + * 实现要点:主要调用:new McDecompress。 + * + * @param source 参数 {@code source}({@code ByteBuffer}) + * @param noHeader 参数 {@code noHeader}({@code boolean}) + * @return 处理结果 + */ public static byte[] decompress(ByteBuffer source, boolean noHeader) { return (new McDecompress(source, noHeader)).toByteArray(); } + /** + * 处理decompress。 + * + * @param source 参数 {@code source}({@code ByteBuffer}) + * @return 处理结果 + */ public static byte[] decompress(ByteBuffer source) { return decompress(source, true); } diff --git a/src/main/java/com/mitac/cell/data/McXml.java b/src/main/java/com/mitac/cell/data/McXml.java index c0ff5a5..e701371 100644 --- a/src/main/java/com/mitac/cell/data/McXml.java +++ b/src/main/java/com/mitac/cell/data/McXml.java @@ -18,10 +18,46 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; +/** + * 【通用基础库】{@code McXml} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code TAG_SOURCE}(String):字段 TAG_SOURCE
  • + *
  • {@code parentDir}(File):父级Dir
  • + *
+ * + * 协作对象:{@code File}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McXml { + /** + * 字段 TAG_SOURCE。 + */ private static final String TAG_SOURCE = "src"; + /** + * 父级Dir。 + */ private File parentDir; + /** + * 处理加载。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:exists、new FileInputStream。 + * + * @param file 文件({@code File}) + * @return 处理结果 + * @throws ParserConfigurationException 当 ParserConfigurationException 条件不满足或底层调用失败时抛出。 + * @throws SAXException 当 SAXException 条件不满足或底层调用失败时抛出。 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ public JsonObject load(File file) throws ParserConfigurationException, SAXException, IOException { if (file.exists()) { this.parentDir = file.getParentFile(); @@ -32,6 +68,17 @@ public class McXml { } } + /** + * 处理加载。 + * + * 实现要点:主要调用:parse。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return 处理结果 + * @throws ParserConfigurationException 当 ParserConfigurationException 条件不满足或底层调用失败时抛出。 + * @throws SAXException 当 SAXException 条件不满足或底层调用失败时抛出。 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ public JsonObject load(InputStream is) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); @@ -40,6 +87,17 @@ public class McXml { return this.toJsonObject(root); } + /** + * 处理转换为JSONObject。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、3 个循环;主要调用:new JsonObject、new File、new JsonArray。 + * + * @param root 参数 {@code root}({@code Element}) + * @return 处理结果 + * @throws ParserConfigurationException 当 ParserConfigurationException 条件不满足或底层调用失败时抛出。 + * @throws SAXException 当 SAXException 条件不满足或底层调用失败时抛出。 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ private JsonObject toJsonObject(Element root) throws ParserConfigurationException, SAXException, IOException { JsonObject jParent = new JsonObject(); NamedNodeMap attributes = root.getAttributes(); diff --git a/src/main/java/com/mitac/cell/data/package-info.java b/src/main/java/com/mitac/cell/data/package-info.java new file mode 100644 index 0000000..36294a6 --- /dev/null +++ b/src/main/java/com/mitac/cell/data/package-info.java @@ -0,0 +1,14 @@ +/** + * 包 {@code com.mitac.cell.data}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McCompress}
  • + *
  • {@link McDecompress}
  • + *
  • {@link McXml}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.data; diff --git a/src/main/java/com/mitac/cell/db/DbObject.java b/src/main/java/com/mitac/cell/db/DbObject.java index a003a70..af7b3cb 100644 --- a/src/main/java/com/mitac/cell/db/DbObject.java +++ b/src/main/java/com/mitac/cell/db/DbObject.java @@ -6,20 +6,63 @@ import java.util.Map; import java.util.UUID; import org.bson.Document; +/** + * 【通用基础库】{@code DbObject} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class DbObject extends Document { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = 1L; + /** + * 构造 {@code DbObject} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public DbObject() { } + /** + * 构造 {@code DbObject} 实例。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public DbObject(String key, Object value) { super(key, value); } - public DbObject(Map map) { - super(map); + /** + * 构造 {@code DbObject} 实例。 + * + * @param map 参数 {@code map}({@code Map}) + */ + public DbObject(Map map) { + super((Map)map); } + /** + * 获取String。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code String}) + * @param defaultValue 参数 {@code defaultValue}({@code String}) + * @return 字符串结果 + */ public String getString(String key, String defaultValue) { Object value = this.get(key); @@ -30,10 +73,25 @@ public class DbObject extends Document { } } + /** + * 获取Boolean。 + * + * @param key 键/配置项({@code Object}) + * @return 字段/派生属性 {@code boolean} 的值 + */ public Boolean getBoolean(Object key) { return this.getBoolean(key, false); } + /** + * 获取Boolean。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param key 键/配置项({@code Object}) + * @param defaultValue 参数 {@code defaultValue}({@code boolean}) + * @return 字段/派生属性 {@code boolean} 的值 + */ public boolean getBoolean(Object key, boolean defaultValue) { try { return super.getBoolean(key, defaultValue); @@ -42,42 +100,102 @@ public class DbObject extends Document { } } + /** + * 获取Integer。 + * + * @param key 键/配置项({@code Object}) + * @return 数量/长度 + */ public Integer getInteger(Object key) { return this.getInteger(key, -1); } + /** + * 获取Integer。 + * + * @param key 键/配置项({@code Object}) + * @param defaultValue 参数 {@code defaultValue}({@code int}) + * @return 数量/长度 + */ public int getInteger(Object key, int defaultValue) { Number value = this.getNumber(key); return value != null ? value.intValue() : defaultValue; } + /** + * 获取Long。 + * + * @param key 键/配置项({@code Object}) + * @return 数量/长度 + */ public Long getLong(Object key) { return this.getLong(key, -1L); } + /** + * 获取Long。 + * + * @param key 键/配置项({@code Object}) + * @param defaultValue 参数 {@code defaultValue}({@code long}) + * @return 数量/长度 + */ public long getLong(Object key, long defaultValue) { Number value = this.getNumber(key); return value != null ? value.longValue() : defaultValue; } + /** + * 获取Float。 + * + * @param key 键/配置项({@code Object}) + * @return 字段/派生属性 {@code float} 的值 + */ public Float getFloat(Object key) { return this.getFloat(key, -1.0F); } + /** + * 获取Float。 + * + * @param key 键/配置项({@code Object}) + * @param defaultValue 参数 {@code defaultValue}({@code float}) + * @return 字段/派生属性 {@code float} 的值 + */ public float getFloat(Object key, float defaultValue) { Number value = this.getNumber(key); return value != null ? value.floatValue() : defaultValue; } + /** + * 获取Double。 + * + * @param key 键/配置项({@code Object}) + * @return 字段/派生属性 {@code double} 的值 + */ public Double getDouble(Object key) { return this.getDouble(key, (double)-1.0F); } + /** + * 获取Double。 + * + * @param key 键/配置项({@code Object}) + * @param defaultValue 参数 {@code defaultValue}({@code double}) + * @return 字段/派生属性 {@code double} 的值 + */ public double getDouble(Object key, double defaultValue) { Number value = this.getNumber(key); return value != null ? value.doubleValue() : defaultValue; } + /** + * 获取编号。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code Object}) + * @return 字段/派生属性 {@code number} 的值 + */ private Number getNumber(Object key) { try { Object value = this.get(key); @@ -91,6 +209,14 @@ public class DbObject extends Document { } } + /** + * 获取UUID。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + * @return UUID + */ public UUID getUuid(String key) { Object value = this.get(key); if (value == null) { @@ -115,6 +241,13 @@ public class DbObject extends Document { } } + /** + * 转换UUID。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + */ public void convertUuid(String key) { Object value = this.get(key); if (!(value instanceof UUID)) { @@ -128,6 +261,14 @@ public class DbObject extends Document { } } + /** + * 获取数据库Object。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new DbObject。 + * + * @param keys 参数 {@code keys}({@code String[]}) + * @return MongoDB 文档扩展对象 + */ public DbObject getDbObject(String... keys) { DbObject dbObject = this; @@ -153,7 +294,16 @@ public class DbObject extends Document { return dbObject; } - public List getList(Object key, Class clazz) { + /** + * 获取列出。 + * + * 实现要点:包含 7 个条件分支、0 个循环;主要调用:new ArrayList、new DbObject。 + * + * @param key 键/配置项({@code Object}) + * @param clazz 参数 {@code clazz}({@code Class}) + * @return T列表,可能为空 + */ + public List getList(Object key, Class clazz) { if (clazz.equals(DbObject.class)) { List list = super.getList(key, Object.class); if (list != null) { @@ -191,10 +341,23 @@ public class DbObject extends Document { } } + /** + * 处理转换为Plat。 + * @return MongoDB 文档扩展对象 + */ public DbObject toPlat() { return toFlat((String)null, this); } + /** + * 处理转换为Flat。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new DbObject。 + * + * @param parentKey 参数 {@code parentKey}({@code String}) + * @param nestedObj 参数 {@code nestedObj}({@code DbObject}) + * @return MongoDB 文档扩展对象 + */ public static DbObject toFlat(String parentKey, DbObject nestedObj) { DbObject flatObj = new DbObject(); String prefixKey = parentKey != null ? parentKey + "." : ""; diff --git a/src/main/java/com/mitac/cell/db/package-info.java b/src/main/java/com/mitac/cell/db/package-info.java new file mode 100644 index 0000000..8096cbd --- /dev/null +++ b/src/main/java/com/mitac/cell/db/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.db}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link DbObject}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.db; diff --git a/src/main/java/com/mitac/cell/db/util/JpaQuery.java b/src/main/java/com/mitac/cell/db/util/JpaQuery.java index e821082..bc0e0a3 100644 --- a/src/main/java/com/mitac/cell/db/util/JpaQuery.java +++ b/src/main/java/com/mitac/cell/db/util/JpaQuery.java @@ -3,24 +3,79 @@ package com.mitac.cell.db.util; import com.google.common.base.Joiner; import com.mitac.cell.utils.McStringUtils; +/** + * 【通用基础库】{@code JpaQuery} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code sbColumns}(StringBuilder):字段 sbColumns
  • + *
  • {@code sbConditions}(StringBuilder):字段 sbConditions
  • + *
  • {@code tableName}(String):table名称
  • + *
  • {@code orderBy}(String):order按
  • + *
+ * + * 协作对象:{@code StringBuilder}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class JpaQuery { + /** + * 字段 sbColumns。 + */ private StringBuilder sbColumns = new StringBuilder(); + /** + * 字段 sbConditions。 + */ private StringBuilder sbConditions = new StringBuilder(); + /** + * table名称。 + */ private String tableName; + /** + * order按。 + */ private String orderBy; + /** + * 构造 {@code JpaQuery} 实例。 + * + * @param tableName 参数 {@code tableName}({@code String}) + */ public JpaQuery(String tableName) { this.setTableName(tableName); } + /** + * 设置 {@code tableName}。 + * + * @param tableName 参数 {@code tableName}({@code String}) + */ public void setTableName(String tableName) { this.tableName = tableName; } + /** + * 设置 {@code orderBy}。 + * + * @param orderBy 参数 {@code orderBy}({@code String}) + */ public void setOrderBy(String orderBy) { this.orderBy = orderBy; } + /** + * 添加Column。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param column 参数 {@code column}({@code String}) + */ public void addColumn(String column) { if (this.sbColumns.length() > 0) { this.sbColumns.append(", "); @@ -29,20 +84,45 @@ public class JpaQuery { this.sbColumns.append(column); } + /** + * 添加Column。 + * + * @param column 参数 {@code column}({@code String[]}) + */ public void addColumn(String... column) { this.addColumn(Joiner.on(",").join(column)); } + /** + * 添加JSONColumn。 + * + * @param dbColumn 参数 {@code dbColumn}({@code String}) + * @param columnName 参数 {@code columnName}({@code String}) + */ public void addJsonColumn(String dbColumn, String columnName) { String column = "CAST(COLUMN_JSON(" + dbColumn + ") AS CHAR) AS " + columnName; this.addColumn(column); } + /** + * 添加JSONColumn。 + * + * @param dbColumn 参数 {@code dbColumn}({@code String}) + * @param dynamicColumn 参数 {@code dynamicColumn}({@code String}) + * @param type 类型({@code String}) + * @param columnName 参数 {@code columnName}({@code String}) + */ public void addJsonColumn(String dbColumn, String dynamicColumn, String type, String columnName) { String column = "COLUMN_GET(" + dbColumn + ", " + dynamicColumn + " AS " + type + ") AS " + columnName; this.addColumn(column); } + /** + * 处理转换为查询。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new StringBuilder。 + * @return 字符串结果 + */ public String toQuery() { StringBuilder sbQuery = new StringBuilder("SELECT "); if (this.sbColumns.length() == 0) { diff --git a/src/main/java/com/mitac/cell/db/util/McDbUtils.java b/src/main/java/com/mitac/cell/db/util/McDbUtils.java index 8898986..988dc52 100644 --- a/src/main/java/com/mitac/cell/db/util/McDbUtils.java +++ b/src/main/java/com/mitac/cell/db/util/McDbUtils.java @@ -1,10 +1,35 @@ package com.mitac.cell.db.util; +/** + * 【通用基础库】{@code McDbUtils} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McDbUtils { + /** + * 处理从。 + * + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @return 数量/长度 + */ public static int from(int page, int size) { return page * size; } + /** + * 处理转换为。 + * + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @param total 总数({@code int}) + * @return 数量/长度 + */ public static int to(int page, int size, int total) { ++page; int max = page * size; diff --git a/src/main/java/com/mitac/cell/db/util/McMongoUtils.java b/src/main/java/com/mitac/cell/db/util/McMongoUtils.java index 3d89aac..23e429e 100644 --- a/src/main/java/com/mitac/cell/db/util/McMongoUtils.java +++ b/src/main/java/com/mitac/cell/db/util/McMongoUtils.java @@ -28,12 +28,39 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; +/** + * 【通用基础库】{@code McMongoUtils} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McMongoUtils { + /** + * 处理转换为Pageable。 + * + * @param page 页码(从 0 开始)({@code int}) + * @param size 每页数量({@code int}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code String}) + * @return 分页结果 + */ public static Pageable toPageable(int page, int size, String sortBy, String direction) { Sort.Direction dir = toDirection(direction); return dir != null && !McStringUtils.isNullOrEmpty(sortBy) ? PageRequest.of(page, size, dir, new String[]{sortBy}) : PageRequest.of(page, size); } + /** + * 处理转换为Direction。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param direction 排序方向({@code String}) + * @return 处理结果 + */ public static Sort.Direction toDirection(String direction) { try { return Direction.valueOf(direction.trim().toUpperCase()); @@ -42,6 +69,16 @@ public class McMongoUtils { } } + /** + * 处理转换为查询。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new Query。 + * + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @param sortBy 排序字段({@code String}) + * @param direction 排序方向({@code Sort.Direction}) + * @return 处理结果 + */ public static Query toQuery(JsonObject jFilter, String sortBy, Sort.Direction direction) { Sort sort = Strings.isNullOrEmpty(sortBy) ? null : Sort.by(direction, new String[]{sortBy}); Query query = new Query(); @@ -57,6 +94,14 @@ public class McMongoUtils { } } + /** + * 添加过滤。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 13 个条件分支、1 个循环;主要调用:new Criteria。 + * + * @param query 查询对象({@code Query}) + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + */ public static void addFilter(Query query, JsonObject jFilter) { for(Map.Entry jElement : jFilter.entrySet()) { String key = (String)jElement.getKey(); @@ -120,10 +165,26 @@ public class McMongoUtils { } + /** + * 处理转换为Criteria。 + * + * 实现要点:主要调用:new Criteria。 + * + * @param jFilter 参数 {@code jFilter}({@code String}) + * @return 处理结果 + */ public static Criteria toCriteria(String jFilter) { return Strings.isNullOrEmpty(jFilter) ? new Criteria() : toCriteria(McJsonUtils.toJsonElement(jFilter).getAsJsonObject()); } + /** + * 处理转换为Criteria。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 13 个条件分支、2 个循环;主要调用:new Criteria、new ArrayList。 + * + * @param jFilter 参数 {@code jFilter}({@code JsonObject}) + * @return 处理结果 + */ public static Criteria toCriteria(JsonObject jFilter) { if (jFilter.size() == 0) { return new Criteria(); @@ -192,14 +253,36 @@ public class McMongoUtils { } } + /** + * 处理escapedPattern。 + * + * @param value 值({@code String}) + * @return 处理结果 + */ public static Pattern escapedPattern(String value) { return Pattern.compile(Pattern.quote(value), 66); } + /** + * 处理转换为LikeCriteria。 + * + * @param key 键/配置项({@code String}) + * @param regex 参数 {@code regex}({@code String}) + * @return 处理结果 + */ public static Criteria toLikeCriteria(String key, String regex) { return Criteria.where(key).regex(escapedPattern(regex)); } + /** + * 处理转换为或Criteria。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new Criteria、new ArrayList。 + * + * @param key 键/配置项({@code String}) + * @param jArray 参数 {@code jArray}({@code JsonArray}) + * @return 处理结果 + */ public static Criteria toOrCriteria(String key, JsonArray jArray) { Criteria criteria = new Criteria(); List subCriterias = new ArrayList(); @@ -224,14 +307,35 @@ public class McMongoUtils { return criteria; } + /** + * 处理转换为UUIDCriteria。 + * + * @param key 键/配置项({@code String}) + * @param uuid 对象 UUID({@code UUID}) + * @return 处理结果 + */ public static Criteria toUuidCriteria(String key, UUID uuid) { return Criteria.where(key).is(uuid); } + /** + * 处理转换为EmptyCriteria。 + * + * @param key 键/配置项({@code String}) + * @return 处理结果 + */ public static Criteria toEmptyCriteria(String key) { return Criteria.where(key).exists(false); } + /** + * 处理转换为总数Supplier。 + * + * 实现要点:主要调用:new LongSupplier。 + * + * @param total 总数({@code long}) + * @return 处理结果 + */ public static LongSupplier toTotalSupplier(final long total) { return new LongSupplier() { public long getAsLong() { @@ -240,6 +344,18 @@ public class McMongoUtils { }; } + /** + * 创建Index。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 13 个条件分支、1 个循环;主要调用:new IndexOptions、dropIndex、createIndex。 + * + * @param mongoTemplate 参数 {@code mongoTemplate}({@code MongoTemplate}) + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param keys 参数 {@code keys}({@code Document}) + * @param indexName 参数 {@code indexName}({@code String}) + * @param isUnique 参数 {@code isUnique}({@code Boolean}) + * @param expireAfter 参数 {@code expireAfter}({@code Long}) + */ public static void createIndex(MongoTemplate mongoTemplate, String collectionName, Document keys, String indexName, Boolean isUnique, Long expireAfter) { MongoCollection collection = mongoTemplate.collectionExists(collectionName) ? mongoTemplate.getCollection(collectionName) : mongoTemplate.createCollection(collectionName); IndexOptions options = new IndexOptions(); @@ -300,6 +416,15 @@ public class McMongoUtils { collection.createIndex(keys, options); } + /** + * 处理dropIndex。 + * + * 实现要点:通过 MongoTemplate 访问 MongoDB(查询/写入/聚合);包含 3 个条件分支、1 个循环;主要调用:dropIndex。 + * + * @param mongoTemplate 参数 {@code mongoTemplate}({@code MongoTemplate}) + * @param collectionName 参数 {@code collectionName}({@code String}) + * @param fields 参数 {@code fields}({@code String[]}) + */ public static void dropIndex(MongoTemplate mongoTemplate, String collectionName, String... fields) { if (mongoTemplate.collectionExists(collectionName)) { MongoCollection collection = mongoTemplate.getCollection(collectionName); diff --git a/src/main/java/com/mitac/cell/db/util/McPipeLine.java b/src/main/java/com/mitac/cell/db/util/McPipeLine.java index f9866d8..24ee76f 100644 --- a/src/main/java/com/mitac/cell/db/util/McPipeLine.java +++ b/src/main/java/com/mitac/cell/db/util/McPipeLine.java @@ -1,4 +1,14 @@ package com.mitac.cell.db.util; +/** + * 【通用基础库】{@code McPipeLine} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McPipeLine { } diff --git a/src/main/java/com/mitac/cell/db/util/package-info.java b/src/main/java/com/mitac/cell/db/util/package-info.java new file mode 100644 index 0000000..08c609b --- /dev/null +++ b/src/main/java/com/mitac/cell/db/util/package-info.java @@ -0,0 +1,15 @@ +/** + * 包 {@code com.mitac.cell.db.util}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link JpaQuery}
  • + *
  • {@link McDbUtils}
  • + *
  • {@link McMongoUtils}
  • + *
  • {@link McPipeLine}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.db.util; diff --git a/src/main/java/com/mitac/cell/doc/Csv.java b/src/main/java/com/mitac/cell/doc/Csv.java index 36a7cb1..567d3c9 100644 --- a/src/main/java/com/mitac/cell/doc/Csv.java +++ b/src/main/java/com/mitac/cell/doc/Csv.java @@ -5,41 +5,144 @@ import java.util.ArrayList; import java.util.List; import java.util.Set; +/** + * 【通用基础库】{@code Csv} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code separator}(char):字段 separator
  • + *
  • {@code quoteChar}(char):字段 quoteChar
  • + *
  • {@code escapeChar}(char):转义Char
  • + *
  • {@code strictQuotes}(boolean):是否strictQuotes
  • + *
  • {@code inToken}(boolean):在令牌
  • + *
  • {@code ignoreLeadingWhiteSpace}(boolean):是否ignoreLeadingWhiteSpace
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class Csv { + /** + * 字段 separator。 + */ private final char separator; + /** + * 字段 quoteChar。 + */ private final char quoteChar; + /** + * 转义Char。 + */ private final char escapeChar; + /** + * 是否strictQuotes。 + */ private final boolean strictQuotes; + /** + * 在令牌。 + */ private boolean inToken; + /** + * 是否ignoreLeadingWhiteSpace。 + */ private final boolean ignoreLeadingWhiteSpace; + /** + * 字段 DEFAULT_SEPARATOR。 + */ public static final char DEFAULT_SEPARATOR = ','; + /** + * 字段 DEFAULT_QUOTE_CHARACTER。 + */ public static final char DEFAULT_QUOTE_CHARACTER = '"'; + /** + * 字段 DEFAULT_ESCAPE_CHARACTER。 + */ public static final char DEFAULT_ESCAPE_CHARACTER = '\\'; + /** + * 字段 NULL_CHARACTER。 + */ public static final char NULL_CHARACTER = '\u0000'; + /** + * 字段 DEFAULT_LINE_END。 + */ public static final String DEFAULT_LINE_END = "\n"; + /** + * 字段 NO_QUOTE_CHARACTER。 + */ public static final char NO_QUOTE_CHARACTER = '\u0000'; + /** + * 字段 NO_ESCAPE_CHARACTER。 + */ public static final char NO_ESCAPE_CHARACTER = '\u0000'; + /** + * 构造 {@code Csv} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Csv() { this(',', '"', '\\'); } + /** + * 构造 {@code Csv} 实例。 + * + * @param separator 参数 {@code separator}({@code char}) + */ public Csv(char separator) { this(separator, '"', '\\'); } + /** + * 构造 {@code Csv} 实例。 + * + * @param separator 参数 {@code separator}({@code char}) + * @param quoteChar 参数 {@code quoteChar}({@code char}) + */ public Csv(char separator, char quoteChar) { this(separator, quoteChar, '\\'); } + /** + * 构造 {@code Csv} 实例。 + * + * @param separator 参数 {@code separator}({@code char}) + * @param quoteChar 参数 {@code quoteChar}({@code char}) + * @param escape 参数 {@code escape}({@code char}) + */ public Csv(char separator, char quoteChar, char escape) { this(separator, quoteChar, escape, false); } + /** + * 构造 {@code Csv} 实例。 + * + * @param separator 参数 {@code separator}({@code char}) + * @param quoteChar 参数 {@code quoteChar}({@code char}) + * @param escape 参数 {@code escape}({@code char}) + * @param strictQuotes 参数 {@code strictQuotes}({@code boolean}) + */ public Csv(char separator, char quoteChar, char escape, boolean strictQuotes) { this(separator, quoteChar, escape, strictQuotes, true, "\n"); } + /** + * 构造 {@code Csv} 实例。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new UnsupportedOperationException。 + * + * @param separator 参数 {@code separator}({@code char}) + * @param quoteChar 参数 {@code quoteChar}({@code char}) + * @param escape 参数 {@code escape}({@code char}) + * @param strictQuotes 参数 {@code strictQuotes}({@code boolean}) + * @param ignoreLeadingWhiteSpace 参数 {@code ignoreLeadingWhiteSpace}({@code boolean}) + * @param lineEnd 参数 {@code lineEnd}({@code String}) + * @throws UnsupportedOperationException 当 UnsupportedOperationException 条件不满足或底层调用失败时抛出。 + */ public Csv(char separator, char quoteChar, char escape, boolean strictQuotes, boolean ignoreLeadingWhiteSpace, String lineEnd) { this.inToken = false; if (this.anyCharactersAreTheSame(separator, quoteChar, escape)) { @@ -55,14 +158,38 @@ public class Csv { } } + /** + * 处理任意CharactersAreTheSame。 + * + * @param separator 参数 {@code separator}({@code char}) + * @param quoteChar 参数 {@code quoteChar}({@code char}) + * @param escape 参数 {@code escape}({@code char}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ private boolean anyCharactersAreTheSame(char separator, char quoteChar, char escape) { return this.isSameCharacter(separator, quoteChar) || this.isSameCharacter(separator, escape) || this.isSameCharacter(quoteChar, escape); } + /** + * 判断是否SameCharacter。 + * + * @param c1 参数 {@code c1}({@code char}) + * @param c2 参数 {@code c2}({@code char}) + * @return 字段/派生属性 {@code sameCharacter} 的值 + */ private boolean isSameCharacter(char c1, char c2) { return c1 != 0 && c1 == c2; } + /** + * 处理解析。 + * + * 实现要点:包含 10 个条件分支、1 个循环;主要调用:new ArrayList、new StringBuilder。 + * + * @param csvText 参数 {@code csvText}({@code String}) + * @return 处理结果 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ public String[] parse(String csvText) throws IOException { if (csvText == null) { return null; @@ -113,17 +240,41 @@ public class Csv { } } + /** + * 判断是否NextCharacterEscapedQuote。 + * + * @param csvText 参数 {@code csvText}({@code String}) + * @param inQuotes 参数 {@code inQuotes}({@code boolean}) + * @param i 参数 {@code i}({@code int}) + * @return 字段/派生属性 {@code nextCharacterEscapedQuote} 的值 + */ private boolean isNextCharacterEscapedQuote(String csvText, boolean inQuotes, int i) { int nextIndex = i + 1; return inQuotes && csvText.length() > nextIndex && csvText.charAt(nextIndex) == this.quoteChar; } + /** + * 判断是否NextCharacterEscapable。 + * + * @param csvText 参数 {@code csvText}({@code String}) + * @param inQuotes 参数 {@code inQuotes}({@code boolean}) + * @param i 参数 {@code i}({@code int}) + * @return 字段/派生属性 {@code nextCharacterEscapable} 的值 + */ protected boolean isNextCharacterEscapable(String csvText, boolean inQuotes, int i) { int nextIndex = i + 1; char nextChar = csvText.charAt(nextIndex); return inQuotes && csvText.length() > nextIndex && (nextChar == this.quoteChar || csvText.charAt(nextIndex) == this.escapeChar); } + /** + * 判断是否全部WhiteSpace。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param sb 参数 {@code sb}({@code CharSequence}) + * @return 字段/派生属性 {@code allWhiteSpace} 的值 + */ protected boolean isAllWhiteSpace(CharSequence sb) { boolean result = true; @@ -138,6 +289,14 @@ public class Csv { return result; } + /** + * 返回对象的可读字符串表示。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:new StringBuilder。 + * + * @param columns 参数 {@code columns}({@code String[]}) + * @return 字符串结果 + */ public String toString(String[] columns) { StringBuilder sb = new StringBuilder(); @@ -162,6 +321,14 @@ public class Csv { return sb.toString(); } + /** + * 返回对象的可读字符串表示。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * @param columns 参数 {@code columns}({@code Object[]}) + * @return 字符串结果 + */ public String toString(Object[] columns) { List list = new ArrayList(); @@ -172,7 +339,15 @@ public class Csv { return this.toString(list); } - public String toString(ArrayList columns) { + /** + * 返回对象的可读字符串表示。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList。 + * + * @param columns 参数 {@code columns}({@code ArrayList}) + * @return 字符串结果 + */ + public String toString(ArrayList columns) { List list = new ArrayList(); for(Object obj : columns) { @@ -182,19 +357,47 @@ public class Csv { return this.toString(list); } - public String toString(Set columns) { + /** + * 返回对象的可读字符串表示。 + * + * 实现要点:主要调用:new ArrayList。 + * + * @param columns 参数 {@code columns}({@code Set}) + * @return 字符串结果 + */ + public String toString(Set columns) { List list = new ArrayList(columns); return this.toString(list); } - public String toString(List columns) { + /** + * 返回对象的可读字符串表示。 + * + * @param columns 参数 {@code columns}({@code List}) + * @return 字符串结果 + */ + public String toString(List columns) { return this.toString((String[])columns.toArray()); } + /** + * 处理string包含SpecialCharacters。 + * + * @param line 参数 {@code line}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ private boolean stringContainsSpecialCharacters(String line) { return line.indexOf(this.quoteChar) != -1 || line.indexOf(this.escapeChar) != -1; } + /** + * 处理Line。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new StringBuilder。 + * + * @param nextElement 参数 {@code nextElement}({@code String}) + * @return 处理结果 + */ protected StringBuilder processLine(String nextElement) { StringBuilder sb = new StringBuilder(); diff --git a/src/main/java/com/mitac/cell/doc/CsvReader.java b/src/main/java/com/mitac/cell/doc/CsvReader.java index 72dcfd1..09806f0 100644 --- a/src/main/java/com/mitac/cell/doc/CsvReader.java +++ b/src/main/java/com/mitac/cell/doc/CsvReader.java @@ -8,13 +8,49 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +/** + * 【通用基础库】{@code CsvReader} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code reader}(BufferedReader):字段 reader
  • + *
+ * + * 协作对象:{@code BufferedReader}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public abstract class CsvReader { + /** + * 字段 reader。 + */ private BufferedReader reader; + /** + * 构造 {@code CsvReader} 实例。 + * + * 实现要点:主要调用:new File。 + * + * @param path 参数 {@code path}({@code String}) + * @throws FileNotFoundException 当 FileNotFoundException 条件不满足或底层调用失败时抛出。 + */ public CsvReader(String path) throws FileNotFoundException { this(new File(path)); } + /** + * 构造 {@code CsvReader} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new BufferedReader、new FileReader。 + * + * @param file 文件({@code File}) + */ public CsvReader(File file) { try { this.reader = new BufferedReader(new FileReader(file)); @@ -23,15 +59,36 @@ public abstract class CsvReader { } + /** + * 构造 {@code CsvReader} 实例。 + * + * 实现要点:主要调用:new BufferedReader、new InputStreamReader。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ public CsvReader(InputStream input) { this.reader = new BufferedReader(new InputStreamReader(input)); } + /** + * 处理处理新Row。 + * + * @param var1 参数 {@code var1}({@code int}) + * @param var2 参数 {@code var2}({@code String[]}) + */ public abstract void onNewRow(int var1, String[] var2); + /** + * 处理处理结束。 + */ public void onEnd() { } + /** + * 解析全部。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new Csv、close。 + */ public void parseAll() { try { int lineNum = 0; diff --git a/src/main/java/com/mitac/cell/doc/ExcelCell.java b/src/main/java/com/mitac/cell/doc/ExcelCell.java index d82feea..fb6d341 100644 --- a/src/main/java/com/mitac/cell/doc/ExcelCell.java +++ b/src/main/java/com/mitac/cell/doc/ExcelCell.java @@ -6,12 +6,49 @@ import com.mitac.cell.utils.McNumberUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; +/** + * 【通用基础库】{@code ExcelCell} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code columnIndex}(int):字段 columnIndex
  • + *
  • {@code rowIndex}(int):字段 rowIndex
  • + *
  • {@code cellName}(String):cell名称
  • + *
  • {@code value}(String):值
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class ExcelCell { + /** + * 字段 columnIndex。 + */ public int columnIndex; + /** + * 字段 rowIndex。 + */ public int rowIndex; + /** + * cell名称。 + */ public String cellName; + /** + * 值。 + */ public String value; + /** + * 构造 {@code ExcelCell} 实例。 + * + * @param cellName 参数 {@code cellName}({@code String}) + * @param value 值({@code String}) + */ public ExcelCell(String cellName, String value) { this.cellName = cellName; this.value = value; @@ -19,18 +56,40 @@ public class ExcelCell { this.rowIndex = this.getRowIndex(cellName); } + /** + * 获取 {@code columnName}。 + * @return 字符串结果 + */ public String getColumnName() { return CharMatcher.inRange('0', '9').removeFrom(this.cellName); } + /** + * 获取 {@code columnIndex}。 + * @return 数量/长度 + */ public int getColumnIndex() { return this.columnIndex; } + /** + * 获取RowIndex。 + * + * @param cellName 参数 {@code cellName}({@code String}) + * @return 数量/长度 + */ private int getRowIndex(String cellName) { return Integer.parseInt(CharMatcher.inRange('0', '9').retainFrom(cellName)) - 1; } + /** + * 获取ColumnIndex。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new StringBuffer。 + * + * @param cellName 参数 {@code cellName}({@code String}) + * @return 数量/长度 + */ private int getColumnIndex(String cellName) { String columnName = CharMatcher.inRange('0', '9').removeFrom(cellName).toUpperCase(); String reversedName = (new StringBuffer(columnName)).reverse().toString(); @@ -44,18 +103,38 @@ public class ExcelCell { return index; } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return this.value; } + /** + * 处理转换为Integer。 + * @return 数量/长度 + */ public int toInteger() { return McNumberUtils.toInt(this.value); } + /** + * 处理转换为Float。 + * @return 处理结果 + */ public float toFloat() { return McNumberUtils.toFloat(this.value); } + /** + * 判断是否Empty。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @return 字段/派生属性 {@code empty} 的值 + */ public static boolean isEmpty(Cell cell) { if (cell == null) { return true; diff --git a/src/main/java/com/mitac/cell/doc/ExcelReader.java b/src/main/java/com/mitac/cell/doc/ExcelReader.java index 416ceec..591d3ab 100644 --- a/src/main/java/com/mitac/cell/doc/ExcelReader.java +++ b/src/main/java/com/mitac/cell/doc/ExcelReader.java @@ -18,10 +18,42 @@ import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; +/** + * 【通用基础库】{@code ExcelReader} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code xmlReader}(XMLReader):字段 xmlReader
  • + *
  • {@code xssfReader}(XSSFReader):字段 xssfReader
  • + *
+ * + * 协作对象:{@code XMLReader、XSSFReader}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public abstract class ExcelReader { + /** + * 字段 xmlReader。 + */ private XMLReader xmlReader; + /** + * 字段 xssfReader。 + */ private XSSFReader xssfReader; + /** + * 构造 {@code ExcelReader} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param path 参数 {@code path}({@code String}) + */ public ExcelReader(String path) { try { OPCPackage pkg = OPCPackage.open(path); @@ -32,6 +64,13 @@ public abstract class ExcelReader { } + /** + * 构造 {@code ExcelReader} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param file 文件({@code File}) + */ public ExcelReader(File file) { try { OPCPackage pkg = OPCPackage.open(file); @@ -42,6 +81,13 @@ public abstract class ExcelReader { } + /** + * 构造 {@code ExcelReader} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param is 参数 {@code is}({@code InputStream}) + */ public ExcelReader(InputStream is) { try { OPCPackage pkg = OPCPackage.open(is); @@ -54,6 +100,13 @@ public abstract class ExcelReader { } + /** + * 设置 {@code package}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new XSSFReader。 + * + * @param pkg 参数 {@code pkg}({@code OPCPackage}) + */ private void setPackage(OPCPackage pkg) { try { this.xssfReader = new XSSFReader(pkg); @@ -69,6 +122,13 @@ public abstract class ExcelReader { } + /** + * 处理parceSheet。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new InputSource、parse、close。 + * + * @param sheetName 参数 {@code sheetName}({@code String}) + */ public void parceSheet(String sheetName) { try { InputStream sheetIS = this.xssfReader.getSheet(sheetName); @@ -85,6 +145,11 @@ public abstract class ExcelReader { } + /** + * 解析全部。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new InputSource、parse、close。 + */ public void parseAll() { try { Iterator sheets = this.xssfReader.getSheetsData(); @@ -105,6 +170,14 @@ public abstract class ExcelReader { } + /** + * 处理fetchSheetParser。 + * + * 实现要点:主要调用:new SheetHandler。 + * + * @param stringsTable 参数 {@code stringsTable}({@code SharedStrings}) + * @return 处理结果 + */ public XMLReader fetchSheetParser(SharedStrings stringsTable) { XMLReader xmlReader = this.xmlReader(); ContentHandler handler = new SheetHandler(stringsTable); @@ -112,6 +185,12 @@ public abstract class ExcelReader { return xmlReader; } + /** + * 处理xmlReader。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 处理结果 + */ public XMLReader xmlReader() { SAXParserFactory parserFactory = SAXParserFactory.newInstance(); @@ -123,25 +202,96 @@ public abstract class ExcelReader { } } + /** + * 处理处理Sheet数据启动。 + */ public abstract void onSheetDataStart(); + /** + * 处理处理新Row。 + * + * @param var1 参数 {@code var1}({@code ExcelRow}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public abstract boolean onNewRow(ExcelRow var1); + /** + * 处理处理Sheet数据结束。 + */ public abstract void onSheetDataEnd(); + /** + * 【通用基础库】{@code SheetHandler} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code CELL_NUM}(String):字段 CELL_NUM
  • + *
  • {@code CELL_TYPE}(String):字段 CELL_TYPE
  • + *
  • {@code stringsTable}(SharedStrings):字段 stringsTable
  • + *
  • {@code row}(ExcelRow):字段 row
  • + *
  • {@code curCellName}(String):curCell名称
  • + *
  • {@code curCellType}(String):curCell类型
  • + *
+ * + * 协作对象:{@code SharedStrings、ExcelRow}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ private class SheetHandler extends DefaultHandler { + /** + * 字段 CELL_NUM。 + */ private static final String CELL_NUM = "r"; + /** + * 字段 CELL_TYPE。 + */ private static final String CELL_TYPE = "t"; + /** + * 字段 stringsTable。 + */ private SharedStrings stringsTable; + /** + * 字段 row。 + */ private ExcelRow row = null; + /** + * curCell名称。 + */ private String curCellName = null; + /** + * curCell类型。 + */ private String curCellType = null; + /** + * curCell值。 + */ private String curCellValue; + /** + * 构造 {@code SheetHandler} 实例。 + * + * @param stringsTable 参数 {@code stringsTable}({@code SharedStrings}) + */ private SheetHandler(SharedStrings stringsTable) { this.stringsTable = stringsTable; } + /** + * 启动Element。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new ExcelRow。 + * + * @param uri 参数 {@code uri}({@code String}) + * @param localName 参数 {@code localName}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param attributes 参数 {@code attributes}({@code Attributes}) + */ public void startElement(String uri, String localName, String name, Attributes attributes) { if (name.equals("row")) { this.row = new ExcelRow(); @@ -155,6 +305,15 @@ public abstract class ExcelReader { } + /** + * 处理结束Element。 + * + * 实现要点:包含 4 个条件分支、0 个循环。 + * + * @param uri 参数 {@code uri}({@code String}) + * @param localName 参数 {@code localName}({@code String}) + * @param name 参数 {@code name}({@code String}) + */ public void endElement(String uri, String localName, String name) { if (name.equals("row")) { ExcelReader.this.onNewRow(this.row); @@ -172,11 +331,23 @@ public abstract class ExcelReader { } + /** + * 处理characters。 + * + * 实现要点:主要调用:new String。 + * + * @param ch 参数 {@code ch}({@code char[]}) + * @param start 参数 {@code start}({@code int}) + * @param length 参数 {@code length}({@code int}) + */ public void characters(char[] ch, int start, int length) { - String var10001 = this.curCellValue; - this.curCellValue = var10001 + new String(ch, start, length); + this.curCellValue += new String(ch, start, length); } + /** + * 判断 {@code stringCell}。 + * @return 字段/派生属性 {@code stringCell} 的值 + */ private boolean isStringCell() { return this.curCellType != null && this.curCellType.equals("s"); } diff --git a/src/main/java/com/mitac/cell/doc/ExcelRow.java b/src/main/java/com/mitac/cell/doc/ExcelRow.java index e44a6a7..e1c4571 100644 --- a/src/main/java/com/mitac/cell/doc/ExcelRow.java +++ b/src/main/java/com/mitac/cell/doc/ExcelRow.java @@ -5,33 +5,90 @@ import java.util.Iterator; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; -public class ExcelRow extends HashMap { +/** + * 【通用基础库】{@code ExcelRow} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ +public class ExcelRow extends HashMap { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = -2035806587539130093L; + /** + * 添加Cell。 + * + * 实现要点:主要调用:new ExcelCell。 + * + * @param cellName 参数 {@code cellName}({@code String}) + * @param value 值({@code String}) + */ public void addCell(String cellName, String value) { ExcelCell cell = new ExcelCell(cellName, value); this.put(cell.columnIndex, cell); } + /** + * 获取 {@code rowIndex}。 + * @return 数量/长度 + */ public int getRowIndex() { return this.size() > 0 ? ((ExcelCell)this.get(0)).rowIndex : -1; } + /** + * 获取String。 + * + * @param columnIndex 参数 {@code columnIndex}({@code int}) + * @return 字符串结果 + */ public String getString(int columnIndex) { ExcelCell cell = (ExcelCell)this.get(columnIndex); return cell == null ? "" : cell.toString(); } + /** + * 获取Integer。 + * + * @param columnIndex 参数 {@code columnIndex}({@code int}) + * @return 数量/长度 + */ public int getInteger(int columnIndex) { ExcelCell cell = (ExcelCell)this.get(columnIndex); return cell == null ? 0 : cell.toInteger(); } + /** + * 获取Float。 + * + * @param columnIndex 参数 {@code columnIndex}({@code int}) + * @return 字段/派生属性 {@code float} 的值 + */ public float getFloat(int columnIndex) { ExcelCell cell = (ExcelCell)this.get(columnIndex); return cell == null ? 0.0F : cell.toFloat(); } + /** + * 判断是否Empty。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param row 参数 {@code row}({@code Row}) + * @return 字段/派生属性 {@code empty} 的值 + */ public static boolean isEmpty(Row row) { if (row != null && row.getPhysicalNumberOfCells() != 0) { Iterator it = row.cellIterator(); diff --git a/src/main/java/com/mitac/cell/doc/ExcelWriter.java b/src/main/java/com/mitac/cell/doc/ExcelWriter.java index 2e24341..55f73f2 100644 --- a/src/main/java/com/mitac/cell/doc/ExcelWriter.java +++ b/src/main/java/com/mitac/cell/doc/ExcelWriter.java @@ -41,25 +41,94 @@ import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.bouncycastle.util.encoders.Hex; +/** + * 【通用基础库】{@code ExcelWriter} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code INTEGER_COMMA_FORMAT}(String):字段 INTEGER_COMMA_FORMAT
  • + *
  • {@code FLOAT_COMMA_FORMAT}(String):字段 FLOAT_COMMA_FORMAT
  • + *
  • {@code workbook}(XSSFWorkbook):字段 workbook
  • + *
  • {@code properties}(POIXMLProperties):字段 properties
  • + *
  • {@code createHelper}(CreationHelper):创建Helper
  • + *
  • {@code activeSheet}(Sheet):字段 activeSheet
  • + *
+ * + * 协作对象:{@code XSSFWorkbook、POIXMLProperties、CreationHelper、Sheet、CellStyle}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class ExcelWriter { + /** + * 字段 INTEGER_COMMA_FORMAT。 + */ public static final String INTEGER_COMMA_FORMAT = "#,##0"; + /** + * 字段 FLOAT_COMMA_FORMAT。 + */ public static final String FLOAT_COMMA_FORMAT = "#,##0.00"; + /** + * 字段 workbook。 + */ private XSSFWorkbook workbook; + /** + * 字段 properties。 + */ private POIXMLProperties properties; + /** + * 创建Helper。 + */ private CreationHelper createHelper; + /** + * 字段 activeSheet。 + */ private Sheet activeSheet; - Map fontMap; - Map styleMap; + /** + * 映射表。 + */ + Map fontMap; + /** + * 映射表。 + */ + Map styleMap; + /** + * 字段 tempStyle。 + */ private CellStyle tempStyle; + /** + * 构造 {@code ExcelWriter} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public ExcelWriter() { this((InputStream)null); } + /** + * 构造 {@code ExcelWriter} 实例。 + * + * 实现要点:主要调用:new FileInputStream。 + * + * @param input 参数 {@code input}({@code File}) + * @throws FileNotFoundException 当 FileNotFoundException 条件不满足或底层调用失败时抛出。 + */ public ExcelWriter(File input) throws FileNotFoundException { this((InputStream)(new FileInputStream(input))); } + /** + * 构造 {@code ExcelWriter} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new HashMap、new XSSFWorkbook。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ public ExcelWriter(InputStream input) { this.fontMap = new HashMap(); this.styleMap = new HashMap(); @@ -73,6 +142,9 @@ public class ExcelWriter { } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + */ private void init() { this.properties = this.workbook.getProperties(); this.createHelper = this.workbook.getCreationHelper(); @@ -80,6 +152,11 @@ public class ExcelWriter { this.initActiveSheet(); } + /** + * 处理关闭。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:close。 + */ public void close() { try { this.workbook.close(); @@ -89,32 +166,67 @@ public class ExcelWriter { } + /** + * 获取 {@code coreProperty}。 + * @return 字段/派生属性 {@code coreProperty} 的值 + */ public POIXMLProperties.CoreProperties getCoreProperty() { return this.properties.getCoreProperties(); } + /** + * 获取 {@code customProperty}。 + * @return 字段/派生属性 {@code customProperty} 的值 + */ public POIXMLProperties.CustomProperties getCustomProperty() { return this.properties.getCustomProperties(); } + /** + * 获取 {@code numberOfSheets}。 + * @return 数量/长度 + */ public int getNumberOfSheets() { return this.workbook.getNumberOfSheets(); } + /** + * 获取 {@code activeSheetIndex}。 + * @return 数量/长度 + */ public int getActiveSheetIndex() { return this.workbook.getActiveSheetIndex(); } + /** + * 获取Sheet。 + * + * @param index 参数 {@code index}({@code int}) + * @return 字段/派生属性 {@code sheet} 的值 + */ public Sheet getSheet(int index) { return this.workbook.getSheetAt(index); } + /** + * 添加Sheet。 + * + * @param sheetName 参数 {@code sheetName}({@code String}) + * @return 处理结果 + */ public Sheet addSheet(String sheetName) { this.activeSheet = Strings.isNullOrEmpty(sheetName) ? this.workbook.createSheet() : this.workbook.createSheet(sheetName); this.setActive(this.activeSheet); return this.activeSheet; } + /** + * 移除Sheet。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param index 参数 {@code index}({@code int}) + */ public void removeSheet(int index) { if (index >= 0 && index < this.getNumberOfSheets()) { this.workbook.removeSheetAt(index); @@ -122,6 +234,13 @@ public class ExcelWriter { } + /** + * 移除Sheet。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param sheetNames 参数 {@code sheetNames}({@code String[]}) + */ public void removeSheet(String... sheetNames) { for(String sheetName : sheetNames) { int sheetIndex = this.workbook.getSheetIndex(sheetName); @@ -132,24 +251,53 @@ public class ExcelWriter { } + /** + * 设置 {@code columns}。 + * + * @param names 参数 {@code names}({@code String[]}) + */ public void setColumns(String... names) { this.setRow(0, (Object[])names); this.activeSheet.createFreezePane(0, 1); } + /** + * 设置Columns。 + * + * @param rowNum 参数 {@code rowNum}({@code int}) + * @param names 参数 {@code names}({@code String[]}) + */ public void setColumns(int rowNum, String... names) { this.setRow(rowNum, (Object[])names); this.activeSheet.createFreezePane(0, 1); } + /** + * 处理freezeRows。 + * + * @param rowNum 参数 {@code rowNum}({@code int}) + */ public void freezeRows(int rowNum) { this.freeze(rowNum, 0); } + /** + * 处理freeze。 + * + * @param rowNum 参数 {@code rowNum}({@code int}) + * @param colNum 参数 {@code colNum}({@code int}) + */ public void freeze(int rowNum, int colNum) { this.activeSheet.createFreezePane(colNum, rowNum); } + /** + * 设置 {@code autoSizeColumn}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param colIndex 参数 {@code colIndex}({@code int}) + */ public void setAutoSizeColumn(int colIndex) { int orgWidth = this.activeSheet.getColumnWidth(colIndex); this.activeSheet.autoSizeColumn(colIndex); @@ -160,10 +308,21 @@ public class ExcelWriter { } + /** + * 设置Auto数量Columns。 + */ public void setAutoSizeColumns() { this.setAutoSizeColumns(0, this.getLastColIndex()); } + /** + * 设置Auto数量Columns。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + */ public void setAutoSizeColumns(int colFrom, int colTo) { for(int i = colFrom; i <= colTo; ++i) { this.setAutoSizeColumn(i); @@ -171,6 +330,13 @@ public class ExcelWriter { } + /** + * 设置 {@code autoSizeColumns}。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param colIndexes 参数 {@code colIndexes}({@code int[]}) + */ public void setAutoSizeColumns(int... colIndexes) { for(int colIndex : colIndexes) { this.setAutoSizeColumn(colIndex); @@ -178,17 +344,37 @@ public class ExcelWriter { } + /** + * 设置Column格式化。 + * + * @param colIndex 参数 {@code colIndex}({@code int}) + * @param formatNo 参数 {@code formatNo}({@code short}) + */ public void setColumnFormat(int colIndex, short formatNo) { CellStyle style = this.workbook.createCellStyle(); style.setDataFormat(formatNo); this.activeSheet.setDefaultColumnStyle(colIndex, style); } + /** + * 设置Column格式化。 + * + * @param colIndex 参数 {@code colIndex}({@code int}) + * @param format 参数 {@code format}({@code String}) + */ public void setColumnFormat(int colIndex, String format) { short formatNo = this.createHelper.createDataFormat().getFormat(format); this.setColumnFormat(colIndex, formatNo); } + /** + * 获取Row。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @return 字段/派生属性 {@code row} 的值 + */ public Row getRow(int rowNo) { Row row = this.activeSheet.getRow(rowNo); if (row == null) { @@ -198,10 +384,26 @@ public class ExcelWriter { return row; } + /** + * 获取Cell。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param colNo 参数 {@code colNo}({@code int}) + * @return 字段/派生属性 {@code cell} 的值 + */ public Cell getCell(int rowNo, int colNo) { return this.getCell(this.getRow(rowNo), colNo); } + /** + * 获取Cell。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param row 参数 {@code row}({@code Row}) + * @param colNo 参数 {@code colNo}({@code int}) + * @return 字段/派生属性 {@code cell} 的值 + */ public Cell getCell(Row row, int colNo) { Cell cell = row.getCell(colNo); if (cell == null) { @@ -211,10 +413,25 @@ public class ExcelWriter { return cell; } + /** + * 获取CellStyle。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param colNo 参数 {@code colNo}({@code int}) + * @return 字段/派生属性 {@code cellStyle} 的值 + */ public CellStyle getCellStyle(int rowNo, int colNo) { return this.getCell(rowNo, colNo).getCellStyle(); } + /** + * 设置Row。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param values 参数 {@code values}({@code Object[]}) + */ public void setRow(int rowNo, Object... values) { Row row = this.getRow(rowNo); @@ -227,11 +444,20 @@ public class ExcelWriter { } + /** + * 初始化ActiveSheet。 + */ private void initActiveSheet() { int index = this.getActiveSheetIndex(); this.activeSheet = this.workbook.getSheetAt(index); } + /** + * 获取 {@code activeSheet}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字段/派生属性 {@code activeSheet} 的值 + */ public Sheet getActiveSheet() { if (this.activeSheet == null) { this.initActiveSheet(); @@ -240,6 +466,14 @@ public class ExcelWriter { return this.activeSheet; } + /** + * 设置 {@code active}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param sheetIndex 参数 {@code sheetIndex}({@code int}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setActive(int sheetIndex) { if (sheetIndex >= 0 && sheetIndex < this.getNumberOfSheets()) { this.activeSheet = this.workbook.getSheetAt(sheetIndex); @@ -251,19 +485,45 @@ public class ExcelWriter { } } + /** + * 设置 {@code active}。 + * + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setActive(String name) { this.activeSheet = this.workbook.getSheet(name); return this.setActive(this.activeSheet); } + /** + * 设置 {@code active}。 + * + * @param sheet 参数 {@code sheet}({@code Sheet}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setActive(Sheet sheet) { return this.setActive(this.workbook.getSheetIndex(sheet)); } + /** + * 获取Sheet。 + * + * @param sheetName 参数 {@code sheetName}({@code String}) + * @return 字段/派生属性 {@code sheet} 的值 + */ public Sheet getSheet(String sheetName) { return this.workbook.getSheet(sheetName); } + /** + * 处理changeSheet。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param oldName 参数 {@code oldName}({@code String}) + * @param newName 参数 {@code newName}({@code String}) + */ public void changeSheet(String oldName, String newName) { int index = this.workbook.getSheetIndex(oldName); if (index >= 0) { @@ -272,6 +532,14 @@ public class ExcelWriter { } + /** + * 处理changeSheet。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param index 参数 {@code index}({@code int}) + * @param newName 参数 {@code newName}({@code String}) + */ public void changeSheet(int index, String newName) { if (index >= 0) { this.workbook.setSheetName(index, newName); @@ -279,14 +547,37 @@ public class ExcelWriter { } + /** + * 设置Cell。 + * + * @param cellId 参数 {@code cellId}({@code String}) + * @param value 值({@code Object}) + */ public void setCell(String cellId, Object value) { this.setCell(this.getCell(cellId), value); } + /** + * 设置Cell。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param colNo 参数 {@code colNo}({@code int}) + * @param value 值({@code Object}) + */ public void setCell(int rowNo, int colNo, Object value) { this.setCell(rowNo, colNo, value, (CellStyle)null); } + /** + * 设置Cell。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param colNo 参数 {@code colNo}({@code int}) + * @param value 值({@code Object}) + * @param style 参数 {@code style}({@code CellStyle}) + */ public void setCell(int rowNo, int colNo, Object value, CellStyle style) { Row row = this.activeSheet.getRow(rowNo); if (row == null) { @@ -301,32 +592,75 @@ public class ExcelWriter { this.setCell(cell, value, style); } + /** + * 处理新CellStyle。 + * @return 处理结果 + */ public CellStyle newCellStyle() { return this.workbook.createCellStyle(); } + /** + * 处理clone。 + * + * @param style 参数 {@code style}({@code CellStyle}) + * @return 处理结果 + */ public CellStyle clone(CellStyle style) { CellStyle newStyle = this.newCellStyle(); newStyle.cloneStyleFrom(style); return newStyle; } + /** + * 获取 {@code creationHelper}。 + * @return 字段/派生属性 {@code creationHelper} 的值 + */ public CreationHelper getCreationHelper() { return this.workbook.getCreationHelper(); } + /** + * 获取Custom数据格式化。 + * + * @param format 参数 {@code format}({@code String}) + * @return 字段/派生属性 {@code customDataFormat} 的值 + */ public short getCustomDataFormat(String format) { return this.getCreationHelper().createDataFormat().getFormat(format); } + /** + * 设置Cell。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param value 值({@code Object}) + */ public void setCell(Cell cell, Object value) { this.setCell(cell, value, (CellStyle)null); } + /** + * 设置Cell。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param value 值({@code Object}) + * @param style 参数 {@code style}({@code CellStyle}) + */ public void setCell(Cell cell, Object value, CellStyle style) { this.setCell(cell, value, style, (String)null, (String)null, (String)null, (String)null); } + /** + * 设置文件数量Cell。 + * + * 实现要点:包含 5 个条件分支、0 个循环。 + * + * @param rowNo 参数 {@code rowNo}({@code int}) + * @param colNo 参数 {@code colNo}({@code int}) + * @param value 值({@code long}) + * @param style 参数 {@code style}({@code CellStyle}) + */ public void setFileSizeCell(int rowNo, int colNo, long value, CellStyle style) { String format; float size; @@ -353,10 +687,35 @@ public class ExcelWriter { this.setCell(this.getCell(rowNo, colNo), size, style, format, (String)null, (String)null, (String)null); } + /** + * 设置Cell。 + * + * @param rowIndex 参数 {@code rowIndex}({@code int}) + * @param colIndex 参数 {@code colIndex}({@code int}) + * @param value 值({@code Object}) + * @param style 参数 {@code style}({@code CellStyle}) + * @param format 参数 {@code format}({@code String}) + * @param hAlignment 参数 {@code hAlignment}({@code String}) + * @param vAlignment 参数 {@code vAlignment}({@code String}) + * @param colorName 参数 {@code colorName}({@code String}) + */ public void setCell(int rowIndex, int colIndex, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) { this.setCell(this.getCell(rowIndex, colIndex), value, style, format, hAlignment, vAlignment, colorName); } + /** + * 设置Cell。 + * + * 实现要点:包含 18 个条件分支、0 个循环。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param value 值({@code Object}) + * @param style 参数 {@code style}({@code CellStyle}) + * @param format 参数 {@code format}({@code String}) + * @param hAlignment 参数 {@code hAlignment}({@code String}) + * @param vAlignment 参数 {@code vAlignment}({@code String}) + * @param colorName 参数 {@code colorName}({@code String}) + */ public void setCell(Cell cell, Object value, CellStyle style, String format, String hAlignment, String vAlignment, String colorName) { if (cell != null) { if (style == null) { @@ -419,6 +778,14 @@ public class ExcelWriter { } } + /** + * 设置CellStyle。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param style 参数 {@code style}({@code CellStyle}) + */ private void setCellStyle(Cell cell, CellStyle style) { String styleId = this.cellStyleId(style); if (this.styleMap.containsKey(styleId)) { @@ -431,24 +798,70 @@ public class ExcelWriter { cell.setCellStyle(style); } + /** + * 设置Sell。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param date 参数 {@code date}({@code Date}) + * @param style 参数 {@code style}({@code CellStyle}) + * @param dateFormat 参数 {@code dateFormat}({@code String}) + */ public void setSell(Cell cell, Date date, CellStyle style, String dateFormat) { style.setDataFormat(this.getCustomDataFormat(dateFormat)); } + /** + * 获取Font。 + * + * @param style 参数 {@code style}({@code CellStyle}) + * @return 字段/派生属性 {@code font} 的值 + */ public XSSFFont getFont(CellStyle style) { return this.workbook.getFontAt(style.getFontIndex()); } + /** + * 获取Font。 + * + * @param style 参数 {@code style}({@code CellStyle}) + * @param colorName 参数 {@code colorName}({@code String}) + * @return 字段/派生属性 {@code font} 的值 + */ public XSSFFont getFont(CellStyle style, String colorName) { XSSFFont cellFont = this.getFont(style); return Strings.isNullOrEmpty(colorName) ? cellFont : this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout()); } + /** + * 获取Font。 + * + * @param style 参数 {@code style}({@code CellStyle}) + * @param colorName 参数 {@code colorName}({@code String}) + * @param bold 参数 {@code bold}({@code boolean}) + * @param italic 参数 {@code italic}({@code boolean}) + * @param underline 参数 {@code underline}({@code byte}) + * @param strike 参数 {@code strike}({@code boolean}) + * @return 字段/派生属性 {@code font} 的值 + */ public XSSFFont getFont(CellStyle style, String colorName, boolean bold, boolean italic, byte underline, boolean strike) { XSSFFont cellFont = this.getFont(style); return this.getFont(cellFont.getFontName(), cellFont.getFontHeightInPoints(), colorName, cellFont.getBold(), cellFont.getItalic(), cellFont.getUnderline(), cellFont.getStrikeout()); } + /** + * 获取Font。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param fontName 参数 {@code fontName}({@code String}) + * @param size 每页数量({@code short}) + * @param colorName 参数 {@code colorName}({@code String}) + * @param bold 参数 {@code bold}({@code boolean}) + * @param italic 参数 {@code italic}({@code boolean}) + * @param underline 参数 {@code underline}({@code byte}) + * @param strike 参数 {@code strike}({@code boolean}) + * @return 字段/派生属性 {@code font} 的值 + */ public XSSFFont getFont(String fontName, short size, String colorName, boolean bold, boolean italic, byte underline, boolean strike) { String key = fontName + size + colorName + bold + italic + underline + strike; if (this.fontMap.containsKey(key)) { @@ -467,6 +880,17 @@ public class ExcelWriter { } } + /** + * 设置Formula。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param cell 参数 {@code cell}({@code Cell}) + * @param formular 参数 {@code formular}({@code String}) + * @param format 参数 {@code format}({@code String}) + * @param style 参数 {@code style}({@code CellStyle}) + * @param alignment 参数 {@code alignment}({@code String}) + */ public void setFormula(Cell cell, String formular, String format, CellStyle style, String alignment) { style = this.clone(style); style.setDataFormat(HSSFDataFormat.getBuiltinFormat(format)); @@ -479,10 +903,27 @@ public class ExcelWriter { this.evalueateFormula(cell); } + /** + * 处理evalueateFormula。 + * + * @param cell 参数 {@code cell}({@code Cell}) + */ private void evalueateFormula(Cell cell) { this.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell); } + /** + * 设置Sum转换为Cells。 + * + * 实现要点:包含 1 个条件分支、2 个循环。 + * + * @param writeRowNum 参数 {@code writeRowNum}({@code int}) + * @param colChars 参数 {@code colChars}({@code String[]}) + * @param startNum 参数 {@code startNum}({@code int}) + * @param endNum 参数 {@code endNum}({@code int}) + * @param style 参数 {@code style}({@code CellStyle}) + * @param alignment 参数 {@code alignment}({@code String}) + */ public void setSumToCells(int writeRowNum, String[] colChars, int startNum, int endNum, CellStyle style, String alignment) { for(String colChar : colChars) { int colIndex = 0; @@ -505,6 +946,17 @@ public class ExcelWriter { } + /** + * 添加镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、0 个循环;主要调用:new ByteArrayOutputStream、read、write、close、new XSSFClientAnchor。 + * + * @param input 参数 {@code input}({@code InputStream}) + * @param x 参数 {@code x}({@code int}) + * @param y 参数 {@code y}({@code int}) + * @param width 参数 {@code width}({@code int}) + * @param height 参数 {@code height}({@code int}) + */ public void addImage(InputStream input, int x, int y, int width, int height) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -535,6 +987,18 @@ public class ExcelWriter { } + /** + * 处理fill。 + * + * 实现要点:包含 0 个条件分支、2 个循环。 + * + * @param rowFrom 参数 {@code rowFrom}({@code int}) + * @param rowTo 参数 {@code rowTo}({@code int}) + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + * @param value 值({@code Object}) + * @param cellStyle 参数 {@code cellStyle}({@code CellStyle}) + */ public void fill(int rowFrom, int rowTo, int colFrom, int colTo, Object value, CellStyle cellStyle) { for(int i = rowFrom; i <= rowTo; ++i) { for(int j = colFrom; j <= colTo; ++j) { @@ -544,10 +1008,31 @@ public class ExcelWriter { } + /** + * 处理合并。 + * + * @param rowFrom 参数 {@code rowFrom}({@code int}) + * @param rowTo 参数 {@code rowTo}({@code int}) + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + * @return 数量/长度 + */ public int merge(int rowFrom, int rowTo, int colFrom, int colTo) { return this.merge(rowFrom, rowTo, colFrom, colTo, (CellStyle)null); } + /** + * 处理合并。 + * + * 实现要点:包含 2 个条件分支、2 个循环;主要调用:new CellRangeAddress。 + * + * @param rowFrom 参数 {@code rowFrom}({@code int}) + * @param rowTo 参数 {@code rowTo}({@code int}) + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + * @param cellStyle 参数 {@code cellStyle}({@code CellStyle}) + * @return 数量/长度 + */ public int merge(int rowFrom, int rowTo, int colFrom, int colTo, CellStyle cellStyle) { if (rowFrom == rowTo && colFrom == colTo) { return -1; @@ -566,18 +1051,42 @@ public class ExcelWriter { } } + /** + * 移除Merged区域。 + * + * @param index 参数 {@code index}({@code int}) + */ public void removeMergedRegion(int index) { this.activeSheet.removeMergedRegion(index); } + /** + * 移除Cell。 + * + * @param cell 参数 {@code cell}({@code Cell}) + */ public void removeCell(Cell cell) { cell.getRow().removeCell(cell); } + /** + * 处理insertColumns。 + * + * @param colAfter 参数 {@code colAfter}({@code int}) + * @param colNumbers 参数 {@code colNumbers}({@code int}) + */ public void insertColumns(int colAfter, int colNumbers) { this.shiftColumns(colAfter, this.getLastColIndex(), colNumbers); } + /** + * 移除Columns。 + * + * 实现要点:包含 4 个条件分支、3 个循环。 + * + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + */ public void removeColumns(int colFrom, int colTo) { int mergedRegionNum = this.activeSheet.getNumMergedRegions(); if (mergedRegionNum > 0) { @@ -608,14 +1117,31 @@ public class ExcelWriter { } + /** + * 移除Row。 + * + * @param rowIndex 参数 {@code rowIndex}({@code int}) + */ public void removeRow(int rowIndex) { this.activeSheet.removeRow(this.getRow(rowIndex)); } + /** + * 获取最后ColIndex。 + * + * @param rowNum 参数 {@code rowNum}({@code int}) + * @return 数量/长度 + */ public int getLastColIndex(int rowNum) { return this.getRow(rowNum).getLastCellNum(); } + /** + * 获取 {@code lastColIndex}。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * @return 数量/长度 + */ public int getLastColIndex() { int colNum = 0; @@ -632,6 +1158,15 @@ public class ExcelWriter { return colNum - 1; } + /** + * 处理shiftColumns。 + * + * 实现要点:包含 1 个条件分支、2 个循环。 + * + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + * @param colNumbers 参数 {@code colNumbers}({@code int}) + */ public void shiftColumns(int colFrom, int colTo, int colNumbers) { if (colFrom <= colTo && colNumbers != 0) { int[] widths = new int[colTo - colFrom]; @@ -649,6 +1184,19 @@ public class ExcelWriter { } } + /** + * 添加ConditionalPattern。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new CellRangeAddress。 + * + * @param rowFrom 参数 {@code rowFrom}({@code int}) + * @param rowTo 参数 {@code rowTo}({@code int}) + * @param colFrom 参数 {@code colFrom}({@code int}) + * @param colTo 参数 {@code colTo}({@code int}) + * @param formula 参数 {@code formula}({@code String}) + * @param textColor 参数 {@code textColor}({@code String}) + * @param backgroundColor 参数 {@code backgroundColor}({@code String}) + */ public void addConditionalPattern(int rowFrom, int rowTo, int colFrom, int colTo, String formula, String textColor, String backgroundColor) { SheetConditionalFormatting formatting = this.activeSheet.getSheetConditionalFormatting(); ConditionalFormattingRule rule = formatting.createConditionalFormattingRule(formula); @@ -670,6 +1218,12 @@ public class ExcelWriter { formatting.addConditionalFormatting(ranges, rules); } + /** + * 获取 {@code bytes}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ByteArrayOutputStream、write、close。 + * @return 字段/派生属性 {@code bytes} 的值 + */ public byte[] getBytes() { ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -688,11 +1242,25 @@ public class ExcelWriter { return null; } + /** + * 设置 {@code autoFilter}。 + * + * 实现要点:主要调用:new CellRangeAddress。 + * + * @param row 参数 {@code row}({@code int}) + */ public void setAutoFilter(int row) { CellRangeAddress cellRange = new CellRangeAddress(row, row, 0, this.getLastColIndex()); this.activeSheet.setAutoFilter(cellRange); } + /** + * 处理写入。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:write、close。 + * + * @param output 参数 {@code output}({@code OutputStream}) + */ public void write(OutputStream output) { try { this.workbook.write(output); @@ -706,6 +1274,14 @@ public class ExcelWriter { } + /** + * 获取Cell。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param cellId 参数 {@code cellId}({@code String}) + * @return 字段/派生属性 {@code cell} 的值 + */ public Cell getCell(String cellId) { if (Strings.isNullOrEmpty(cellId)) { return null; @@ -721,22 +1297,30 @@ public class ExcelWriter { colNum = colNum * 26 + colId.charAt(i) - 97 + 1; } - Cell var10000; + Cell cell; if (rowNum >= 0 && colNum >= 0) { --rowNum; --colNum; - var10000 = this.getCell(rowNum, colNum); + cell = this.getCell(rowNum, colNum); } else { - var10000 = null; + cell = null; } - return var10000; + return cell; } else { return null; } } } + /** + * 处理cellStyleID。 + * + * 实现要点:主要调用:new StringBuilder。 + * + * @param style 参数 {@code style}({@code CellStyle}) + * @return 字符串结果 + */ private String cellStyleId(CellStyle style) { StringBuilder sb = new StringBuilder(); sb.append(style.getHidden()); @@ -767,6 +1351,14 @@ public class ExcelWriter { return sb.toString(); } + /** + * 处理转换为Color。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new XSSFColor。 + * + * @param colorName 参数 {@code colorName}({@code String}) + * @return 处理结果 + */ private XSSFColor toColor(String colorName) { byte[] bytes; if (colorName.startsWith("#")) { diff --git a/src/main/java/com/mitac/cell/doc/HtmlToPdf.java b/src/main/java/com/mitac/cell/doc/HtmlToPdf.java index f72ed4f..3e02628 100644 --- a/src/main/java/com/mitac/cell/doc/HtmlToPdf.java +++ b/src/main/java/com/mitac/cell/doc/HtmlToPdf.java @@ -8,7 +8,25 @@ import java.io.OutputStream; import java.net.MalformedURLException; import org.xhtmlrenderer.pdf.ITextRenderer; +/** + * 【通用基础库】{@code HtmlToPdf} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class HtmlToPdf { + /** + * 处理转换为PDF。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileOutputStream。 + * + * @param sourceUrl 参数 {@code sourceUrl}({@code String}) + * @param outputFilePath 参数 {@code outputFilePath}({@code String}) + */ public static void toPdf(String sourceUrl, String outputFilePath) { try { toPdf(sourceUrl, (OutputStream)(new FileOutputStream(outputFilePath))); @@ -18,6 +36,14 @@ public class HtmlToPdf { } + /** + * 处理转换为PDF。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ITextRenderer、close。 + * + * @param sourceUrl 参数 {@code sourceUrl}({@code String}) + * @param output 参数 {@code output}({@code OutputStream}) + */ public static void toPdf(String sourceUrl, OutputStream output) { try { ITextRenderer renderer = new ITextRenderer(); diff --git a/src/main/java/com/mitac/cell/doc/McHtmlDoc.java b/src/main/java/com/mitac/cell/doc/McHtmlDoc.java index 6245752..2d74087 100644 --- a/src/main/java/com/mitac/cell/doc/McHtmlDoc.java +++ b/src/main/java/com/mitac/cell/doc/McHtmlDoc.java @@ -5,27 +5,114 @@ import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; +/** + * 【通用基础库】{@code McHtmlDoc} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code SCHEME_HTTP}(String):字段 SCHEME_HTTP
  • + *
  • {@code SCHEME_HTTPS}(String):字段 SCHEME_HTTPS
  • + *
  • {@code TAG_DIV}(String):字段 TAG_DIV
  • + *
  • {@code TAG_META}(String):字段 TAG_META
  • + *
  • {@code TAG_H1}(String):字段 TAG_H1
  • + *
  • {@code TAG_SPAN}(String):字段 TAG_SPAN
  • + *
+ * + * 协作对象:{@code Document}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McHtmlDoc { + /** + * 字段 SCHEME_HTTP。 + */ public static final String SCHEME_HTTP = "http"; + /** + * 字段 SCHEME_HTTPS。 + */ public static final String SCHEME_HTTPS = "https"; + /** + * 字段 TAG_DIV。 + */ public static final String TAG_DIV = "div"; + /** + * 字段 TAG_META。 + */ public static final String TAG_META = "meta"; + /** + * 字段 TAG_H1。 + */ public static final String TAG_H1 = "h1"; + /** + * 字段 TAG_SPAN。 + */ public static final String TAG_SPAN = "span"; + /** + * 字段 TAG_IMG。 + */ public static final String TAG_IMG = "img"; + /** + * 字段 TAG_A。 + */ public static final String TAG_A = "a"; + /** + * 字段 ATTR_CLASS。 + */ public static final String ATTR_CLASS = "class"; + /** + * 字段 ATTR_HREF。 + */ public static final String ATTR_HREF = "href"; + /** + * 字段 ATTR_TITLE。 + */ public static final String ATTR_TITLE = "title"; + /** + * 字段 ATTR_NAME。 + */ public static final String ATTR_NAME = "name"; + /** + * 字段 ATTR_SRC。 + */ public static final String ATTR_SRC = "src"; + /** + * 字段 ATTR_ITEMPROP。 + */ public static final String ATTR_ITEMPROP = "itemprop"; + /** + * 字段 ATTR_ALT。 + */ public static final String ATTR_ALT = "alt"; + /** + * 字段 ATTR_IMAGE。 + */ public static final String ATTR_IMAGE = "image"; + /** + * 字段 ATTR_CONTENT。 + */ public static final String ATTR_CONTENT = "content"; + /** + * 字段 ATTR_DESCRIPTION。 + */ public static final String ATTR_DESCRIPTION = "image"; + /** + * 字段 document。 + */ protected Document document; + /** + * 构造 {@code McHtmlDoc} 实例。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param url 参数 {@code url}({@code String}) + */ public McHtmlDoc(String url) { if (!Strings.isNullOrEmpty(url)) { this.document = McHtmlUtils.loadHtml(url); @@ -33,46 +120,125 @@ public class McHtmlDoc { } + /** + * 处理存在。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists() { return this.document != null; } + /** + * 获取 {@code document}。 + * @return MongoDB 文档对象 + */ public Document getDocument() { return this.document; } + /** + * 处理HTML。 + * @return 字符串结果 + */ public String html() { return this.document.html(); } + /** + * 获取DivText。 + * + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字符串结果 + */ public String getDivText(String findAttrName, String findAttrValue) { return this.getText("div", findAttrName, findAttrValue); } + /** + * 获取Text。 + * + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字符串结果 + */ public String getText(String tag, String findAttrName, String findAttrValue) { return this.getElements(tag, findAttrName, findAttrValue).text(); } + /** + * 获取Attr。 + * + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @param attr 参数 {@code attr}({@code String}) + * @return 字符串结果 + */ public String getAttr(String tag, String findAttrName, String findAttrValue, String attr) { return this.getElements(tag, findAttrName, findAttrValue).attr(attr); } + /** + * 获取Elements。 + * + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字段/派生属性 {@code elements} 的值 + */ public Elements getElements(String tag, String findAttrName, String findAttrValue) { return this.document.select(this.selectEquals(tag, findAttrName, findAttrValue)); } + /** + * 获取Text。 + * + * @param element 参数 {@code element}({@code Element}) + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字符串结果 + */ public String getText(Element element, String tag, String findAttrName, String findAttrValue) { return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).text(); } + /** + * 获取Attr。 + * + * @param element 参数 {@code element}({@code Element}) + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @param attr 参数 {@code attr}({@code String}) + * @return 字符串结果 + */ public String getAttr(Element element, String tag, String findAttrName, String findAttrValue, String attr) { return element.select(this.selectEquals(tag, findAttrName, findAttrValue)).attr(attr); } + /** + * 处理select比较。 + * + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字符串结果 + */ public String selectEquals(String tag, String findAttrName, String findAttrValue) { return String.format("%s[%s=%s]", tag, findAttrName, findAttrValue); } + /** + * 处理select包含。 + * + * @param tag 参数 {@code tag}({@code String}) + * @param findAttrName 参数 {@code findAttrName}({@code String}) + * @param findAttrValue 参数 {@code findAttrValue}({@code String}) + * @return 字符串结果 + */ public String selectContains(String tag, String findAttrName, String findAttrValue) { return String.format("%s[%s*=%s]", tag, findAttrName, findAttrValue); } diff --git a/src/main/java/com/mitac/cell/doc/McHtmlUtils.java b/src/main/java/com/mitac/cell/doc/McHtmlUtils.java index a169569..4cab416 100644 --- a/src/main/java/com/mitac/cell/doc/McHtmlUtils.java +++ b/src/main/java/com/mitac/cell/doc/McHtmlUtils.java @@ -9,11 +9,36 @@ import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.parser.Parser; +/** + * 【通用基础库】{@code McHtmlUtils} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McHtmlUtils { + /** + * 加载HTML。 + * + * @param urlRef 参数 {@code urlRef}({@code String}) + * @return MongoDB 文档对象 + */ public static Document loadHtml(String urlRef) { return load(urlRef, Parser.htmlParser()); } + /** + * 处理加载。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param urlRef 参数 {@code urlRef}({@code String}) + * @param parser 参数 {@code parser}({@code Parser}) + * @return MongoDB 文档对象 + */ public static Document load(String urlRef, Parser parser) { try { return Jsoup.connect(urlRef).parser(parser).maxBodySize(0).get(); @@ -24,6 +49,15 @@ public class McHtmlUtils { return null; } + /** + * 处理加载。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:parse、close。 + * + * @param url 参数 {@code url}({@code URL}) + * @param parser 参数 {@code parser}({@code Parser}) + * @return MongoDB 文档对象 + */ public static Document load(URL url, Parser parser) { try { if (url == null) { diff --git a/src/main/java/com/mitac/cell/doc/WordTemplate.java b/src/main/java/com/mitac/cell/doc/WordTemplate.java index 590d1da..c54ef60 100644 --- a/src/main/java/com/mitac/cell/doc/WordTemplate.java +++ b/src/main/java/com/mitac/cell/doc/WordTemplate.java @@ -29,18 +29,62 @@ import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; +/** + * 【通用基础库】{@code WordTemplate} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code document}(XWPFDocument):字段 document
  • + *
  • {@code model}(Map):模型
  • + *
+ * + * 协作对象:{@code XWPFDocument}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class WordTemplate { + /** + * 字段 document。 + */ private XWPFDocument document; - private Map model; + /** + * 模型。 + */ + private Map model; + /** + * 构造 {@code WordTemplate} 实例。 + * + * @param filePath 参数 {@code filePath}({@code String}) + */ public WordTemplate(String filePath) { this.open(filePath); } + /** + * 处理打开。 + * + * 实现要点:主要调用:new File。 + * + * @param filePath 参数 {@code filePath}({@code String}) + */ public void open(String filePath) { this.open(new File(filePath)); } + /** + * 处理打开。 + * + * 实现要点:调用持久化方法保存数据;包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:exists、new ByteArrayOutputStream、save、close、new ByteArrayInputStream。 + * + * @param file 文件({@code File}) + */ public void open(File file) { try { if (file.exists()) { @@ -58,6 +102,13 @@ public class WordTemplate { } + /** + * 处理打开。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new XWPFDocument。 + * + * @param is 参数 {@code is}({@code InputStream}) + */ public void open(InputStream is) { try { if (is != null) { @@ -71,6 +122,11 @@ public class WordTemplate { } + /** + * 处理关闭。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:close。 + */ public void close() { try { if (this.document != null) { @@ -81,7 +137,13 @@ public class WordTemplate { } - public Map getModel() { + /** + * 获取 {@code model}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new HashMap。 + * @return 处理结果 + */ + public Map getModel() { if (this.model == null) { this.model = new HashMap(); } @@ -89,14 +151,30 @@ public class WordTemplate { return this.model; } - public void setModel(Map model) { + /** + * 设置 {@code model}。 + * + * @param model 参数 {@code model}({@code Map}) + */ + public void setModel(Map model) { this.model = model; } + /** + * 设置模型。 + * + * @param key 键/配置项({@code String}) + * @param value 值({@code Object}) + */ public void setModel(String key, Object value) { this.getModel().put(key, value); } + /** + * 处理patch。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + */ public void patch() { for(IBodyElement bodyElement : this.document.getBodyElements()) { switch (bodyElement.getElementType()) { @@ -110,10 +188,24 @@ public class WordTemplate { } + /** + * 处理写入。 + * + * 实现要点:主要调用:write、new File。 + * + * @param filePath 参数 {@code filePath}({@code String}) + */ public void write(String filePath) { this.write(new File(filePath)); } + /** + * 处理写入。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:write、new FileOutputStream。 + * + * @param file 文件({@code File}) + */ public void write(File file) { try { this.write((OutputStream)(new FileOutputStream(file))); @@ -123,6 +215,13 @@ public class WordTemplate { } + /** + * 处理写入。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:write。 + * + * @param os 参数 {@code os}({@code OutputStream}) + */ public void write(OutputStream os) { try { if (os != null) { @@ -135,6 +234,14 @@ public class WordTemplate { } + /** + * 处理写入。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:write。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param fileName 文件名({@code String}) + */ public void write(HttpServletResponse response, String fileName) { if (!McStringUtils.isNullOrEmpty(fileName)) { try { @@ -149,6 +256,13 @@ public class WordTemplate { } } + /** + * 处理patch。 + * + * 实现要点:包含 3 个条件分支、2 个循环;主要调用:new PositionInParagraph、new StringBuilder。 + * + * @param paragraph 参数 {@code paragraph}({@code XWPFParagraph}) + */ private void patch(XWPFParagraph paragraph) { TextSegment segmentStart = paragraph.searchText("{{", new PositionInParagraph()); if (segmentStart != null) { @@ -179,6 +293,13 @@ public class WordTemplate { } } + /** + * 处理patch。 + * + * 实现要点:包含 0 个条件分支、3 个循环。 + * + * @param table 参数 {@code table}({@code XWPFTable}) + */ private void patch(XWPFTable table) { for(XWPFTableRow row : table.getRows()) { for(XWPFTableCell cell : row.getTableCells()) { @@ -190,6 +311,14 @@ public class WordTemplate { } + /** + * 解析Text。 + * + * 实现要点:包含 4 个条件分支、1 个循环;主要调用:new StringBuilder、find、new SimpleDateFormat。 + * + * @param source 参数 {@code source}({@code String}) + * @return 字符串结果 + */ public String parseText(String source) { Pattern pattern = Pattern.compile("\\{\\{(.*?)\\}\\}"); Matcher matcher = pattern.matcher(source); diff --git a/src/main/java/com/mitac/cell/doc/package-info.java b/src/main/java/com/mitac/cell/doc/package-info.java new file mode 100644 index 0000000..39caa6f --- /dev/null +++ b/src/main/java/com/mitac/cell/doc/package-info.java @@ -0,0 +1,21 @@ +/** + * 包 {@code com.mitac.cell.doc}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link Csv}
  • + *
  • {@link CsvReader}
  • + *
  • {@link ExcelCell}
  • + *
  • {@link ExcelReader}
  • + *
  • {@link ExcelRow}
  • + *
  • {@link ExcelWriter}
  • + *
  • {@link HtmlToPdf}
  • + *
  • {@link McHtmlDoc}
  • + *
  • {@link McHtmlUtils}
  • + *
  • {@link WordTemplate}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.doc; diff --git a/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java b/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java index a2e1f18..56ffa71 100644 --- a/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java +++ b/src/main/java/com/mitac/cell/gson/typeAdapter/CipherTypeAdapter.java @@ -10,11 +10,40 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import javax.crypto.Cipher; -public class CipherTypeAdapter implements JsonSerializer, JsonDeserializer { +/** + * 【通用基础库】{@code CipherTypeAdapter} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ +public class CipherTypeAdapter implements JsonSerializer, JsonDeserializer { + /** + * 处理deserialize。 + * + * @param json 参数 {@code json}({@code JsonElement}) + * @param typeOfTarget 参数 {@code typeOfTarget}({@code Type}) + * @param context 参数 {@code context}({@code JsonDeserializationContext}) + * @return 处理结果 + * @throws JsonParseException 当 JsonParseException 条件不满足或底层调用失败时抛出。 + */ public Cipher deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException { return null; } + /** + * 处理serialize。 + * + * 实现要点:主要调用:new JsonPrimitive。 + * + * @param src 参数 {@code src}({@code Cipher}) + * @param typeOfSrc 参数 {@code typeOfSrc}({@code Type}) + * @param context 参数 {@code context}({@code JsonSerializationContext}) + * @return 处理结果 + */ public JsonElement serialize(Cipher src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getAlgorithm()); } diff --git a/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java b/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java index 1c3a0fd..257f3f9 100644 --- a/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java +++ b/src/main/java/com/mitac/cell/gson/typeAdapter/CompatibleTimeZoneTypeAdapter.java @@ -10,12 +10,41 @@ import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.util.TimeZone; -public class CompatibleTimeZoneTypeAdapter implements JsonSerializer, JsonDeserializer { +/** + * 【通用基础库】{@code CompatibleTimeZoneTypeAdapter} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ +public class CompatibleTimeZoneTypeAdapter implements JsonSerializer, JsonDeserializer { + /** + * 处理deserialize。 + * + * @param json 参数 {@code json}({@code JsonElement}) + * @param typeOfTarget 参数 {@code typeOfTarget}({@code Type}) + * @param context 参数 {@code context}({@code JsonDeserializationContext}) + * @return 处理结果 + * @throws JsonParseException 当 JsonParseException 条件不满足或底层调用失败时抛出。 + */ public TimeZone deserialize(JsonElement json, Type typeOfTarget, JsonDeserializationContext context) throws JsonParseException { String timeZone = json.getAsString(); return TimeZone.getTimeZone(timeZone); } + /** + * 处理serialize。 + * + * 实现要点:主要调用:new JsonPrimitive。 + * + * @param timeZone 参数 {@code timeZone}({@code TimeZone}) + * @param typeOfSrc 参数 {@code typeOfSrc}({@code Type}) + * @param context 参数 {@code context}({@code JsonSerializationContext}) + * @return 处理结果 + */ public JsonElement serialize(TimeZone timeZone, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(timeZone.getID()); } diff --git a/src/main/java/com/mitac/cell/gson/typeAdapter/package-info.java b/src/main/java/com/mitac/cell/gson/typeAdapter/package-info.java new file mode 100644 index 0000000..815c7cc --- /dev/null +++ b/src/main/java/com/mitac/cell/gson/typeAdapter/package-info.java @@ -0,0 +1,13 @@ +/** + * 包 {@code com.mitac.cell.gson.typeAdapter}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link CipherTypeAdapter}
  • + *
  • {@link CompatibleTimeZoneTypeAdapter}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.gson.typeAdapter; diff --git a/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java b/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java index bddbb8b..99a4bc1 100644 --- a/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java +++ b/src/main/java/com/mitac/cell/internet/app/McPlayMarket.java @@ -6,17 +6,67 @@ import java.util.ArrayList; import java.util.List; import org.jsoup.select.Elements; +/** + * 【基础设施】{@code McPlayMarket} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code BASE_URL}(String):字段 BASE_URL
  • + *
  • {@code URL_PLAY_STORE}(String):字段 URL_PLAY_STORE
  • + *
  • {@code URL_APP_URL}(String):字段 URL_APP_URL
  • + *
  • {@code URL_APP_SEARCH}(String):字段 URL_APP_SEARCH
  • + *
  • {@code LOCALE_DEFAULT}(String):字段 LOCALE_DEFAULT
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McPlayMarket { + /** + * 字段 BASE_URL。 + */ public static final String BASE_URL = "https://play.google.com"; + /** + * 字段 URL_PLAY_STORE。 + */ private static final String URL_PLAY_STORE = "https://play.google.com/store"; + /** + * 字段 URL_APP_URL。 + */ private static final String URL_APP_URL = "https://play.google.com/store/apps/details?id=%s&hl=%s"; + /** + * 字段 URL_APP_SEARCH。 + */ private static final String URL_APP_SEARCH = "https://play.google.com/store/search?q=%s&hl=%s&c=apps"; + /** + * 字段 LOCALE_DEFAULT。 + */ private static final String LOCALE_DEFAULT = "en-GB"; + /** + * 获取APK信息。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @return 字段/派生属性 {@code apkInfo} 的值 + */ public static PlayApp getApkInfo(String packageName) { return getApkInfo(packageName, "en-GB"); } + /** + * 获取APK信息。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McHtmlDoc、exists、new PlayApp。 + * + * @param packageName 参数 {@code packageName}({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @return 字段/派生属性 {@code apkInfo} 的值 + */ public static PlayApp getApkInfo(String packageName, String locale) { if (Strings.isNullOrEmpty(packageName)) { return null; @@ -42,11 +92,26 @@ public class McPlayMarket { } } - public static List search(String keyword) { + /** + * 处理搜索。 + * + * @param keyword 参数 {@code keyword}({@code String}) + * @return Play应用列表,可能为空 + */ + public static List search(String keyword) { return search(keyword, "en-GB"); } - public static List search(String keyword, String locale) { + /** + * 处理搜索。 + * + * 实现要点:包含 3 个条件分支、0 个循环;主要调用:new McHtmlDoc、exists、new ArrayList、new PlayApp。 + * + * @param keyword 参数 {@code keyword}({@code String}) + * @param locale 参数 {@code locale}({@code String}) + * @return Play应用列表,可能为空 + */ + public static List search(String keyword, String locale) { if (Strings.isNullOrEmpty(keyword)) { return null; } else { diff --git a/src/main/java/com/mitac/cell/internet/app/PlayApp.java b/src/main/java/com/mitac/cell/internet/app/PlayApp.java index ee52558..247ac0c 100644 --- a/src/main/java/com/mitac/cell/internet/app/PlayApp.java +++ b/src/main/java/com/mitac/cell/internet/app/PlayApp.java @@ -2,61 +2,156 @@ package com.mitac.cell.internet.app; import com.google.common.base.Strings; +/** + * 【基础设施】{@code PlayApp} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code appId}(String):应用ID
  • + *
  • {@code title}(String):字段 title
  • + *
  • {@code summary}(String):字段 summary
  • + *
  • {@code developer}(String):字段 developer
  • + *
  • {@code icon}(String):字段 icon
  • + *
  • {@code score}(Float):字段 score
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class PlayApp { + /** + * 应用ID。 + */ private String appId; + /** + * 字段 title。 + */ private String title; + /** + * 字段 summary。 + */ private String summary; + /** + * 字段 developer。 + */ private String developer; + /** + * 字段 icon。 + */ private String icon; + /** + * 字段 score。 + */ private Float score; + /** + * 获取 {@code appId}。 + * @return 字符串结果 + */ public String getAppId() { return this.appId; } + /** + * 设置 {@code appId}。 + * + * @param appId 参数 {@code appId}({@code String}) + */ public void setAppId(String appId) { int idIndex = appId.indexOf("id="); this.appId = idIndex >= 0 ? appId.substring(idIndex + 3) : appId; } + /** + * 获取 {@code title}。 + * @return 字符串结果 + */ public String getTitle() { return this.title; } + /** + * 设置 {@code title}。 + * + * @param title 参数 {@code title}({@code String}) + */ public void setTitle(String title) { this.title = title; } + /** + * 获取 {@code summary}。 + * @return 字符串结果 + */ public String getSummary() { return this.summary; } + /** + * 设置 {@code summary}。 + * + * @param summary 参数 {@code summary}({@code String}) + */ public void setSummary(String summary) { this.summary = summary; } + /** + * 获取 {@code developer}。 + * @return 字符串结果 + */ public String getDeveloper() { return this.developer; } + /** + * 设置 {@code developer}。 + * + * @param developer 参数 {@code developer}({@code String}) + */ public void setDeveloper(String developer) { this.developer = developer; } + /** + * 获取 {@code icon}。 + * @return 字符串结果 + */ public String getIcon() { return this.icon; } + /** + * 设置 {@code icon}。 + * + * @param icon 参数 {@code icon}({@code String}) + */ public void setIcon(String icon) { int indexSlash = icon.lastIndexOf("/"); int endsIndex = icon.lastIndexOf("="); this.icon = indexSlash >= 0 ? icon.substring(indexSlash + 1, endsIndex > 0 ? endsIndex : icon.length()) : icon; } + /** + * 获取 {@code score}。 + * @return 字段/派生属性 {@code score} 的值 + */ public Float getScore() { return this.score; } + /** + * 设置 {@code score}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param score 参数 {@code score}({@code String}) + */ public void setScore(String score) { try { if (!Strings.isNullOrEmpty(score)) { @@ -67,6 +162,11 @@ public class PlayApp { } + /** + * 设置 {@code score}。 + * + * @param score 参数 {@code score}({@code Float}) + */ public void setScore(Float score) { this.score = score; } diff --git a/src/main/java/com/mitac/cell/internet/app/package-info.java b/src/main/java/com/mitac/cell/internet/app/package-info.java new file mode 100644 index 0000000..a0be76f --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/app/package-info.java @@ -0,0 +1,13 @@ +/** + * 包 {@code com.mitac.cell.internet.app}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McPlayMarket}
  • + *
  • {@link PlayApp}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.internet.app; diff --git a/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java b/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java index 2a1e65e..fa0b00f 100644 --- a/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java +++ b/src/main/java/com/mitac/cell/internet/html/McHtmlTemplateEngine.java @@ -7,43 +7,114 @@ import org.thymeleaf.context.Context; import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.StringTemplateResolver; +/** + * 【通用基础库】{@code McHtmlTemplateEngine} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code context}(Context):字段 context
  • + *
  • {@code templateResolver}(StringTemplateResolver):模板解析器
  • + *
+ * + * 协作对象:{@code Context、StringTemplateResolver}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McHtmlTemplateEngine extends TemplateEngine { + /** + * 字段 context。 + */ private final Context context; + /** + * 模板解析器。 + */ private StringTemplateResolver templateResolver; + /** + * 构造 {@code McHtmlTemplateEngine} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new Context。 + */ public McHtmlTemplateEngine() { this.context = new Context(); this.init(); } + /** + * 构造 {@code McHtmlTemplateEngine} 实例。 + * + * @param templateMode 参数 {@code templateMode}({@code String}) + * @param locale 参数 {@code locale}({@code Locale}) + */ public McHtmlTemplateEngine(String templateMode, Locale locale) { this(); this.setLocale(locale); this.setTemplateMode(templateMode); } + /** + * 设置 {@code locale}。 + * + * @param locale 参数 {@code locale}({@code Locale}) + */ public void setLocale(Locale locale) { this.context.setLocale(locale); } + /** + * 设置Variable。 + * + * @param name 参数 {@code name}({@code String}) + * @param value 值({@code Object}) + */ public void setVariable(String name, Object value) { this.context.setVariable(name, value); } - public void setVariables(Map attrs) { + /** + * 设置 {@code variables}。 + * + * @param attrs 参数 {@code attrs}({@code Map}) + */ + public void setVariables(Map attrs) { this.context.setVariables(attrs); } + /** + * 设置 {@code templateMode}。 + * + * @param templateMode 参数 {@code templateMode}({@code String}) + */ public void setTemplateMode(String templateMode) { this.templateResolver.setTemplateMode(templateMode); } + /** + * 处理处理。 + * + * 实现要点:主要调用:process。 + * + * @param htmlContent 参数 {@code htmlContent}({@code String}) + * @return 字符串结果 + */ public String process(String htmlContent) { String template = null; this.process(htmlContent, this.context); return template; } + /** + * 初始化对象状态(补齐 UUID/时间戳/默认字段)。 + * + * 实现要点:主要调用:new StringTemplateResolver。 + */ private void init() { this.templateResolver = new StringTemplateResolver(); this.templateResolver.setTemplateMode(TemplateMode.HTML); diff --git a/src/main/java/com/mitac/cell/internet/html/package-info.java b/src/main/java/com/mitac/cell/internet/html/package-info.java new file mode 100644 index 0000000..5ed1d10 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/html/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.internet.html}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McHtmlTemplateEngine}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.internet.html; diff --git a/src/main/java/com/mitac/cell/internet/http/McHttpClient.java b/src/main/java/com/mitac/cell/internet/http/McHttpClient.java index 4ec7e1b..474da3b 100644 --- a/src/main/java/com/mitac/cell/internet/http/McHttpClient.java +++ b/src/main/java/com/mitac/cell/internet/http/McHttpClient.java @@ -20,14 +20,61 @@ import org.apache.tika.mime.MimeType; import org.apache.tika.mime.MimeTypes; import org.springframework.http.ContentDisposition; +/** + * 【通用基础库】{@code McHttpClient} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code HEADER_CONTENT_DISPOSITION}(String):字段 HEADER_CONTENT_DISPOSITION
  • + *
  • {@code HEADER_CONTENT_TYPE}(String):字段 HEADER_CONTENT_TYPE
  • + *
  • {@code HEADER_USER_AGENT}(String):字段 HEADER_USER_AGENT
  • + *
  • {@code HEADER_ENCRPYT_STRING}(String):字段 HEADER_ENCRPYT_STRING
  • + *
  • {@code CONTENT_TYPE_HTML}(String):字段 CONTENT_TYPE_HTML
  • + *
  • {@code CONTENT_TYPE_OCTET_STREAM}(String):字段 CONTENT_TYPE_OCTET_STREAM
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McHttpClient { + /** + * 字段 HEADER_CONTENT_DISPOSITION。 + */ public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition"; + /** + * 字段 HEADER_CONTENT_TYPE。 + */ public static final String HEADER_CONTENT_TYPE = "Content-Type"; + /** + * 字段 HEADER_USER_AGENT。 + */ public static final String HEADER_USER_AGENT = "User-Agent"; + /** + * 字段 HEADER_ENCRPYT_STRING。 + */ public static final String HEADER_ENCRPYT_STRING = "encryptString"; + /** + * 字段 CONTENT_TYPE_HTML。 + */ public static final String CONTENT_TYPE_HTML = "text/html; utf-8"; + /** + * 字段 CONTENT_TYPE_OCTET_STREAM。 + */ public static final String CONTENT_TYPE_OCTET_STREAM = "application/octet-stream"; + /** + * 处理打开。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。 + * + * @param link 参数 {@code link}({@code String}) + * @return 处理结果 + */ public static HttpURLConnection open(String link) { try { return Strings.isNullOrEmpty(link) ? null : open(new URL(link)); @@ -36,6 +83,14 @@ public class McHttpClient { } } + /** + * 处理打开。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 处理结果 + */ public static HttpURLConnection open(URL url) { try { HttpURLConnection conn = (HttpURLConnection)url.openConnection(); @@ -55,6 +110,14 @@ public class McHttpClient { } } + /** + * 判断是否Redirected。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param conn 参数 {@code conn}({@code HttpURLConnection}) + * @return 字段/派生属性 {@code redirected} 的值 + */ public static boolean isRedirected(HttpURLConnection conn) { if (conn == null) { return false; @@ -68,6 +131,14 @@ public class McHttpClient { } } + /** + * 获取RedirectedConnection。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。 + * + * @param conn 参数 {@code conn}({@code HttpURLConnection}) + * @return 字段/派生属性 {@code redirectedConnection} 的值 + */ public static HttpURLConnection getRedirectedConnection(HttpURLConnection conn) { String newUrl = conn.getHeaderField("Location"); @@ -78,6 +149,14 @@ public class McHttpClient { } } + /** + * 获取InputStream。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。 + * + * @param urlRef 参数 {@code urlRef}({@code String}) + * @return 字段/派生属性 {@code inputStream} 的值 + */ public static InputStream getInputStream(String urlRef) { try { return getInputStream(new URL(urlRef)); @@ -86,6 +165,14 @@ public class McHttpClient { } } + /** + * 获取InputStream。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 字段/派生属性 {@code inputStream} 的值 + */ public static InputStream getInputStream(URL url) { try { URLConnection connection = url.openConnection(); @@ -99,6 +186,14 @@ public class McHttpClient { return null; } + /** + * 获取文件名称。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、0 个循环。 + * + * @param conn 参数 {@code conn}({@code HttpURLConnection}) + * @return 字符串结果 + */ public static String getFileName(HttpURLConnection conn) { if (conn != null) { String fileName = null; @@ -143,14 +238,37 @@ public class McHttpClient { return UUID.randomUUID().toString(); } + /** + * 获取文件名称从ContentDisposition。 + * + * 实现要点:主要调用:parse。 + * + * @param headerString 参数 {@code headerString}({@code String}) + * @return 字符串结果 + */ public static String getFileNameFromContentDisposition(String headerString) { return ContentDisposition.parse(headerString).getFilename(); } + /** + * 处理转换为ContentDisposition。 + * + * @param fileName 文件名({@code String}) + * @return 字符串结果 + */ public static String toContentDisposition(String fileName) { return String.format("attachment; filename=\"%s\"", UrlEscapers.urlFragmentEscaper().escape(fileName)); } + /** + * 查找Cookie。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param name 参数 {@code name}({@code String}) + * @return 处理结果 + */ public static Cookie findCookie(HttpServletRequest request, String name) { Cookie foundCookie = null; @@ -164,6 +282,15 @@ public class McHttpClient { return foundCookie; } + /** + * 获取Cookie值。 + * + * 实现要点:主要调用:find。 + * + * @param cookie 参数 {@code cookie}({@code String}) + * @param key 键/配置项({@code String}) + * @return 字符串结果 + */ public static String getCookieValue(String cookie, String key) { Pattern PATTERN_JSESSIONID = Pattern.compile(String.format("\\b%s=([^;]+)", key)); Matcher m = PATTERN_JSESSIONID.matcher(cookie); diff --git a/src/main/java/com/mitac/cell/internet/http/McRequest.java b/src/main/java/com/mitac/cell/internet/http/McRequest.java index 8274653..453b03f 100644 --- a/src/main/java/com/mitac/cell/internet/http/McRequest.java +++ b/src/main/java/com/mitac/cell/internet/http/McRequest.java @@ -9,11 +9,36 @@ import java.net.URISyntaxException; import java.net.URL; import javax.servlet.http.HttpServletRequest; +/** + * 【通用基础库】{@code McRequest} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McRequest { + /** + * 获取BaseURL。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @return 字符串结果 + */ public static String getBaseUrl(HttpServletRequest request) { return getBaseUrl(request, (String)null); } + /** + * 获取BaseURL。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new URL、new URI。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param path 参数 {@code path}({@code String}) + * @return 字符串结果 + */ public static String getBaseUrl(HttpServletRequest request, String path) { try { URL url = new URL(request.getRequestURL().toString()); diff --git a/src/main/java/com/mitac/cell/internet/http/McResponse.java b/src/main/java/com/mitac/cell/internet/http/McResponse.java index 609a0fc..747b220 100644 --- a/src/main/java/com/mitac/cell/internet/http/McResponse.java +++ b/src/main/java/com/mitac/cell/internet/http/McResponse.java @@ -14,8 +14,28 @@ import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +/** + * 【通用基础库】{@code McResponse} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McResponse { - public static ResponseEntity getServletResource(HttpServletRequest request, MediaType mediaType, String resourcePath) { + /** + * 获取ServletResource。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ClassPathResource、new ResponseEntity。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param mediaType 参数 {@code mediaType}({@code MediaType}) + * @param resourcePath 参数 {@code resourcePath}({@code String}) + * @return 字段/派生属性 {@code servletResource} 的值 + */ + public static ResponseEntity getServletResource(HttpServletRequest request, MediaType mediaType, String resourcePath) { ClassPathResource resource = new ClassPathResource(resourcePath); try { @@ -26,7 +46,17 @@ public class McResponse { } } - public static ResponseEntity getFile(HttpServletRequest request, MediaType mediaType, String path) { + /** + * 获取文件。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new File、exists、new FileInputStream、new ResponseEntity。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param mediaType 参数 {@code mediaType}({@code MediaType}) + * @param path 参数 {@code path}({@code String}) + * @return 字段/派生属性 {@code file} 的值 + */ + public static ResponseEntity getFile(HttpServletRequest request, MediaType mediaType, String path) { try { File file = new File(path); return file.exists() && file.isFile() ? getResponseFromStream(request, mediaType, file.getName(), new FileInputStream(file)) : new ResponseEntity(HttpStatus.NO_CONTENT); @@ -36,7 +66,18 @@ public class McResponse { } } - public static ResponseEntity getResponseFromStream(HttpServletRequest request, MediaType mediaType, String fileName, InputStream is) { + /** + * 获取响应从Stream。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new InputStreamResource、new ResponseEntity。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param mediaType 参数 {@code mediaType}({@code MediaType}) + * @param fileName 文件名({@code String}) + * @param is 参数 {@code is}({@code InputStream}) + * @return 字段/派生属性 {@code responseFromStream} 的值 + */ + public static ResponseEntity getResponseFromStream(HttpServletRequest request, MediaType mediaType, String fileName, InputStream is) { try { ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); builder.contentLength((long)is.available()); @@ -49,6 +90,15 @@ public class McResponse { } } + /** + * 发送错误。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param statusCode 参数 {@code statusCode}({@code int}) + * @param message 消息内容({@code String}) + */ public static void sendError(HttpServletResponse response, int statusCode, String message) { try { response.sendError(statusCode, message); @@ -58,10 +108,27 @@ public class McResponse { } + /** + * 设置Cookie。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param name 参数 {@code name}({@code String}) + * @param value 值({@code String}) + */ public static void setCookie(HttpServletResponse response, String name, String value) { setCookie(response, "/", name, value); } + /** + * 设置Cookie。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Cookie。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param path 参数 {@code path}({@code String}) + * @param name 参数 {@code name}({@code String}) + * @param value 值({@code String}) + */ public static void setCookie(HttpServletResponse response, String path, String name, String value) { Cookie cookie = new Cookie(name, Strings.isNullOrEmpty(value) ? null : value); cookie.setPath(path); diff --git a/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java b/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java index f1c0507..5360fc7 100644 --- a/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java +++ b/src/main/java/com/mitac/cell/internet/http/McResponseEntity.java @@ -6,15 +6,43 @@ import org.springframework.core.io.InputStreamResource; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +/** + * 【通用基础库】{@code McResponseEntity} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McResponseEntity { - public static ResponseEntity get(HttpServletRequest request, MediaType mediaType, byte[] bytes) { + /** + * 处理获取。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @param mediaType 参数 {@code mediaType}({@code MediaType}) + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @return 处理结果 + */ + public static ResponseEntity get(HttpServletRequest request, MediaType mediaType, byte[] bytes) { ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); builder.contentLength((long)bytes.length); builder.contentType(mediaType); return builder.body(bytes); } - public static ResponseEntity get(MediaType mediaType, InputStream is, int contentLength) { + /** + * 处理获取。 + * + * 实现要点:主要调用:new InputStreamResource。 + * + * @param mediaType 参数 {@code mediaType}({@code MediaType}) + * @param is 参数 {@code is}({@code InputStream}) + * @param contentLength 参数 {@code contentLength}({@code int}) + * @return 处理结果 + */ + public static ResponseEntity get(MediaType mediaType, InputStream is, int contentLength) { ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); builder.contentLength((long)contentLength); builder.contentType(mediaType); diff --git a/src/main/java/com/mitac/cell/internet/http/UserAgent.java b/src/main/java/com/mitac/cell/internet/http/UserAgent.java index d541dd2..3415b69 100644 --- a/src/main/java/com/mitac/cell/internet/http/UserAgent.java +++ b/src/main/java/com/mitac/cell/internet/http/UserAgent.java @@ -9,11 +9,47 @@ import ua_parser.Device; import ua_parser.OS; import ua_parser.Parser; +/** + * 【通用基础库】{@code UserAgent} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code browsers}(Set):String集合
  • + *
  • {@code uaParser}(Parser):字段 uaParser
  • + *
  • {@code client}(Client):字段 client
  • + *
+ * + * 协作对象:{@code Parser、Client}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class UserAgent { - private static final Set browsers = (Set)Arrays.stream(new String[]{"chrome", "firefox", "edge", "safari", "vivaldi", "opera"}).collect(Collectors.toSet()); + /** + * String集合。 + */ + private static final Set browsers = (Set)Arrays.stream(new String[]{"chrome", "firefox", "edge", "safari", "vivaldi", "opera"}).collect(Collectors.toSet()); + /** + * 字段 uaParser。 + */ private static final Parser uaParser = new Parser(new LoaderOptions()); + /** + * 字段 client。 + */ private Client client; + /** + * 构造 {@code UserAgent} 实例。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Client、new UserAgent、parse。 + * + * @param source 参数 {@code source}({@code String}) + */ public UserAgent(String source) { if (source.startsWith("MiDM")) { OS os = uaParser.parseOS(source); @@ -26,38 +62,74 @@ public class UserAgent { } + /** + * 处理操作系统。 + * @return 处理结果 + */ public OS os() { return this.client.os; } + /** + * 处理操作系统Family。 + * @return 字符串结果 + */ public String osFamily() { return this.os().family; } + /** + * 处理设备。 + * @return 匹配的设备对象;未找到时返回 {@code null} + */ public Device device() { return this.client.device; } + /** + * 处理设备Family。 + * @return 字符串结果 + */ public String deviceFamily() { return this.device().family; } + /** + * 处理client。 + * @return 处理结果 + */ public Client client() { return this.client; } + /** + * 处理agent。 + * @return 处理结果 + */ public ua_parser.UserAgent agent() { return this.client.userAgent; } + /** + * 处理agentFamily。 + * @return 字符串结果 + */ public String agentFamily() { return this.agent().family; } + /** + * 判断 {@code browser}。 + * @return 字段/派生属性 {@code browser} 的值 + */ public boolean isBrowser() { return this.agentFamily() != null && browsers.contains(this.agent().family.toLowerCase()); } + /** + * 判断 {@code device}。 + * @return 字段/派生属性 {@code device} 的值 + */ public boolean isDevice() { return this.agentFamily() != null && this.agent().family.equals("okhttp") || this.agent().family.equals("MiDM"); } diff --git a/src/main/java/com/mitac/cell/internet/http/package-info.java b/src/main/java/com/mitac/cell/internet/http/package-info.java new file mode 100644 index 0000000..fc665be --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/http/package-info.java @@ -0,0 +1,16 @@ +/** + * 包 {@code com.mitac.cell.internet.http}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McHttpClient}
  • + *
  • {@link McRequest}
  • + *
  • {@link McResponse}
  • + *
  • {@link McResponseEntity}
  • + *
  • {@link UserAgent}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.internet.http; diff --git a/src/main/java/com/mitac/cell/internet/mail/McMailSender.java b/src/main/java/com/mitac/cell/internet/mail/McMailSender.java index 3445996..253c148 100644 --- a/src/main/java/com/mitac/cell/internet/mail/McMailSender.java +++ b/src/main/java/com/mitac/cell/internet/mail/McMailSender.java @@ -16,10 +16,44 @@ import org.springframework.core.io.InputStreamResource; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; +/** + * 【通用基础库】{@code McMailSender} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mailMessage}(MimeMessageHelper):邮件消息
  • + *
  • {@code mailSender}(JavaMailSenderImpl):邮件Sender
  • + *
+ * + * 协作对象:{@code MimeMessageHelper、JavaMailSenderImpl}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McMailSender { + /** + * 邮件消息。 + */ private MimeMessageHelper mailMessage; + /** + * 邮件Sender。 + */ private JavaMailSenderImpl mailSender; + /** + * 构造 {@code McMailSender} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new MimeMessageHelper。 + * + * @param mailSender 参数 {@code mailSender}({@code JavaMailSenderImpl}) + * @param senderEmail 参数 {@code senderEmail}({@code String}) + * @param senderName 参数 {@code senderName}({@code String}) + */ public McMailSender(JavaMailSenderImpl mailSender, String senderEmail, String senderName) { this.mailSender = mailSender; @@ -32,10 +66,25 @@ public class McMailSender { this.setSender(senderEmail, senderName); } + /** + * 设置 {@code sender}。 + * + * @param email 邮箱({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSender(String email) { return this.setSender(email, (String)null); } + /** + * 设置Sender。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param email 邮箱({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSender(String email, String name) { try { this.mailMessage.setFrom(email, name); @@ -49,10 +98,25 @@ public class McMailSender { return false; } + /** + * 添加转换为。 + * + * @param email 邮箱({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addTo(String email) { return this.addTo(email, (String)null); } + /** + * 添加转换为。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param email 邮箱({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addTo(String email, String name) { try { this.mailMessage.addTo(email, name); @@ -66,6 +130,14 @@ public class McMailSender { return false; } + /** + * 添加转换为。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param address 参数 {@code address}({@code InternetAddress}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addTo(InternetAddress address) { try { if (address != null) { @@ -79,7 +151,15 @@ public class McMailSender { } } - public boolean addTo(Collection addresses) { + /** + * 添加转换为。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param addresses 参数 {@code addresses}({@code Collection}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean addTo(Collection addresses) { if (addresses != null && !addresses.isEmpty()) { addresses.forEach((address) -> this.addTo(address)); } @@ -87,7 +167,15 @@ public class McMailSender { return true; } - public boolean setTo(Collection addresses) { + /** + * 设置 {@code to}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param addresses 参数 {@code addresses}({@code Collection}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean setTo(Collection addresses) { if (addresses != null && !addresses.isEmpty()) { try { this.mailMessage.setTo((InternetAddress[])addresses.toArray(new InternetAddress[addresses.size()])); @@ -100,10 +188,25 @@ public class McMailSender { return false; } + /** + * 添加Cc。 + * + * @param email 邮箱({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addCc(String email) { return this.addCc(email, (String)null); } + /** + * 添加Cc。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param email 邮箱({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addCc(String email, String name) { try { this.mailMessage.addCc(email, name); @@ -117,6 +220,14 @@ public class McMailSender { return false; } + /** + * 添加Cc。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param address 参数 {@code address}({@code InternetAddress}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addCc(InternetAddress address) { try { if (address != null) { @@ -130,7 +241,15 @@ public class McMailSender { } } - public boolean addCc(Collection addresses) { + /** + * 添加Cc。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param addresses 参数 {@code addresses}({@code Collection}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean addCc(Collection addresses) { if (addresses != null && !addresses.isEmpty()) { addresses.forEach((address) -> this.addCc(address)); } @@ -138,10 +257,25 @@ public class McMailSender { return true; } + /** + * 添加Bcc。 + * + * @param email 邮箱({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addBcc(String email) { return this.addBcc(email, (String)null); } + /** + * 添加Bcc。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param email 邮箱({@code String}) + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addBcc(String email, String name) { try { this.mailMessage.addBcc(email, name); @@ -155,6 +289,14 @@ public class McMailSender { return false; } + /** + * 添加Bcc。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param address 参数 {@code address}({@code InternetAddress}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addBcc(InternetAddress address) { try { if (address != null) { @@ -168,7 +310,15 @@ public class McMailSender { } } - public boolean addBcc(Collection addresses) { + /** + * 添加Bcc。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param addresses 参数 {@code addresses}({@code Collection}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ + public boolean addBcc(Collection addresses) { if (addresses != null && !addresses.isEmpty()) { addresses.forEach((address) -> this.addBcc(address)); } @@ -176,6 +326,12 @@ public class McMailSender { return true; } + /** + * 获取 {@code allRecipients}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字段/派生属性 {@code allRecipients} 的值 + */ public Address[] getAllRecipients() { try { return this.mailMessage != null ? this.mailMessage.getMimeMessage().getAllRecipients() : null; @@ -184,11 +340,20 @@ public class McMailSender { } } + /** + * 判断 {@code recipients}。 + * @return 字段/派生属性 {@code recipients} 的值 + */ public boolean hasRecipients() { Address[] addresses = this.getAllRecipients(); return addresses != null && addresses.length > 0; } + /** + * 清理转换为。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + */ public void clearTo() { try { this.mailMessage.getMimeMessage().setRecipients(RecipientType.TO, (String)null); @@ -198,6 +363,11 @@ public class McMailSender { } + /** + * 清理Cc。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + */ public void clearCc() { try { this.mailMessage.getMimeMessage().setRecipients(RecipientType.CC, (String)null); @@ -207,6 +377,11 @@ public class McMailSender { } + /** + * 清理Bcc。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + */ public void clearBcc() { try { this.mailMessage.getMimeMessage().setRecipients(RecipientType.BCC, (String)null); @@ -216,12 +391,23 @@ public class McMailSender { } + /** + * 清理全部Recipients。 + */ public void clearAllRecipients() { this.clearTo(); this.clearCc(); this.clearBcc(); } + /** + * 设置 {@code subject}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param subject 参数 {@code subject}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSubject(String subject) { try { this.mailMessage.setSubject(subject); @@ -232,14 +418,35 @@ public class McMailSender { } } + /** + * 设置 {@code text}。 + * + * @param content 参数 {@code content}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setText(String content) { return this.setContent(content, false); } + /** + * 设置 {@code html}。 + * + * @param content 参数 {@code content}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setHtml(String content) { return this.setContent(content, true); } + /** + * 设置Content。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param content 参数 {@code content}({@code String}) + * @param isHtml 参数 {@code isHtml}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setContent(String content, boolean isHtml) { try { this.mailMessage.setText(content, isHtml); @@ -250,15 +457,40 @@ public class McMailSender { } } + /** + * 添加Attachment。 + * + * 实现要点:主要调用:new McFile、exists。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(String filePath) { McFile file = new McFile(filePath); return file.exists() ? this.addAttachment((String)file.getName(), (File)file) : false; } + /** + * 添加Attachment。 + * + * 实现要点:主要调用:exists。 + * + * @param file 文件({@code File}) + * @param fileName 文件名({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(File file, String fileName) { return file.exists() ? this.addAttachment(fileName, file) : false; } + /** + * 添加Attachment。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param filePaths 参数 {@code filePaths}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(String... filePaths) { if (filePaths != null && filePaths.length != 0) { for(String filePath : filePaths) { @@ -273,6 +505,15 @@ public class McMailSender { } } + /** + * 添加Attachment。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param fileName 文件名({@code String}) + * @param file 文件({@code File}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(String fileName, File file) { try { this.mailMessage.addAttachment(fileName, file); @@ -283,6 +524,15 @@ public class McMailSender { } } + /** + * 添加Attachment。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new InputStreamResource。 + * + * @param fileName 文件名({@code String}) + * @param is 参数 {@code is}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(String fileName, InputStream is) { try { this.mailMessage.addAttachment(fileName, new InputStreamResource(is)); @@ -293,6 +543,16 @@ public class McMailSender { } } + /** + * 添加Attachment。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ByteArrayResource。 + * + * @param fileName 文件名({@code String}) + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @param contentType Content-Type({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addAttachment(String fileName, byte[] bytes, String contentType) { try { this.mailMessage.addAttachment(fileName, new ByteArrayResource(bytes), contentType); @@ -303,11 +563,27 @@ public class McMailSender { } } + /** + * 添加镜像。 + * + * 实现要点:主要调用:new McFile、exists。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addImage(String filePath) { McFile file = new McFile(filePath); return file.exists() ? this.addImage(file.getName(), (File)file) : false; } + /** + * 添加镜像。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param filePaths 参数 {@code filePaths}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addImage(String... filePaths) { if (filePaths != null && filePaths.length != 0) { for(String filePath : filePaths) { @@ -322,6 +598,15 @@ public class McMailSender { } } + /** + * 添加镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param fileName 文件名({@code String}) + * @param file 文件({@code File}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addImage(String fileName, File file) { try { this.mailMessage.addInline(fileName, file); @@ -332,6 +617,15 @@ public class McMailSender { } } + /** + * 添加镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new InputStreamResource。 + * + * @param fileName 文件名({@code String}) + * @param is 参数 {@code is}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addImage(String fileName, InputStream is) { try { this.mailMessage.addInline(fileName, new InputStreamResource(is)); @@ -342,6 +636,16 @@ public class McMailSender { } } + /** + * 添加镜像。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ByteArrayResource。 + * + * @param fileName 文件名({@code String}) + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @param contentType Content-Type({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean addImage(String fileName, byte[] bytes, String contentType) { try { this.mailMessage.addInline(fileName, new ByteArrayResource(bytes), contentType); @@ -352,6 +656,11 @@ public class McMailSender { } } + /** + * 处理发送。 + * + * 实现要点:涉及邮件发送;包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new Runnable、send、execute。 + */ public void send() { if (this.hasRecipients()) { Runnable sendMail = new Runnable() { diff --git a/src/main/java/com/mitac/cell/internet/mail/package-info.java b/src/main/java/com/mitac/cell/internet/mail/package-info.java new file mode 100644 index 0000000..e61977d --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/mail/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.internet.mail}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McMailSender}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.internet.mail; diff --git a/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java b/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java index 6fbbaba..fe5b52f 100644 --- a/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java +++ b/src/main/java/com/mitac/cell/internet/websocket/SocketCloseStatus.java @@ -3,6 +3,22 @@ package com.mitac.cell.internet.websocket; import com.google.common.base.Strings; import org.springframework.web.socket.CloseStatus; +/** + * 【枚举常量】{@code SocketCloseStatus} + * + * 类职责: + *

    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code code}(int):代码
  • + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public enum SocketCloseStatus { NORMAL(1000), GOING_AWAY(1001), @@ -21,12 +37,28 @@ public enum SocketCloseStatus { SESSION_NOT_RELIABLE(4500), UNKNOWN(-1); + /** + * 代码。 + */ private int code; + /** + * 构造 {@code SocketCloseStatus} 实例。 + * + * @param code 状态码/业务码({@code int}) + */ private SocketCloseStatus(int code) { this.code = code; } + /** + * 处理获取。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param code 状态码/业务码({@code int}) + * @return 处理结果 + */ public static SocketCloseStatus get(int code) { for(SocketCloseStatus status : values()) { if (status.code == code) { @@ -37,6 +69,14 @@ public enum SocketCloseStatus { return UNKNOWN; } + /** + * 处理reason。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param status 状态({@code CloseStatus}) + * @return 字符串结果 + */ public static String reason(CloseStatus status) { String reason = status.getReason(); if (Strings.isNullOrEmpty(reason)) { diff --git a/src/main/java/com/mitac/cell/internet/websocket/package-info.java b/src/main/java/com/mitac/cell/internet/websocket/package-info.java new file mode 100644 index 0000000..934dde3 --- /dev/null +++ b/src/main/java/com/mitac/cell/internet/websocket/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.internet.websocket}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link SocketCloseStatus}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.internet.websocket; diff --git a/src/main/java/com/mitac/cell/io/ApkSign.java b/src/main/java/com/mitac/cell/io/ApkSign.java index af3fcfc..87a19c3 100644 --- a/src/main/java/com/mitac/cell/io/ApkSign.java +++ b/src/main/java/com/mitac/cell/io/ApkSign.java @@ -3,13 +3,55 @@ package com.mitac.cell.io; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; +/** + * 【通用基础库】{@code ApkSign} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code type}(String):类型
  • + *
  • {@code certificate}(byte[]):字段 certificate
  • + *
  • {@code publicKey}(byte[]):public密钥
  • + *
  • {@code algorithm}(String):字段 algorithm
  • + *
  • {@code format}(String):格式化
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class ApkSign { + /** + * 类型。 + */ private String type; + /** + * 字段 certificate。 + */ private byte[] certificate; + /** + * public密钥。 + */ private byte[] publicKey; + /** + * 字段 algorithm。 + */ private String algorithm; + /** + * 格式化。 + */ private String format; + /** + * 构造 {@code ApkSign} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param certificate 参数 {@code certificate}({@code Certificate}) + */ public ApkSign(Certificate certificate) { try { this.setType(certificate.getType()); @@ -23,42 +65,87 @@ public class ApkSign { } + /** + * 获取 {@code type}。 + * @return 字符串结果 + */ public String getType() { return this.type; } + /** + * 设置 {@code type}。 + * + * @param type 类型({@code String}) + */ public void setType(String type) { this.type = type; } + /** + * 获取 {@code certificate}。 + * @return 字段/派生属性 {@code certificate} 的值 + */ public byte[] getCertificate() { return this.certificate; } + /** + * 设置 {@code certificate}。 + * + * @param certificate 参数 {@code certificate}({@code byte[]}) + */ public void setCertificate(byte[] certificate) { this.certificate = certificate; } + /** + * 获取 {@code publicKey}。 + * @return 字段/派生属性 {@code publicKey} 的值 + */ public byte[] getPublicKey() { return this.publicKey; } + /** + * 设置 {@code publicKey}。 + * + * @param publicKey 参数 {@code publicKey}({@code byte[]}) + */ public void setPublicKey(byte[] publicKey) { this.publicKey = publicKey; } + /** + * 获取 {@code algorithm}。 + * @return 字符串结果 + */ public String getAlgorithm() { return this.algorithm; } + /** + * 设置 {@code algorithm}。 + * + * @param algorithm 参数 {@code algorithm}({@code String}) + */ public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } + /** + * 获取 {@code format}。 + * @return 字符串结果 + */ public String getFormat() { return this.format; } + /** + * 设置 {@code format}。 + * + * @param format 参数 {@code format}({@code String}) + */ public void setFormat(String format) { this.format = format; } diff --git a/src/main/java/com/mitac/cell/io/McApkFile.java b/src/main/java/com/mitac/cell/io/McApkFile.java index 0b5dbe1..951f345 100644 --- a/src/main/java/com/mitac/cell/io/McApkFile.java +++ b/src/main/java/com/mitac/cell/io/McApkFile.java @@ -36,15 +36,45 @@ import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; +/** + * 【通用基础库】{@code McApkFile} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McApkFile extends ApkFile { + /** + * 构造 {@code McApkFile} 实例。 + * + * @param apkFile 参数 {@code apkFile}({@code File}) + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ public McApkFile(File apkFile) throws IOException { super(apkFile); } + /** + * 构造 {@code McApkFile} 实例。 + * + * 实现要点:主要调用:new File。 + * + * @param apkFile 参数 {@code apkFile}({@code String}) + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + */ public McApkFile(String apkFile) throws IOException { super(new File(apkFile)); } + /** + * 获取 {@code certMd5}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getCertMd5() { try { List signers = this.getApkSingers(); @@ -58,6 +88,12 @@ public class McApkFile extends ApkFile { return null; } + /** + * 处理iconBytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、1 个循环。 + * @return 处理结果 + */ public byte[] iconBytes() { try { Icon bigIcon = null; @@ -89,11 +125,27 @@ public class McApkFile extends ApkFile { } } + /** + * 保存Icon。 + * + * 实现要点:主要调用:new McFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean saveIcon(String path) { byte[] iconBytes = this.iconBytes(); return iconBytes != null ? (new McFile(path)).write(iconBytes) : false; } + /** + * 处理androidVectorDrawable转换为Svg。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:parse、new InputSource、new StringReader。 + * + * @param drawable 参数 {@code drawable}({@code String}) + * @return 字符串结果 + */ public String androidVectorDrawableToSvg(String drawable) { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); @@ -116,6 +168,16 @@ public class McApkFile extends ApkFile { return null; } + /** + * 转换转换为Svg。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param doc 参数 {@code doc}({@code Document}) + * @param srcNode 参数 {@code srcNode}({@code Node}) + * @param destNode 参数 {@code destNode}({@code Node}) + * @return 处理结果 + */ public Node convertToSvg(Document doc, Node srcNode, Node destNode) { String nodeName = srcNode.getNodeName(); Element element = null; @@ -151,6 +213,14 @@ public class McApkFile extends ApkFile { } } + /** + * 设置Attribute。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param srcNode 参数 {@code srcNode}({@code Node}) + * @param destNode 参数 {@code destNode}({@code Element}) + */ private void setAttribute(Node srcNode, Element destNode) { String nodeName = srcNode.getNodeName(); NamedNodeMap attrs = srcNode.getAttributes(); @@ -198,6 +268,14 @@ public class McApkFile extends ApkFile { } + /** + * 处理color值。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * + * @param color 参数 {@code color}({@code String}) + * @return 字符串结果 + */ private String colorValue(String color) { if (color.startsWith("#")) { return color; @@ -213,6 +291,14 @@ public class McApkFile extends ApkFile { } } + /** + * 处理转换为Xml。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new StringWriter、new DOMSource、new StreamResult。 + * + * @param doc 参数 {@code doc}({@code Document}) + * @return 字符串结果 + */ public String toXml(Document doc) { try { TransformerFactory tf = TransformerFactory.newInstance(); @@ -229,6 +315,14 @@ public class McApkFile extends ApkFile { return null; } + /** + * 处理svg转换为Png。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ByteArrayInputStream、new TranscoderInput、new ByteArrayOutputStream、new TranscoderOutput、new PNGTranscoder、close。 + * + * @param svg 参数 {@code svg}({@code String}) + * @return 处理结果 + */ public byte[] svgToPng(String svg) { try { ByteArrayInputStream input = new ByteArrayInputStream(svg.getBytes()); diff --git a/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java b/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java index 0e92c9c..3abb46f 100644 --- a/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java +++ b/src/main/java/com/mitac/cell/io/McEncryptedFileDrive.java @@ -17,27 +17,94 @@ import java.io.OutputStream; import java.util.Arrays; import java.util.List; +/** + * 【通用基础库】{@code McEncryptedFileDrive} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mKey}(byte[]):m密钥
  • + *
  • {@code mFile}(File):m文件
  • + *
  • {@code mUnclocked}(boolean):是否mUnclocked
  • + *
  • {@code mInstantSave}(boolean):mInstant保存
  • + *
  • {@code mFileTable}(McFileTable):m文件Table
  • + *
  • {@code mHeader}(Header):字段 mHeader
  • + *
+ * + * 协作对象:{@code File、McFileTable、Header}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McEncryptedFileDrive { + /** + * m密钥。 + */ private byte[] mKey; + /** + * m文件。 + */ private File mFile; + /** + * 是否mUnclocked。 + */ private boolean mUnclocked; + /** + * mInstant保存。 + */ private boolean mInstantSave; + /** + * m文件Table。 + */ private McFileTable mFileTable; + /** + * 字段 mHeader。 + */ private Header mHeader; + /** + * 构造 {@code McEncryptedFileDrive} 实例。 + * + * 实现要点:主要调用:new McFile。 + * + * @param path 参数 {@code path}({@code String}) + */ public McEncryptedFileDrive(String path) { this(new McFile(path)); } + /** + * 构造 {@code McEncryptedFileDrive} 实例。 + * + * @param path 参数 {@code path}({@code String}) + * @param key 键/配置项({@code String}) + */ public McEncryptedFileDrive(String path, String key) { this(path, key.getBytes()); } + /** + * 构造 {@code McEncryptedFileDrive} 实例。 + * + * @param path 参数 {@code path}({@code String}) + * @param key 键/配置项({@code byte[]}) + */ public McEncryptedFileDrive(String path, byte[] key) { this(path); this.setKey(key); } + /** + * 构造 {@code McEncryptedFileDrive} 实例。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Header、new McFileTable、exists。 + * + * @param file 文件({@code McFile}) + */ public McEncryptedFileDrive(McFile file) { this.mUnclocked = false; this.mInstantSave = true; @@ -49,71 +116,167 @@ public class McEncryptedFileDrive { } + /** + * 处理解锁。 + * + * @param key 键/配置项({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean unlock(String key) { return this.mUnclocked; } + /** + * 判断 {@code sameKey}。 + * @return 字段/派生属性 {@code sameKey} 的值 + */ public boolean isSameKey() { return Arrays.equals(this.mKey, this.mHeader.getKey()); } + /** + * 处理compressed。 + * + * @param compressed 参数 {@code compressed}({@code boolean}) + */ public void compressed(boolean compressed) { this.mHeader.compressed(compressed); } + /** + * 处理compressed。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compressed() { return this.mHeader.compressed(); } + /** + * 启用Instant保存。 + * + * @param enable 参数 {@code enable}({@code boolean}) + */ public void enableInstantSave(boolean enable) { this.mInstantSave = enable; } + /** + * 设置 {@code key}。 + * + * @param key 键/配置项({@code String}) + */ public void setKey(String key) { this.setKey(key.getBytes()); } + /** + * 设置 {@code key}。 + * + * @param key 键/配置项({@code byte[]}) + */ public void setKey(byte[] key) { this.mHeader.setKey(this.mKey = McCrypto.encryptMessageByHmacMd5(key)); } + /** + * 设置 {@code maxSize}。 + * + * @param size 每页数量({@code long}) + */ public void setMaxSize(long size) { } + /** + * 处理length。 + */ public void length() { } + /** + * 判断 {@code encrypted}。 + * @return 字段/派生属性 {@code encrypted} 的值 + */ public boolean isEncrypted() { return this.mKey != null; } + /** + * 设置 {@code curPath}。 + * + * @param curPath 参数 {@code curPath}({@code String}) + */ public void setCurPath(String curPath) { } + /** + * 获取文件。 + * + * 实现要点:主要调用:getFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 字段/派生属性 {@code file} 的值 + */ public McJsonFile getFile(String path) { return this.mFileTable.getFile(path); } - public List getFiles() { + /** + * 获取 {@code files}。 + * @return Mc文件列表,可能为空 + */ + public List getFiles() { return this.mFileTable.getFiles("/"); } - public List getFiles(String path) { + /** + * 获取文件列表。 + * + * @param path 参数 {@code path}({@code String}) + * @return Mc文件列表,可能为空 + */ + public List getFiles(String path) { return this.mFileTable.getFiles(path); } + /** + * 判断是否Directory。 + * + * @param folderPath 参数 {@code folderPath}({@code String}) + * @return 字段/派生属性 {@code directory} 的值 + */ public boolean isDirectory(String folderPath) { return this.mFileTable.getFolder(folderPath) != null; } + /** + * 判断是否文件。 + * + * 实现要点:主要调用:getFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 字段/派生属性 {@code file} 的值 + */ public boolean isFile(String path) { return this.mFileTable.getFile(path) != null; } + /** + * 处理存在。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean exists(String path) { return this.isDirectory(path) || this.isFile(path); } + /** + * 添加Folder。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * @param folderPath 参数 {@code folderPath}({@code String}) + */ public void addFolder(String folderPath) { this.mFileTable.addFolder(folderPath); if (this.mInstantSave) { @@ -122,6 +285,14 @@ public class McEncryptedFileDrive { } + /** + * 添加文件。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @param data 参数 {@code data}({@code byte[]}) + */ public void addFile(String filePath, byte[] data) { this.mFileTable.addFile(filePath, data); if (this.mInstantSave) { @@ -130,6 +301,14 @@ public class McEncryptedFileDrive { } + /** + * 添加文件。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:new File、exists、save。 + * + * @param sourcePath 参数 {@code sourcePath}({@code String}) + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void addFile(String sourcePath, String destinationPath) { File file = new File(sourcePath); if (file.exists()) { @@ -141,17 +320,45 @@ public class McEncryptedFileDrive { } } + /** + * 复制转换为。 + * + * 实现要点:主要调用:getFile。 + * + * @param orgFilePath 参数 {@code orgFilePath}({@code String}) + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void copyTo(String orgFilePath, String destinationPath) { this.mFileTable.getFile(orgFilePath).extractTo(destinationPath); } + /** + * 处理移动。 + * + * @param orgfilPath 参数 {@code orgfilPath}({@code String}) + * @param destinatinFile 参数 {@code destinatinFile}({@code String}) + */ public void move(String orgfilPath, String destinatinFile) { } + /** + * 处理删除。 + * + * 实现要点:主要调用:remove。 + * + * @param path 参数 {@code path}({@code String}) + */ public void delete(String path) { this.remove(path); } + /** + * 处理移除。 + * + * 实现要点:调用持久化方法保存数据;包含 2 个条件分支、0 个循环;主要调用:save。 + * + * @param path 参数 {@code path}({@code String}) + */ public void remove(String path) { if (!this.mFileTable.removeFolder(path)) { this.mFileTable.removeFile(path); @@ -163,6 +370,14 @@ public class McEncryptedFileDrive { } + /** + * 处理重命名。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * @param path 参数 {@code path}({@code String}) + * @param newFileName 参数 {@code newFileName}({@code String}) + */ public void rename(String path, String newFileName) { if (this.mInstantSave) { this.save(); @@ -170,6 +385,13 @@ public class McEncryptedFileDrive { } + /** + * 处理paste。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:save。 + * + * @param destinationFolder 参数 {@code destinationFolder}({@code String}) + */ public void paste(String destinationFolder) { if (this.mInstantSave) { this.save(); @@ -177,10 +399,22 @@ public class McEncryptedFileDrive { } + /** + * 处理列出。 + * + * @param folderName 参数 {@code folderName}({@code String}) + * @return 处理结果 + */ public String[] list(String folderName) { return null; } + /** + * 处理加载。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:new BufferedInputStream、new FileInputStream、new ByteArrayOutputStream、read、write、close。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean load() { InputStream ios = null; ByteArrayOutputStream ous = null; @@ -231,10 +465,20 @@ public class McEncryptedFileDrive { } } + /** + * 处理extract文件列表。 + * + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void extractFiles(String destinationPath) { this.mFileTable.extractFiles(destinationPath); } + /** + * 处理保存。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileOutputStream、write、close。 + */ public void save() { try { OutputStream os = new FileOutputStream(this.mFile); @@ -251,6 +495,12 @@ public class McEncryptedFileDrive { } + /** + * 获取 {@code encryptedData}。 + * + * 实现要点:包含 2 个条件分支、1 个循环。 + * @return 字段/派生属性 {@code encryptedData} 的值 + */ private byte[] getEncryptedData() { int bufferSize = 65536; byte[] source = this.mFileTable.getBytes(); @@ -274,22 +524,84 @@ public class McEncryptedFileDrive { } } + /** + * 【通用基础库】{@code Header} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code FILE_PREFIX}(byte[]):字段 FILE_PREFIX
  • + *
  • {@code FLAG_TRASHCAN_EANABLED}(byte):字段 FLAG_TRASHCAN_EANABLED
  • + *
  • {@code FLAG_COMPRESSED}(byte):字段 FLAG_COMPRESSED
  • + *
  • {@code FLAG_HAS_KEY}(byte):字段 FLAG_HAS_KEY
  • + *
  • {@code mVersion}(byte[]):m版本
  • + *
  • {@code mCompressed}(boolean):是否mCompressed
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ protected final class Header { + /** + * 字段 FILE_PREFIX。 + */ private final byte[] FILE_PREFIX; + /** + * 字段 FLAG_TRASHCAN_EANABLED。 + */ private final byte FLAG_TRASHCAN_EANABLED; + /** + * 字段 FLAG_COMPRESSED。 + */ private final byte FLAG_COMPRESSED; + /** + * 字段 FLAG_HAS_KEY。 + */ private final byte FLAG_HAS_KEY; + /** + * m版本。 + */ private final byte[] mVersion; + /** + * 是否mCompressed。 + */ private boolean mCompressed; + /** + * 是否mTrashcanEnabled。 + */ private boolean mTrashcanEnabled; + /** + * m判断是否存在密钥。 + */ private boolean mHasKey; + /** + * 字段 mReservedFlag。 + */ private byte mReservedFlag; + /** + * 字段 mPassword。 + */ private byte[] mPassword; + /** + * 构造 {@code Header} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public Header() { this(true, false, false); } + /** + * 构造 {@code Header} 实例。 + * + * @param compressed 参数 {@code compressed}({@code boolean}) + * @param encrypted 参数 {@code encrypted}({@code boolean}) + * @param trashcanEnabled 参数 {@code trashcanEnabled}({@code boolean}) + */ public Header(boolean compressed, boolean encrypted, boolean trashcanEnabled) { this.FILE_PREFIX = new byte[]{69, 70, 68, 3}; this.FLAG_TRASHCAN_EANABLED = 1; @@ -302,6 +614,13 @@ public class McEncryptedFileDrive { this.mTrashcanEnabled = trashcanEnabled; } + /** + * 设置 {@code version}。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param version 参数 {@code version}({@code String}) + */ public final void setVersion(String version) { String[] data = version.split("\\."); @@ -311,10 +630,21 @@ public class McEncryptedFileDrive { } + /** + * 获取 {@code version}。 + * @return 字符串结果 + */ public final String getVersion() { return String.format("%d.%d.%d.%d", this.mVersion[0], this.mVersion[1], this.mVersion[2], this.mVersion[3]); } + /** + * 设置 {@code key}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code byte[]}) + */ public final void setKey(byte[] key) { if (key != null) { this.mPassword = key; @@ -323,30 +653,62 @@ public class McEncryptedFileDrive { } + /** + * 获取 {@code key}。 + * @return 字段/派生属性 {@code key} 的值 + */ public byte[] getKey() { return this.mPassword; } + /** + * 处理compressed。 + * + * @param compressed 参数 {@code compressed}({@code boolean}) + */ public final void compressed(boolean compressed) { this.mCompressed = compressed; } + /** + * 处理compressed。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public final boolean compressed() { return this.mCompressed; } + /** + * 判断 {@code key}。 + * @return 字段/派生属性 {@code key} 的值 + */ public final boolean hasKey() { return this.mHasKey; } + /** + * 处理trashcanEnabled。 + * + * @param trashcanEnabled 参数 {@code trashcanEnabled}({@code boolean}) + */ public final void trashcanEnabled(boolean trashcanEnabled) { this.mTrashcanEnabled = trashcanEnabled; } + /** + * 处理trashcanEnabled。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public final boolean trashcanEnabled() { return this.mTrashcanEnabled; } + /** + * 获取 {@code flag}。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * @return 字段/派生属性 {@code flag} 的值 + */ private final byte getFlag() { byte flag = 0; if (this.mCompressed) { @@ -364,10 +726,26 @@ public class McEncryptedFileDrive { return flag; } + /** + * 设置 {@code bytes}。 + * + * 实现要点:主要调用:new ByteArrayInputStream。 + * + * @param headerBytes 参数 {@code headerBytes}({@code byte[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public final boolean setBytes(byte[] headerBytes) { return this.setBytes((InputStream)(new ByteArrayInputStream(headerBytes))); } + /** + * 设置 {@code bytes}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:read。 + * + * @param bis 参数 {@code bis}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public final boolean setBytes(InputStream bis) { try { byte[] header = new byte[4]; @@ -397,6 +775,12 @@ public class McEncryptedFileDrive { } } + /** + * 获取 {@code bytes}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new ByteArrayOutputStream、write、close。 + * @return 字段/派生属性 {@code bytes} 的值 + */ public final byte[] getBytes() { byte[] header = null; diff --git a/src/main/java/com/mitac/cell/io/McFile.java b/src/main/java/com/mitac/cell/io/McFile.java index 4560245..092b86d 100644 --- a/src/main/java/com/mitac/cell/io/McFile.java +++ b/src/main/java/com/mitac/cell/io/McFile.java @@ -21,34 +21,107 @@ import java.security.NoSuchAlgorithmException; import org.apache.commons.io.FileUtils; import org.apache.tika.Tika; +/** + * 【通用基础库】{@code McFile} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KB}(long):字段 KB
  • + *
  • {@code MB}(long):字段 MB
  • + *
  • {@code GB}(long):字段 GB
  • + *
  • {@code TB}(long):字段 TB
  • + *
  • {@code CONTENT_TYPE_XLS}(String):字段 CONTENT_TYPE_XLS
  • + *
  • {@code CONTENT_TYPE_XLSX}(String):字段 CONTENT_TYPE_XLSX
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McFile extends File { + /** + * 字段 KB。 + */ public static final long KB = 1024L; + /** + * 字段 MB。 + */ public static final long MB = 1048576L; + /** + * 字段 GB。 + */ public static final long GB = 1073741824L; + /** + * 字段 TB。 + */ public static final long TB = 1099511627776L; + /** + * 字段 CONTENT_TYPE_XLS。 + */ public static String CONTENT_TYPE_XLS = "application/vnd.ms-excel"; + /** + * 字段 CONTENT_TYPE_XLSX。 + */ public static String CONTENT_TYPE_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + /** + * 构造 {@code McFile} 实例。 + * + * @param filePath 参数 {@code filePath}({@code String}) + */ public McFile(String filePath) { super(filePath); } + /** + * 构造 {@code McFile} 实例。 + * + * @param folderPath 参数 {@code folderPath}({@code String}) + * @param fileName 文件名({@code String}) + */ public McFile(String folderPath, String fileName) { super(folderPath, fileName); } + /** + * 构造 {@code McFile} 实例。 + * + * @param file 文件({@code File}) + */ public McFile(File file) { this(file.getPath()); } + /** + * 构造 {@code McFile} 实例。 + * + * @param file 文件({@code File}) + * @param fileName 文件名({@code String}) + */ public McFile(File file, String fileName) { super(file, fileName); } + /** + * 构造 {@code McFile} 实例。 + * + * @param file 文件({@code McFile}) + * @param fileName 文件名({@code String}) + */ public McFile(McFile file, String fileName) { super(file, fileName); } + /** + * 创建父级Dirs。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean createParentDirs() { if (this.getParentFile().exists() && this.getParentFile().isDirectory()) { return true; @@ -63,6 +136,12 @@ public class McFile extends File { } } + /** + * 创建Dirs。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:exists。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean createDirs() { if (!this.createParentDirs()) { return false; @@ -73,15 +152,31 @@ public class McFile extends File { } } + /** + * 获取 {@code parentFile}。 + * + * 实现要点:主要调用:new McFile。 + * @return 字段/派生属性 {@code parentFile} 的值 + */ public McFile getParentFile() { return new McFile(this.getParent()); } + /** + * 处理转换为Base64。 + * @return 字符串结果 + */ public String toBase64() { byte[] bytes = this.toBytes(); return bytes == null ? null : BaseEncoding.base64().encode(bytes); } + /** + * 处理转换为Bytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:exists。 + * @return 处理结果 + */ public byte[] toBytes() { try { return this.exists() ? Files.toByteArray(this) : null; @@ -91,6 +186,12 @@ public class McFile extends File { } } + /** + * 获取 {@code contentType}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new Tika。 + * @return 字符串结果 + */ public String getContentType() { try { return (new Tika()).detect(this); @@ -99,10 +200,22 @@ public class McFile extends File { } } + /** + * 获取 {@code crcChecksum}。 + * @return 数量/长度 + */ public long getCrcChecksum() { return this.getCrcChecksum((Integer)null); } + /** + * 获取CrcChecksum。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new BufferedInputStream、read。 + * + * @param length 参数 {@code length}({@code Integer}) + * @return 数量/长度 + */ public long getCrcChecksum(Integer length) { HashFunction hf = Hashing.crc32(); @@ -133,6 +246,12 @@ public class McFile extends File { } } + /** + * 获取 {@code md5}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字段/派生属性 {@code md5} 的值 + */ public byte[] getMd5() { try { MessageDigest md = MessageDigest.getInstance("MD5"); @@ -142,23 +261,51 @@ public class McFile extends File { } } + /** + * 获取 {@code md5Hex}。 + * @return 字符串结果 + */ public String getMd5Hex() { return McStringUtils.toHexString(this.getMd5()); } + /** + * 获取 {@code extension}。 + * @return 字符串结果 + */ public String getExtension() { return Files.getFileExtension(this.getName()); } + /** + * 获取 {@code nameWithoutExtension}。 + * @return 字符串结果 + */ public String getNameWithoutExtension() { return Files.getNameWithoutExtension(this.getName()); } + /** + * 处理写入。 + * + * 实现要点:主要调用:new ByteArrayInputStream、write。 + * + * @param data 参数 {@code data}({@code byte[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean write(byte[] data) { ByteArrayInputStream bis = new ByteArrayInputStream(data); return this.write((InputStream)bis); } + /** + * 处理写入。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new BufferedOutputStream、read、write、close。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean write(InputStream is) { try { OutputStream os = this.getOutputStream(); @@ -187,10 +334,28 @@ public class McFile extends File { return false; } + /** + * 保存As。 + * + * 实现要点:主要调用:new McFile。 + * + * @param targetFileName 参数 {@code targetFileName}({@code String}) + * @param overwrite 参数 {@code overwrite}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean saveAs(String targetFileName, boolean overwrite) { return this.saveAs(new McFile(targetFileName), overwrite); } + /** + * 保存As。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:exists。 + * + * @param target 参数 {@code target}({@code McFile}) + * @param overwrite 参数 {@code overwrite}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean saveAs(McFile target, boolean overwrite) { if (this.exists() && !target.isDirectory()) { if (target.exists() && !overwrite) { @@ -209,6 +374,14 @@ public class McFile extends File { } } + /** + * 移动从。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:exists、write、delete。 + * + * @param file 文件({@code McFile}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean moveFrom(McFile file) { if (!file.exists()) { return false; @@ -222,14 +395,36 @@ public class McFile extends File { } } + /** + * 移动从。 + * + * 实现要点:主要调用:new McFile。 + * + * @param file 文件({@code File}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean moveFrom(File file) { return this.moveFrom(new McFile(file)); } + /** + * 移动转换为。 + * + * 实现要点:主要调用:new McFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean moveTo(String path) { return (new McFile(path)).moveFrom(this); } + /** + * 处理删除。 + * + * 实现要点:包含 5 个条件分支、1 个循环;主要调用:exists、delete、new McFile。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean delete() { if (!this.exists()) { return true; @@ -255,6 +450,12 @@ public class McFile extends File { } } + /** + * 删除父级。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean deleteParent() { try { FileUtils.deleteDirectory(this.getParentFile()); @@ -265,6 +466,12 @@ public class McFile extends File { } } + /** + * 获取 {@code inputStream}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileInputStream。 + * @return 字段/派生属性 {@code inputStream} 的值 + */ public InputStream getInputStream() { try { return new FileInputStream(this); @@ -274,6 +481,12 @@ public class McFile extends File { } } + /** + * 获取 {@code outputStream}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileOutputStream。 + * @return 字段/派生属性 {@code outputStream} 的值 + */ public OutputStream getOutputStream() { try { return new FileOutputStream(this); @@ -282,10 +495,24 @@ public class McFile extends File { } } + /** + * 处理存在。 + * + * 实现要点:主要调用:new McFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public static boolean exists(String path) { return (new McFile(path)).exists(); } + /** + * 处理length。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:exists、new McFile。 + * @return 数量/长度 + */ public long length() { long total = 0L; if (!this.exists()) { diff --git a/src/main/java/com/mitac/cell/io/McFileTable.java b/src/main/java/com/mitac/cell/io/McFileTable.java index 8cb89d6..383d494 100644 --- a/src/main/java/com/mitac/cell/io/McFileTable.java +++ b/src/main/java/com/mitac/cell/io/McFileTable.java @@ -14,18 +14,69 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +/** + * 【通用基础库】{@code McFileTable} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_EFD}(String):字段 KEY_EFD
  • + *
  • {@code KEY_FILE}(String):字段 KEY_FILE
  • + *
  • {@code mFileTable}(JsonObject):m文件Table
  • + *
  • {@code mRoot}(JsonObject):字段 mRoot
  • + *
  • {@code mFileArray}(ArrayList):m文件Array
  • + *
+ * + * 协作对象:{@code JsonObject、ArrayList}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McFileTable { + /** + * 字段 KEY_EFD。 + */ private static final String KEY_EFD = "EFD"; + /** + * 字段 KEY_FILE。 + */ private static final String KEY_FILE = "file"; + /** + * m文件Table。 + */ private JsonObject mFileTable = new JsonObject(); + /** + * 字段 mRoot。 + */ private JsonObject mRoot = new JsonObject(); - private final ArrayList mFileArray; + /** + * m文件Array。 + */ + private final ArrayList mFileArray; + /** + * 构造 {@code McFileTable} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new ArrayList。 + */ public McFileTable() { this.mFileTable.add("EFD", this.mRoot); this.mFileArray = new ArrayList(); } + /** + * 添加文件。 + * + * 实现要点:主要调用:new File、new McJsonFile。 + * + * @param sourceFilePath 参数 {@code sourceFilePath}({@code String}) + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void addFile(String sourceFilePath, String destinationPath) { JsonObject targetFolder = this.addFolder((new File(destinationPath)).getParent()); JsonArray filesArray = this.getFilesArray(targetFolder); @@ -34,6 +85,14 @@ public class McFileTable { this.mFileArray.add(jsonFile); } + /** + * 添加文件。 + * + * 实现要点:主要调用:new File、new McJsonFile。 + * + * @param destinationFile 参数 {@code destinationFile}({@code String}) + * @param data 参数 {@code data}({@code byte[]}) + */ public void addFile(String destinationFile, byte[] data) { JsonObject targetFolder = this.addFolder((new File(destinationFile)).getParent()); JsonArray filesArray = this.getFilesArray(targetFolder); @@ -43,6 +102,14 @@ public class McFileTable { this.mFileArray.add(jsonFile); } + /** + * 移除文件。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new File、new JsonArray、new McJsonFile、remove。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean removeFile(String path) { File file = new File(path); JsonObject folder = this.getFolder(file.getParent()); @@ -71,6 +138,14 @@ public class McFileTable { } } + /** + * 获取Names。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环。 + * + * @param jPath 参数 {@code jPath}({@code JsonObject}) + * @return 字段/派生属性 {@code names} 的值 + */ private String[] getNames(JsonObject jPath) { String[] names = new String[jPath.size()]; int i = 0; @@ -82,7 +157,15 @@ public class McFileTable { return names; } - public ArrayList getFiles(String path) { + /** + * 获取文件列表。 + * + * 实现要点:包含 3 个条件分支、2 个循环;主要调用:new ArrayList、new McFile、new McJsonFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 字段/派生属性 {@code files} 的值 + */ + public ArrayList getFiles(String path) { JsonObject folder = this.getFolder(path); String[] names = this.getNames(folder); if (names == null) { @@ -108,6 +191,14 @@ public class McFileTable { } } + /** + * 获取文件。 + * + * 实现要点:包含 3 个条件分支、1 个循环;主要调用:new File、new McJsonFile。 + * + * @param path 参数 {@code path}({@code String}) + * @return 字段/派生属性 {@code file} 的值 + */ public McJsonFile getFile(String path) { File file = new File(path); JsonObject folder = this.getFolder(file.getParent()); @@ -132,12 +223,28 @@ public class McFileTable { } } + /** + * 获取Folder。 + * + * 实现要点:主要调用:parse。 + * + * @param folderPath 参数 {@code folderPath}({@code String}) + * @return 字段/派生属性 {@code folder} 的值 + */ public JsonObject getFolder(String folderPath) { Uri uri = Uri.parse(folderPath); List paths = uri.getPathSegments(); return paths.size() > 0 && this.mRoot.has((String)paths.get(0)) ? this.mRoot.getAsJsonObject((String)paths.get(0)) : this.mRoot; } + /** + * 获取文件列表Array。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new JsonArray。 + * + * @param jsonFolder 参数 {@code jsonFolder}({@code JsonObject}) + * @return 字段/派生属性 {@code filesArray} 的值 + */ private JsonArray getFilesArray(JsonObject jsonFolder) { JsonArray fileArray = jsonFolder.getAsJsonArray("file"); if (fileArray == null) { @@ -148,6 +255,14 @@ public class McFileTable { return fileArray; } + /** + * 添加Folder。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:parse、new JsonObject。 + * + * @param path 参数 {@code path}({@code String}) + * @return 处理结果 + */ public JsonObject addFolder(String path) { if (path != null && !path.isEmpty()) { Uri uri = Uri.parse(path); @@ -171,6 +286,14 @@ public class McFileTable { } } + /** + * 移除Folder。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:parse、remove。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean removeFolder(String path) { Uri uri = Uri.parse(path); List paths = uri.getPathSegments(); @@ -182,6 +305,13 @@ public class McFileTable { } } + /** + * 处理extract文件列表。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void extractFiles(String destinationPath) { for(int i = 0; i < this.mFileArray.size(); ++i) { McJsonFile file = (McJsonFile)this.mFileArray.get(i); @@ -190,6 +320,14 @@ public class McFileTable { } + /** + * 设置 {@code bytes}。 + * + * 实现要点:主要调用:new ByteArrayInputStream、read。 + * + * @param buffer 参数 {@code buffer}({@code byte[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setBytes(byte[] buffer) { ByteArrayInputStream bos = new ByteArrayInputStream(buffer); byte[] data = new byte[4]; @@ -204,6 +342,15 @@ public class McFileTable { return true; } + /** + * 处理dispatch文件列表。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、2 个循环;主要调用:new McJsonFile。 + * + * @param buffer 参数 {@code buffer}({@code byte[]}) + * @param fileTable 参数 {@code fileTable}({@code JsonObject}) + * @param startOffset 参数 {@code startOffset}({@code int}) + */ private void dispatchFiles(byte[] buffer, JsonObject fileTable, int startOffset) { for(Map.Entry entry : fileTable.entrySet()) { JsonElement jPath = (JsonElement)entry.getValue(); @@ -224,6 +371,12 @@ public class McFileTable { } + /** + * 获取 {@code bytes}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、3 个循环;主要调用:new ByteArrayOutputStream、write。 + * @return 字段/派生属性 {@code bytes} 的值 + */ public byte[] getBytes() { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); diff --git a/src/main/java/com/mitac/cell/io/McInputStream.java b/src/main/java/com/mitac/cell/io/McInputStream.java index 3f55982..1ff9f15 100644 --- a/src/main/java/com/mitac/cell/io/McInputStream.java +++ b/src/main/java/com/mitac/cell/io/McInputStream.java @@ -5,7 +5,25 @@ import com.google.common.io.ByteStreams; import java.io.IOException; import java.io.InputStream; +/** + * 【通用基础库】{@code McInputStream} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McInputStream { + /** + * 处理转换为Bytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return 处理结果 + */ public static byte[] toBytes(InputStream is) { try { return ByteStreams.toByteArray(is); @@ -15,6 +33,12 @@ public class McInputStream { } } + /** + * 处理转换为Base64Encoded。 + * + * @param is 参数 {@code is}({@code InputStream}) + * @return 字符串结果 + */ public static String toBase64Encoded(InputStream is) { byte[] bytes = toBytes(is); return bytes == null ? null : BaseEncoding.base64().encode(bytes); diff --git a/src/main/java/com/mitac/cell/io/McJsonFile.java b/src/main/java/com/mitac/cell/io/McJsonFile.java index aef6284..de5c72a 100644 --- a/src/main/java/com/mitac/cell/io/McJsonFile.java +++ b/src/main/java/com/mitac/cell/io/McJsonFile.java @@ -10,56 +10,158 @@ import java.io.File; import java.io.IOException; import java.sql.Date; +/** + * 【通用基础库】{@code McJsonFile} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code KEY_NAME}(String):字段 KEY_NAME
  • + *
  • {@code KEY_OFFSET}(String):字段 KEY_OFFSET
  • + *
  • {@code KEY_SIZE}(String):字段 KEY_SIZE
  • + *
  • {@code KEY_UPDATED}(String):字段 KEY_UPDATED
  • + *
  • {@code KEY_PERMISSION}(String):字段 KEY_PERMISSION
  • + *
  • {@code KEY_DATA}(String):字段 KEY_DATA
  • + *
+ * + * 协作对象:{@code JsonObject}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McJsonFile { + /** + * 字段 KEY_NAME。 + */ private static final String KEY_NAME = "name"; + /** + * 字段 KEY_OFFSET。 + */ private static final String KEY_OFFSET = "offset"; + /** + * 字段 KEY_SIZE。 + */ private static final String KEY_SIZE = "size"; + /** + * 字段 KEY_UPDATED。 + */ private static final String KEY_UPDATED = "updated"; + /** + * 字段 KEY_PERMISSION。 + */ private static final String KEY_PERMISSION = "permission"; + /** + * 字段 KEY_DATA。 + */ private static final String KEY_DATA = "data"; + /** + * j文件。 + */ private JsonObject jFile; + /** + * 构造 {@code McJsonFile} 实例。 + * + * 实现要点:主要调用:new JsonObject。 + * + * @param sourceFile 参数 {@code sourceFile}({@code File}) + */ public McJsonFile(File sourceFile) { this.jFile = new JsonObject(); this.setName(sourceFile.getName()); this.setData(sourceFile); } + /** + * 构造 {@code McJsonFile} 实例。 + * + * 实现要点:主要调用:new File。 + * + * @param filePath 参数 {@code filePath}({@code String}) + */ public McJsonFile(String filePath) { this(new File(filePath)); } + /** + * 构造 {@code McJsonFile} 实例。 + * + * 实现要点:主要调用:new File。 + * + * @param sourceFile 参数 {@code sourceFile}({@code String}) + * @param destinationFile 参数 {@code destinationFile}({@code String}) + */ public McJsonFile(String sourceFile, String destinationFile) { this.setName(destinationFile); this.setData(new File(sourceFile)); } + /** + * 构造 {@code McJsonFile} 实例。 + * + * @param sourceFile 参数 {@code sourceFile}({@code File}) + * @param destinationFile 参数 {@code destinationFile}({@code String}) + */ public McJsonFile(File sourceFile, String destinationFile) { this.setName(destinationFile); this.setData(sourceFile); } + /** + * 构造 {@code McJsonFile} 实例。 + * + * @param destinationFile 参数 {@code destinationFile}({@code String}) + * @param data 参数 {@code data}({@code byte[]}) + */ public McJsonFile(String destinationFile, byte[] data) { this.setName(destinationFile); this.setData(data); } + /** + * 构造 {@code McJsonFile} 实例。 + * + * @param jsonFile 参数 {@code jsonFile}({@code JsonObject}) + */ public McJsonFile(JsonObject jsonFile) { this.jFile = jsonFile; } + /** + * 设置 {@code name}。 + * + * @param name 参数 {@code name}({@code String}) + */ public void setName(String name) { this.jFile.addProperty("name", name); } + /** + * 获取 {@code name}。 + * @return 字符串结果 + */ public String getName() { return this.jFile.getAsJsonPrimitive("name").getAsString(); } + /** + * 处理更新。 + */ public void update() { this.jFile.addProperty("size", this.getData().length); } + /** + * 设置 {@code data}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param file 文件({@code File}) + */ public void setData(File file) { if (file.exists()) { try { @@ -73,6 +175,13 @@ public class McJsonFile { } + /** + * 设置 {@code data}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param data 参数 {@code data}({@code byte[]}) + */ public void setData(byte[] data) { String base64 = McStringUtils.toBase64(data); if (base64 != null) { @@ -82,6 +191,12 @@ public class McJsonFile { } + /** + * 获取 {@code data}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 字段/派生属性 {@code data} 的值 + */ public byte[] getData() { if (this.jFile.has("data")) { JsonPrimitive jPrimitive = this.jFile.getAsJsonPrimitive("data"); @@ -91,33 +206,71 @@ public class McJsonFile { } } + /** + * 处理转换为JSONObject。 + * @return 处理结果 + */ public JsonObject toJsonObject() { JsonElement jsonElement = McJsonUtils.toJsonElement((Object)this.jFile); return jsonElement.getAsJsonObject(); } + /** + * 返回对象的可读字符串表示。 + * @return 字符串结果 + */ public String toString() { return this.jFile.toString(); } + /** + * 处理extract。 + * + * 实现要点:主要调用:new McFile、write。 + * + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void extract(String destinationPath) { McFile file = new McFile(destinationPath, this.getName()); file.write(this.getData()); } + /** + * 处理extract转换为。 + * + * 实现要点:主要调用:new McFile、write。 + * + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void extractTo(String destinationPath) { McFile file = new McFile(destinationPath); file.write(this.getData()); } + /** + * 设置 {@code lastUpdated}。 + * + * @param date 参数 {@code date}({@code Date}) + */ public void setLastUpdated(Date date) { this.setLastUpdated(date.getTime()); } + /** + * 设置 {@code lastUpdated}。 + * + * @param date 参数 {@code date}({@code long}) + */ public void setLastUpdated(long date) { this.jFile.addProperty("updated", date); } + /** + * 获取 {@code lastUpdated}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new Date。 + * @return 字段/派生属性 {@code lastUpdated} 的值 + */ public Date getLastUpdated() { if (this.jFile.has("updated")) { long date = this.jFile.getAsJsonPrimitive("updated").getAsLong(); @@ -127,6 +280,12 @@ public class McJsonFile { } } + /** + * 获取 {@code size}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 数量/长度 + */ public int getSize() { if (this.jFile.has("size")) { int size = this.jFile.getAsJsonPrimitive("size").getAsInt(); @@ -136,6 +295,12 @@ public class McJsonFile { } } + /** + * 获取 {@code offset}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 数量/长度 + */ public int getOffset() { if (this.jFile.has("offset")) { int offset = this.jFile.getAsJsonPrimitive("offset").getAsInt(); @@ -145,10 +310,20 @@ public class McJsonFile { } } + /** + * 设置 {@code offset}。 + * + * @param value 值({@code int}) + */ public void setOffset(int value) { this.jFile.addProperty("offset", value); } + /** + * 设置 {@code permission}。 + * + * @param value 值({@code String}) + */ public void setPermission(String value) { this.jFile.addProperty("permission", value); } diff --git a/src/main/java/com/mitac/cell/io/McResource.java b/src/main/java/com/mitac/cell/io/McResource.java index 0f5275e..d752e98 100644 --- a/src/main/java/com/mitac/cell/io/McResource.java +++ b/src/main/java/com/mitac/cell/io/McResource.java @@ -16,7 +16,30 @@ import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; +/** + * 【通用基础库】{@code McResource} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McResource { + /** + * 复制文件转换为响应。 + * + * 实现要点:包含 8 个条件分支、0 个循环。 + * + * @param servletContext 参数 {@code servletContext}({@code ServletContext}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param file 文件({@code McFile}) + * @param fileName 文件名({@code String}) + * @param lastModified 参数 {@code lastModified}({@code long}) + * @param range 参数 {@code range}({@code String}) + * @param checksum 参数 {@code checksum}({@code long}) + */ public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, long lastModified, String range, long checksum) { Integer to = -1; Integer from = -1; @@ -64,6 +87,18 @@ public class McResource { copyFileToResponse(servletContext, response, file, fileName, from, to); } + /** + * 复制文件转换为响应。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、0 个循环;主要调用:exists。 + * + * @param servletContext 参数 {@code servletContext}({@code ServletContext}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param file 文件({@code McFile}) + * @param fileName 文件名({@code String}) + * @param from 起始时间({@code int}) + * @param to 结束时间({@code int}) + */ public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, McFile file, String fileName, int from, int to) { if (McStringUtils.isNullOrEmpty(fileName)) { fileName = file.getName(); @@ -108,6 +143,15 @@ public class McResource { } + /** + * 复制转换为响应。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:close。 + * + * @param servletContext 参数 {@code servletContext}({@code ServletContext}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param is 参数 {@code is}({@code InputStream}) + */ public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, InputStream is) { try { ByteStreams.copy(is, response.getOutputStream()); @@ -122,6 +166,17 @@ public class McResource { } + /** + * 复制转换为响应。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 3 个条件分支、1 个循环;主要调用:exists、new RandomAccessFile、new BufferedOutputStream、read、write、close。 + * + * @param servletContext 参数 {@code servletContext}({@code ServletContext}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param file 文件({@code File}) + * @param from 起始时间({@code int}) + * @param to 结束时间({@code int}) + */ public static void copyToResponse(ServletContext servletContext, HttpServletResponse response, File file, int from, int to) { try { if (file.exists()) { @@ -154,6 +209,14 @@ public class McResource { } + /** + * 复制转换为响应。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:write。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + * @param image 参数 {@code image}({@code BufferedImage}) + */ public static void copyToResponse(HttpServletResponse response, BufferedImage image) { try { response.setContentType("image/png"); @@ -164,6 +227,16 @@ public class McResource { } + /** + * 复制文件转换为响应。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:write。 + * + * @param servletContext 参数 {@code servletContext}({@code ServletContext}) + * @param response HTTP 响应({@code HttpServletResponse}) + * @param data 参数 {@code data}({@code byte[]}) + * @param fileName 文件名({@code String}) + */ public static void copyFileToResponse(ServletContext servletContext, HttpServletResponse response, byte[] data, String fileName) { response.setContentType(servletContext.getMimeType(fileName)); response.setHeader("Content-Disposition", McHttpClient.toContentDisposition(fileName)); @@ -176,6 +249,11 @@ public class McResource { } + /** + * 设置 {@code noCacheControl}。 + * + * @param response HTTP 响应({@code HttpServletResponse}) + */ public static void setNoCacheControl(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate"); response.setHeader("Expires", "0"); diff --git a/src/main/java/com/mitac/cell/io/McUrl.java b/src/main/java/com/mitac/cell/io/McUrl.java index da9e8bb..c27a5e7 100644 --- a/src/main/java/com/mitac/cell/io/McUrl.java +++ b/src/main/java/com/mitac/cell/io/McUrl.java @@ -12,11 +12,35 @@ import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.InputStreamSource; +/** + * 【通用基础库】{@code McUrl} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McUrl { + /** + * 获取Host。 + * + * @param request HTTP 请求({@code HttpServletRequest}) + * @return 字符串结果 + */ public static String getHost(HttpServletRequest request) { return request == null ? null : getHost(request.getRequestURL().toString()); } + /** + * 获取Host。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。 + * + * @param stringUrl 参数 {@code stringUrl}({@code String}) + * @return 字符串结果 + */ public static String getHost(String stringUrl) { try { URL url = new URL(stringUrl); @@ -26,6 +50,14 @@ public class McUrl { } } + /** + * 处理转换为Bytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new URL。 + * + * @param url 参数 {@code url}({@code String}) + * @return 处理结果 + */ public static byte[] toBytes(String url) { try { return toBytes(new URL(url)); @@ -35,6 +67,14 @@ public class McUrl { } } + /** + * 处理转换为Bytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 处理结果 + */ public static byte[] toBytes(URL url) { try { return Resources.toByteArray(url); @@ -44,21 +84,49 @@ public class McUrl { } } + /** + * 处理转换为Base64Encoded。 + * + * @param url 参数 {@code url}({@code String}) + * @return 字符串结果 + */ public static String toBase64Encoded(String url) { byte[] bytes = toBytes(url); return bytes == null ? null : BaseEncoding.base64().encode(bytes); } + /** + * 处理转换为Base64Encoded。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 字符串结果 + */ public static String toBase64Encoded(URL url) { byte[] bytes = toBytes(url); return bytes == null ? null : BaseEncoding.base64().encode(bytes); } + /** + * 处理转换为InputStreamSource。 + * + * 实现要点:主要调用:new ByteArrayResource。 + * + * @param url 参数 {@code url}({@code String}) + * @return 处理结果 + */ public static InputStreamSource toInputStreamSource(String url) { byte[] bytes = toBytes(url); return bytes == null ? null : new ByteArrayResource(bytes); } + /** + * 处理转换为InputStream。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 处理结果 + */ public static InputStream toInputStream(URL url) { try { return url.openStream(); @@ -68,6 +136,14 @@ public class McUrl { } } + /** + * 处理转换为InputStreamResource。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new InputStreamResource。 + * + * @param url 参数 {@code url}({@code URL}) + * @return 处理结果 + */ public static InputStreamResource toInputStreamResource(URL url) { if (url != null) { InputStream is = toInputStream(url); diff --git a/src/main/java/com/mitac/cell/io/McZipFile.java b/src/main/java/com/mitac/cell/io/McZipFile.java index 0ad202e..5c7b8e1 100644 --- a/src/main/java/com/mitac/cell/io/McZipFile.java +++ b/src/main/java/com/mitac/cell/io/McZipFile.java @@ -13,47 +13,128 @@ import net.lingala.zip4j.model.enums.CompressionLevel; import net.lingala.zip4j.model.enums.CompressionMethod; import net.lingala.zip4j.model.enums.EncryptionMethod; +/** + * 【通用基础库】{@code McZipFile} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
  • {@code zipFile}(ZipFile):zip文件
  • + *
  • {@code zipParams}(ZipParameters):字段 zipParams
  • + *
+ * + * 协作对象:{@code ZipFile、ZipParameters}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McZipFile extends McFile { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = 1L; + /** + * zip文件。 + */ private ZipFile zipFile; + /** + * 字段 zipParams。 + */ private ZipParameters zipParams; + /** + * 构造 {@code McZipFile} 实例。 + * + * @param zipFilePath 参数 {@code zipFilePath}({@code String}) + */ public McZipFile(String zipFilePath) { super(zipFilePath); this.genZipFile(); } + /** + * 构造 {@code McZipFile} 实例。 + * + * @param zipFile 参数 {@code zipFile}({@code File}) + */ public McZipFile(File zipFile) { super(zipFile); this.genZipFile(); } + /** + * 构造 {@code McZipFile} 实例。 + * + * 实现要点:主要调用:new McFile。 + * + * @param folder 参数 {@code folder}({@code String}) + * @param name 参数 {@code name}({@code String}) + */ public McZipFile(String folder, String name) { super(new McFile(folder), name); this.genZipFile(); } + /** + * 构造 {@code McZipFile} 实例。 + * + * @param file 文件({@code File}) + * @param name 参数 {@code name}({@code String}) + */ public McZipFile(File file, String name) { super(file, name); this.genZipFile(); } + /** + * 处理保存。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean save() { return this.saveAs(this, true); } + /** + * 处理保存。 + * + * @param overwrite 参数 {@code overwrite}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean save(boolean overwrite) { return this.saveAs(this, true); } + /** + * 处理genZip文件。 + * + * 实现要点:主要调用:new ZipFile。 + */ private void genZipFile() { this.zipFile = new ZipFile(this.getAbsolutePath()); } + /** + * 判断 {@code zipped}。 + * @return 字段/派生属性 {@code zipped} 的值 + */ public boolean isZipped() { return this.zipFile.isValidZipFile(); } + /** + * 处理compressFolder。 + * + * 实现要点:包含 2 个条件分支、1 个循环;主要调用:new McFile、exists。 + * + * @param folder 参数 {@code folder}({@code String}) + * @param includeFolder 参数 {@code includeFolder}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compressFolder(String folder, boolean includeFolder) { McFile dir = new McFile(folder); if (dir.exists() && !dir.isFile()) { @@ -74,6 +155,14 @@ public class McZipFile extends McFile { } } + /** + * 处理compress。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param filesToBeCompressed 参数 {@code filesToBeCompressed}({@code File[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compress(File... filesToBeCompressed) { String[] paths = new String[filesToBeCompressed.length]; @@ -84,14 +173,38 @@ public class McZipFile extends McFile { return this.compress(paths); } + /** + * 处理compress。 + * + * @param filePathToBeCompressed 参数 {@code filePathToBeCompressed}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compress(String... filePathToBeCompressed) { return this.compress((String)null, true, false, filePathToBeCompressed); } + /** + * 处理compress。 + * + * @param fileName 文件名({@code String}) + * @param input 参数 {@code input}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compress(String fileName, InputStream input) { return this.compress((String)null, true, false, fileName, input); } + /** + * 处理compress。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 6 个条件分支、1 个循环;主要调用:exists、new McFile、delete。 + * + * @param password 密码({@code String}) + * @param overwriteIfExists 参数 {@code overwriteIfExists}({@code boolean}) + * @param deleteOnSucceed 参数 {@code deleteOnSucceed}({@code boolean}) + * @param pathsToBeCompressed 参数 {@code pathsToBeCompressed}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String... pathsToBeCompressed) { if (!this.exists() || !this.isDirectory() && overwriteIfExists && pathsToBeCompressed != null) { if (!this.getParentFile().exists()) { @@ -132,6 +245,18 @@ public class McZipFile extends McFile { } } + /** + * 处理compress。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:close。 + * + * @param password 密码({@code String}) + * @param overwriteIfExists 参数 {@code overwriteIfExists}({@code boolean}) + * @param deleteOnSucceed 参数 {@code deleteOnSucceed}({@code boolean}) + * @param fileName 文件名({@code String}) + * @param input 参数 {@code input}({@code InputStream}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compress(String password, boolean overwriteIfExists, boolean deleteOnSucceed, String fileName, InputStream input) { if (input != null && !Strings.isNullOrEmpty(fileName)) { try { @@ -157,6 +282,15 @@ public class McZipFile extends McFile { } } + /** + * 处理compressAs。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:exists。 + * + * @param file 文件({@code File}) + * @param name 参数 {@code name}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean compressAs(File file, String name) { if (file != null && file.exists()) { try { @@ -173,14 +307,38 @@ public class McZipFile extends McFile { } } + /** + * 处理extract。 + * + * @param extractTo 参数 {@code extractTo}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean extract(String extractTo) { return this.extract(extractTo, (String)null, false, false); } + /** + * 处理extract。 + * + * @param extractTo 参数 {@code extractTo}({@code String}) + * @param password 密码({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean extract(String extractTo, String password) { return this.extract(extractTo, password, false, false); } + /** + * 处理extract。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、0 个循环;主要调用:new ZipFile、close、new McFile、exists、delete。 + * + * @param extractTo 参数 {@code extractTo}({@code String}) + * @param password 密码({@code String}) + * @param deleteOnExists 参数 {@code deleteOnExists}({@code boolean}) + * @param deleteOnSuccess 参数 {@code deleteOnSuccess}({@code boolean}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean extract(String extractTo, String password, boolean deleteOnExists, boolean deleteOnSuccess) { if (this.isDirectory()) { return false; @@ -215,14 +373,35 @@ public class McZipFile extends McFile { } } + /** + * 获取ZipParams。 + * + * @param deflateLevel 参数 {@code deflateLevel}({@code int}) + * @return 字段/派生属性 {@code zipParams} 的值 + */ public ZipParameters getZipParams(int deflateLevel) { return this.getZipParams(this.getLevel(deflateLevel), false); } + /** + * 获取ZipParams。 + * + * @param hasPassword 参数 {@code hasPassword}({@code boolean}) + * @return 字段/派生属性 {@code zipParams} 的值 + */ public ZipParameters getZipParams(boolean hasPassword) { return this.getZipParams(CompressionLevel.NORMAL, hasPassword); } + /** + * 获取ZipParams。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ZipParameters。 + * + * @param deflateLevel 参数 {@code deflateLevel}({@code CompressionLevel}) + * @param hasPassword 参数 {@code hasPassword}({@code boolean}) + * @return 字段/派生属性 {@code zipParams} 的值 + */ public ZipParameters getZipParams(CompressionLevel deflateLevel, boolean hasPassword) { ZipParameters zParams = new ZipParameters(); zParams.setCompressionMethod(CompressionMethod.DEFLATE); @@ -235,6 +414,14 @@ public class McZipFile extends McFile { return zParams; } + /** + * 获取Level。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param level 参数 {@code level}({@code int}) + * @return 字段/派生属性 {@code level} 的值 + */ private CompressionLevel getLevel(int level) { for(CompressionLevel compressionLevel : CompressionLevel.values()) { if (compressionLevel.getLevel() == level) { diff --git a/src/main/java/com/mitac/cell/io/Vector2Svg.java b/src/main/java/com/mitac/cell/io/Vector2Svg.java index e2ef2c3..2ab5693 100644 --- a/src/main/java/com/mitac/cell/io/Vector2Svg.java +++ b/src/main/java/com/mitac/cell/io/Vector2Svg.java @@ -23,25 +23,80 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; +/** + * 【通用基础库】{@code Vector2Svg} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code source}(InputStream):字段 source
  • + *
+ * + * 协作对象:{@code InputStream}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class Vector2Svg { + /** + * 字段 source。 + */ private final InputStream source; + /** + * 构造 {@code Vector2Svg} 实例。 + * + * 实现要点:主要调用:new File。 + * + * @param source 参数 {@code source}({@code String}) + * @throws FileNotFoundException 当 FileNotFoundException 条件不满足或底层调用失败时抛出。 + */ public Vector2Svg(String source) throws FileNotFoundException { this(new File(source)); } + /** + * 构造 {@code Vector2Svg} 实例。 + * + * 实现要点:主要调用:new FileInputStream。 + * + * @param source 参数 {@code source}({@code File}) + * @throws FileNotFoundException 当 FileNotFoundException 条件不满足或底层调用失败时抛出。 + */ public Vector2Svg(File source) throws FileNotFoundException { this((InputStream)(new FileInputStream(source))); } + /** + * 构造 {@code Vector2Svg} 实例。 + * + * 实现要点:主要调用:new ByteArrayInputStream。 + * + * @param data 参数 {@code data}({@code byte[]}) + */ public Vector2Svg(byte[] data) { this((InputStream)(new ByteArrayInputStream(data))); } + /** + * 构造 {@code Vector2Svg} 实例。 + * + * @param source 参数 {@code source}({@code InputStream}) + */ public Vector2Svg(InputStream source) { this.source = source; } + /** + * 处理转换为SvgBytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、3 个循环;主要调用:new DOMSource、new ByteArrayOutputStream、new StreamResult。 + * @return 处理结果 + */ public byte[] toSvgBytes() { try { AndroidVectorDrawable drawable = this.getDrawable(); @@ -91,6 +146,15 @@ public class Vector2Svg { } } + /** + * 获取 {@code drawable}。 + * + * 实现要点:包含 6 个条件分支、3 个循环;主要调用:new ArrayList、new Group、new AndroidVectorDrawable。 + * @return 字段/派生属性 {@code drawable} 的值 + * @throws ParserConfigurationException 当 ParserConfigurationException 条件不满足或底层调用失败时抛出。 + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + * @throws SAXException 当 SAXException 条件不满足或底层调用失败时抛出。 + */ private AndroidVectorDrawable getDrawable() throws ParserConfigurationException, IOException, SAXException { Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(this.source); xml.getDocumentElement().normalize(); @@ -137,6 +201,14 @@ public class Vector2Svg { return new AndroidVectorDrawable(paths, groups, width, height); } + /** + * 获取Double。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param nodeValue 参数 {@code nodeValue}({@code String}) + * @return 字段/派生属性 {@code double} 的值 + */ private Double getDouble(String nodeValue) { if (nodeValue.startsWith("{")) { String[] token = nodeValue.split(":"); @@ -148,6 +220,14 @@ public class Vector2Svg { } } + /** + * 获取Vector路径从Node。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:new VectorPath。 + * + * @param item 参数 {@code item}({@code Node}) + * @return 字段/派生属性 {@code vectorPathFromNode} 的值 + */ private VectorPath getVectorPathFromNode(Node item) { if (item.getNodeName().equals("path")) { String pathData = null; @@ -177,6 +257,14 @@ public class Vector2Svg { return null; } + /** + * 处理normalized路径数据。 + * + * 实现要点:包含 1 个条件分支、1 个循环;主要调用:new StringBuilder。 + * + * @param value 值({@code String}) + * @return 字符串结果 + */ private String normalizedPathData(String value) { StringBuilder sb = new StringBuilder(); @@ -192,30 +280,122 @@ public class Vector2Svg { return sb.toString(); } + /** + * 【通用基础库】{@code VectorPath} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code pathData}(String):路径数据
  • + *
  • {@code fillColor}(String):字段 fillColor
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ private class VectorPath { + /** + * 路径数据。 + */ private String pathData; + /** + * 字段 fillColor。 + */ private String fillColor; + /** + * 构造 {@code VectorPath} 实例。 + * + * @param pathData 参数 {@code pathData}({@code String}) + * @param fillColor 参数 {@code fillColor}({@code String}) + */ private VectorPath(String pathData, String fillColor) { this.pathData = pathData; this.fillColor = fillColor; } } + /** + * 【通用基础库】{@code Group} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code paths}(List):Vector路径集合
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ private class Group { + /** + * Vector路径集合。 + */ private final List paths; + /** + * 构造 {@code Group} 实例。 + * + * @param paths 对象存储路径片段({@code List}) + */ public Group(List paths) { this.paths = paths; } } + /** + * 【通用基础库】{@code AndroidVectorDrawable} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code paths}(List):Vector路径集合
  • + *
  • {@code groups}(List):分组列表
  • + *
  • {@code height}(double):字段 height
  • + *
  • {@code width}(double):字段 width
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ private class AndroidVectorDrawable { + /** + * Vector路径集合。 + */ private final List paths; + /** + * 分组列表。 + */ private final List groups; + /** + * 字段 height。 + */ private final double height; + /** + * 字段 width。 + */ private final double width; + /** + * 构造 {@code AndroidVectorDrawable} 实例。 + * + * @param paths 对象存储路径片段({@code List}) + * @param groups 参数 {@code groups}({@code List}) + * @param width 参数 {@code width}({@code double}) + * @param height 参数 {@code height}({@code double}) + */ private AndroidVectorDrawable(List paths, List groups, double width, double height) { this.paths = paths; this.groups = groups; diff --git a/src/main/java/com/mitac/cell/io/package-info.java b/src/main/java/com/mitac/cell/io/package-info.java new file mode 100644 index 0000000..4fb8a58 --- /dev/null +++ b/src/main/java/com/mitac/cell/io/package-info.java @@ -0,0 +1,22 @@ +/** + * 包 {@code com.mitac.cell.io}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link ApkSign}
  • + *
  • {@link McApkFile}
  • + *
  • {@link McEncryptedFileDrive}
  • + *
  • {@link McFile}
  • + *
  • {@link McFileTable}
  • + *
  • {@link McInputStream}
  • + *
  • {@link McJsonFile}
  • + *
  • {@link McResource}
  • + *
  • {@link McUrl}
  • + *
  • {@link McZipFile}
  • + *
  • {@link Vector2Svg}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.io; diff --git a/src/main/java/com/mitac/cell/map/GeoCode.java b/src/main/java/com/mitac/cell/map/GeoCode.java index 7f8367c..4fd09c2 100644 --- a/src/main/java/com/mitac/cell/map/GeoCode.java +++ b/src/main/java/com/mitac/cell/map/GeoCode.java @@ -7,7 +7,27 @@ import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; +/** + * 【通用基础库】{@code GeoCode} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class GeoCode { + /** + * 获取Address。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new OkHttpClient、new Builder。 + * + * @param apiKey 参数 {@code apiKey}({@code String}) + * @param latitude 参数 {@code latitude}({@code String}) + * @param longitude 参数 {@code longitude}({@code String}) + * @return 字符串结果 + */ public static String getAddress(String apiKey, String latitude, String longitude) { try { String url = String.format("https://maps.googleapis.com/maps/api/geocode/json?latlng=%s,%s&key=%s", latitude, longitude, apiKey); diff --git a/src/main/java/com/mitac/cell/map/package-info.java b/src/main/java/com/mitac/cell/map/package-info.java new file mode 100644 index 0000000..c4568f1 --- /dev/null +++ b/src/main/java/com/mitac/cell/map/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.map}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link GeoCode}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.map; diff --git a/src/main/java/com/mitac/cell/must/MustBuilder.java b/src/main/java/com/mitac/cell/must/MustBuilder.java index fd726d2..3826800 100644 --- a/src/main/java/com/mitac/cell/must/MustBuilder.java +++ b/src/main/java/com/mitac/cell/must/MustBuilder.java @@ -19,29 +19,95 @@ import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException; import org.yaml.snakeyaml.Yaml; +/** + * 【通用基础库】{@code MustBuilder} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DEFAULT_KEY}(byte[]):字段 DEFAULT_KEY
  • + *
  • {@code DEFAULT_SRC_FILE}(String):字段 DEFAULT_SRC_FILE
  • + *
  • {@code format}(String):格式化
  • + *
  • {@code sourceFile}(McFile):source文件
  • + *
  • {@code outputFile}(McFile):output文件
  • + *
  • {@code mustObject}(JsonObject):字段 mustObject
  • + *
+ * + * 协作对象:{@code McFile、JsonObject}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class MustBuilder { + /** + * 字段 DEFAULT_KEY。 + */ private static byte[] DEFAULT_KEY = "MUST@mitac".getBytes(); + /** + * 字段 DEFAULT_SRC_FILE。 + */ private static String DEFAULT_SRC_FILE = "must.must"; + /** + * 格式化。 + */ private String format; + /** + * source文件。 + */ private McFile sourceFile; + /** + * output文件。 + */ private McFile outputFile; + /** + * 字段 mustObject。 + */ private JsonObject mustObject; + /** + * 构造 {@code MustBuilder} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public MustBuilder() { } + /** + * 构造 {@code MustBuilder} 实例。 + * + * @param mustObject 参数 {@code mustObject}({@code JsonObject}) + */ public MustBuilder(JsonObject mustObject) { this.mustObject = mustObject; } + /** + * 获取 {@code source}。 + * @return 字段/派生属性 {@code source} 的值 + */ public McFile getSource() { return this.sourceFile; } + /** + * 获取 {@code sourcePath}。 + * @return 字符串结果 + */ public String getSourcePath() { return this.sourceFile.getAbsolutePath(); } + /** + * 设置 {@code source}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile、exists。 + * + * @param path 参数 {@code path}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setSource(String path) { if (Strings.isNullOrEmpty(path)) { this.sourceFile = new McFile(".", DEFAULT_SRC_FILE); @@ -55,10 +121,22 @@ public class MustBuilder { return this.isSourceExists(); } + /** + * 判断 {@code sourceExists}。 + * + * 实现要点:主要调用:exists。 + * @return 字段/派生属性 {@code sourceExists} 的值 + */ public boolean isSourceExists() { return this.sourceFile != null && this.sourceFile.exists(); } + /** + * 获取 {@code format}。 + * + * 实现要点:包含 3 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getFormat() { if (Strings.isNullOrEmpty(this.format)) { String ext = this.sourceFile.getExtension(); @@ -77,6 +155,14 @@ public class MustBuilder { return this.format; } + /** + * 设置 {@code format}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param format 参数 {@code format}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean setFormat(String format) { if (!format.equals("xml") && !format.equals("json") && !format.equals("yaml")) { return false; @@ -86,14 +172,29 @@ public class MustBuilder { } } + /** + * 获取 {@code output}。 + * @return 字段/派生属性 {@code output} 的值 + */ public McFile getOutput() { return this.outputFile; } + /** + * 获取 {@code outputPath}。 + * @return 字符串结果 + */ public String getOutputPath() { return this.outputFile.getAbsolutePath(); } + /** + * 设置 {@code output}。 + * + * 实现要点:包含 2 个条件分支、0 个循环;主要调用:new McFile、exists。 + * + * @param path 参数 {@code path}({@code String}) + */ public void setOutput(String path) { if (Strings.isNullOrEmpty(path)) { this.outputFile = new McFile(this.sourceFile.getParent(), this.sourceFile.getNameWithoutExtension() + ".mst"); @@ -106,6 +207,17 @@ public class MustBuilder { } + /** + * 处理构建。 + * + * 实现要点:包含 5 个条件分支、0 个循环;主要调用:new McXml、new FileReader、new Yaml、new GsonBuilder。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + * @throws IOException 当 IOException 条件不满足或底层调用失败时抛出。 + * @throws JsonIOException 当 JsonIOException 条件不满足或底层调用失败时抛出。 + * @throws JsonSyntaxException 当 JsonSyntaxException 条件不满足或底层调用失败时抛出。 + * @throws ParserConfigurationException 当 ParserConfigurationException 条件不满足或底层调用失败时抛出。 + * @throws SAXException 当 SAXException 条件不满足或底层调用失败时抛出。 + */ public boolean build() throws IOException, JsonIOException, JsonSyntaxException, ParserConfigurationException, SAXException { this.mustObject = null; String format = this.getFormat(); @@ -130,6 +242,14 @@ public class MustBuilder { return this.hasContents(); } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;主要调用:new McEncryptedFileDrive、save。 + * + * @param destPath 参数 {@code destPath}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean save(String destPath) { this.setOutput(destPath); McFile destFile = this.outputFile; @@ -141,6 +261,12 @@ public class MustBuilder { return true; } + /** + * 处理保存。 + * + * 实现要点:调用持久化方法保存数据;包含 1 个条件分支、0 个循环;主要调用:new McEncryptedFileDrive、save。 + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean save() { if (this.outputFile == null) { this.setOutput((String)null); @@ -155,10 +281,20 @@ public class MustBuilder { return true; } + /** + * 判断 {@code contents}。 + * @return 字段/派生属性 {@code contents} 的值 + */ public boolean hasContents() { return this.mustObject != null && this.mustObject.size() > 0; } + /** + * 返回对象的可读字符串表示。 + * + * 实现要点:主要调用:new GsonBuilder。 + * @return 字符串结果 + */ public String toString() { return this.hasContents() ? (new GsonBuilder()).setPrettyPrinting().create().toJson(this.mustObject) : "No configurations."; } diff --git a/src/main/java/com/mitac/cell/must/package-info.java b/src/main/java/com/mitac/cell/must/package-info.java new file mode 100644 index 0000000..d2d5dd3 --- /dev/null +++ b/src/main/java/com/mitac/cell/must/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.must}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link MustBuilder}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.must; diff --git a/src/main/java/com/mitac/cell/net/McNetUtils.java b/src/main/java/com/mitac/cell/net/McNetUtils.java index d220813..fa52064 100644 --- a/src/main/java/com/mitac/cell/net/McNetUtils.java +++ b/src/main/java/com/mitac/cell/net/McNetUtils.java @@ -17,10 +17,43 @@ import java.util.List; import java.util.Scanner; import java.util.regex.Pattern; +/** + * 【通用基础库】{@code McNetUtils} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code netMaskArray}(String[]):字段 netMaskArray
  • + *
  • {@code IPv4RegexPattern}(Pattern):字段 IPv4RegexPattern
  • + *
+ * + * 协作对象:{@code String[]、Pattern}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McNetUtils { + /** + * 字段 netMaskArray。 + */ private static final String[] netMaskArray = new String[]{"255.255.255.255", "255.255.255.254", "255.255.255.252", "255.255.255.248", "255.255.255.240", "255.255.255.224", "255.255.255.192", "255.255.255.128", "255.255.255.0", "255.255.254.0", "255.255.252.0", "255.255.248.0", "255.255.240.0", "255.255.224.0", "255.255.192.0", "255.255.128.0", "255.255.0.0", "255.254.0.0", "255.252.0.0", "255.248.0.0", "255.240.0.0", "255.224.0.0", "255.192.0.0", "255.128.0.0", "255.0.0.0", "254.0.0.0", "252.0.0.0", "248.0.0.0", "240.0.0.0", "224.0.0.0", "192.0.0.0", "128.0.0.0", "0.0.0.0"}; + /** + * 字段 IPv4RegexPattern。 + */ private static final Pattern IPv4RegexPattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.) {3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + /** + * 处理转换为Int。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param hostName 参数 {@code hostName}({@code String}) + * @return 数量/长度 + */ public static int toInt(String hostName) { try { InetAddress inetAddress = InetAddress.getByName(hostName); @@ -34,6 +67,14 @@ public class McNetUtils { } } + /** + * 处理转换为Address。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param ipAddress 参数 {@code ipAddress}({@code int}) + * @return 处理结果 + */ public static InetAddress toAddress(int ipAddress) { byte[] byteArray = McNumberUtils.toBytes(4, false, ipAddress); @@ -45,6 +86,14 @@ public class McNetUtils { } } + /** + * 处理转换为PrefixLength。 + * + * 实现要点:包含 1 个条件分支、1 个循环。 + * + * @param netMask 参数 {@code netMask}({@code String}) + * @return 数量/长度 + */ public static int toPrefixLength(String netMask) { int prefixLength = 0; @@ -58,10 +107,24 @@ public class McNetUtils { return prefixLength; } + /** + * 处理转换为NetMask。 + * + * @param prefixLength 参数 {@code prefixLength}({@code int}) + * @return 字符串结果 + */ public static String toNetMask(int prefixLength) { return netMaskArray[prefixLength]; } + /** + * 处理ip转换为Long。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param ipAddress 参数 {@code ipAddress}({@code String}) + * @return 数量/长度 + */ public static long ipToLong(String ipAddress) { try { return ipToLong(InetAddress.getByName(ipAddress)); @@ -71,15 +134,33 @@ public class McNetUtils { } } + /** + * 处理ip转换为Long。 + * + * @param inetAddr 参数 {@code inetAddr}({@code InetAddress}) + * @return 数量/长度 + */ public static long ipToLong(InetAddress inetAddr) { byte[] rawIp = inetAddr.getAddress(); return (((long)rawIp[0] & 255L) << 24) + (((long)rawIp[1] & 255L) << 16) + (((long)rawIp[2] & 255L) << 8) + ((long)rawIp[3] & 255L); } + /** + * 处理long转换为Ip。 + * + * @param i 参数 {@code i}({@code long}) + * @return 字符串结果 + */ public static String longToIp(long i) { return (i >> 24 & 255L) + "." + (i >> 16 & 255L) + "." + (i >> 8 & 255L) + "." + (i & 255L); } + /** + * 处理host名称。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new Scanner。 + * @return 字符串结果 + */ public static String hostName() { try { String hostName = InetAddress.getLocalHost().getHostName(); @@ -100,6 +181,14 @@ public class McNetUtils { return null; } + /** + * 判断是否VmMacAddress。 + * + * 实现要点:包含 3 个条件分支、1 个循环。 + * + * @param mac 参数 {@code mac}({@code byte[]}) + * @return 字段/派生属性 {@code vmMacAddress} 的值 + */ public static boolean isVmMacAddress(byte[] mac) { if (null == mac) { return true; @@ -118,11 +207,23 @@ public class McNetUtils { } } + /** + * 处理转换为MacAddressString。 + * + * @param macAddrBytes 参数 {@code macAddrBytes}({@code byte[]}) + * @return 字符串结果 + */ public static String toMacAddressString(byte[] macAddrBytes) { return BaseEncoding.base16().withSeparator(":", 2).encode(macAddrBytes); } - public static List macAddress() { + /** + * 处理macAddress。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new ArrayList。 + * @return byte[]列表,可能为空 + */ + public static List macAddress() { try { Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces(); List macList = new ArrayList(); @@ -144,6 +245,14 @@ public class McNetUtils { } } + /** + * 获取Host。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * + * @param hostName 参数 {@code hostName}({@code String}) + * @return 字符串结果 + */ public static String getHost(String hostName) { if (!Strings.isNullOrEmpty(hostName)) { hostName = hostName.trim(); @@ -158,11 +267,23 @@ public class McNetUtils { } } + /** + * 获取 {@code macAddr}。 + * @return 字段/派生属性 {@code macAddr} 的值 + */ public static byte[] getMacAddr() { List macAddresses = macAddress(); return macAddresses != null && macAddresses.size() > 0 ? (byte[])macAddress().get(0) : null; } + /** + * 处理ipAddress。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param inetAddress 参数 {@code inetAddress}({@code InetAddress}) + * @return 字符串结果 + */ public static String ipAddress(InetAddress inetAddress) { if (inetAddress == null) { return null; @@ -172,6 +293,13 @@ public class McNetUtils { } } + /** + * 获取 {@code ipAddress}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、2 个循环;主要调用:new RuntimeException。 + * @return 字符串结果 + * @throws RuntimeException 当 RuntimeException 条件不满足或底层调用失败时抛出。 + */ public static String getIpAddress() { String ip = null; @@ -198,6 +326,12 @@ public class McNetUtils { } } + /** + * 处理校验。 + * + * @param ip 参数 {@code ip}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public static boolean validate(String ip) { return IPv4RegexPattern.matcher(ip).matches(); } diff --git a/src/main/java/com/mitac/cell/net/Uri.java b/src/main/java/com/mitac/cell/net/Uri.java index c0f031a..4ef24ff 100644 --- a/src/main/java/com/mitac/cell/net/Uri.java +++ b/src/main/java/com/mitac/cell/net/Uri.java @@ -5,19 +5,55 @@ import java.net.URI; import java.util.ArrayList; import java.util.List; +/** + * 【通用基础库】{@code Uri} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code uri}(URI):URI
  • + *
+ * + * 协作对象:{@code URI}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class Uri { + /** + * URI。 + */ private URI uri; + /** + * 构造 {@code Uri} 实例。 + * + * @param uri 参数 {@code uri}({@code String}) + */ public Uri(String uri) { this.uri = URI.create(uri); } + /** + * 处理paths。 + * @return 处理结果 + */ public String[] paths() { String path = this.uri.getPath(); return Strings.isNullOrEmpty(path) ? new String[0] : this.uri.getPath().split("/"); } - public List getPathSegments() { + /** + * 获取 {@code pathSegments}。 + * + * 实现要点:包含 0 个条件分支、1 个循环;主要调用:new ArrayList。 + * @return String列表,可能为空 + */ + public List getPathSegments() { ArrayList list = new ArrayList(); for(String path : this.paths()) { @@ -27,6 +63,14 @@ public class Uri { return list; } + /** + * 处理解析。 + * + * 实现要点:主要调用:new Uri。 + * + * @param uri 参数 {@code uri}({@code String}) + * @return 处理结果 + */ public static Uri parse(String uri) { return new Uri(uri); } diff --git a/src/main/java/com/mitac/cell/net/package-info.java b/src/main/java/com/mitac/cell/net/package-info.java new file mode 100644 index 0000000..b7e0afa --- /dev/null +++ b/src/main/java/com/mitac/cell/net/package-info.java @@ -0,0 +1,13 @@ +/** + * 包 {@code com.mitac.cell.net}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McNetUtils}
  • + *
  • {@link Uri}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.net; diff --git a/src/main/java/com/mitac/cell/security/McBase64.java b/src/main/java/com/mitac/cell/security/McBase64.java index 8530fd4..11794a9 100644 --- a/src/main/java/com/mitac/cell/security/McBase64.java +++ b/src/main/java/com/mitac/cell/security/McBase64.java @@ -4,19 +4,55 @@ import com.google.common.base.Strings; import com.google.common.io.BaseEncoding; import java.io.UnsupportedEncodingException; +/** + * 【通用基础库】{@code McBase64} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McBase64 { + /** + * 处理转换为Base64。 + * + * @param source 参数 {@code source}({@code String}) + * @return 字符串结果 + */ public static String toBase64(String source) { return Strings.isNullOrEmpty(source) ? null : toBase64(source.getBytes()); } + /** + * 处理转换为Base64。 + * + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @return 字符串结果 + */ public static String toBase64(byte[] bytes) { return bytes == null ? null : BaseEncoding.base64().encode(bytes); } + /** + * 处理从Base64。 + * + * @param source 参数 {@code source}({@code String}) + * @return 处理结果 + */ public static byte[] fromBase64(String source) { return Strings.isNullOrEmpty(source) ? null : BaseEncoding.base64().decode(source); } + /** + * 处理从Base64转换为String。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new String。 + * + * @param source 参数 {@code source}({@code String}) + * @return 字符串结果 + */ public static String fromBase64ToString(String source) { if (Strings.isNullOrEmpty(source)) { return null; diff --git a/src/main/java/com/mitac/cell/security/McCrypto.java b/src/main/java/com/mitac/cell/security/McCrypto.java index 2cc4e73..817a241 100644 --- a/src/main/java/com/mitac/cell/security/McCrypto.java +++ b/src/main/java/com/mitac/cell/security/McCrypto.java @@ -38,34 +38,119 @@ import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; +/** + * 【通用基础库】{@code McCrypto} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code ENCRYPT_MODE}(int):字段 ENCRYPT_MODE
  • + *
  • {@code DECRYPT_MODE}(int):字段 DECRYPT_MODE
  • + *
  • {@code CIPHER_ALGORITHM}(String):字段 CIPHER_ALGORITHM
  • + *
  • {@code PBE_ALGORITHM}(String):字段 PBE_ALGORITHM
  • + *
  • {@code RANDOM_ALGORITHM}(String):字段 RANDOM_ALGORITHM
  • + *
  • {@code mKeyLength}(int):m密钥Length
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McCrypto { + /** + * 字段 ENCRYPT_MODE。 + */ public static final int ENCRYPT_MODE = 1; + /** + * 字段 DECRYPT_MODE。 + */ public static final int DECRYPT_MODE = 2; + /** + * 字段 CIPHER_ALGORITHM。 + */ private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; + /** + * 字段 PBE_ALGORITHM。 + */ private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; + /** + * 字段 RANDOM_ALGORITHM。 + */ private static final String RANDOM_ALGORITHM = "SHA1PRNG"; + /** + * m密钥Length。 + */ private int mKeyLength; + /** + * 字段 mAlgorithm。 + */ private String mAlgorithm; + /** + * m密钥。 + */ private byte[] mKey; + /** + * 字段 mSource。 + */ private byte[] mSource; + /** + * 字段 mTarget。 + */ private byte[] mTarget; + /** + * m初始化Vector。 + */ private byte[] mInitVector; + /** + * mPrivate密钥。 + */ private byte[] mPrivateKey; + /** + * 字段 mCipherMode。 + */ private int mCipherMode; + /** + * m文件Header。 + */ private byte[] mFileHeader; + /** + * 构造 {@code McCrypto} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public McCrypto() { this(1, "AES/CBC/PKCS5Padding", 128); } + /** + * 构造 {@code McCrypto} 实例。 + * + * @param cipherMode 参数 {@code cipherMode}({@code int}) + */ public McCrypto(int cipherMode) { this(cipherMode, "AES/CBC/PKCS5Padding", 128); } + /** + * 构造 {@code McCrypto} 实例。 + * + * @param cipherMode 参数 {@code cipherMode}({@code int}) + * @param algorithm 参数 {@code algorithm}({@code String}) + */ public McCrypto(int cipherMode, String algorithm) { this(cipherMode, algorithm, 128); } + /** + * 构造 {@code McCrypto} 实例。 + * + * @param cipherMode 参数 {@code cipherMode}({@code int}) + * @param algorithm 参数 {@code algorithm}({@code String}) + * @param keyLength 参数 {@code keyLength}({@code int}) + */ public McCrypto(int cipherMode, String algorithm, int keyLength) { this.mCipherMode = 1; this.mCipherMode = cipherMode; @@ -73,26 +158,57 @@ public class McCrypto { this.mAlgorithm = algorithm; } + /** + * 设置 {@code fileHeader}。 + * + * @param header 参数 {@code header}({@code byte[]}) + */ public void setFileHeader(byte[] header) { this.mFileHeader = header; } + /** + * 设置 {@code fileHeader}。 + * + * @param header 参数 {@code header}({@code String}) + */ public void setFileHeader(String header) { this.setFileHeader(header.getBytes()); } + /** + * 获取 {@code fileHeader}。 + * @return 字段/派生属性 {@code fileHeader} 的值 + */ public byte[] getFileHeader() { return this.mFileHeader; } + /** + * 设置 {@code key}。 + * + * @param key 键/配置项({@code String}) + */ public void setKey(String key) { this.mKey = key.getBytes(); } + /** + * 设置 {@code key}。 + * + * @param key 键/配置项({@code byte[]}) + */ public void setKey(byte[] key) { this.mKey = key; } + /** + * 设置 {@code source}。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ByteArrayInputStream。 + * + * @param source 参数 {@code source}({@code byte[]}) + */ public void setSource(byte[] source) { if (this.mCipherMode == 2) { this.setSource((InputStream)(new ByteArrayInputStream(source))); @@ -102,10 +218,22 @@ public class McCrypto { } + /** + * 设置 {@code source}。 + * + * @param source 参数 {@code source}({@code String}) + */ public void setSource(String source) { this.setSource(source.getBytes()); } + /** + * 设置 {@code sourcePath}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileInputStream。 + * + * @param sourcePath 参数 {@code sourcePath}({@code String}) + */ public void setSourcePath(String sourcePath) { try { this.setSource((InputStream)(new FileInputStream(sourcePath))); @@ -115,6 +243,13 @@ public class McCrypto { } + /** + * 设置 {@code source}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 8 个条件分支、1 个循环;主要调用:read、new GZIPInputStream、new BufferedInputStream、new ByteArrayOutputStream、write、close。 + * + * @param sourceStream 参数 {@code sourceStream}({@code InputStream}) + */ public void setSource(InputStream sourceStream) { try { if (this.mCipherMode == 2) { @@ -181,6 +316,13 @@ public class McCrypto { } + /** + * 处理保存。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new FileOutputStream、write、close。 + * + * @param destinationPath 参数 {@code destinationPath}({@code String}) + */ public void save(String destinationPath) { try { FileOutputStream stream = new FileOutputStream(destinationPath); @@ -195,6 +337,12 @@ public class McCrypto { } + /** + * 获取 {@code encryptedDataHeader}。 + * + * 实现要点:包含 4 个条件分支、5 个循环。 + * @return 字段/派生属性 {@code encryptedDataHeader} 的值 + */ private byte[] getEncryptedDataHeader() { int size = 12; int pkLen = 0; @@ -242,14 +390,30 @@ public class McCrypto { return header; } + /** + * 获取 {@code inputStream}。 + * + * 实现要点:主要调用:new ByteArrayInputStream。 + * @return 字段/派生属性 {@code inputStream} 的值 + */ public InputStream getInputStream() { return this.mTarget != null ? new ByteArrayInputStream(this.mTarget) : null; } + /** + * 获取 {@code raw}。 + * @return 字段/派生属性 {@code raw} 的值 + */ public byte[] getRaw() { return this.mTarget; } + /** + * 获取 {@code bytes}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、0 个循环;主要调用:new ByteArrayOutputStream、write、new GZIPOutputStream、close。 + * @return 字段/派生属性 {@code bytes} 的值 + */ public byte[] getBytes() { if (this.mCipherMode == 1) { try { @@ -278,18 +442,38 @@ public class McCrypto { } } + /** + * 获取 {@code initVector}。 + * @return 字段/派生属性 {@code initVector} 的值 + */ public byte[] getInitVector() { return this.mInitVector; } + /** + * 获取 {@code privateKey}。 + * @return 字段/派生属性 {@code privateKey} 的值 + */ public byte[] getPrivateKey() { return this.mPrivateKey; } + /** + * 执行本次任务的主体逻辑。 + * + * 实现要点:主要调用:encrypt、decrypt。 + * @return 处理结果 + */ public byte[] run() { return this.mCipherMode == 1 ? this.encrypt() : this.decrypt(); } + /** + * 处理加密。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 处理结果 + */ private byte[] encrypt() { this.mTarget = null; if (this.mAlgorithm.toUpperCase().equals("RC4")) { @@ -301,6 +485,12 @@ public class McCrypto { return this.mTarget; } + /** + * 处理解密。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * @return 处理结果 + */ private byte[] decrypt() { this.mTarget = null; if (this.mAlgorithm.toUpperCase().equals("RC4")) { @@ -312,6 +502,15 @@ public class McCrypto { return this.mTarget; } + /** + * 初始化Cipher。 + * + * 实现要点:包含 10 个条件分支、0 个循环;主要调用:new IvParameterSpec。 + * + * @param cipher 参数 {@code cipher}({@code Cipher}) + * @throws InvalidKeyException 当 InvalidKeyException 条件不满足或底层调用失败时抛出。 + * @throws InvalidAlgorithmParameterException 当 InvalidAlgorithmParameterException 条件不满足或底层调用失败时抛出。 + */ private void initCipher(Cipher cipher) throws InvalidKeyException, InvalidAlgorithmParameterException { if (this.mCipherMode == 1 && !this.mAlgorithm.contains("ECB") && !this.mAlgorithm.contains("RSA")) { this.mInitVector = this.generateIvSpec(); @@ -347,6 +546,12 @@ public class McCrypto { } + /** + * 生成IvSpec。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * @return 处理结果 + */ private byte[] generateIvSpec() { try { int count = 16; @@ -364,6 +569,15 @@ public class McCrypto { } } + /** + * 获取AES密钥。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 0 个条件分支、1 个循环;主要调用:new PBEKeySpec、new SecretKeySpec。 + * + * @param key 键/配置项({@code byte[]}) + * @param keyLength 参数 {@code keyLength}({@code int}) + * @return 字段/派生属性 {@code aesKey} 的值 + */ public Key getAesKey(byte[] key, int keyLength) { byte[] SALT = encryptMessageByHmacMd5(key); int ITERATION_COUNT = SALT.length % 10 * 10; @@ -388,6 +602,14 @@ public class McCrypto { return null; } + /** + * 获取Des密钥。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new DESKeySpec。 + * + * @param key 键/配置项({@code byte[]}) + * @return 字段/派生属性 {@code desKey} 的值 + */ private Key getDesKey(byte[] key) { try { DESKeySpec keySpec = new DESKeySpec(key); @@ -404,6 +626,12 @@ public class McCrypto { return null; } + /** + * 获取 {@code rsaPublicKey}。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * @return 字段/派生属性 {@code rsaPublicKey} 的值 + */ private Key getRsaPublicKey() { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); @@ -417,6 +645,14 @@ public class McCrypto { } } + /** + * 获取RSAPrivate密钥。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new PKCS8EncodedKeySpec。 + * + * @param keyBytes 参数 {@code keyBytes}({@code byte[]}) + * @return 字段/派生属性 {@code rsaPrivateKey} 的值 + */ private Key getRsaPrivateKey(byte[] keyBytes) { try { KeyFactory keyFactory = KeyFactory.getInstance("RSA"); @@ -431,6 +667,14 @@ public class McCrypto { return null; } + /** + * 获取Desede密钥。 + * + * 实现要点:主要调用:new SecretKeySpec。 + * + * @param key 键/配置项({@code byte[]}) + * @return 字段/派生属性 {@code desedeKey} 的值 + */ private Key getDesedeKey(byte[] key) { int len = 24; byte[] newKey = new byte[len]; @@ -438,6 +682,14 @@ public class McCrypto { return new SecretKeySpec(newKey, "DESede"); } + /** + * 处理do按Cipher。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param cipherMode 参数 {@code cipherMode}({@code int}) + * @return 处理结果 + */ private byte[] doByCipher(int cipherMode) { try { Cipher cipher = Cipher.getInstance(this.mAlgorithm); @@ -460,11 +712,25 @@ public class McCrypto { return this.mTarget; } + /** + * 处理do按Rc4。 + * + * 实现要点:主要调用:new McRc4、decrypt。 + * @return 处理结果 + */ private byte[] doByRc4() { McRc4 cipher = new McRc4(this.mKey); return cipher.decrypt(this.mSource); } + /** + * 加密消息按HmacMd5。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new SecretKeySpec。 + * + * @param message 消息内容({@code byte[]}) + * @return 处理结果 + */ public static byte[] encryptMessageByHmacMd5(byte[] message) { try { Mac mac = Mac.getInstance("HmacMD5"); @@ -481,10 +747,24 @@ public class McCrypto { return null; } + /** + * 加密消息按Md5。 + * + * @param message 消息内容({@code String}) + * @return 处理结果 + */ public static byte[] encryptMessageByMd5(String message) { return message != null ? encryptMessageByMd5(message.getBytes()) : null; } + /** + * 加密消息按Md5。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param message 消息内容({@code byte[]}) + * @return 处理结果 + */ public static byte[] encryptMessageByMd5(byte[] message) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); @@ -496,6 +776,16 @@ public class McCrypto { } } + /** + * 加密按AES。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new BouncyCastleProvider、new SecretKeySpec。 + * + * @param key 键/配置项({@code byte[]}) + * @param src 参数 {@code src}({@code byte[]}) + * @param mode 参数 {@code mode}({@code int}) + * @return 处理结果 + */ public static byte[] encryptByAES(byte[] key, byte[] src, int mode) { try { Provider bcProvider = new BouncyCastleProvider(); diff --git a/src/main/java/com/mitac/cell/security/McOtaCert.java b/src/main/java/com/mitac/cell/security/McOtaCert.java index 08d88df..9e3aa3f 100644 --- a/src/main/java/com/mitac/cell/security/McOtaCert.java +++ b/src/main/java/com/mitac/cell/security/McOtaCert.java @@ -8,36 +8,105 @@ import java.security.NoSuchAlgorithmException; import java.util.Arrays; import org.apache.commons.io.IOUtils; +/** + * 【通用基础库】{@code McOtaCert} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code DIGEST_ALGORITHM}(String):字段 DIGEST_ALGORITHM
  • + *
  • {@code Base64}(BaseEncoding):字段 Base64
  • + *
  • {@code keyBytes}(byte[]):密钥Bytes
  • + *
  • {@code hashBytes}(byte[]):哈希Bytes
  • + *
+ * + * 协作对象:{@code BaseEncoding}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McOtaCert { + /** + * 字段 DIGEST_ALGORITHM。 + */ private static final String DIGEST_ALGORITHM = "SHA-256"; + /** + * 字段 Base64。 + */ private static BaseEncoding Base64 = BaseEncoding.base64(); + /** + * 密钥Bytes。 + */ private byte[] keyBytes = null; + /** + * 哈希Bytes。 + */ private byte[] hashBytes = null; + /** + * 构造 {@code McOtaCert} 实例。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ public McOtaCert(InputStream input) { this.dispatch(input); } + /** + * 获取 {@code key}。 + * @return 字段/派生属性 {@code key} 的值 + */ public byte[] getKey() { return this.keyBytes; } + /** + * 获取 {@code hash}。 + * @return 字段/派生属性 {@code hash} 的值 + */ public byte[] getHash() { return this.hashBytes; } + /** + * 处理same密钥。 + * + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean sameKey(byte[] bytes) { return Arrays.equals(bytes, this.getKey()); } + /** + * 处理same哈希。 + * + * @param base64Hash 参数 {@code base64Hash}({@code String}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public boolean sameHash(String base64Hash) { return base64Hash.equals(this.getBase64Hash()); } + /** + * 获取 {@code base64Hash}。 + * @return 字符串结果 + */ public String getBase64Hash() { return BaseEncoding.base64Url().encode(this.getHash()); } + /** + * 处理dispatch。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param input 参数 {@code input}({@code InputStream}) + */ private void dispatch(InputStream input) { try { String keyContent = IOUtils.toString(input, "UTF-8"); @@ -50,10 +119,24 @@ public class McOtaCert { } + /** + * 获取密钥Body。 + * + * @param keyContent 参数 {@code keyContent}({@code String}) + * @return 字符串结果 + */ private String getKeyBody(String keyContent) { return keyContent.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "").replace("\n", "").replace("\r", ""); } + /** + * 处理gen哈希。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param bytes 参数 {@code bytes}({@code byte[]}) + * @return 处理结果 + */ private byte[] genHash(byte[] bytes) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); diff --git a/src/main/java/com/mitac/cell/security/McTextEncryptor.java b/src/main/java/com/mitac/cell/security/McTextEncryptor.java index dd3dd62..2cd09fd 100644 --- a/src/main/java/com/mitac/cell/security/McTextEncryptor.java +++ b/src/main/java/com/mitac/cell/security/McTextEncryptor.java @@ -15,10 +15,43 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; +/** + * 【通用基础库】{@code McTextEncryptor} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code secretKey}(SecretKey):secret密钥
  • + *
  • {@code decryptor}(Cipher):字段 decryptor
  • + *
+ * + * 协作对象:{@code SecretKey、Cipher}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McTextEncryptor { + /** + * secret密钥。 + */ private SecretKey secretKey; + /** + * 字段 decryptor。 + */ private final Cipher decryptor; + /** + * 构造 {@code McTextEncryptor} 实例。 + * + * 实现要点:主要调用:new PBEKeySpec、new SecretKeySpec。 + * + * @param password 密码({@code String}) + * @param salt 参数 {@code salt}({@code String}) + */ public McTextEncryptor(String password, String salt) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), McStringUtils.toBytes(salt), 1024, 256); SecretKey secretKey = this.newSecretKey("PBKDF2WithHmacSHA1", keySpec); @@ -26,44 +59,72 @@ public class McTextEncryptor { this.decryptor = this.newCipher("AES/CBC/PKCS5Padding"); } + /** + * 处理解密。 + * + * 实现要点:主要调用:decrypt、new String。 + * + * @param encrypted 参数 {@code encrypted}({@code String}) + * @return 字符串结果 + */ public String decrypt(String encrypted) { byte[] bytes = McStringUtils.toBytes(encrypted); byte[] decryptedBytes = this.decrypt(bytes); return decryptedBytes == null ? null : new String(decryptedBytes); } + /** + * 处理解密。 + * + * 实现要点:包含同步块;包含异常捕获与降级/回滚分支;主要调用:new IvParameterSpec。 + * + * @param encryptedBytes 参数 {@code encryptedBytes}({@code byte[]}) + * @return 处理结果 + */ public byte[] decrypt(byte[] encryptedBytes) { synchronized(this.decryptor) { byte[] iv = new byte[16]; - byte[] var10000; try { this.decryptor.init(2, this.secretKey, new IvParameterSpec(iv)); - var10000 = this.decryptor.doFinal(encryptedBytes); + return this.decryptor.doFinal(encryptedBytes); } catch (Exception var6) { return null; } - - return var10000; } } + /** + * 处理加密。 + * + * 实现要点:包含同步块;包含异常捕获与降级/回滚分支;主要调用:new IvParameterSpec。 + * + * @param source 参数 {@code source}({@code String}) + * @return 字符串结果 + */ public String encrypt(String source) { synchronized(this.decryptor) { - String var10000; try { byte[] iv = new byte[16]; this.decryptor.init(1, this.secretKey, new IvParameterSpec(iv)); byte[] bytes = this.decryptor.doFinal(source.getBytes()); - var10000 = McStringUtils.toHexString(bytes); + return McStringUtils.toHexString(bytes); } catch (BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException var6) { return null; } - - return var10000; } } + /** + * 处理新Cipher。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new IllegalArgumentException、new IllegalStateException。 + * + * @param algorithm 参数 {@code algorithm}({@code String}) + * @return 处理结果 + * @throws IllegalArgumentException 当 IllegalArgumentException 条件不满足或底层调用失败时抛出。 + * @throws IllegalStateException 当 IllegalStateException 条件不满足或底层调用失败时抛出。 + */ private Cipher newCipher(String algorithm) { try { return Cipher.getInstance(algorithm); @@ -74,6 +135,16 @@ public class McTextEncryptor { } } + /** + * 处理新Secret密钥。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new IllegalArgumentException。 + * + * @param algorithm 参数 {@code algorithm}({@code String}) + * @param keySpec 参数 {@code keySpec}({@code PBEKeySpec}) + * @return 处理结果 + * @throws IllegalArgumentException 当 IllegalArgumentException 条件不满足或底层调用失败时抛出。 + */ private SecretKey newSecretKey(String algorithm, PBEKeySpec keySpec) { try { SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm); diff --git a/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java b/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java index 7741cc4..ed2b559 100644 --- a/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java +++ b/src/main/java/com/mitac/cell/security/McUserAuthenticationProvider.java @@ -8,7 +8,27 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; +/** + * 【通用基础库】{@code McUserAuthenticationProvider} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McUserAuthenticationProvider implements AuthenticationProvider { + /** + * 处理认证。 + * + * 实现要点:包含 1 个条件分支、0 个循环;主要调用:new ArrayList、new McUserAuthenticationToken、new BadCredentialsException。 + * + * @param authentication Spring Security 认证信息({@code Authentication}) + * @return 处理结果 + * @throws AuthenticationException 当 AuthenticationException 条件不满足或底层调用失败时抛出。 + * @throws BadCredentialsException 当 BadCredentialsException 条件不满足或底层调用失败时抛出。 + */ public Authentication authenticate(Authentication authentication) throws AuthenticationException { boolean result = false; if (result) { @@ -20,7 +40,16 @@ public class McUserAuthenticationProvider implements AuthenticationProvider { } } - public boolean supports(Class authentication) { + /** + * 判断本 Provider 是否支持给定的认证令牌类型。 + * + *

当前实现接受所有 {@link org.springframework.security.core.Authentication} 子类型, + * 具体凭据校验在 {@code authenticate} 中完成。 + * + * @param authentication 待判断的认证令牌类型 + * @return 固定返回 {@code true} + */ + public boolean supports(Class authentication) { return true; } } diff --git a/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java b/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java index 36c8cd7..a143013 100644 --- a/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java +++ b/src/main/java/com/mitac/cell/security/McUserAuthenticationToken.java @@ -4,22 +4,64 @@ import java.util.Collection; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; +/** + * 【通用基础库】{@code McUserAuthenticationToken} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code serialVersionUID}(long):序列版本UID
  • + *
  • {@code principal}(Object):字段 principal
  • + *
  • {@code credentials}(Object):字段 credentials
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McUserAuthenticationToken extends AbstractAuthenticationToken { + /** + * 序列版本UID。 + */ private static final long serialVersionUID = 503883598783793420L; + /** + * 字段 principal。 + */ private final Object principal; + /** + * 字段 credentials。 + */ private Object credentials; - public McUserAuthenticationToken(Object principal, Object credentials, Collection authorities) { + /** + * 构造 {@code McUserAuthenticationToken} 实例。 + * + * @param principal 参数 {@code principal}({@code Object}) + * @param credentials 参数 {@code credentials}({@code Object}) + * @param authorities 参数 {@code authorities}({@code Collection}) + */ + public McUserAuthenticationToken(Object principal, Object credentials, Collection authorities) { super(authorities); this.principal = principal; this.credentials = credentials; super.setAuthenticated(true); } + /** + * 获取 {@code credentials}。 + * @return 字段/派生属性 {@code credentials} 的值 + */ public Object getCredentials() { return this.credentials; } + /** + * 获取 {@code principal}。 + * @return 字段/派生属性 {@code principal} 的值 + */ public Object getPrincipal() { return this.principal; } diff --git a/src/main/java/com/mitac/cell/security/cipher/McRc4.java b/src/main/java/com/mitac/cell/security/cipher/McRc4.java index 0e29fa1..210e719 100644 --- a/src/main/java/com/mitac/cell/security/cipher/McRc4.java +++ b/src/main/java/com/mitac/cell/security/cipher/McRc4.java @@ -1,26 +1,77 @@ package com.mitac.cell.security.cipher; +/** + * 【通用基础库】{@code McRc4} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code mPermutationArray}(byte[]):字段 mPermutationArray
  • + *
  • {@code mMixedArray}(byte[]):字段 mMixedArray
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McRc4 { + /** + * 字段 mPermutationArray。 + */ private final byte[] mPermutationArray = new byte[256]; + /** + * 字段 mMixedArray。 + */ private final byte[] mMixedArray = new byte[256]; + /** + * 构造 {@code McRc4} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + */ public McRc4() { } + /** + * 构造 {@code McRc4} 实例。 + * + * @param key 键/配置项({@code String}) + */ public McRc4(String key) { this.setKey(key); } + /** + * 构造 {@code McRc4} 实例。 + * + * @param key 键/配置项({@code byte[]}) + */ public McRc4(byte[] key) { this.setKey(key); } + /** + * 设置 {@code key}。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param key 键/配置项({@code String}) + */ public void setKey(String key) { if (key != null) { this.setKey(key.getBytes()); } } + /** + * 设置 {@code key}。 + * + * 实现要点:包含 2 个条件分支、2 个循环。 + * + * @param keyBytes 参数 {@code keyBytes}({@code byte[]}) + */ public void setKey(byte[] keyBytes) { if (keyBytes != null) { int keyLen = keyBytes.length; @@ -34,18 +85,23 @@ public class McRc4 { for(int i = 0; i < 256; ++i) { j = j + this.mPermutationArray[i] + this.mMixedArray[i] & 255; - byte[] var10000 = this.mPermutationArray; - var10000[i] ^= this.mPermutationArray[j]; - var10000 = this.mPermutationArray; - var10000[j] ^= this.mPermutationArray[i]; - var10000 = this.mPermutationArray; - var10000[i] ^= this.mPermutationArray[j]; + this.mPermutationArray[i] ^= this.mPermutationArray[j]; + this.mPermutationArray[j] ^= this.mPermutationArray[i]; + this.mPermutationArray[i] ^= this.mPermutationArray[j]; } } } } + /** + * 处理加密。 + * + * 实现要点:包含 0 个条件分支、1 个循环。 + * + * @param sourceData 参数 {@code sourceData}({@code byte[]}) + * @return 处理结果 + */ public byte[] encrypt(byte[] sourceData) { byte[] encryptedData = new byte[sourceData.length]; int i = 0; @@ -54,12 +110,9 @@ public class McRc4 { for(int count = 0; count < sourceData.length; ++count) { i = i + 1 & 255; j = j + this.mPermutationArray[i] & 255; - byte[] var10000 = this.mPermutationArray; - var10000[i] ^= this.mPermutationArray[j]; - var10000 = this.mPermutationArray; - var10000[j] ^= this.mPermutationArray[i]; - var10000 = this.mPermutationArray; - var10000[i] ^= this.mPermutationArray[j]; + this.mPermutationArray[i] ^= this.mPermutationArray[j]; + this.mPermutationArray[j] ^= this.mPermutationArray[i]; + this.mPermutationArray[i] ^= this.mPermutationArray[j]; int t = this.mPermutationArray[i] + this.mPermutationArray[j] & 255; int k = this.mPermutationArray[t]; encryptedData[count] = (byte)(sourceData[count] ^ k); @@ -68,6 +121,14 @@ public class McRc4 { return encryptedData; } + /** + * 处理解密。 + * + * 实现要点:主要调用:encrypt。 + * + * @param encryptedData 参数 {@code encryptedData}({@code byte[]}) + * @return 处理结果 + */ public byte[] decrypt(byte[] encryptedData) { return this.encrypt(encryptedData); } diff --git a/src/main/java/com/mitac/cell/security/cipher/package-info.java b/src/main/java/com/mitac/cell/security/cipher/package-info.java new file mode 100644 index 0000000..856aab1 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/cipher/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.security.cipher}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McRc4}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.security.cipher; diff --git a/src/main/java/com/mitac/cell/security/package-info.java b/src/main/java/com/mitac/cell/security/package-info.java new file mode 100644 index 0000000..7f98d78 --- /dev/null +++ b/src/main/java/com/mitac/cell/security/package-info.java @@ -0,0 +1,17 @@ +/** + * 包 {@code com.mitac.cell.security}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McBase64}
  • + *
  • {@link McCrypto}
  • + *
  • {@link McOtaCert}
  • + *
  • {@link McTextEncryptor}
  • + *
  • {@link McUserAuthenticationProvider}
  • + *
  • {@link McUserAuthenticationToken}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.security; diff --git a/src/main/java/com/mitac/cell/shell/McRuntime.java b/src/main/java/com/mitac/cell/shell/McRuntime.java index c29f544..ca4a948 100644 --- a/src/main/java/com/mitac/cell/shell/McRuntime.java +++ b/src/main/java/com/mitac/cell/shell/McRuntime.java @@ -11,9 +11,38 @@ import java.io.Reader; import java.util.ArrayList; import java.util.List; +/** + * 【通用基础库】{@code McRuntime} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code runtime}(Runtime):字段 runtime
  • + *
+ * + * 协作对象:{@code Runtime}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McRuntime { + /** + * 字段 runtime。 + */ private static Runtime runtime = Runtime.getRuntime(); + /** + * 处理exec。 + * + * 实现要点:包含异常捕获与降级/回滚分支。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 处理结果 + */ public static Process exec(String... cmdArray) { try { return cmdArray.length == 1 ? runtime.exec(cmdArray[0]) : runtime.exec(cmdArray); @@ -22,16 +51,38 @@ public class McRuntime { } } + /** + * 处理execInputStream。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 处理结果 + */ public static InputStream execInputStream(String... cmdArray) { Process process = exec(cmdArray); return process == null ? null : process.getInputStream(); } + /** + * 处理execReader。 + * + * 实现要点:主要调用:new InputStreamReader。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 处理结果 + */ public static Reader execReader(String... cmdArray) { InputStream is = execInputStream(cmdArray); return is == null ? null : new InputStreamReader(is); } + /** + * 处理execBytes。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 处理结果 + */ public static byte[] execBytes(String... cmdArray) { InputStream is = execInputStream(cmdArray); if (is == null) { @@ -45,6 +96,14 @@ public class McRuntime { } } + /** + * 处理execString。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、0 个循环;主要调用:new InputStreamReader。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 字符串结果 + */ public static String execString(String... cmdArray) { InputStream is = execInputStream(cmdArray); if (is == null) { @@ -58,7 +117,15 @@ public class McRuntime { } } - public static List execStrings(String... cmdArray) { + /** + * 处理execStrings。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 1 个条件分支、1 个循环;主要调用:new ArrayList、new BufferedReader。 + * + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return String列表,可能为空 + */ + public static List execStrings(String... cmdArray) { Reader reader = execReader(cmdArray); if (reader == null) { return null; @@ -79,10 +146,28 @@ public class McRuntime { } } + /** + * 处理exec文件。 + * + * 实现要点:主要调用:new McFile。 + * + * @param filePath 参数 {@code filePath}({@code String}) + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public static boolean execFile(String filePath, String... cmdArray) { return execFile(new McFile(filePath), cmdArray); } + /** + * 处理exec文件。 + * + * 实现要点:主要调用:write。 + * + * @param file 文件({@code McFile}) + * @param cmdArray 参数 {@code cmdArray}({@code String[]}) + * @return 条件成立返回 {@code true},否则返回 {@code false} + */ public static boolean execFile(McFile file, String... cmdArray) { InputStream is = execInputStream(cmdArray); return is != null ? file.write(is) : false; diff --git a/src/main/java/com/mitac/cell/shell/package-info.java b/src/main/java/com/mitac/cell/shell/package-info.java new file mode 100644 index 0000000..62bef48 --- /dev/null +++ b/src/main/java/com/mitac/cell/shell/package-info.java @@ -0,0 +1,12 @@ +/** + * 包 {@code com.mitac.cell.shell}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link McRuntime}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.shell; diff --git a/src/main/java/com/mitac/cell/system/HwInfo.java b/src/main/java/com/mitac/cell/system/HwInfo.java index e5b2bbb..d9faab0 100644 --- a/src/main/java/com/mitac/cell/system/HwInfo.java +++ b/src/main/java/com/mitac/cell/system/HwInfo.java @@ -10,17 +10,72 @@ import java.util.UUID; import javax.management.MBeanServer; import javax.management.ObjectName; +/** + * 【通用基础库】{@code HwInfo} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code computerName}(String):computer名称
  • + *
  • {@code processors}(int):字段 processors
  • + *
  • {@code serialNo}(String):序列号
  • + *
  • {@code systemUuid}(UUID):系统UUID
  • + *
  • {@code maxMemory}(long):字段 maxMemory
  • + *
  • {@code totalMemory}(long):总数Memory
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class HwInfo { + /** + * computer名称。 + */ private String computerName; + /** + * 字段 processors。 + */ private int processors; + /** + * 序列号。 + */ private String serialNo; + /** + * 系统UUID。 + */ private UUID systemUuid; + /** + * 字段 maxMemory。 + */ private long maxMemory; + /** + * 总数Memory。 + */ private long totalMemory; + /** + * 字段 freeMemory。 + */ private long freeMemory; + /** + * physical总数。 + */ private Long physicalTotal; + /** + * 字段 physicalFree。 + */ private Long physicalFree; + /** + * 构造 {@code HwInfo} 实例。 + * + * 实现要点:包含异常捕获与降级/回滚分支;主要调用:new ObjectName。 + * + * @param osType 参数 {@code osType}({@code OsInfo.OS_TYPE}) + */ public HwInfo(OsInfo.OS_TYPE osType) { this.retreiveDeviceInfo(osType); MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer(); @@ -39,6 +94,11 @@ public class HwInfo { this.processors = runtime.availableProcessors(); } + /** + * 处理retreive设备信息。 + * + * @param osType 参数 {@code osType}({@code OsInfo.OS_TYPE}) + */ private void retreiveDeviceInfo(OsInfo.OS_TYPE osType) { switch (osType) { case LINUX: @@ -53,42 +113,83 @@ public class HwInfo { } + /** + * 获取 {@code computerName}。 + * @return 字符串结果 + */ public String getComputerName() { return this.computerName; } + /** + * 获取 {@code processors}。 + * @return 数量/长度 + */ public int getProcessors() { return this.processors; } + /** + * 获取 {@code systemUuid}。 + * @return UUID + */ public UUID getSystemUuid() { return this.systemUuid; } + /** + * 处理序列号。 + * @return 字符串结果 + */ public String serialNo() { return this.serialNo; } + /** + * 获取 {@code maxMemory}。 + * @return 数量/长度 + */ public long getMaxMemory() { return this.maxMemory; } + /** + * 获取 {@code totalMemory}。 + * @return 数量/长度 + */ public long getTotalMemory() { return this.totalMemory; } + /** + * 获取 {@code freeMemory}。 + * @return 数量/长度 + */ public long getFreeMemory() { return this.freeMemory; } + /** + * 获取 {@code physicalTotal}。 + * @return 数量/长度 + */ public long getPhysicalTotal() { return this.physicalTotal; } + /** + * 获取 {@code physicalFree}。 + * @return 数量/长度 + */ public long getPhysicalFree() { return this.physicalFree; } + /** + * 处理retrieve设备信息在Windows。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、1 个循环;主要调用:new BufferedReader。 + */ private void retrieveDeviceInfoInWindows() { this.computerName = McNetUtils.hostName(); if (Strings.isNullOrEmpty(this.computerName)) { @@ -112,6 +213,11 @@ public class HwInfo { } + /** + * 处理retrieve设备信息在Linux。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 5 个条件分支、1 个循环;主要调用:new BufferedReader。 + */ private void retrieveDeviceInfoInLinux() { this.computerName = McNetUtils.hostName(); @@ -143,6 +249,11 @@ public class HwInfo { } + /** + * 处理retrieve设备信息在Mac。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 4 个条件分支、1 个循环;主要调用:new BufferedReader。 + */ private void retrieveDeviceInfoInMac() { this.computerName = McNetUtils.hostName(); diff --git a/src/main/java/com/mitac/cell/system/McSystemInfo.java b/src/main/java/com/mitac/cell/system/McSystemInfo.java index f01f7c1..765bbd8 100644 --- a/src/main/java/com/mitac/cell/system/McSystemInfo.java +++ b/src/main/java/com/mitac/cell/system/McSystemInfo.java @@ -3,34 +3,93 @@ package com.mitac.cell.system; import com.mitac.cell.net.McNetUtils; import java.util.List; +/** + * 【通用基础库】{@code McSystemInfo} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code osInfo}(OsInfo):操作系统信息
  • + *
  • {@code hwInfo}(HwInfo):hw信息
  • + *
  • {@code macAddr}(byte[]):字段 macAddr
  • + *
  • {@code macAddresses}(List):byte[]集合
  • + *
+ * + * 协作对象:{@code OsInfo、HwInfo}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class McSystemInfo { + /** + * 操作系统信息。 + */ private OsInfo osInfo = new OsInfo(); + /** + * hw信息。 + */ private HwInfo hwInfo; + /** + * 字段 macAddr。 + */ private byte[] macAddr; - private List macAddresses; + /** + * byte[]集合。 + */ + private List macAddresses; + /** + * 构造 {@code McSystemInfo} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:主要调用:new HwInfo。 + */ public McSystemInfo() { this.hwInfo = new HwInfo(this.osInfo.osType()); this.macAddresses = McNetUtils.macAddress(); this.macAddr = McNetUtils.getMacAddr(); } + /** + * 获取 {@code osInfo}。 + * @return 字段/派生属性 {@code osInfo} 的值 + */ public OsInfo getOsInfo() { return this.osInfo; } + /** + * 获取 {@code hwInfo}。 + * @return 字段/派生属性 {@code hwInfo} 的值 + */ public HwInfo getHwInfo() { return this.hwInfo; } - public List getMacAddresses() { + /** + * 获取 {@code macAddresses}。 + * @return byte[]列表,可能为空 + */ + public List getMacAddresses() { return this.macAddresses; } + /** + * 获取 {@code macAddress}。 + * @return 字段/派生属性 {@code macAddress} 的值 + */ public byte[] getMacAddress() { return this.macAddr; } + /** + * 生成哈希。 + * @return 字符串结果 + */ public String generateHash() { return ""; } diff --git a/src/main/java/com/mitac/cell/system/MsWindows.java b/src/main/java/com/mitac/cell/system/MsWindows.java index 240bc11..214b956 100644 --- a/src/main/java/com/mitac/cell/system/MsWindows.java +++ b/src/main/java/com/mitac/cell/system/MsWindows.java @@ -3,11 +3,47 @@ package com.mitac.cell.system; import com.google.common.base.Strings; import com.mitac.cell.shell.McRuntime; +/** + * 【通用基础库】{@code MsWindows} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code REGQUERY_UTIL}(String):字段 REGQUERY_UTIL
  • + *
  • {@code REGBINARY_TOKEN}(String):字段 REGBINARY_TOKEN
  • + *
  • {@code PRODUCT_KEY_CMD}(String):字段 PRODUCT_KEY_CMD
  • + *
+ * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class MsWindows { + /** + * 字段 REGQUERY_UTIL。 + */ private static final String REGQUERY_UTIL = "reg query "; + /** + * 字段 REGBINARY_TOKEN。 + */ private static final String REGBINARY_TOKEN = "REG_BINARY"; + /** + * 字段 PRODUCT_KEY_CMD。 + */ private static final String PRODUCT_KEY_CMD = "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\" /v DigitalProductId"; + /** + * 查询Registry。 + * + * 实现要点:包含 1 个条件分支、0 个循环。 + * + * @param cmd 参数 {@code cmd}({@code String}) + * @param token 令牌({@code String}) + * @return 字符串结果 + */ public static String queryRegistry(String cmd, String token) { String cmdOutput = McRuntime.execString(cmd); if (Strings.isNullOrEmpty(cmdOutput)) { @@ -18,6 +54,12 @@ public class MsWindows { } } + /** + * 获取 {@code productKey}。 + * + * 实现要点:包含异常捕获与降级/回滚分支;包含 2 个条件分支、4 个循环。 + * @return 字符串结果 + */ public static String getProductKey() { String fullPID = ""; String encodedKey = ""; @@ -37,8 +79,7 @@ public class MsWindows { String rval = ""; for(int var12 = 0; var12 <= 14; ++var12) { - String var10002 = encodedKey.substring(var12 * 2, var12 * 2 + 2); - hexDigitalPID[var12] = Integer.decode("0x" + var10002); + hexDigitalPID[var12] = Integer.decode("0x" + encodedKey.substring(var12 * 2, var12 * 2 + 2)); } for(int var13 = 28; var13 >= 0; --var13) { diff --git a/src/main/java/com/mitac/cell/system/OsInfo.java b/src/main/java/com/mitac/cell/system/OsInfo.java index dd03778..531913d 100644 --- a/src/main/java/com/mitac/cell/system/OsInfo.java +++ b/src/main/java/com/mitac/cell/system/OsInfo.java @@ -2,11 +2,46 @@ package com.mitac.cell.system; import java.io.File; +/** + * 【通用基础库】{@code OsInfo} + * + * 类职责: + *
    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
  • {@code osType}(OS_TYPE):操作系统类型
  • + *
  • {@code name}(String):名称
  • + *
  • {@code version}(String):版本
  • + *
+ * + * 协作对象:{@code OS_TYPE}。 + * + * 学习提示:这是通用基础库,重点关注静态方法的边界条件、空值和异常处理。 + */ public class OsInfo { + /** + * 操作系统类型。 + */ private OS_TYPE osType; + /** + * 名称。 + */ private String name = System.getProperty("os.name"); + /** + * 版本。 + */ private String version; + /** + * 构造 {@code OsInfo} 实例。 + * 使用默认字段值,后续通常由 Spring/Mongo 或调用方填充。 + * + * 实现要点:包含 7 个条件分支、0 个循环。 + */ public OsInfo() { if (this.name != null) { this.name = this.name.toLowerCase(); @@ -37,10 +72,20 @@ public class OsInfo { } + /** + * 处理操作系统类型。 + * @return 处理结果 + */ public OS_TYPE osType() { return this.osType; } + /** + * 获取 {@code appDataFolderPath}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getAppDataFolderPath() { if (this.osType == OsInfo.OS_TYPE.WINDOWS) { return System.getenv("AppData"); @@ -51,10 +96,24 @@ public class OsInfo { } } + /** + * 获取应用数据Folder路径。 + * + * 实现要点:主要调用:new File。 + * + * @param appName 参数 {@code appName}({@code String}) + * @return 字段/派生属性 {@code appDataFolderPath} 的值 + */ public File getAppDataFolderPath(String appName) { return new File(this.getAppDataFolderPath(), appName); } + /** + * 获取 {@code configFolderPath}。 + * + * 实现要点:包含 2 个条件分支、0 个循环。 + * @return 字符串结果 + */ public String getConfigFolderPath() { if (this.osType == OsInfo.OS_TYPE.WINDOWS) { return "c:\\ProgramData"; @@ -65,18 +124,49 @@ public class OsInfo { } } + /** + * 获取配置Folder。 + * + * 实现要点:主要调用:new File。 + * + * @param appName 参数 {@code appName}({@code String}) + * @return 字段/派生属性 {@code configFolder} 的值 + */ public File getConfigFolder(String appName) { return new File(this.getConfigFolderPath(), appName); } + /** + * 处理名称。 + * @return 字符串结果 + */ public String name() { return this.name; } + /** + * 处理版本。 + * @return 字符串结果 + */ public String version() { return this.version; } + /** + * 【枚举常量】{@code OS_TYPE} + * + * 类职责: + *
    + *
  • 用有限枚举值表达状态/类型,避免魔法字符串。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *
    + *
+ * + * 学习提示:注意枚举顺序、value 字段与 fromValue/get 静态方法的映射关系。 + */ public static enum OS_TYPE { WINDOWS, LINUX, diff --git a/src/main/java/com/mitac/cell/system/package-info.java b/src/main/java/com/mitac/cell/system/package-info.java new file mode 100644 index 0000000..00c0969 --- /dev/null +++ b/src/main/java/com/mitac/cell/system/package-info.java @@ -0,0 +1,15 @@ +/** + * 包 {@code com.mitac.cell.system}:包含该模块的模型、服务或工具类。 + * + *

本包主要类型: + *

    + *
  • {@link HwInfo}
  • + *
  • {@link McSystemInfo}
  • + *
  • {@link MsWindows}
  • + *
  • {@link OsInfo}
  • + *
+ * + *

阅读建议:结合本包内类的 Javadoc 与 {@code docs/CODE_WALKTHROUGH.md} 一起看, + * 先理解输入/输出,再跟踪 Service 与 MongoTemplate 的调用链。 + */ +package com.mitac.cell.system; diff --git a/src/main/java/com/mitac/cell/utils/McBooleanUtils.java b/src/main/java/com/mitac/cell/utils/McBooleanUtils.java index 522bf9a..e426942 100644 --- a/src/main/java/com/mitac/cell/utils/McBooleanUtils.java +++ b/src/main/java/com/mitac/cell/utils/McBooleanUtils.java @@ -4,14 +4,41 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +/** + * 【通用基础库】{@code McBooleanUtils} + * + * 类职责: + *

    + *
  • 提供该包内的可复用能力。
  • + *
  • 通过字段/依赖注入持有运行期状态,字段含义见下方“核心字段”。
  • + *
+ * + * 核心字段(按声明顺序): + *