From e47299a327c23f89d96ecf135f9bf570de0ac4e6 Mon Sep 17 00:00:00 2001 From: pnoker Date: Thu, 7 May 2026 23:03:16 +0800 Subject: [PATCH] chore: remove format and format-check targets from Makefile --- .claude/CLAUDE.md | 87 +- .mvn/settings.xml | 3 + .springjavaformatconfig | 0 Makefile | 12 +- README.ja.md | 9 +- README.md | 15 +- README.vi.md | 30 +- README.zh.md | 3 +- SECURITY.md | 21 +- checkstyle.xml | 65 - dc3-api/dc3-api-auth/README.md | 3 +- dc3-api/dc3-api-data/README.md | 3 +- dc3-api/dc3-api-driver/README.md | 3 +- dc3-api/dc3-api-manager/README.md | 3 +- dc3-api/pom.xml | 47 - .../center/agentic/AgenticApplication.java | 6 +- dc3-center/dc3-center-auth/README.md | 6 +- .../pnoker/center/auth/AuthApplication.java | 15 +- dc3-center/dc3-center-data/README.md | 9 +- .../pnoker/center/data/DataApplication.java | 15 +- dc3-center/dc3-center-manager/README.md | 3 +- .../center/manager/ManagerApplication.java | 15 +- dc3-center/dc3-center-single/README.md | 3 +- .../pnoker/center/SingleApplication.java | 19 +- .../agentic/config/AgenticProperties.java | 24 +- .../agentic/config/ChatClientConfig.java | 66 +- .../agentic/constant/AgenticConstant.java | 24 +- .../agentic/controller/ChatController.java | 292 ++- .../agentic/controller/SessionController.java | 81 +- .../common/agentic/entity/bo/SessionBO.java | 16 +- .../entity/builder/SessionBuilder.java | 48 +- .../agentic/entity/model/SessionDO.java | 74 +- .../agentic/entity/query/SessionQuery.java | 14 +- .../entity/request/ChatCompletionRequest.java | 64 +- .../entity/request/ChatMessageDTO.java | 16 +- .../response/ChatCompletionChunkResponse.java | 50 +- .../response/ChatCompletionResponse.java | 66 +- .../common/agentic/entity/vo/SessionVO.java | 16 +- .../agentic/service/SessionService.java | 56 +- .../service/impl/SessionServiceImpl.java | 124 +- .../common/agentic/skill/SkillDefinition.java | 82 +- .../common/agentic/skill/SkillLoader.java | 90 +- .../common/agentic/skill/SkillRegistry.java | 82 +- .../common/agentic/tool/AuthToolSet.java | 80 +- .../common/agentic/tool/DataToolSet.java | 142 +- .../common/agentic/tool/ManagerToolSet.java | 312 +-- dc3-common/dc3-common-api/README.md | 9 +- .../pnoker/common/utils/GrpcBuilderUtil.java | 239 +-- dc3-common/dc3-common-auth/README.md | 3 +- .../auth/biz/DictionaryForAuthService.java | 11 +- .../auth/biz/ResourceRegistrySyncService.java | 45 +- .../pnoker/common/auth/biz/TokenService.java | 44 +- .../impl/DictionaryForAuthServiceImpl.java | 28 +- .../impl/ResourceRegistrySyncServiceImpl.java | 874 ++++---- .../auth/biz/impl/TokenServiceImpl.java | 127 +- .../common/auth/controller/ApiController.java | 131 +- .../DictionaryForAuthController.java | 46 +- .../auth/controller/MenuController.java | 236 ++- .../auth/controller/ResourceController.java | 236 ++- .../auth/controller/RoleController.java | 244 ++- .../RoleResourceBindController.java | 176 +- .../controller/RoleUserBindController.java | 147 +- .../auth/controller/TenantController.java | 232 +-- .../auth/controller/TokenController.java | 93 +- .../auth/controller/UserController.java | 186 +- .../auth/controller/UserLoginController.java | 295 ++- .../auth/dal/impl/DriverTokenManagerImpl.java | 2 +- .../dal/impl/RoleResourceBindManagerImpl.java | 2 +- .../dal/impl/RoleUserBindManagerImpl.java | 2 +- .../dal/impl/UserPasswordManagerImpl.java | 2 +- .../common/auth/entity/bean/AuthHeader.java | 10 +- .../pnoker/common/auth/entity/bean/Login.java | 24 +- .../common/auth/entity/bean/TokenValid.java | 8 +- .../pnoker/common/auth/entity/bo/ApiBO.java | 56 +- .../common/auth/entity/bo/DriverTokenBO.java | 56 +- .../pnoker/common/auth/entity/bo/MenuBO.java | 64 +- .../common/auth/entity/bo/MenuTreeBO.java | 54 +- .../common/auth/entity/bo/ResourceBO.java | 78 +- .../entity/bo/ResourceRegistryScannedApi.java | 52 +- .../bo/ResourceRegistrySyncCommand.java | 26 +- .../entity/bo/ResourceRegistrySyncResult.java | 8 +- .../common/auth/entity/bo/ResourceTreeBO.java | 60 +- .../pnoker/common/auth/entity/bo/RoleBO.java | 48 +- .../auth/entity/bo/RoleResourceBindBO.java | 16 +- .../common/auth/entity/bo/RoleTreeBO.java | 56 +- .../common/auth/entity/bo/RoleUserBindBO.java | 16 +- .../common/auth/entity/bo/TenantBO.java | 32 +- .../common/auth/entity/bo/TenantBindBO.java | 16 +- .../pnoker/common/auth/entity/bo/UserBO.java | 56 +- .../common/auth/entity/bo/UserLoginBO.java | 32 +- .../common/auth/entity/bo/UserPasswordBO.java | 8 +- .../auth/entity/builder/ApiBuilder.java | 256 +-- .../builder/DictionaryForAuthBuilder.java | 90 +- .../auth/entity/builder/MenuBuilder.java | 270 +-- .../auth/entity/builder/ResourceBuilder.java | 270 +-- .../auth/entity/builder/RoleBuilder.java | 240 +-- .../builder/RoleResourceBindBuilder.java | 158 +- .../entity/builder/RoleUserBindBuilder.java | 158 +- .../entity/builder/TenantBindBuilder.java | 158 +- .../auth/entity/builder/TenantBuilder.java | 238 ++- .../auth/entity/builder/UserBuilder.java | 260 +-- .../auth/entity/builder/UserLoginBuilder.java | 186 +- .../entity/builder/UserPasswordBuilder.java | 158 +- .../common/auth/entity/model/ApiDO.java | 166 +- .../auth/entity/model/DriverTokenDO.java | 166 +- .../common/auth/entity/model/MenuDO.java | 176 +- .../common/auth/entity/model/ResourceDO.java | 176 +- .../common/auth/entity/model/RoleDO.java | 156 +- .../auth/entity/model/RoleResourceBindDO.java | 116 +- .../auth/entity/model/RoleUserBindDO.java | 116 +- .../auth/entity/model/TenantBindDO.java | 116 +- .../common/auth/entity/model/TenantDO.java | 136 +- .../common/auth/entity/model/UserDO.java | 166 +- .../common/auth/entity/model/UserLoginDO.java | 136 +- .../auth/entity/model/UserPasswordDO.java | 106 +- .../common/auth/entity/query/ApiQuery.java | 56 +- .../auth/entity/query/DriverTokenQuery.java | 48 +- .../common/auth/entity/query/MenuQuery.java | 48 +- .../auth/entity/query/ResourceQuery.java | 88 +- .../common/auth/entity/query/RoleQuery.java | 40 +- .../entity/query/RoleResourceBindQuery.java | 24 +- .../auth/entity/query/RoleUserBindQuery.java | 24 +- .../auth/entity/query/TenantBindQuery.java | 24 +- .../common/auth/entity/query/TenantQuery.java | 32 +- .../common/auth/entity/query/TokenQuery.java | 44 +- .../auth/entity/query/UserLoginQuery.java | 40 +- .../auth/entity/query/UserPasswordQuery.java | 16 +- .../common/auth/entity/query/UserQuery.java | 56 +- .../pnoker/common/auth/entity/vo/ApiVO.java | 60 +- .../common/auth/entity/vo/DriverTokenVO.java | 48 +- .../common/auth/entity/vo/MenuTreeVO.java | 2 +- .../pnoker/common/auth/entity/vo/MenuVO.java | 72 +- .../common/auth/entity/vo/ResourceTreeVO.java | 2 +- .../common/auth/entity/vo/ResourceVO.java | 88 +- .../auth/entity/vo/RoleResourceBindVO.java | 20 +- .../common/auth/entity/vo/RoleTreeVO.java | 2 +- .../common/auth/entity/vo/RoleUserBindVO.java | 20 +- .../pnoker/common/auth/entity/vo/RoleVO.java | 48 +- .../common/auth/entity/vo/TenantBindVO.java | 20 +- .../common/auth/entity/vo/TenantVO.java | 44 +- .../common/auth/entity/vo/UserLoginVO.java | 32 +- .../common/auth/entity/vo/UserPasswordVO.java | 12 +- .../pnoker/common/auth/entity/vo/UserVO.java | 74 +- .../auth/generator/MybatisGenerator.java | 46 +- .../auth/grpc/ResourceRegistryServer.java | 93 +- .../pnoker/common/auth/grpc/TenantServer.java | 47 +- .../pnoker/common/auth/grpc/TokenServer.java | 54 +- .../common/auth/grpc/UserLoginServer.java | 47 +- .../pnoker/common/auth/grpc/UserServer.java | 47 +- .../auth/grpc/builder/GrpcTenantBuilder.java | 53 +- .../auth/grpc/builder/GrpcUserBuilder.java | 65 +- .../grpc/builder/GrpcUserLoginBuilder.java | 51 +- .../mapper/ResourceRegistryLockMapper.java | 24 +- .../common/auth/service/MenuService.java | 15 +- .../common/auth/service/ResourceService.java | 13 +- .../auth/service/RoleResourceBindService.java | 64 +- .../common/auth/service/RoleService.java | 15 +- .../auth/service/RoleUserBindService.java | 49 +- .../auth/service/TenantBindService.java | 28 +- .../common/auth/service/TenantService.java | 13 +- .../common/auth/service/UserLoginService.java | 28 +- .../auth/service/UserPasswordService.java | 8 +- .../common/auth/service/UserService.java | 51 +- .../auth/service/impl/ApiServiceImpl.java | 183 +- .../auth/service/impl/MenuServiceImpl.java | 300 +-- .../service/impl/ResourceServiceImpl.java | 332 ++- .../impl/RoleResourceBindServiceImpl.java | 388 ++-- .../auth/service/impl/RoleServiceImpl.java | 284 +-- .../service/impl/RoleUserBindServiceImpl.java | 294 +-- .../service/impl/TenantBindServiceImpl.java | 215 +- .../auth/service/impl/TenantServiceImpl.java | 191 +- .../service/impl/UserLoginServiceImpl.java | 227 +- .../service/impl/UserPasswordServiceImpl.java | 187 +- .../auth/service/impl/UserServiceImpl.java | 360 ++-- .../config/ActiveAuthProfileConfig.java | 8 +- .../pnoker/common/init/AuthInitRunner.java | 14 +- dc3-common/dc3-common-constant/README.md | 6 +- .../constant/cache/TimeoutConstant.java | 30 +- .../constant/common/AlgorithmConstant.java | 70 +- .../constant/common/DefaultConstant.java | 70 +- .../constant/common/EnvironmentConstant.java | 144 +- .../constant/common/FolderConstant.java | 22 +- .../constant/common/PrefixConstant.java | 198 +- .../constant/common/QueryWrapperConstant.java | 14 +- .../constant/common/RequestConstant.java | 136 +- .../constant/common/SuffixConstant.java | 262 +-- .../constant/common/SymbolConstant.java | 78 +- .../common/constant/common/TimeConstant.java | 36 +- .../common/constant/driver/EventConstant.java | 92 +- .../constant/driver/MetadataConstant.java | 156 +- .../constant/driver/RabbitConstant.java | 74 +- .../constant/driver/ScheduleConstant.java | 62 +- .../constant/driver/StorageConstant.java | 16 +- .../constant/driver/StrategyConstant.java | 44 +- .../common/constant/service/AuthConstant.java | 36 +- .../common/constant/service/DataConstant.java | 44 +- .../constant/service/DriverConstant.java | 16 +- .../constant/service/ManagerConstant.java | 44 +- .../pnoker/common/enums/AccrueFlagEnum.java | 123 +- .../enums/AlarmMessageLevelFlagEnum.java | 131 +- .../common/enums/AlarmTypeFlagEnum.java | 123 +- .../pnoker/common/enums/ApiTypeFlagEnum.java | 131 +- .../common/enums/AttributeTypeFlagEnum.java | 163 +- .../common/enums/AutoConfirmFlagEnum.java | 115 +- .../common/enums/DeviceCommandTypeEnum.java | 139 +- .../common/enums/DeviceEventTypeEnum.java | 115 +- .../pnoker/common/enums/DeviceStatusEnum.java | 103 +- .../common/enums/DriverCommandTypeEnum.java | 107 +- .../common/enums/DriverEventTypeEnum.java | 115 +- .../pnoker/common/enums/DriverStatusEnum.java | 103 +- .../common/enums/DriverTypeFlagEnum.java | 131 +- .../pnoker/common/enums/EnableFlagEnum.java | 115 +- .../common/enums/EntityTypeFlagEnum.java | 155 +- .../pnoker/common/enums/ExpireFlagEnum.java | 163 +- .../common/enums/GroupTypeFlagEnum.java | 100 +- .../common/enums/MenuLevelFlagEnum.java | 139 +- .../pnoker/common/enums/MenuTypeFlagEnum.java | 115 +- .../common/enums/MetadataOperateTypeEnum.java | 123 +- .../pnoker/common/enums/MetadataTypeEnum.java | 115 +- .../common/enums/PointTypeFlagEnum.java | 163 +- .../common/enums/ProfileShareFlagEnum.java | 123 +- .../common/enums/ProfileTypeFlagEnum.java | 123 +- .../common/enums/ResourceScopeFlagEnum.java | 131 +- .../common/enums/ResourceTypeFlagEnum.java | 155 +- .../pnoker/common/enums/ResponseEnum.java | 111 +- .../pnoker/common/enums/RwFlagEnum.java | 123 +- .../pnoker/common/enums/TimeRangeKeyEnum.java | 65 +- dc3-common/dc3-common-dal/README.md | 3 +- .../pnoker/common/config/DalConfig.java | 4 +- .../common/dal/entity/bo/DictionaryBO.java | 52 +- .../pnoker/common/dal/entity/bo/GroupBO.java | 64 +- .../pnoker/common/dal/entity/bo/LabelBO.java | 48 +- .../common/dal/entity/bo/LabelBindBO.java | 32 +- .../dal/entity/builder/DictionaryBuilder.java | 79 +- .../dal/entity/builder/GroupBuilder.java | 212 +- .../dal/entity/builder/LabelBindBuilder.java | 188 +- .../dal/entity/builder/LabelBuilder.java | 212 +- .../common/dal/entity/model/GroupBindDO.java | 136 +- .../common/dal/entity/model/GroupDO.java | 176 +- .../common/dal/entity/model/LabelBindDO.java | 136 +- .../common/dal/entity/model/LabelDO.java | 156 +- .../common/dal/entity/query/GroupQuery.java | 56 +- .../dal/entity/query/LabelBindQuery.java | 32 +- .../common/dal/entity/query/LabelQuery.java | 48 +- .../common/dal/entity/vo/DictionaryVO.java | 52 +- .../pnoker/common/dal/entity/vo/GroupVO.java | 62 +- .../common/dal/entity/vo/LabelBindVO.java | 30 +- .../pnoker/common/dal/entity/vo/LabelVO.java | 46 +- .../dal/generator/MybatisGenerator.java | 42 +- .../dal/service/impl/GroupServiceImpl.java | 199 +- .../service/impl/LabelBindServiceImpl.java | 191 +- .../dal/service/impl/LabelServiceImpl.java | 209 +- dc3-common/dc3-common-data/README.md | 3 +- .../config/ActiveDataProfileConfig.java | 8 +- .../pnoker/common/config/DataTopicConfig.java | 102 +- .../common/data/biz/DashboardService.java | 283 +-- .../common/data/biz/DeviceEventService.java | 26 +- .../common/data/biz/DeviceStatusService.java | 30 +- .../common/data/biz/DriverEventService.java | 26 +- .../common/data/biz/DriverStatusService.java | 41 +- .../data/biz/PointValueCommandService.java | 22 +- .../common/data/biz/PointValueService.java | 67 +- .../data/biz/ScheduleForDataService.java | 8 +- .../common/data/biz/SystemHealthService.java | 20 +- .../data/biz/impl/DashboardServiceImpl.java | 1219 ++++++----- .../data/biz/impl/DeviceEventServiceImpl.java | 128 +- .../biz/impl/DeviceStatusServiceImpl.java | 86 +- .../data/biz/impl/DriverEventServiceImpl.java | 124 +- .../biz/impl/DriverStatusServiceImpl.java | 144 +- .../data/biz/impl/OfflineExpiryListener.java | 203 +- .../impl/PointValueCommandServiceImpl.java | 60 +- .../data/biz/impl/PointValueServiceImpl.java | 303 +-- .../biz/impl/ScheduleForDataServiceImpl.java | 41 +- .../biz/impl/SystemHealthServiceImpl.java | 298 ++- .../PostgresRepositoryServiceImpl.java | 155 +- .../common/data/cache/LocalCacheService.java | 165 +- .../cache/PointValueLocalCacheService.java | 68 +- .../common/data/constant/DashboardLimits.java | 132 +- .../data/controller/DashboardController.java | 822 ++++---- .../controller/DeviceStatusController.java | 118 +- .../controller/DriverStatusController.java | 112 +- .../PointValueCommandController.java | 72 +- .../data/controller/PointValueController.java | 142 +- .../data/dal/impl/DeviceEventManagerImpl.java | 2 +- .../data/dal/impl/DriverEventManagerImpl.java | 2 +- .../dal/impl/PointValueBoolManagerImpl.java | 2 +- .../dal/impl/PointValueDoubleManagerImpl.java | 2 +- .../dal/impl/PointValueFloatManagerImpl.java | 2 +- .../dal/impl/PointValueIntManagerImpl.java | 2 +- .../dal/impl/PointValueJsonManagerImpl.java | 2 +- .../dal/impl/PointValueLongManagerImpl.java | 2 +- .../common/data/entity/bo/MessageBO.java | 48 +- .../common/data/entity/bo/NotifyBO.java | 56 +- .../pnoker/common/data/entity/bo/RuleBO.java | 72 +- .../entity/bo/dashboard/ActivityCellRow.java | 6 +- .../entity/bo/dashboard/AgingBucketRow.java | 10 +- .../entity/bo/dashboard/AlertCountersRow.java | 4 +- .../entity/bo/dashboard/AlertItemRow.java | 16 +- .../entity/bo/dashboard/AlertTrendRow.java | 6 +- .../data/entity/bo/dashboard/BucketRow.java | 4 +- .../bo/dashboard/CorrelationPairRow.java | 14 +- .../entity/bo/dashboard/CoverageGapRow.java | 4 +- .../entity/bo/dashboard/EntityCountRow.java | 4 +- .../data/entity/bo/dashboard/FlappingRow.java | 8 +- .../entity/bo/dashboard/HourCountRow.java | 4 +- .../entity/bo/dashboard/LatencyBinRow.java | 4 +- .../bo/dashboard/LatestPointValueRow.java | 16 +- .../entity/bo/dashboard/MttaTrendRow.java | 8 +- .../entity/bo/dashboard/PeerAlarmRow.java | 6 +- .../bo/dashboard/ProtocolHealthRow.java | 8 +- .../entity/bo/dashboard/RecentChangeRow.java | 6 +- .../entity/bo/dashboard/SilentSourceRow.java | 6 +- .../entity/bo/dashboard/SourceCountRow.java | 6 +- .../entity/bo/dashboard/SourceStatsRow.java | 6 +- .../entity/bo/dashboard/TimeBucketRow.java | 4 +- .../data/entity/builder/MessageBuilder.java | 256 +-- .../data/entity/builder/NotifyBuilder.java | 256 +-- .../entity/builder/PointValueBuilder.java | 156 +- .../data/entity/builder/RuleBuilder.java | 256 +-- .../data/entity/model/DeviceEventDO.java | 116 +- .../data/entity/model/DriverEventDO.java | 106 +- .../common/data/entity/model/MessageDO.java | 156 +- .../common/data/entity/model/NotifyDO.java | 166 +- .../data/entity/model/PointValueBoolDO.java | 74 +- .../data/entity/model/PointValueDO.java | 84 +- .../data/entity/model/PointValueDoubleDO.java | 74 +- .../data/entity/model/PointValueFloatDO.java | 74 +- .../data/entity/model/PointValueIntDO.java | 74 +- .../data/entity/model/PointValueJsonDO.java | 78 +- .../data/entity/model/PointValueLongDO.java | 74 +- .../common/data/entity/model/RuleDO.java | 186 +- .../data/entity/query/AlertPageQuery.java | 48 +- .../data/entity/query/DeviceEventQuery.java | 32 +- .../common/data/entity/query/DeviceQuery.java | 66 +- .../data/entity/query/DriverEventQuery.java | 24 +- .../common/data/entity/query/DriverQuery.java | 72 +- .../data/entity/query/MessageQuery.java | 48 +- .../common/data/entity/query/NotifyQuery.java | 56 +- .../common/data/entity/query/RuleQuery.java | 56 +- .../common/data/entity/vo/MessageVO.java | 40 +- .../common/data/entity/vo/NotifyVO.java | 48 +- .../data/entity/vo/PointValueReadVO.java | 12 +- .../common/data/entity/vo/PointValueVO.java | 72 +- .../data/entity/vo/PointValueWriteVO.java | 16 +- .../pnoker/common/data/entity/vo/RuleVO.java | 64 +- .../entity/vo/dashboard/ActivityCellVO.java | 10 +- .../entity/vo/dashboard/AgingBacklogVO.java | 20 +- .../vo/dashboard/AlertActivityCellVO.java | 28 +- .../data/entity/vo/dashboard/AlertItemVO.java | 28 +- .../entity/vo/dashboard/AlertStatsVO.java | 56 +- .../entity/vo/dashboard/AlertTopSourceVO.java | 10 +- .../entity/vo/dashboard/AlertTrendVO.java | 10 +- .../vo/dashboard/AlertTypeBucketVO.java | 8 +- .../entity/vo/dashboard/ChangeImpactVO.java | 16 +- .../vo/dashboard/CorrelationPairVO.java | 18 +- .../entity/vo/dashboard/CoverageGapVO.java | 30 +- .../entity/vo/dashboard/FlappingSourceVO.java | 12 +- .../entity/vo/dashboard/LatencyBucketVO.java | 8 +- .../vo/dashboard/LatestPointValueVO.java | 54 +- .../data/entity/vo/dashboard/MttaTrendVO.java | 24 +- .../entity/vo/dashboard/PeerDeviationVO.java | 20 +- .../entity/vo/dashboard/ProtocolHealthVO.java | 18 +- .../entity/vo/dashboard/SilentSourceVO.java | 18 +- .../entity/vo/dashboard/SystemHealthVO.java | 76 +- .../vo/dashboard/TimeseriesPointVO.java | 10 +- .../data/entity/vo/dashboard/TopEntityVO.java | 16 +- .../data/generator/MybatisGenerator.java | 46 +- .../data/grpc/server/PointValueServer.java | 286 ++- .../common/data/job/HourlyJobForData.java | 25 +- .../pnoker/common/data/job/PointValueJob.java | 119 +- .../common/data/mapper/AlertMapper.java | 64 +- .../common/data/mapper/DashboardMapper.java | 34 +- .../data/rabbit/DeviceEventReceiver.java | 61 +- .../data/rabbit/DriverEventReceiver.java | 61 +- .../data/rabbit/PointValueReceiver.java | 77 +- .../data/service/impl/MessageServiceImpl.java | 191 +- .../data/service/impl/NotifyServiceImpl.java | 191 +- .../data/service/impl/RuleServiceImpl.java | 191 +- .../pnoker/common/init/DataInitRunner.java | 40 +- .../main/resources/mapping/AlertMapper.xml | 22 +- dc3-common/dc3-common-driver/README.md | 3 +- .../config/ActiveDriverProfileConfig.java | 8 +- .../config/DriverEnvironmentConfig.java | 36 +- .../common/config/DriverTopicConfig.java | 174 +- .../common/driver/entity/bean/PointValue.java | 78 +- .../common/driver/entity/bean/RValue.java | 333 +-- .../common/driver/entity/bean/WValue.java | 153 +- .../common/driver/entity/bo/AttributeBO.java | 153 +- .../common/driver/entity/bo/DeviceBO.java | 98 +- .../common/driver/entity/bo/DriverBO.java | 80 +- .../common/driver/entity/bo/PointBO.java | 112 +- .../common/driver/entity/bo/RegisterBO.java | 44 +- .../driver/entity/builder/DeviceBuilder.java | 50 +- .../driver/entity/builder/DriverBuilder.java | 106 +- .../builder/GrpcDriverAttributeBuilder.java | 104 +- .../GrpcDriverAttributeConfigBuilder.java | 34 +- .../builder/GrpcPointAttributeBuilder.java | 104 +- .../GrpcPointAttributeConfigBuilder.java | 34 +- .../driver/entity/builder/PointBuilder.java | 48 +- .../entity/dto/DriverAttributeConfigDTO.java | 56 +- .../driver/entity/dto/DriverAttributeDTO.java | 80 +- .../entity/dto/PointAttributeConfigDTO.java | 64 +- .../driver/entity/dto/PointAttributeDTO.java | 80 +- .../entity/property/DriverProperties.java | 182 +- .../event/metadata/MetadataEventListener.java | 45 +- .../metadata/MetadataEventPublisher.java | 25 +- .../driver/grpc/client/DeviceClient.java | 153 +- .../driver/grpc/client/DriverClient.java | 121 +- .../driver/grpc/client/PointClient.java | 107 +- .../grpc/client/config/GrpcStubConfig.java | 24 +- .../driver/job/DriverCustomScheduleJob.java | 25 +- .../driver/job/DriverReadScheduleJob.java | 61 +- .../driver/job/DriverStatusScheduleJob.java | 32 +- .../driver/metadata/DeviceMetadata.java | 307 +-- .../driver/metadata/DriverMetadata.java | 56 +- .../common/driver/metadata/PointMetadata.java | 102 +- .../rabbit/DeviceCommandReceiver.java | 88 +- .../rabbit/DriverCommandReceiver.java | 40 +- .../receiver/rabbit/MetadataReceiver.java | 126 +- .../driver/service/DriverCustomService.java | 141 +- .../driver/service/DriverReadService.java | 24 +- .../driver/service/DriverRegisterService.java | 8 +- .../driver/service/DriverScheduleService.java | 8 +- .../driver/service/DriverSenderService.java | 100 +- .../driver/service/DriverWriteService.java | 26 +- .../service/impl/DriverReadServiceImpl.java | 106 +- .../impl/DriverRegisterServiceImpl.java | 86 +- .../impl/DriverScheduleServiceImpl.java | 91 +- .../service/impl/DriverSenderServiceImpl.java | 291 +-- .../service/impl/DriverWriteServiceImpl.java | 103 +- .../pnoker/common/init/DriverInitRunner.java | 38 +- .../github/pnoker/common/utils/CodecUtil.java | 383 ++-- dc3-common/dc3-common-exception/README.md | 3 +- .../constant/common/ExceptionConstant.java | 30 +- .../pnoker/common/exception/AddException.java | 18 +- .../common/exception/AssociatedException.java | 18 +- .../common/exception/ConfigException.java | 18 +- .../common/exception/ConnectorException.java | 18 +- .../common/exception/CronException.java | 18 +- .../common/exception/DeleteException.java | 18 +- .../common/exception/DuplicateException.java | 18 +- .../common/exception/EmptyException.java | 18 +- .../common/exception/ImportException.java | 18 +- .../common/exception/JsonException.java | 18 +- .../common/exception/NotFoundException.java | 18 +- .../common/exception/OutRangeException.java | 18 +- .../common/exception/ReadPointException.java | 18 +- .../common/exception/RegisterException.java | 18 +- .../common/exception/RepositoryException.java | 18 +- .../common/exception/RequestException.java | 18 +- .../common/exception/SecurityException.java | 18 +- .../common/exception/ServiceException.java | 46 +- .../common/exception/TypeException.java | 18 +- .../exception/UnAuthorizedException.java | 18 +- .../common/exception/UnSupportException.java | 18 +- .../common/exception/UpdateException.java | 18 +- .../common/exception/WritePointException.java | 18 +- .../pnoker/common/utils/ExceptionUtil.java | 28 +- .../common/facade/api/DeviceFacade.java | 44 +- .../common/facade/api/DriverFacade.java | 27 +- .../pnoker/common/facade/api/PointFacade.java | 16 +- .../facade/api/PointValueCommandFacade.java | 22 +- .../common/facade/api/PointValueFacade.java | 24 +- .../facade/api/ResourceRegistryFacade.java | 10 +- .../common/facade/api/TenantFacade.java | 8 +- .../pnoker/common/facade/api/TokenFacade.java | 19 +- .../pnoker/common/facade/api/UserFacade.java | 8 +- .../common/facade/api/UserLoginFacade.java | 8 +- .../facade/entity/bo/FacadeDeviceBO.java | 18 +- .../facade/entity/bo/FacadeDriverBO.java | 20 +- .../facade/entity/bo/FacadePointBO.java | 28 +- .../facade/entity/bo/FacadePointValueBO.java | 40 +- .../FacadeResourceRegistrySyncCommandBO.java | 6 +- .../FacadeResourceRegistrySyncResultBO.java | 8 +- .../facade/entity/bo/FacadeScannedApiBO.java | 18 +- .../facade/entity/bo/FacadeTenantBO.java | 6 +- .../common/facade/entity/bo/FacadeUserBO.java | 12 +- .../facade/entity/bo/FacadeUserLoginBO.java | 8 +- .../facade/entity/common/FacadePage.java | 20 +- .../entity/query/FacadeDeviceQuery.java | 20 +- .../entity/query/FacadeDriverQuery.java | 22 +- .../facade/entity/query/FacadePointQuery.java | 30 +- .../entity/query/FacadePointValueQuery.java | 12 +- .../common/facade/grpc/DeviceGrpcFacade.java | 120 +- .../common/facade/grpc/DriverGrpcFacade.java | 90 +- .../common/facade/grpc/PointGrpcFacade.java | 70 +- .../grpc/PointValueCommandGrpcFacade.java | 42 +- .../facade/grpc/PointValueGrpcFacade.java | 92 +- .../grpc/ResourceRegistryGrpcFacade.java | 64 +- .../common/facade/grpc/TenantGrpcFacade.java | 42 +- .../common/facade/grpc/TokenGrpcFacade.java | 26 +- .../common/facade/grpc/UserGrpcFacade.java | 42 +- .../facade/grpc/UserLoginGrpcFacade.java | 44 +- .../grpc/builder/FacadeGrpcDeviceBuilder.java | 76 +- .../grpc/builder/FacadeGrpcDriverBuilder.java | 84 +- .../grpc/builder/FacadeGrpcPointBuilder.java | 106 +- .../builder/FacadeGrpcPointValueBuilder.java | 41 +- .../grpc/builder/FacadeGrpcTenantBuilder.java | 22 +- .../grpc/builder/FacadeGrpcUserBuilder.java | 28 +- .../builder/FacadeGrpcUserLoginBuilder.java | 24 +- .../facade/grpc/config/GrpcStubConfig.java | 74 +- .../local/ResourceRegistryLocalFacade.java | 68 +- .../facade/local/TenantLocalFacade.java | 18 +- .../common/facade/local/TokenLocalFacade.java | 14 +- .../common/facade/local/UserLocalFacade.java | 18 +- .../facade/local/UserLoginLocalFacade.java | 18 +- .../local/builder/FacadeTenantBuilder.java | 4 +- .../local/builder/FacadeUserBuilder.java | 30 +- .../local/builder/FacadeUserLoginBuilder.java | 4 +- .../LocalFacadeAuthAutoConfiguration.java | 26 +- .../local/PointValueCommandLocalFacade.java | 38 +- .../facade/local/PointValueLocalFacade.java | 50 +- .../builder/FacadePointValueBuilder.java | 26 +- .../LocalFacadeDataAutoConfiguration.java | 16 +- .../facade/local/DeviceLocalFacade.java | 70 +- .../facade/local/DriverLocalFacade.java | 48 +- .../common/facade/local/PointLocalFacade.java | 38 +- .../local/builder/FacadeDeviceBuilder.java | 6 +- .../local/builder/FacadeDriverBuilder.java | 6 +- .../local/builder/FacadePointBuilder.java | 6 +- .../LocalFacadeManagerAutoConfiguration.java | 22 +- dc3-common/dc3-common-gateway/README.md | 3 +- .../config/ActiveGatewayProfileConfig.java | 12 +- .../filter/AuthenticGatewayFilter.java | 64 +- .../filter/AuthenticGatewayFilterFactory.java | 16 +- .../common/gateway/service/FilterService.java | 8 +- .../service/impl/FilterServiceImpl.java | 131 +- .../pnoker/common/init/GatewayInitRunner.java | 2 +- dc3-common/dc3-common-log/README.md | 3 +- .../github/pnoker/common/annotation/Logs.java | 51 +- .../pnoker/common/annotation/LogsAspect.java | 72 +- .../pnoker/common/annotation/LogsType.java | 2 +- dc3-common/dc3-common-manager/README.md | 3 +- .../config/ActiveManagerProfileConfig.java | 8 +- .../pnoker/common/init/ManagerInitRunner.java | 46 +- .../biz/DictionaryForManagerService.java | 78 +- .../manager/biz/DriverRegisterService.java | 37 +- .../manager/biz/ImportDeviceService.java | 23 +- .../biz/ScheduleForManagerService.java | 8 +- .../impl/DictionaryForManagerServiceImpl.java | 182 +- .../biz/impl/DriverRegisterServiceImpl.java | 211 +- .../biz/impl/ImportDeviceServiceImpl.java | 220 +- .../impl/ScheduleForManagerServiceImpl.java | 27 +- .../manager/constant/TopologyLimits.java | 70 +- .../controller/DashboardController.java | 136 +- .../manager/controller/DeviceController.java | 333 ++- .../DictionaryForManagerController.java | 270 +-- .../DriverAttributeConfigController.java | 286 +-- .../controller/DriverAttributeController.java | 241 ++- .../manager/controller/DriverController.java | 274 +-- .../manager/controller/GroupController.java | 185 +- .../manager/controller/LabelController.java | 185 +- .../PointAttributeConfigController.java | 328 +-- .../controller/PointAttributeController.java | 241 ++- .../manager/controller/PointController.java | 644 +++--- .../manager/controller/ProfileController.java | 268 +-- .../manager/controller/TopicController.java | 29 +- .../common/manager/dal/DeviceManager.java | 22 +- .../manager/dal/impl/DeviceManagerImpl.java | 48 +- .../DriverAttributeConfigManagerImpl.java | 2 +- .../dal/impl/DriverAttributeManagerImpl.java | 2 +- .../impl/PointAttributeConfigManagerImpl.java | 2 +- .../dal/impl/PointAttributeManagerImpl.java | 2 +- .../PointDataVolumeHistoryManagerImpl.java | 2 +- .../impl/PointDataVolumeRunManagerImpl.java | 2 +- .../dal/impl/ProfileBindManagerImpl.java | 2 +- .../common/manager/entity/bo/DeviceBO.java | 74 +- .../manager/entity/bo/DeviceByPointBO.java | 16 +- .../entity/bo/DeviceDataVolumeRunBO.java | 16 +- .../manager/entity/bo/DriverAttributeBO.java | 80 +- .../entity/bo/DriverAttributeConfigBO.java | 64 +- .../common/manager/entity/bo/DriverBO.java | 80 +- .../manager/entity/bo/PointAttributeBO.java | 80 +- .../entity/bo/PointAttributeConfigBO.java | 72 +- .../common/manager/entity/bo/PointBO.java | 134 +- .../entity/bo/PointConfigByDeviceBO.java | 24 +- .../bo/PointDataStatisticsByDriverIdBO.java | 16 +- .../entity/bo/PointDataVolumeRunBO.java | 16 +- .../common/manager/entity/bo/ProfileBO.java | 72 +- .../manager/entity/bo/ProfileBindBO.java | 24 +- .../entity/bo/dashboard/BucketRow.java | 14 +- .../entity/bo/dashboard/DailyGrowthRow.java | 4 +- .../entity/bo/dashboard/PointVolumeRow.java | 6 +- .../bo/dashboard/ProfileBindingRow.java | 4 +- .../bo/dashboard/TopologyDeviceRow.java | 8 +- .../bo/dashboard/TopologyDriverRow.java | 6 +- .../entity/bo/dashboard/TopologyPointRow.java | 6 +- .../bo/dashboard/TopologyProfileRow.java | 4 +- .../manager/entity/builder/DeviceBuilder.java | 244 +-- .../builder/DictionaryForManagerBuilder.java | 178 +- .../builder/DriverAttributeBuilder.java | 248 +-- .../builder/DriverAttributeConfigBuilder.java | 188 +- .../manager/entity/builder/DriverBuilder.java | 256 +-- .../entity/builder/PointAttributeBuilder.java | 248 +-- .../builder/PointAttributeConfigBuilder.java | 188 +- .../manager/entity/builder/PointBuilder.java | 282 +-- .../entity/builder/ProfileBindBuilder.java | 160 +- .../entity/builder/ProfileBuilder.java | 272 +-- .../common/manager/entity/model/DeviceDO.java | 176 +- .../entity/model/DriverAttributeConfigDO.java | 176 +- .../entity/model/DriverAttributeDO.java | 196 +- .../common/manager/entity/model/DriverDO.java | 196 +- .../entity/model/PointAttributeConfigDO.java | 186 +- .../entity/model/PointAttributeDO.java | 196 +- .../common/manager/entity/model/PointDO.java | 236 +-- .../model/PointDataVolumeHistoryDO.java | 156 +- .../entity/model/PointDataVolumeRunDO.java | 156 +- .../manager/entity/model/ProfileBindDO.java | 126 +- .../manager/entity/model/ProfileDO.java | 186 +- .../manager/entity/query/DeviceQuery.java | 66 +- .../manager/entity/query/DictionaryQuery.java | 20 +- .../query/DriverAttributeConfigQuery.java | 48 +- .../entity/query/DriverAttributeQuery.java | 64 +- .../manager/entity/query/DriverQuery.java | 72 +- .../query/PointAttributeConfigQuery.java | 56 +- .../entity/query/PointAttributeQuery.java | 64 +- .../manager/entity/query/PointQuery.java | 82 +- .../entity/query/ProfileBindQuery.java | 32 +- .../manager/entity/query/ProfileQuery.java | 74 +- .../manager/entity/query/TopicQuery.java | 22 +- .../manager/entity/vo/DeviceByPointVO.java | 16 +- .../entity/vo/DeviceDataVolumeRunVO.java | 4 +- .../common/manager/entity/vo/DeviceVO.java | 70 +- .../entity/vo/DriverAttributeConfigVO.java | 62 +- .../manager/entity/vo/DriverAttributeVO.java | 86 +- .../common/manager/entity/vo/DriverVO.java | 90 +- .../entity/vo/PointAttributeConfigVO.java | 72 +- .../manager/entity/vo/PointAttributeVO.java | 86 +- .../entity/vo/PointConfigByDeviceVO.java | 24 +- .../vo/PointDataStatisticsByDriverIdVO.java | 4 +- .../entity/vo/PointDataVolumeRunVO.java | 4 +- .../common/manager/entity/vo/PointVO.java | 112 +- .../manager/entity/vo/ProfileBindVO.java | 20 +- .../common/manager/entity/vo/ProfileVO.java | 70 +- .../common/manager/entity/vo/TopicVO.java | 6 +- .../manager/entity/vo/dashboard/BucketVO.java | 16 +- .../entity/vo/dashboard/DeviceStatsVO.java | 32 +- .../entity/vo/dashboard/DriverStatsVO.java | 38 +- .../manager/entity/vo/dashboard/GrowthVO.java | 12 +- .../vo/dashboard/TopologyHiddenChildVO.java | 24 +- .../entity/vo/dashboard/TopologyLinkVO.java | 10 +- .../entity/vo/dashboard/TopologyNodeVO.java | 54 +- .../entity/vo/dashboard/TopologyStatsVO.java | 24 +- .../entity/vo/dashboard/TopologyVO.java | 10 +- .../event/metadata/MetadataEventListener.java | 66 +- .../metadata/MetadataEventPublisher.java | 22 +- .../manager/generator/MybatisGenerator.java | 46 +- .../grpc/builder/GrpcDeviceBuilder.java | 135 +- .../builder/GrpcDriverAttributeBuilder.java | 126 +- .../GrpcDriverAttributeConfigBuilder.java | 55 +- .../grpc/builder/GrpcDriverBuilder.java | 165 +- .../builder/GrpcPointAttributeBuilder.java | 126 +- .../GrpcPointAttributeConfigBuilder.java | 55 +- .../grpc/builder/GrpcPointBuilder.java | 150 +- .../server/driver/DriverDeviceServer.java | 172 +- .../server/driver/DriverDriverServer.java | 99 +- .../grpc/server/driver/DriverPointServer.java | 112 +- .../server/manager/ManagerDeviceServer.java | 202 +- .../server/manager/ManagerDriverServer.java | 151 +- .../server/manager/ManagerPointServer.java | 112 +- .../manager/job/HourlyJobForManager.java | 25 +- .../manager/mapper/DashboardMapper.java | 94 +- .../common/manager/mapper/DeviceMapper.java | 4 +- .../common/manager/mapper/PointMapper.java | 4 +- .../common/manager/mapper/ProfileMapper.java | 4 +- .../manager/service/DashboardService.java | 63 +- .../common/manager/service/DeviceService.java | 102 +- .../service/DriverAttributeConfigService.java | 51 +- .../service/DriverAttributeService.java | 28 +- .../common/manager/service/DriverService.java | 67 +- .../service/PointAttributeConfigService.java | 68 +- .../service/PointAttributeService.java | 28 +- .../common/manager/service/PointService.java | 169 +- .../manager/service/ProfileBindService.java | 69 +- .../manager/service/ProfileService.java | 43 +- .../common/manager/service/TopicService.java | 2 +- .../service/impl/DashboardServiceImpl.java | 1008 +++++---- .../service/impl/DeviceServiceImpl.java | 810 ++++---- .../DriverAttributeConfigServiceImpl.java | 285 +-- .../impl/DriverAttributeServiceImpl.java | 223 +- .../service/impl/DriverServiceImpl.java | 289 +-- .../impl/PointAttributeConfigServiceImpl.java | 325 +-- .../impl/PointAttributeServiceImpl.java | 225 +- .../service/impl/PointServiceImpl.java | 741 ++++--- .../service/impl/ProfileBindServiceImpl.java | 253 +-- .../service/impl/ProfileServiceImpl.java | 267 +-- .../service/impl/TopicServiceImpl.java | 100 +- dc3-common/dc3-common-model/README.md | 3 +- .../pnoker/common/entity/base/BaseBO.java | 68 +- .../pnoker/common/entity/base/BaseDTO.java | 68 +- .../pnoker/common/entity/base/BaseVO.java | 74 +- .../common/entity/builder/BaseBuilder.java | 106 +- .../common/entity/dto/CmdParameterDTO.java | 28 +- .../common/entity/dto/DeviceCommandDTO.java | 168 +- .../common/entity/dto/DeviceEventDTO.java | 162 +- .../common/entity/dto/DriverCommandDTO.java | 28 +- .../common/entity/dto/DriverEventDTO.java | 118 +- .../common/entity/dto/MetadataEventDTO.java | 28 +- .../common/entity/event/MetadataEvent.java | 33 +- .../pnoker/common/entity/ext/ApiExt.java | 48 +- .../pnoker/common/entity/ext/BaseExt.java | 30 +- .../pnoker/common/entity/ext/DeviceExt.java | 30 +- .../common/entity/ext/DriverAttributeExt.java | 26 +- .../pnoker/common/entity/ext/DriverExt.java | 26 +- .../pnoker/common/entity/ext/JsonExt.java | 38 +- .../pnoker/common/entity/ext/MenuExt.java | 76 +- .../pnoker/common/entity/ext/MessageExt.java | 26 +- .../pnoker/common/entity/ext/NotifyExt.java | 26 +- .../common/entity/ext/PointAttributeExt.java | 26 +- .../pnoker/common/entity/ext/PointExt.java | 26 +- .../pnoker/common/entity/ext/ProfileExt.java | 26 +- .../pnoker/common/entity/ext/ResourceExt.java | 26 +- .../pnoker/common/entity/ext/RoleExt.java | 26 +- .../pnoker/common/entity/ext/RuleExt.java | 26 +- .../pnoker/common/entity/ext/TenantExt.java | 26 +- .../common/entity/ext/UserIdentityExt.java | 56 +- .../common/entity/ext/UserSocialExt.java | 64 +- dc3-common/dc3-common-mqtt/README.md | 6 +- .../config/ActiveMqttProfileConfig.java | 18 +- .../pnoker/common/config/MqttConfig.java | 154 +- .../common/config/MqttEnvironmentConfig.java | 40 +- .../pnoker/common/init/MqttInitRunner.java | 42 +- .../common/mqtt/entity/MessageHeader.java | 70 +- .../common/mqtt/entity/MqttMessage.java | 4 +- .../mqtt/entity/property/MqttProperties.java | 80 +- .../mqtt/handler/MqttReceiveHandler.java | 95 +- .../mqtt/service/MqttReceiveService.java | 38 +- .../mqtt/service/MqttScheduleService.java | 8 +- .../service/impl/MqttScheduleServiceImpl.java | 29 +- .../mqtt/service/job/MqttScheduleJob.java | 116 +- .../github/pnoker/common/utils/MqttUtil.java | 67 +- dc3-common/dc3-common-postgres/README.md | 3 +- .../config/ActivePostgresProfileConfig.java | 18 +- .../common/config/MybatisPlusConfig.java | 21 +- .../TimestamptzLocalDateTimeTypeHandler.java | 40 +- .../pnoker/common/utils/MybatisUtil.java | 188 +- dc3-common/dc3-common-public/README.md | 3 +- .../common/base/service/BaseService.java | 59 +- .../pnoker/common/config/OkHttpConfig.java | 31 +- .../io/github/pnoker/common/entity/R.java | 433 ++-- .../pnoker/common/entity/auth/Keys.java | 48 +- .../pnoker/common/entity/common/Pages.java | 14 +- .../common/entity/common/RequestHeader.java | 78 +- .../pnoker/common/entity/common/TreeNode.java | 25 +- .../common/optional/CollectionOptional.java | 39 +- .../common/optional/EnableOptional.java | 51 +- .../common/optional/IntegerOptional.java | 39 +- .../pnoker/common/optional/JsonOptional.java | 39 +- .../pnoker/common/optional/LongOptional.java | 39 +- .../common/optional/StringOptional.java | 39 +- .../pnoker/common/utils/ArithmeticUtil.java | 359 ++-- .../github/pnoker/common/utils/CmdUtil.java | 46 +- .../github/pnoker/common/utils/CodeUtil.java | 21 +- .../pnoker/common/utils/DecodeUtil.java | 178 +- .../pnoker/common/utils/EnvironmentUtil.java | 67 +- .../github/pnoker/common/utils/FieldUtil.java | 61 +- .../github/pnoker/common/utils/FileUtil.java | 55 +- .../github/pnoker/common/utils/HostUtil.java | 258 ++- .../github/pnoker/common/utils/JsonUtil.java | 722 +++---- .../pnoker/common/utils/KeyStoreUtil.java | 99 +- .../github/pnoker/common/utils/KeyUtil.java | 340 +-- .../common/utils/LocalDateTimeUtil.java | 212 +- .../pnoker/common/utils/MapStructUtil.java | 32 +- .../github/pnoker/common/utils/PageUtil.java | 71 +- .../github/pnoker/common/utils/PoiUtil.java | 157 +- .../github/pnoker/common/utils/RegexUtil.java | 152 +- .../pnoker/common/utils/TimeRangeUtil.java | 195 +- .../github/pnoker/common/utils/TimeUtil.java | 179 +- .../github/pnoker/common/utils/TreeUtil.java | 119 +- .../github/pnoker/common/utils/X509Util.java | 168 +- .../pnoker/common/utils/ZoneDateTimeUtil.java | 212 +- dc3-common/dc3-common-quartz/README.md | 3 +- .../config/ActiveQuartzProfileConfig.java | 19 +- .../pnoker/common/quartz/QuartzService.java | 137 +- dc3-common/dc3-common-rabbitmq/README.md | 3 +- .../config/ActiveRabbitProfileConfig.java | 19 +- .../pnoker/common/config/ExchangeConfig.java | 85 +- .../pnoker/common/config/RabbitConfig.java | 101 +- .../config/RabbitmqEnvironmentConfig.java | 65 +- dc3-common/dc3-common-repository/README.md | 9 +- .../config/ActiveRepositoryProfileConfig.java | 19 +- .../pnoker/common/entity/bo/PointQueryBO.java | 20 +- .../pnoker/common/entity/bo/PointValueBO.java | 68 +- .../common/entity/query/PointValueQuery.java | 90 +- .../common/repository/RepositoryService.java | 103 +- .../strategy/RepositoryStrategyFactory.java | 61 +- .../resource/registrar/ResourceRegistrar.java | 101 +- .../ResourceRegistrarAutoConfiguration.java | 22 +- .../config/ResourceRegistrarProperties.java | 48 +- .../registrar/scan/ApiEndpointScanner.java | 150 +- dc3-common/dc3-common-thread/README.md | 6 +- .../config/ActiveThreadProfileConfig.java | 19 +- .../common/config/ThreadPoolConfig.java | 146 +- .../pnoker/common/init/ThreadInitRunner.java | 23 +- .../entity/property/ThreadProperties.java | 32 +- dc3-common/dc3-common-web/README.md | 3 +- .../pnoker/common/base/BaseController.java | 75 +- .../common/config/ActiveWebProfileConfig.java | 19 +- .../pnoker/common/config/ExceptionConfig.java | 181 +- .../pnoker/common/config/WebFilterConfig.java | 98 +- .../pnoker/common/config/WebFluxConfig.java | 36 +- .../pnoker/common/utils/RequestUtil.java | 138 +- .../pnoker/common/utils/ResponseUtil.java | 48 +- .../pnoker/common/utils/UserHeaderUtil.java | 141 +- dc3-common/pom.xml | 47 - .../dc3-driver-listening-virtual/README.md | 3 +- .../ListeningVirtualDriverApplication.java | 15 +- .../service/impl/DriverCustomServiceImpl.java | 212 +- .../service/netty/NettyServerHandler.java | 101 +- .../service/netty/tcp/NettyTcpServer.java | 72 +- .../netty/tcp/NettyTcpServerHandler.java | 70 +- .../service/netty/udp/NettyUdpServer.java | 50 +- .../netty/udp/NettyUdpServerHandler.java | 70 +- dc3-driver/dc3-driver-modbus-tcp/README.md | 3 +- .../serotonin/modbus4j/BasicProcessImage.java | 1154 ++++++----- .../com/serotonin/modbus4j/BatchRead.java | 439 ++-- .../com/serotonin/modbus4j/BatchResults.java | 136 +- .../serotonin/modbus4j/ExceptionResult.java | 63 +- .../java/com/serotonin/modbus4j/Modbus.java | 273 +-- .../com/serotonin/modbus4j/ModbusFactory.java | 281 +-- .../com/serotonin/modbus4j/ModbusMaster.java | 1039 +++++----- .../serotonin/modbus4j/ModbusSlaveSet.java | 193 +- .../serotonin/modbus4j/NodeScanListener.java | 15 +- .../com/serotonin/modbus4j/ProcessImage.java | 239 ++- .../modbus4j/ProcessImageListener.java | 38 +- .../modbus4j/base/BaseMessageParser.java | 71 +- .../modbus4j/base/BaseRequestHandler.java | 82 +- .../modbus4j/base/KeyedModbusLocator.java | 216 +- .../serotonin/modbus4j/base/ModbusUtils.java | 453 ++-- .../modbus4j/base/RangeAndOffset.java | 109 +- .../modbus4j/base/ReadFunctionGroup.java | 174 +- .../modbus4j/base/SlaveAndRange.java | 113 +- .../serotonin/modbus4j/base/SlaveProfile.java | 40 +- .../com/serotonin/modbus4j/code/DataType.java | 498 ++--- .../modbus4j/code/ExceptionCode.java | 133 +- .../serotonin/modbus4j/code/FunctionCode.java | 109 +- .../modbus4j/code/RegisterRange.java | 155 +- .../exception/ErrorResponseException.java | 75 +- .../IllegalDataAddressException.java | 37 +- .../exception/IllegalDataTypeException.java | 21 +- .../exception/IllegalFunctionException.java | 46 +- .../exception/IllegalSlaveIdException.java | 21 +- .../InvalidDataConversionException.java | 21 +- .../modbus4j/exception/ModbusIdException.java | 40 +- .../exception/ModbusInitException.java | 77 +- .../exception/ModbusTransportException.java | 171 +- .../modbus4j/exception/SlaveIdNotEqual.java | 19 +- .../com/serotonin/modbus4j/ip/IpMessage.java | 52 +- .../modbus4j/ip/IpMessageResponse.java | 15 +- .../serotonin/modbus4j/ip/IpParameters.java | 160 +- .../modbus4j/ip/encap/EncapMessage.java | 50 +- .../modbus4j/ip/encap/EncapMessageParser.java | 31 +- .../ip/encap/EncapMessageRequest.java | 62 +- .../ip/encap/EncapMessageResponse.java | 54 +- .../ip/encap/EncapRequestHandler.java | 35 +- .../ip/encap/EncapWaitingRoomKeyFactory.java | 99 +- .../modbus4j/ip/listener/TcpListener.java | 562 +++-- .../serotonin/modbus4j/ip/tcp/TcpMaster.java | 539 ++--- .../serotonin/modbus4j/ip/tcp/TcpSlave.java | 261 ++- .../serotonin/modbus4j/ip/udp/UdpMaster.java | 235 ++- .../serotonin/modbus4j/ip/udp/UdpSlave.java | 190 +- .../serotonin/modbus4j/ip/xa/XaMessage.java | 99 +- .../modbus4j/ip/xa/XaMessageParser.java | 31 +- .../modbus4j/ip/xa/XaMessageRequest.java | 70 +- .../modbus4j/ip/xa/XaMessageResponse.java | 62 +- .../modbus4j/ip/xa/XaRequestHandler.java | 35 +- .../ip/xa/XaWaitingRoomKeyFactory.java | 109 +- .../modbus4j/locator/BaseLocator.java | 552 ++--- .../modbus4j/locator/BinaryLocator.java | 180 +- .../modbus4j/locator/NumericLocator.java | 779 +++---- .../modbus4j/locator/StringLocator.java | 313 ++- .../modbus4j/msg/ExceptionRequest.java | 100 +- .../modbus4j/msg/ExceptionResponse.java | 55 +- .../serotonin/modbus4j/msg/ModbusMessage.java | 227 +- .../serotonin/modbus4j/msg/ModbusRequest.java | 209 +- .../modbus4j/msg/ModbusResponse.java | 297 +-- .../modbus4j/msg/ReadBinaryRequest.java | 145 +- .../modbus4j/msg/ReadCoilsRequest.java | 73 +- .../modbus4j/msg/ReadCoilsResponse.java | 34 +- .../msg/ReadDiscreteInputsRequest.java | 63 +- .../msg/ReadDiscreteInputsResponse.java | 34 +- .../msg/ReadExceptionStatusRequest.java | 69 +- .../msg/ReadExceptionStatusResponse.java | 59 +- .../msg/ReadHoldingRegistersRequest.java | 75 +- .../msg/ReadHoldingRegistersResponse.java | 34 +- .../msg/ReadInputRegistersRequest.java | 75 +- .../msg/ReadInputRegistersResponse.java | 34 +- .../modbus4j/msg/ReadNumericRequest.java | 143 +- .../serotonin/modbus4j/msg/ReadResponse.java | 138 +- .../modbus4j/msg/ReportSlaveIdRequest.java | 69 +- .../modbus4j/msg/ReportSlaveIdResponse.java | 69 +- .../modbus4j/msg/WriteCoilRequest.java | 93 +- .../modbus4j/msg/WriteCoilResponse.java | 86 +- .../modbus4j/msg/WriteCoilsRequest.java | 113 +- .../modbus4j/msg/WriteCoilsResponse.java | 86 +- .../msg/WriteMaskRegisterRequest.java | 187 +- .../msg/WriteMaskRegisterResponse.java | 113 +- .../modbus4j/msg/WriteRegisterRequest.java | 93 +- .../modbus4j/msg/WriteRegisterResponse.java | 86 +- .../modbus4j/msg/WriteRegistersRequest.java | 113 +- .../modbus4j/msg/WriteRegistersResponse.java | 86 +- .../modbus4j/serial/SerialMaster.java | 236 ++- .../modbus4j/serial/SerialMessage.java | 60 +- .../modbus4j/serial/SerialPortWrapper.java | 108 +- .../modbus4j/serial/SerialSlave.java | 75 +- .../serial/SerialWaitingRoomKeyFactory.java | 50 +- .../modbus4j/serial/ascii/AsciiMaster.java | 148 +- .../modbus4j/serial/ascii/AsciiMessage.java | 255 +-- .../serial/ascii/AsciiMessageParser.java | 31 +- .../serial/ascii/AsciiMessageRequest.java | 60 +- .../serial/ascii/AsciiMessageResponse.java | 52 +- .../serial/ascii/AsciiRequestHandler.java | 35 +- .../modbus4j/serial/ascii/AsciiSlave.java | 60 +- .../modbus4j/serial/rtu/RtuMaster.java | 318 +-- .../modbus4j/serial/rtu/RtuMessage.java | 50 +- .../modbus4j/serial/rtu/RtuMessageParser.java | 45 +- .../serial/rtu/RtuMessageRequest.java | 62 +- .../serial/rtu/RtuMessageResponse.java | 54 +- .../serial/rtu/RtuRequestHandler.java | 35 +- .../modbus4j/serial/rtu/RtuSlave.java | 62 +- .../sero/NotImplementedException.java | 37 +- .../sero/ShouldNeverHappenException.java | 40 +- .../sero/epoll/InputStreamEPollWrapper.java | 32 +- .../epoll/Modbus4JInputStreamCallback.java | 46 +- .../modbus4j/sero/io/LineHandler.java | 27 +- .../modbus4j/sero/io/NullWriter.java | 24 +- .../modbus4j/sero/io/StreamUtils.java | 1230 +++++------ .../modbus4j/sero/log/BaseIOLog.java | 263 +-- .../serotonin/modbus4j/sero/log/IOLog.java | 121 +- .../modbus4j/sero/log/RollingIOLog.java | 136 +- .../modbus4j/sero/log/SimpleLog.java | 172 +- .../modbus4j/sero/messaging/DataConsumer.java | 28 +- .../DefaultMessagingExceptionHandler.java | 6 +- .../sero/messaging/EpollStreamTransport.java | 128 +- .../EpollStreamTransportCharSpaced.java | 121 +- .../sero/messaging/IncomingMessage.java | 2 +- .../messaging/IncomingRequestMessage.java | 2 +- .../messaging/IncomingResponseMessage.java | 2 +- .../sero/messaging/InputStreamListener.java | 205 +- .../sero/messaging/MessageControl.java | 581 +++--- .../sero/messaging/MessageParser.java | 33 +- .../messaging/MessagingExceptionHandler.java | 15 +- .../sero/messaging/OutgoingMessage.java | 11 +- .../messaging/OutgoingRequestMessage.java | 11 +- .../messaging/OutgoingResponseMessage.java | 2 +- .../sero/messaging/RequestHandler.java | 17 +- .../sero/messaging/StreamTransport.java | 156 +- .../messaging/StreamTransportCharSpaced.java | 113 +- .../sero/messaging/TestableTransport.java | 72 +- .../sero/messaging/TimeoutException.java | 23 +- .../modbus4j/sero/messaging/Transport.java | 65 +- .../modbus4j/sero/messaging/WaitingRoom.java | 212 +- .../sero/messaging/WaitingRoomException.java | 23 +- .../sero/messaging/WaitingRoomKey.java | 2 +- .../sero/messaging/WaitingRoomKeyFactory.java | 34 +- .../modbus4j/sero/timer/SystemTimeSource.java | 19 +- .../modbus4j/sero/timer/TimeSource.java | 15 +- .../modbus4j/sero/util/ArrayUtils.java | 673 +++--- .../modbus4j/sero/util/ProgressiveTask.java | 210 +- .../sero/util/ProgressiveTaskListener.java | 33 +- .../modbus4j/sero/util/queue/ByteQueue.java | 1831 +++++++++-------- .../serotonin/modbus4j/value/ModbusValue.java | 243 +-- .../driver/ModbusTcpDriverApplication.java | 15 +- .../service/impl/DriverCustomServiceImpl.java | 426 ++-- dc3-driver/dc3-driver-mqtt/README.md | 3 +- .../pnoker/driver/MqttDriverApplication.java | 15 +- .../service/impl/MqttReceiveServiceImpl.java | 76 +- .../driver/service/MqttSendService.java | 52 +- .../service/impl/DriverCustomServiceImpl.java | 315 +-- dc3-driver/dc3-driver-opc-da/README.md | 3 +- .../pnoker/driver/OpcDaApplication.java | 15 +- .../service/impl/DriverCustomServiceImpl.java | 431 ++-- .../openscada/opc/dcom/common/Categories.java | 8 +- .../openscada/opc/dcom/common/Constants.java | 14 +- .../opc/dcom/common/EventHandler.java | 6 +- .../openscada/opc/dcom/common/FILETIME.java | 196 +- .../opc/dcom/common/KeyedResult.java | 28 +- .../opc/dcom/common/KeyedResultSet.java | 16 +- .../org/openscada/opc/dcom/common/Result.java | 46 +- .../openscada/opc/dcom/common/ResultSet.java | 14 +- .../opc/dcom/common/impl/BaseCOMObject.java | 23 +- .../opc/dcom/common/impl/EnumGUID.java | 126 +- .../opc/dcom/common/impl/EnumString.java | 142 +- .../dcom/common/impl/EventHandlerImpl.java | 45 +- .../opc/dcom/common/impl/Helper.java | 69 +- .../opc/dcom/common/impl/OPCCommon.java | 84 +- .../org/openscada/opc/dcom/da/Constants.java | 20 +- .../opc/dcom/da/IOPCDataCallback.java | 12 +- .../org/openscada/opc/dcom/da/IORequest.java | 36 +- .../opc/dcom/da/OPCBROWSEDIRECTION.java | 40 +- .../openscada/opc/dcom/da/OPCBROWSETYPE.java | 40 +- .../openscada/opc/dcom/da/OPCDATASOURCE.java | 36 +- .../openscada/opc/dcom/da/OPCENUMSCOPE.java | 54 +- .../openscada/opc/dcom/da/OPCGroupState.java | 112 +- .../org/openscada/opc/dcom/da/OPCITEMDEF.java | 119 +- .../openscada/opc/dcom/da/OPCITEMRESULT.java | 94 +- .../openscada/opc/dcom/da/OPCITEMSTATE.java | 106 +- .../opc/dcom/da/OPCNAMESPACETYPE.java | 36 +- .../openscada/opc/dcom/da/OPCSERVERSTATE.java | 54 +- .../opc/dcom/da/OPCSERVERSTATUS.java | 214 +- .../opc/dcom/da/PropertyDescription.java | 42 +- .../org/openscada/opc/dcom/da/ValueData.java | 42 +- .../openscada/opc/dcom/da/WriteRequest.java | 59 +- .../opc/dcom/da/impl/OPCAsyncIO2.java | 130 +- .../openscada/opc/dcom/da/impl/OPCBrowse.java | 6 +- .../da/impl/OPCBrowseServerAddressSpace.java | 182 +- .../opc/dcom/da/impl/OPCDataCallback.java | 325 ++- .../opc/dcom/da/impl/OPCGroupStateMgt.java | 257 +-- .../openscada/opc/dcom/da/impl/OPCItemIO.java | 50 +- .../opc/dcom/da/impl/OPCItemMgt.java | 250 +-- .../opc/dcom/da/impl/OPCItemProperties.java | 164 +- .../openscada/opc/dcom/da/impl/OPCServer.java | 226 +- .../openscada/opc/dcom/da/impl/OPCSyncIO.java | 100 +- .../openscada/opc/dcom/list/ClassDetails.java | 42 +- .../openscada/opc/dcom/list/Constants.java | 4 +- .../opc/dcom/list/impl/OPCServerList.java | 170 +- .../lib/common/AlreadyConnectedException.java | 2 +- .../opc/lib/common/ConnectionInformation.java | 168 +- .../opc/lib/common/NotConnectedException.java | 2 +- .../org/openscada/opc/lib/da/AccessBase.java | 418 ++-- .../opc/lib/da/AccessStateListener.java | 4 +- .../opc/lib/da/AddFailedException.java | 52 +- .../openscada/opc/lib/da/Async20Access.java | 139 +- .../opc/lib/da/AutoReconnectController.java | 262 ++- .../opc/lib/da/AutoReconnectListener.java | 2 +- .../opc/lib/da/AutoReconnectState.java | 44 +- .../openscada/opc/lib/da/DataCallback.java | 2 +- .../opc/lib/da/DuplicateGroupException.java | 8 +- .../opc/lib/da/ErrorMessageResolver.java | 58 +- .../java/org/openscada/opc/lib/da/Group.java | 550 ++--- .../java/org/openscada/opc/lib/da/Item.java | 66 +- .../org/openscada/opc/lib/da/ItemState.java | 185 +- .../java/org/openscada/opc/lib/da/Server.java | 619 +++--- .../lib/da/ServerConnectionStateListener.java | 2 +- .../opc/lib/da/ServerStateListener.java | 2 +- .../opc/lib/da/ServerStateOperation.java | 126 +- .../opc/lib/da/ServerStateReader.java | 95 +- .../org/openscada/opc/lib/da/SyncAccess.java | 118 +- .../opc/lib/da/UnknownGroupException.java | 30 +- .../openscada/opc/lib/da/WriteRequest.java | 26 +- .../openscada/opc/lib/da/browser/Access.java | 16 +- .../opc/lib/da/browser/BaseBrowser.java | 138 +- .../openscada/opc/lib/da/browser/Branch.java | 138 +- .../opc/lib/da/browser/FlatBrowser.java | 67 +- .../openscada/opc/lib/da/browser/Leaf.java | 54 +- .../opc/lib/da/browser/TreeBrowser.java | 333 +-- .../openscada/opc/lib/list/Categories.java | 32 +- .../org/openscada/opc/lib/list/Category.java | 73 +- .../openscada/opc/lib/list/ServerList.java | 231 ++- dc3-driver/dc3-driver-opc-ua/README.md | 3 +- .../pnoker/driver/OpcUaApplication.java | 15 +- .../github/pnoker/driver/key/KeyLoader.java | 145 +- .../service/impl/DriverCustomServiceImpl.java | 364 ++-- dc3-driver/dc3-driver-plcs7/README.md | 3 +- .../pnoker/driver/PlcS7DriverApplication.java | 15 +- .../io/github/pnoker/driver/api/DaveArea.java | 58 +- .../github/pnoker/driver/api/S7Connector.java | 36 +- .../pnoker/driver/api/S7Serializable.java | 64 +- .../pnoker/driver/api/S7Serializer.java | 74 +- .../io/github/pnoker/driver/api/S7Type.java | 82 +- .../github/pnoker/driver/api/SiemensPLCS.java | 10 +- .../pnoker/driver/api/annotation/Array.java | 4 +- .../driver/api/annotation/Datablock.java | 2 +- .../driver/api/annotation/S7Variable.java | 42 +- .../api/factory/S7ConnectorFactory.java | 170 +- .../api/factory/S7SerializerFactory.java | 23 +- .../driver/api/impl/S7BaseConnection.java | 171 +- .../driver/api/impl/S7TCPConnection.java | 201 +- .../pnoker/driver/api/impl/nodave/Nodave.java | 618 +++--- .../pnoker/driver/api/impl/nodave/PDU.java | 828 ++++---- .../driver/api/impl/nodave/PLCinterface.java | 105 +- .../pnoker/driver/api/impl/nodave/Result.java | 6 +- .../driver/api/impl/nodave/ResultSet.java | 32 +- .../driver/api/impl/nodave/S7Connection.java | 648 +++--- .../driver/api/impl/nodave/TCPConnection.java | 192 +- .../api/impl/serializer/S7SerializerImpl.java | 302 ++- .../serializer/converter/BitConverter.java | 57 +- .../serializer/converter/ByteConverter.java | 44 +- .../converter/DateAndTimeConverter.java | 272 ++- .../serializer/converter/DateConverter.java | 97 +- .../converter/IntegerConverter.java | 60 +- .../serializer/converter/LongConverter.java | 70 +- .../serializer/converter/RealConverter.java | 76 +- .../serializer/converter/ShortConverter.java | 60 +- .../serializer/converter/StringConverter.java | 70 +- .../serializer/converter/StructConverter.java | 42 +- .../serializer/converter/TimeConverter.java | 62 +- .../api/impl/serializer/parser/BeanEntry.java | 60 +- .../serializer/parser/BeanParseResult.java | 16 +- .../impl/serializer/parser/BeanParser.java | 235 ++- .../driver/bean/PlcS7PointVariable.java | 128 +- .../pnoker/driver/exception/S7Exception.java | 65 +- .../service/impl/DriverCustomServiceImpl.java | 331 ++- dc3-driver/dc3-driver-virtual/README.md | 3 +- .../driver/VirtualDriverApplication.java | 17 +- .../service/impl/DriverCustomServiceImpl.java | 312 +-- dc3-gateway/README.md | 6 +- .../pnoker/gateway/GatewayApplication.java | 15 +- docs/MODULES.md | 96 +- docs/QUICKSTART.md | 10 +- docs/TROUBLESHOOTING.md | 12 + pom.xml | 53 +- 1102 files changed, 54464 insertions(+), 53518 deletions(-) delete mode 100644 .springjavaformatconfig delete mode 100644 checkstyle.xml diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 8710585e6..8faa9672f 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -4,8 +4,10 @@ This file provides guidance to AI coding assistants when working with code in th ## Project Overview -IoT DC3 is a distributed IoT platform built on Spring Cloud for industrial device connectivity, data collection, and management. It uses a microservices architecture with gRPC + -RabbitMQ for inter-service communication and supports multiple industrial protocols (Modbus TCP, OPC DA/UA, MQTT, Siemens S7, virtual listening). +IoT DC3 is a distributed IoT platform built on Spring Cloud for industrial device connectivity, data collection, and +management. It uses a microservices architecture with gRPC + +RabbitMQ for inter-service communication and supports multiple industrial protocols (Modbus TCP, OPC DA/UA, MQTT, +Siemens S7, virtual listening). **Architecture Layers:** @@ -18,7 +20,8 @@ RabbitMQ for inter-service communication and supports multiple industrial protoc - Java 21, Spring Boot 4.0.6, Spring Framework 7.0.7 (project version `2026.5.5`, parent `dc3-parent:2026.5.5`) - PostgreSQL (primary DB), RabbitMQ (messaging), EMQX/MQTT (IoT protocol); in-process `LocalCacheService` replaces Redis -- gRPC/Protobuf for inter-service APIs via `org.springframework.grpc:spring-grpc-spring-boot-starter` — server classes use `@Service` + extend generated `*ImplBase`; clients are +- gRPC/Protobuf for inter-service APIs via `org.springframework.grpc:spring-grpc-spring-boot-starter` — server classes + use `@Service` + extend generated `*ImplBase`; clients are registered as beans in a central `GrpcStubConfig` using `GrpcChannelFactory` - Docker / Podman Compose for deployment; a top-level `Makefile` wraps the common flows @@ -26,7 +29,8 @@ RabbitMQ for inter-service communication and supports multiple industrial protoc ### Infrastructure Stacks (docker-compose files under `dc3/`) -The `dc3/` directory ships multiple compose files. Each has an `-aliyun` variant that pulls images from the Aliyun registry (for users in mainland China): +The `dc3/` directory ships multiple compose files. Each has an `-aliyun` variant that pulls images from the Aliyun +registry (for users in mainland China): | Stack | File | Contents | |-----------------|----------------------------------------|---------------------------------------------------| @@ -37,7 +41,8 @@ The `dc3/` directory ships multiple compose files. Each has an `-aliyun` variant | `grafana` | `dc3/docker-compose-grafana.yml` | Grafana observability stack | | `elasticsearch` | `dc3/docker-compose-elasticsearch.yml` | Elasticsearch stack | -Note: The project no longer depends on Redis — caching is handled by the in-process `LocalCacheService` (see `dc3-common-public`). +Note: The project no longer depends on Redis — caching is handled by the in-process `LocalCacheService` (see +`dc3-common-public`). ### Starting Dependencies @@ -76,7 +81,8 @@ podman compose -f dc3/docker-compose-optional.yml up -d ### Building -Maven settings are checked in at `.mvn/settings.xml` — always pass `-s .mvn/settings.xml` so local builds match CI / Dockerfile behavior: +Maven settings are checked in at `.mvn/settings.xml` — always pass `-s .mvn/settings.xml` so local builds match CI / +Dockerfile behavior: ```bash # Load local env vars used by application YAMLs @@ -93,7 +99,8 @@ mvn -s .mvn/settings.xml clean package mvn -s .mvn/settings.xml clean package -pl dc3-center/dc3-center-auth -am ``` -There are no Java test sources under `**/src/test/**/*.java` — rely on compile + targeted runtime smoke checks when refactoring. +There are no Java test sources under `**/src/test/**/*.java` — rely on compile + targeted runtime smoke checks when +refactoring. ### Running Services (manual, JAR mode) @@ -106,10 +113,12 @@ Services must be started in this order: 2. **Auth Center** — HTTP `8300`, gRPC `9300` 3. **Data Center** — HTTP `8500`, gRPC `9500` 4. **Manager Center** — HTTP `8400`, gRPC `9400` -5. **Drivers** — e.g. `dc3-driver-virtual`, `dc3-driver-listening-virtual` (HTTP `6270`, gRPC `6271`), `dc3-driver-modbus-tcp`, `dc3-driver-mqtt`, `dc3-driver-opc-da`, +5. **Drivers** — e.g. `dc3-driver-virtual`, `dc3-driver-listening-virtual` (HTTP `6270`, gRPC `6271`), + `dc3-driver-modbus-tcp`, `dc3-driver-mqtt`, `dc3-driver-opc-da`, `dc3-driver-opc-ua`, `dc3-driver-plcs7` -`dc3/env/dev.env.sh` defines host/port/credentials for local infra and `CENTER_AUTH_HOST` / `CENTER_DATA_HOST` / `CENTER_MANAGER_HOST` gRPC targets. `source dc3/env/dev.env.sh` +`dc3/env/dev.env.sh` defines host/port/credentials for local infra and `CENTER_AUTH_HOST` / `CENTER_DATA_HOST` / +`CENTER_MANAGER_HOST` gRPC targets. `source dc3/env/dev.env.sh` before running services from the shell or IDE. ## Module Structure @@ -174,52 +183,64 @@ Proto files live under `dc3-api/*/src/main/protobuf/api///`: - **dc3-api-auth** (`api/center/auth/`): `tenant.proto`, `token.proto`, `user.proto`, `user_login.proto` - **dc3-api-data** (`api/center/data/`): `point_value.proto` -- **dc3-api-driver** (`api/common/driver/`): `driver_device.proto`, `driver_driver.proto`, `driver_entity.proto`, `driver_point.proto`, `driver_query.proto`, +- **dc3-api-driver** (`api/common/driver/`): `driver_device.proto`, `driver_driver.proto`, `driver_entity.proto`, + `driver_point.proto`, `driver_query.proto`, `driver_query_page.proto` -- **dc3-api-manager** (`api/center/manager/`): `manager_device.proto`, `manager_driver.proto`, `manager_point.proto`, `manager_query.proto`, `manager_query_page.proto` +- **dc3-api-manager** (`api/center/manager/`): `manager_device.proto`, `manager_driver.proto`, `manager_point.proto`, + `manager_query.proto`, `manager_query_page.proto` When modifying service APIs: 1. Edit the `.proto` file in the appropriate `dc3-api-*` module 2. Regenerate Java classes: `mvn -s .mvn/settings.xml clean package` (protobuf-maven-plugin runs at compile phase) -3. Implement the service interface in the corresponding `dc3-center-*` or driver module — the class extends the generated `*ImplBase` and is annotated with `@Service`. Spring gRPC +3. Implement the service interface in the corresponding `dc3-center-*` or driver module — the class extends the + generated `*ImplBase` and is annotated with `@Service`. Spring gRPC auto-registers all `BindableService` beans on the server. -4. Inter-service calls use gRPC stubs produced by a central `GrpcStubConfig` (`@Bean` methods calling `GrpcChannelFactory.createChannel()`) and injected via +4. Inter-service calls use gRPC stubs produced by a central `GrpcStubConfig` (`@Bean` methods calling + `GrpcChannelFactory.createChannel()`) and injected via `@Resource` — **not REST** ## Service Boundaries & Runtime Data Flow -- HTTP enters via `dc3-gateway` (port 8000). Routes defined in `dc3-gateway/src/main/resources/application-pre.yml` strip the `/api/v3` prefix (`StripPrefix=2`) and optionally +- HTTP enters via `dc3-gateway` (port 8000). Routes defined in `dc3-gateway/src/main/resources/application-pre.yml` + strip the `/api/v3` prefix (`StripPrefix=2`) and optionally apply the `Authentic` filter. - Manager / Data / Auth each expose both **REST** (for the gateway) and **gRPC** (for inter-service + drivers). - Drivers register and fetch device/point config via Manager gRPC: - - Server: `@Service`-annotated `*ImplBase` subclasses under `dc3-common-manager/.../grpc/server/driver/` (e.g. `DriverDriverServer`); Spring gRPC registers them automatically - - Client stubs: drivers and Data service obtain stubs from `GrpcStubConfig` (channel named `ManagerConstant.SERVICE_NAME`) and inject them with `@Resource` + - Server: `@Service`-annotated `*ImplBase` subclasses under `dc3-common-manager/.../grpc/server/driver/` (e.g. + `DriverDriverServer`); Spring gRPC registers them automatically + - Client stubs: drivers and Data service obtain stubs from `GrpcStubConfig` (channel named + `ManagerConstant.SERVICE_NAME`) and inject them with `@Resource` - Commands and metadata changes flow asynchronously over **RabbitMQ topic exchanges**: - Exchange/routing key constants: `dc3-common-constant/.../RabbitConstant.java` - Exchange declarations: `dc3-common-rabbitmq/.../ExchangeConfig.java` - - Example command path — Data service resolves the driver by gRPC, then publishes to `dc3.e.command` keyed by driver service name ( + - Example command path — Data service resolves the driver by gRPC, then publishes to `dc3.e.command` keyed by driver + service name ( `dc3-common-data/.../PointValueCommandServiceImpl.java`). ## Code Architecture Patterns **Reactive Web Layer (center services, gateway):** -- Controllers return `Mono>` and typically `extends BaseController` to pull tenant/user headers from the reactive context. +- Controllers return `Mono>` and typically `extends BaseController` to pull tenant/user headers from the reactive + context. - Response envelope is always `R` (`dc3-common-public/.../R.java`) for REST, `GrpcR` for gRPC. - Validation uses grouped marker interfaces (`Add`, `Update`, etc.) with `@Validated(...)` on controller methods. -- URL prefixes/constants go in `*Constant` classes (e.g. `ManagerConstant.DRIVER_URL_PREFIX`), never hardcoded in controllers. +- URL prefixes/constants go in `*Constant` classes (e.g. `ManagerConstant.DRIVER_URL_PREFIX`), never hardcoded in + controllers. **Models & Mapping:** - Explicit BO / VO / DTO separation — **never expose entities directly**. -- Conversions go through `*Builder` classes (e.g. `DriverBuilder`, `GrpcDriverBuilder`) rather than reflection-based mappers. +- Conversions go through `*Builder` classes (e.g. `DriverBuilder`, `GrpcDriverBuilder`) rather than reflection-based + mappers. **Configuration:** - All YAML uses `${ENV:default}` placeholders — **never hardcode `localhost` in code paths**. - Profile selection via `${NODE_ENV:dev}`; Maven profiles: `dev` (default), `test`, `pre`, `pro`. -- `pre` / `pro` profiles resolve service discovery/config through Nacos (`spring.cloud.nacos.*` in gateway + center YAMLs). +- `pre` / `pro` profiles resolve service discovery/config through Nacos (`spring.cloud.nacos.*` in gateway + center + YAMLs). - gRPC targets overridable via env (`CENTER_AUTH_HOST`, `CENTER_DATA_HOST`, `CENTER_MANAGER_HOST`). **Driver Services:** @@ -228,12 +249,14 @@ When modifying service APIs: - Extend base classes from `dc3-common-driver`. - Implement gRPC service interfaces from `dc3-api-driver`. - Register with Manager Center on startup via `DriverApi.DriverRegister()`. -- **Driver service names are routing-critical** — they become suffixes in RabbitMQ routing keys and gRPC target names. Preserve existing naming constants when refactoring. +- **Driver service names are routing-critical** — they become suffixes in RabbitMQ routing keys and gRPC target names. + Preserve existing naming constants when refactoring. **Center Services:** - Implement gRPC service interfaces from the matching `dc3-api-*` module. -- Use `dc3-common-dal` for data access, `LocalCacheService` from `dc3-common-public` for caching, `dc3-common-rabbitmq` for messaging. +- Use `dc3-common-dal` for data access, `LocalCacheService` from `dc3-common-public` for caching, `dc3-common-rabbitmq` + for messaging. **Multi-tenancy:** @@ -251,13 +274,15 @@ When modifying service APIs: 2. Add it to `dc3-driver/pom.xml` ``. 3. Depend on `dc3-common-driver`; implement the required protocol adapter. 4. Keep the driver service name consistent across `application.yml`, RabbitMQ routing, and gRPC registration. -5. Handle the standard driver responsibilities: connect to devices, acquire data, execute commands, register with Manager, report status/events. +5. Handle the standard driver responsibilities: connect to devices, acquire data, execute commands, register with + Manager, report status/events. ## Git Commit Identity (for Claude's commits) **Project-only rule — only applies to commits Claude makes in this repository.** -When committing, Claude must use the `claude[bot]` GitHub App identity so commits show Claude's real avatar on GitHub, consistent with how Copilot's commits already appear in this +When committing, Claude must use the `claude[bot]` GitHub App identity so commits show Claude's real avatar on GitHub, +consistent with how Copilot's commits already appear in this repo's history. Run every commit as: ```bash @@ -271,8 +296,10 @@ EOF )" ``` -- `209825114` is the GitHub user ID of the official `claude[bot]` account; the `+@users.noreply.github.com` form is what GitHub uses to link a commit to a bot avatar. -- Do **NOT** run `git config --local user.name` / `user.email` — the repo's default git identity must stay as-is so the human author's own commits keep their own identity. +- `209825114` is the GitHub user ID of the official `claude[bot]` account; the `+@users.noreply.github.com` + form is what GitHub uses to link a commit to a bot avatar. +- Do **NOT** run `git config --local user.name` / `user.email` — the repo's default git identity must stay as-is so the + human author's own commits keep their own identity. - The `Co-Authored-By` trailer may remain; it is harmless alongside the bot-identity author. ## Branching and Contribution @@ -285,7 +312,9 @@ EOF ## Notes on Existing State -- No Java unit tests (`**/src/test/**/*.java` is empty). Validate changes by compile + targeted runtime smoke (spin up a compose stack, hit gateway, check driver registration / +- No Java unit tests (`**/src/test/**/*.java` is empty). Validate changes by compile + targeted runtime smoke (spin up a + compose stack, hit gateway, check driver registration / gRPC calls). -- READMEs with additional context: root `README.md` (and `.ja.md`, `.vi.md`, `.zh.md`), plus per-API READMEs (`dc3-api/dc3-api-auth/README.md`, `.../dc3-api-data/README.md`, +- READMEs with additional context: root `README.md` (and `.ja.md`, `.vi.md`, `.zh.md`), plus per-API READMEs ( + `dc3-api/dc3-api-auth/README.md`, `.../dc3-api-data/README.md`, `.../dc3-api-driver/README.md`). diff --git a/.mvn/settings.xml b/.mvn/settings.xml index 35638c255..00a3930eb 100644 --- a/.mvn/settings.xml +++ b/.mvn/settings.xml @@ -43,4 +43,7 @@ + + io.spring.javaformat + \ No newline at end of file diff --git a/.springjavaformatconfig b/.springjavaformatconfig deleted file mode 100644 index e69de29bb..000000000 diff --git a/Makefile b/Makefile index 60279b4b9..d5f38a3ed 100644 --- a/Makefile +++ b/Makefile @@ -18,7 +18,7 @@ # tip: # make -f ./Makefile help -.PHONY: help clean package format format-check app app-all dev dev-all dev-db dev-optional build deploy tag \ +.PHONY: help clean package app app-all dev dev-all dev-db dev-optional build deploy tag \ check-compose compose-file compose-up compose-down compose-ps compose-config compose-build \ compose-logs compose-pull compose-restart @@ -58,11 +58,9 @@ endif help: echo 'You can use make to execute the following commands:' \ - && echo 'Usage: make [help | clean | package | format | format-check | app | app-all | dev-db | dev-optional | dev | dev-all | build | deploy | tag]' \ + && echo 'Usage: make [help | clean | package | app | app-all | dev-db | dev-optional | dev | dev-all | build | deploy | tag]' \ && echo ' - make clean: clean Maven build artifacts' \ && echo ' - make package: package all modules with Maven' \ - && echo ' - make format: apply Spring Java Format to all Java sources' \ - && echo ' - make format-check: validate code style without modifying files' \ && echo ' - make tag: git tag' \ && echo ' - make app: run the packaged application stack (docker-compose.yml)' \ && echo ' - make app-all: run db + optional + packaged application stacks' \ @@ -97,12 +95,6 @@ clean: package: $(MVN) clean package -format: - $(MVN) io.spring.javaformat:spring-javaformat-maven-plugin:apply - -format-check: - $(MVN) io.spring.javaformat:spring-javaformat-maven-plugin:validate - tag: dc3/bin/tag.sh diff --git a/README.ja.md b/README.ja.md index 579d9c436..0dfae27f1 100644 --- a/README.ja.md +++ b/README.ja.md @@ -70,7 +70,8 @@ make dev make dev-all ``` -中国本土向けのイメージレジストリを使う場合は `REGISTRY=domestic` を指定してください。互換エイリアスの `REGISTRY=aliyun` と `REGISTRY=cn` も利用できます: +中国本土向けのイメージレジストリを使う場合は `REGISTRY=domestic` を指定してください。互換エイリアスの `REGISTRY=aliyun` と +`REGISTRY=cn` も利用できます: ```bash make dev-db REGISTRY=domestic @@ -88,7 +89,8 @@ make compose-logs STACK=dev REGISTRY=global cp .env.example .env ``` -リポジトリ直下の `.env` は `dc3/` 配下の Compose ファイル用の変数展開に使用されます。アプリケーション実行時の環境変数は引き続き `dc3/env/dev.env` または `dc3/env/dev.env.sh` +リポジトリ直下の `.env` は `dc3/` 配下の Compose ファイル用の変数展開に使用されます。アプリケーション実行時の環境変数は引き続き +`dc3/env/dev.env` または `dc3/env/dev.env.sh` で管理されます。 ## 3.2 準備 @@ -102,7 +104,8 @@ mvn -s .mvn/settings.xml clean package > **ローカル開発ガイド**: ワンストップのローカルセットアップ手順は [`docs/QUICKSTART.md`](docs/QUICKSTART.md) を参照してください。 -> **トラブルシューティング**: よくあるビルド/ランタイムの問題と解決策は [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) を参照してください。 +> **トラブルシューティング**: よくあるビルド/ランタイムの問題と解決策は [ +`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) を参照してください。 ## 3.3 サービスの起動 diff --git a/README.md b/README.md index e638261b0..ccde07f9a 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ All components and code are open-source, ensuring transparency, flexibility, and # 1 Architecture -The architecture is designed for end-to-end IoT capabilities across device connectivity, data services, operational management, and extensible application integration. +The architecture is designed for end-to-end IoT capabilities across device connectivity, data services, operational +management, and extensible application integration. - **Driver Layer**: Provides SDKs for rapid driver development and seamless connectivity to physical devices through standard or proprietary protocols. This layer handles southbound data acquisition and command execution; @@ -55,7 +56,8 @@ The architecture is designed for end-to-end IoT capabilities across device conne > Choose one > -> This base stack starts PostgreSQL and RabbitMQ. If you need a database SQL script, connect directly to the started database in the container for export. +> This base stack starts PostgreSQL and RabbitMQ. If you need a database SQL script, connect directly to the started +> database in the container for export. ```bash # Global access with standard container registry service @@ -74,7 +76,8 @@ make dev make dev-all ``` -Use `REGISTRY=domestic` when you want the mainland China image registry variants. Backward-compatible aliases `REGISTRY=aliyun` and `REGISTRY=cn` still work: +Use `REGISTRY=domestic` when you want the mainland China image registry variants. Backward-compatible aliases +`REGISTRY=aliyun` and `REGISTRY=cn` still work: ```bash make dev-db REGISTRY=domestic @@ -126,11 +129,13 @@ source dc3/env/dev.env.sh mvn -s .mvn/settings.xml clean package ``` -> **Module Overview**: See [`docs/MODULES.md`](docs/MODULES.md) for the full module dependency map and runtime flow diagram. +> **Module Overview**: See [`docs/MODULES.md`](docs/MODULES.md) for the full module dependency map and runtime flow +> diagram. > **Local Dev Guide**: See [`docs/QUICKSTART.md`](docs/QUICKSTART.md) for a one-stop local setup workflow. -> **Troubleshooting**: See [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) for common build/runtime issues and resolutions. +> **Troubleshooting**: See [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) for common build/runtime issues and +> resolutions. ## 3.3 Start Services diff --git a/README.vi.md b/README.vi.md index 271e616c9..6ac463933 100644 --- a/README.vi.md +++ b/README.vi.md @@ -26,20 +26,27 @@ Toàn bộ thành phần và mã nguồn đều mở, đảm bảo tính minh b # 1 Kiến trúc -Kiến trúc được thiết kế để cung cấp năng lực IoT đầu-cuối, bao gồm kết nối thiết bị, dịch vụ dữ liệu, quản lý vận hành và tích hợp ứng dụng mở rộng. +Kiến trúc được thiết kế để cung cấp năng lực IoT đầu-cuối, bao gồm kết nối thiết bị, dịch vụ dữ liệu, quản lý vận hành +và tích hợp ứng dụng mở rộng. -- **Tầng Driver**: Cung cấp SDK để kết nối thiết bị vật lý qua giao thức tiêu chuẩn hoặc độc quyền, đảm nhiệm thu thập dữ liệu hướng nam và thực thi lệnh điều khiển; -- **Tầng Dữ liệu**: Cung cấp thu thập, lưu trữ và truy vấn dữ liệu thiết bị một cách tin cậy, phục vụ cả dữ liệu thời gian thực và lịch sử; -- **Tầng Quản lý**: Đóng vai trò trung tâm hợp tác microservice phân tán, bao gồm đăng ký dịch vụ, quản lý driver/thiết bị, điều phối lệnh và quản trị cấu hình tập trung; -- **Tầng Ứng dụng**: Hỗ trợ mở dữ liệu, lập lịch tác vụ, cảnh báo/thông báo, quản lý log, tích hợp bên thứ ba và các kịch bản tự động hóa tăng cường bởi AI. +- **Tầng Driver**: Cung cấp SDK để kết nối thiết bị vật lý qua giao thức tiêu chuẩn hoặc độc quyền, đảm nhiệm thu thập + dữ liệu hướng nam và thực thi lệnh điều khiển; +- **Tầng Dữ liệu**: Cung cấp thu thập, lưu trữ và truy vấn dữ liệu thiết bị một cách tin cậy, phục vụ cả dữ liệu thời + gian thực và lịch sử; +- **Tầng Quản lý**: Đóng vai trò trung tâm hợp tác microservice phân tán, bao gồm đăng ký dịch vụ, quản lý driver/thiết + bị, điều phối lệnh và quản trị cấu hình tập trung; +- **Tầng Ứng dụng**: Hỗ trợ mở dữ liệu, lập lịch tác vụ, cảnh báo/thông báo, quản lý log, tích hợp bên thứ ba và các + kịch bản tự động hóa tăng cường bởi AI. # 2 Mục tiêu - **Khả năng mở rộng**: Hỗ trợ mở rộng ngang bằng Spring Cloud cho khối lượng công việc IoT phân tán, thông lượng cao; - **Tính bền vững**: Giảm rủi ro điểm lỗi đơn lẻ nhờ thiết kế chịu lỗi và các node dịch vụ có thể thay thế; - **Hiệu năng**: Đáp ứng nhu cầu kết nối thiết bị quy mô lớn và xử lý telemetry; -- **Khả năng mở rộng phát triển**: Tăng tốc tích hợp giao thức mới và driver tùy biến thông qua SDK và cơ chế đăng ký dịch vụ; -- **Linh hoạt triển khai**: Vận hành trên private cloud, public cloud và edge, đồng thời giữ tương thích hệ sinh thái Java; +- **Khả năng mở rộng phát triển**: Tăng tốc tích hợp giao thức mới và driver tùy biến thông qua SDK và cơ chế đăng ký + dịch vụ; +- **Linh hoạt triển khai**: Vận hành trên private cloud, public cloud và edge, đồng thời giữ tương thích hệ sinh thái + Java; - **Hiệu quả vận hành**: Đơn giản hóa quy trình onboarding, đăng ký và xác thực quyền; - **Bảo mật và đa tenant**: Hỗ trợ mã hóa truyền dữ liệu, tách biệt namespace và cơ chế phân tách theo tenant; - **Phân phối cloud-native**: Tối ưu cho Kubernetes và container hóa bằng Docker để triển khai nhất quán; @@ -71,7 +78,8 @@ make dev make dev-all ``` -Nếu bạn muốn dùng registry tối ưu cho người dùng ở Trung Quốc đại lục, hãy đặt `REGISTRY=domestic`. Các bí danh tương thích `REGISTRY=aliyun` và `REGISTRY=cn` vẫn dùng được: +Nếu bạn muốn dùng registry tối ưu cho người dùng ở Trung Quốc đại lục, hãy đặt `REGISTRY=domestic`. Các bí danh tương +thích `REGISTRY=aliyun` và `REGISTRY=cn` vẫn dùng được: ```bash make dev-db REGISTRY=domestic @@ -89,7 +97,8 @@ Trước khi thay đổi cổng publish, tag image hoặc tham số observabilit cp .env.example .env ``` -Tệp `.env` ở thư mục gốc được dùng cho nội suy biến trong các file Compose dưới `dc3/`; các biến runtime của ứng dụng vẫn nằm trong `dc3/env/dev.env` hoặc `dc3/env/dev.env.sh`. +Tệp `.env` ở thư mục gốc được dùng cho nội suy biến trong các file Compose dưới `dc3/`; các biến runtime của ứng dụng +vẫn nằm trong `dc3/env/dev.env` hoặc `dc3/env/dev.env.sh`. ## 3.2 Chuẩn bị @@ -102,7 +111,8 @@ mvn -s .mvn/settings.xml clean package > **Hướng dẫn dev cục bộ**: Xem [`docs/QUICKSTART.md`](docs/QUICKSTART.md) để biết quy trình thiết lập môi trường local. -> **Khắc phục sự cố**: Xem [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) để biết các vấn đề thường gặp khi build/runtime và cách giải quyết. +> **Khắc phục sự cố**: Xem [`docs/TROUBLESHOOTING.md`](docs/TROUBLESHOOTING.md) để biết các vấn đề thường gặp khi +> build/runtime và cách giải quyết. ## 3.3 Khởi động dịch vụ diff --git a/README.zh.md b/README.zh.md index f22dad3aa..9800747fb 100644 --- a/README.zh.md +++ b/README.zh.md @@ -88,7 +88,8 @@ make compose-logs STACK=dev REGISTRY=global cp .env.example .env ``` -根目录 `.env` 用于 `dc3/` 下 Compose 文件的变量插值;应用运行时环境变量仍然位于 `dc3/env/dev.env` 或 `dc3/env/dev.env.sh`。 +根目录 `.env` 用于 `dc3/` 下 Compose 文件的变量插值;应用运行时环境变量仍然位于 `dc3/env/dev.env` 或 +`dc3/env/dev.env.sh`。 ## 3.2 准备工作 diff --git a/SECURITY.md b/SECURITY.md index f06e3cd63..57c67fb6e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,7 +1,9 @@ # Security Policy -> :lock: **Note:** iot-dc3 is a distributed Internet of Things (IoT) platform that involves device access, data collection, and command dispatch. Security issues not only affect -> system operation but may also cause data or control risks. Please pay close attention to security configuration and version updates. +> :lock: **Note:** iot-dc3 is a distributed Internet of Things (IoT) platform that involves device access, data +> collection, and command dispatch. Security issues not only affect +> system operation but may also cause data or control risks. Please pay close attention to security configuration and +> version updates. ## Supported Versions @@ -18,23 +20,28 @@ The following table lists the iot-dc3 versions that are currently supported with ## Reporting a Vulnerability > We take security issues very seriously. -> If a vulnerability is verified, we will fix it as soon as possible and disclose the fix information in the release notes. +> If a vulnerability is verified, we will fix it as soon as possible and disclose the fix information in the release +> notes. -If you find a potential security vulnerability while using **iot-dc3**, **do not disclose it publicly in issues or discussion areas**, but report it through the following private +If you find a potential security vulnerability while using **iot-dc3**, **do not disclose it publicly in issues or +discussion areas**, but report it through the following private channels: 1. **Email report**: - Send an email to the project maintenance team, and please include the keyword `Security Vulnerability` in the subject line. + Send an email to the project maintenance team, and please include the keyword `Security Vulnerability` in the subject + line. 2. **Direct message report**: You can directly contact the project maintainers through the private message function on Gitee or GitHub. ## Security Best Practices -To ensure the security and stability of the iot-dc3 platform in production environments, it is recommended to follow these practices: +To ensure the security and stability of the iot-dc3 platform in production environments, it is recommended to follow +these practices: - :white_check_mark: Always use supported versions; -- :no_entry_sign: Do not expose core communication ports (such as MQTT, TCP, Modbus gateways) directly to the public network; +- :no_entry_sign: Do not expose core communication ports (such as MQTT, TCP, Modbus gateways) directly to the public + network; - :lock: Use secure authentication mechanisms and enable HTTPS / SSL encryption; - :arrows_counterclockwise: Regularly update system dependencies and Docker images; - :jigsaw: Only authorize trusted devices and users to access the system; diff --git a/checkstyle.xml b/checkstyle.xml deleted file mode 100644 index 2620b2405..000000000 --- a/checkstyle.xml +++ /dev/null @@ -1,65 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dc3-api/dc3-api-auth/README.md b/dc3-api/dc3-api-auth/README.md index d2b899fe6..c9637ba90 100644 --- a/dc3-api/dc3-api-auth/README.md +++ b/dc3-api/dc3-api-auth/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-api-auth` provides gRPC service definitions for authentication and authorization in the IoT DC3 platform. It defines the interfaces for tenant management, user authentication, +`dc3-api-auth` provides gRPC service definitions for authentication and authorization in the IoT DC3 platform. It +defines the interfaces for tenant management, user authentication, token validation, and user login operations. ## Module Information diff --git a/dc3-api/dc3-api-data/README.md b/dc3-api/dc3-api-data/README.md index 2c61ef7f4..b7557ab1e 100644 --- a/dc3-api/dc3-api-data/README.md +++ b/dc3-api/dc3-api-data/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-api-data` provides gRPC service definitions for device data collection and management in the IoT DC3 platform. It defines interfaces for querying real-time device point values +`dc3-api-data` provides gRPC service definitions for device data collection and management in the IoT DC3 platform. It +defines interfaces for querying real-time device point values and historical data retrieval. ## Module Information diff --git a/dc3-api/dc3-api-driver/README.md b/dc3-api/dc3-api-driver/README.md index e5905c898..cc4b4b38a 100644 --- a/dc3-api/dc3-api-driver/README.md +++ b/dc3-api/dc3-api-driver/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-api-driver` provides gRPC service definitions for driver services in the IoT DC3 platform. It defines the communication interface between device drivers and the platform's +`dc3-api-driver` provides gRPC service definitions for driver services in the IoT DC3 platform. It defines the +communication interface between device drivers and the platform's manager service, enabling device registration, metadata synchronization, and point value collection. ## Module Information diff --git a/dc3-api/dc3-api-manager/README.md b/dc3-api/dc3-api-manager/README.md index 5ab7d143f..2870fb907 100644 --- a/dc3-api/dc3-api-manager/README.md +++ b/dc3-api/dc3-api-manager/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-api-manager` provides gRPC service definitions for the Manager Center in the IoT DC3 platform. It defines the interfaces used by the Data service and other consumers to query +`dc3-api-manager` provides gRPC service definitions for the Manager Center in the IoT DC3 platform. It defines the +interfaces used by the Data service and other consumers to query driver, device, and point metadata from the Manager Center. ## Module Information diff --git a/dc3-api/pom.xml b/dc3-api/pom.xml index 09d071a62..8c6fabc0d 100644 --- a/dc3-api/pom.xml +++ b/dc3-api/pom.xml @@ -117,53 +117,6 @@ org.xolstice.maven.plugins protobuf-maven-plugin - - - io.spring.javaformat - spring-javaformat-maven-plugin - 0.0.47 - - - validate - validate - - validate - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.1 - - - com.puppycrawl.tools - checkstyle - 9.3 - - - io.spring.javaformat - spring-javaformat-checkstyle - 0.0.47 - - - - - checkstyle-validation - validate - true - - ${maven.multiModuleProjectDirectory}/checkstyle.xml - true - - - check - - - - diff --git a/dc3-center/dc3-center-agentic/src/main/java/io/github/pnoker/center/agentic/AgenticApplication.java b/dc3-center/dc3-center-agentic/src/main/java/io/github/pnoker/center/agentic/AgenticApplication.java index da5aa7544..349bc2250 100644 --- a/dc3-center/dc3-center-agentic/src/main/java/io/github/pnoker/center/agentic/AgenticApplication.java +++ b/dc3-center/dc3-center-agentic/src/main/java/io/github/pnoker/center/agentic/AgenticApplication.java @@ -28,8 +28,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AgenticApplication { - public static void main(String[] args) { - SpringApplication.run(AgenticApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(AgenticApplication.class, args); + } } diff --git a/dc3-center/dc3-center-auth/README.md b/dc3-center/dc3-center-auth/README.md index 26373762a..e76f2eed8 100644 --- a/dc3-center/dc3-center-auth/README.md +++ b/dc3-center/dc3-center-auth/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-center-auth` is the Authorization Center of the IoT DC3 platform. It provides authentication and authorization management for the entire platform including tenant management, +`dc3-center-auth` is the Authorization Center of the IoT DC3 platform. It provides authentication and authorization +management for the entire platform including tenant management, user login, token validation, and permission control. ## Module Information @@ -25,7 +26,8 @@ user login, token validation, and permission control. - **Tenant Management**: Multi-tenant registration, lookup by tenant code - **User Authentication**: User login validation with salt-based encrypted password - **Dictionary Services**: Provide lookup dictionaries for auth-scoped data -- **gRPC Server**: Exposes `TenantApi`, `UserApi`, `UserLoginApi`, `TokenApi` for inter-service consumption (e.g., Gateway) +- **gRPC Server**: Exposes `TenantApi`, `UserApi`, `UserLoginApi`, `TokenApi` for inter-service consumption (e.g., + Gateway) ## REST Endpoints (via Gateway) diff --git a/dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/AuthApplication.java b/dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/AuthApplication.java index 223541aa8..2f7bba5c8 100644 --- a/dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/AuthApplication.java +++ b/dc3-center/dc3-center-auth/src/main/java/io/github/pnoker/center/auth/AuthApplication.java @@ -34,12 +34,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthApplication { - /** - * Main entry point for the Authentication Center Service. - * @param args command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(AuthApplication.class, args); - } + /** + * Main entry point for the Authentication Center Service. + * + * @param args command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(AuthApplication.class, args); + } } diff --git a/dc3-center/dc3-center-data/README.md b/dc3-center/dc3-center-data/README.md index 6c92a6e5b..f37af0b90 100644 --- a/dc3-center/dc3-center-data/README.md +++ b/dc3-center/dc3-center-data/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-center-data` is the Data Center of the IoT DC3 platform. It integrates common messaging middleware including AMQP, WebSocket, and MQTT for collecting device point values from +`dc3-center-data` is the Data Center of the IoT DC3 platform. It integrates common messaging middleware including AMQP, +WebSocket, and MQTT for collecting device point values from drivers, storing them in the time-series repository, and exposing data query APIs. ## Module Information @@ -21,9 +22,11 @@ drivers, storing them in the time-series repository, and exposing data query API ## Key Responsibilities -- **Point Value Ingestion**: Receives point values from drivers via RabbitMQ (`dc3.e.value` exchange, `dc3.q.value.point` queue) and persists them to the time-series storage +- **Point Value Ingestion**: Receives point values from drivers via RabbitMQ (`dc3.e.value` exchange, + `dc3.q.value.point` queue) and persists them to the time-series storage - **Point Value Query**: Exposes REST and gRPC APIs to query the latest and historical point values -- **Device Command Dispatch**: Receives read/write commands, resolves the target driver via Manager gRPC (`ManagerConstant.SERVICE_NAME`), and publishes to `dc3.e.command` +- **Device Command Dispatch**: Receives read/write commands, resolves the target driver via Manager gRPC ( + `ManagerConstant.SERVICE_NAME`), and publishes to `dc3.e.command` - **Driver Status**: Tracks driver online/offline status events - **Data Query**: Supports pagination query, real-time telemetry, and historical data retrieval diff --git a/dc3-center/dc3-center-data/src/main/java/io/github/pnoker/center/data/DataApplication.java b/dc3-center/dc3-center-data/src/main/java/io/github/pnoker/center/data/DataApplication.java index f326c078a..47459d59b 100644 --- a/dc3-center/dc3-center-data/src/main/java/io/github/pnoker/center/data/DataApplication.java +++ b/dc3-center/dc3-center-data/src/main/java/io/github/pnoker/center/data/DataApplication.java @@ -34,12 +34,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DataApplication { - /** - * Main entry point for the Data Center Service. - * @param args command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(DataApplication.class, args); - } + /** + * Main entry point for the Data Center Service. + * + * @param args command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(DataApplication.class, args); + } } diff --git a/dc3-center/dc3-center-manager/README.md b/dc3-center/dc3-center-manager/README.md index 558f89c99..370919101 100644 --- a/dc3-center/dc3-center-manager/README.md +++ b/dc3-center/dc3-center-manager/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-center-manager` is the Device Management Center of the IoT DC3 platform. It provides comprehensive management for all device collections including device/driver registration, +`dc3-center-manager` is the Device Management Center of the IoT DC3 platform. It provides comprehensive management for +all device collections including device/driver registration, profile management, point configuration, permission management, and command interfaces. ## Module Information diff --git a/dc3-center/dc3-center-manager/src/main/java/io/github/pnoker/center/manager/ManagerApplication.java b/dc3-center/dc3-center-manager/src/main/java/io/github/pnoker/center/manager/ManagerApplication.java index c4cc6b135..c2d076f3b 100644 --- a/dc3-center/dc3-center-manager/src/main/java/io/github/pnoker/center/manager/ManagerApplication.java +++ b/dc3-center/dc3-center-manager/src/main/java/io/github/pnoker/center/manager/ManagerApplication.java @@ -34,12 +34,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ManagerApplication { - /** - * Main entry point for the Manager Center Service. - * @param args command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(ManagerApplication.class, args); - } + /** + * Main entry point for the Manager Center Service. + * + * @param args command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(ManagerApplication.class, args); + } } diff --git a/dc3-center/dc3-center-single/README.md b/dc3-center/dc3-center-single/README.md index 3725601e8..4556dd78c 100644 --- a/dc3-center/dc3-center-single/README.md +++ b/dc3-center/dc3-center-single/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-center-single` is the Integrated All-in-One Center of the IoT DC3 platform. It combines authorization, data, and management services into a single deployable module for +`dc3-center-single` is the Integrated All-in-One Center of the IoT DC3 platform. It combines authorization, data, and +management services into a single deployable module for simplified single-node or lightweight deployment scenarios. ## Module Information diff --git a/dc3-center/dc3-center-single/src/main/java/io/github/pnoker/center/SingleApplication.java b/dc3-center/dc3-center-single/src/main/java/io/github/pnoker/center/SingleApplication.java index 30d599bcd..c5d41a85f 100644 --- a/dc3-center/dc3-center-single/src/main/java/io/github/pnoker/center/SingleApplication.java +++ b/dc3-center/dc3-center-single/src/main/java/io/github/pnoker/center/SingleApplication.java @@ -37,16 +37,17 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; * Configures MyBatis mapper scanning for multiple packages. Enables automatic discovery * of mapper interfaces for database access. */ -@MapperScan(basePackages = { "io.github.pnoker.common.dal.mapper", "io.github.pnoker.common.auth.mapper", - "io.github.pnoker.common.data.mapper", "io.github.pnoker.common.manager.mapper" }) +@MapperScan(basePackages = {"io.github.pnoker.common.dal.mapper", "io.github.pnoker.common.auth.mapper", + "io.github.pnoker.common.data.mapper", "io.github.pnoker.common.manager.mapper"}) public class SingleApplication { - /** - * Main entry point for the Single Center Service. - * @param args command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(SingleApplication.class, args); - } + /** + * Main entry point for the Single Center Service. + * + * @param args command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(SingleApplication.class, args); + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/AgenticProperties.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/AgenticProperties.java index 82a617ba7..0ac75ae4a 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/AgenticProperties.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/AgenticProperties.java @@ -31,19 +31,19 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "dc3.agentic") public class AgenticProperties { - /** - * Whether to enable the agentic module. - */ - private boolean enabled = true; + /** + * Whether to enable the agentic module. + */ + private boolean enabled = true; - /** - * Maximum number of messages retained per conversation for chat memory. - */ - private int memoryMaxMessages = 50; + /** + * Maximum number of messages retained per conversation for chat memory. + */ + private int memoryMaxMessages = 50; - /** - * Session time-to-live in hours. Sessions older than this are marked expired. - */ - private int sessionTtlHours = 72; + /** + * Session time-to-live in hours. Sessions older than this are marked expired. + */ + private int sessionTtlHours = 72; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/ChatClientConfig.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/ChatClientConfig.java index eb81958fa..449b7e9ec 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/ChatClientConfig.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/config/ChatClientConfig.java @@ -37,40 +37,40 @@ import org.springframework.context.annotation.Configuration; @EnableConfigurationProperties(AgenticProperties.class) public class ChatClientConfig { - private static final String SYSTEM_PROMPT = """ - You are an intelligent assistant for the IoT DC3 platform. + private static final String SYSTEM_PROMPT = """ + You are an intelligent assistant for the IoT DC3 platform. + + You can help users manage IoT devices, query real-time and historical data, + and perform device operations. You have access to the following capabilities: + + - **Auth tools**: Look up tenants, users, and login records. + - **Manager tools**: Query devices, drivers, and data points (metrics). + - **Data tools**: Read real-time point values, query historical data, and send read/write commands to devices. + + Guidelines: + - Always confirm before sending write commands to physical devices. + - Present data in a clear, structured format. + - If a query fails, explain the error and suggest alternatives. + - Use the tools to fetch real data rather than making up values. + """; - You can help users manage IoT devices, query real-time and historical data, - and perform device operations. You have access to the following capabilities: + @Bean + @ConditionalOnMissingBean + public ChatMemory agenticChatMemory(ChatMemoryRepository chatMemoryRepository, AgenticProperties properties) { + return MessageWindowChatMemory.builder() + .chatMemoryRepository(chatMemoryRepository) + .maxMessages(properties.getMemoryMaxMessages()) + .build(); + } - - **Auth tools**: Look up tenants, users, and login records. - - **Manager tools**: Query devices, drivers, and data points (metrics). - - **Data tools**: Read real-time point values, query historical data, and send read/write commands to devices. - - Guidelines: - - Always confirm before sending write commands to physical devices. - - Present data in a clear, structured format. - - If a query fails, explain the error and suggest alternatives. - - Use the tools to fetch real data rather than making up values. - """; - - @Bean - @ConditionalOnMissingBean - public ChatMemory agenticChatMemory(ChatMemoryRepository chatMemoryRepository, AgenticProperties properties) { - return MessageWindowChatMemory.builder() - .chatMemoryRepository(chatMemoryRepository) - .maxMessages(properties.getMemoryMaxMessages()) - .build(); - } - - @Bean - public ChatClient agenticChatClient(ChatClient.Builder builder, AuthToolSet authToolSet, - ManagerToolSet managerToolSet, DataToolSet dataToolSet, ChatMemory agenticChatMemory, - SkillRegistry skillRegistry) { - return builder.defaultSystem(SYSTEM_PROMPT) - .defaultTools(authToolSet, managerToolSet, dataToolSet) - .defaultAdvisors(MessageChatMemoryAdvisor.builder(agenticChatMemory).build()) - .build(); - } + @Bean + public ChatClient agenticChatClient(ChatClient.Builder builder, AuthToolSet authToolSet, + ManagerToolSet managerToolSet, DataToolSet dataToolSet, ChatMemory agenticChatMemory, + SkillRegistry skillRegistry) { + return builder.defaultSystem(SYSTEM_PROMPT) + .defaultTools(authToolSet, managerToolSet, dataToolSet) + .defaultAdvisors(MessageChatMemoryAdvisor.builder(agenticChatMemory).build()) + .build(); + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/constant/AgenticConstant.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/constant/AgenticConstant.java index a1c448933..f8c027a84 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/constant/AgenticConstant.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/constant/AgenticConstant.java @@ -21,20 +21,20 @@ package io.github.pnoker.common.agentic.constant; */ public class AgenticConstant { - public static final String SERVICE_NAME = "dc3-center-agentic"; + public static final String SERVICE_NAME = "dc3-center-agentic"; - /** - * URL prefix for the chat REST API. Gateway: /api/v3/agentic/chat/** → - * agentic:8600/agentic/chat/** - */ - public static final String CHAT_URL_PREFIX = "/chat"; + /** + * URL prefix for the chat REST API. Gateway: /api/v3/agentic/chat/** → + * agentic:8600/agentic/chat/** + */ + public static final String CHAT_URL_PREFIX = "/chat"; - /** - * URL prefix for the session REST API. - */ - public static final String SESSION_URL_PREFIX = "/session"; + /** + * URL prefix for the session REST API. + */ + public static final String SESSION_URL_PREFIX = "/session"; - private AgenticConstant() { - } + private AgenticConstant() { + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/ChatController.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/ChatController.java index 59a030506..055b2e304 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/ChatController.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/ChatController.java @@ -51,175 +51,173 @@ import java.util.UUID; @RequestMapping(AgenticConstant.CHAT_URL_PREFIX) public class ChatController implements BaseController { - private final ChatClient chatClient; + private final ChatClient chatClient; - private final SkillRegistry skillRegistry; + private final SkillRegistry skillRegistry; - private final SessionService sessionService; + private final SessionService sessionService; - public ChatController(ChatClient chatClient, SkillRegistry skillRegistry, SessionService sessionService) { - this.chatClient = chatClient; - this.skillRegistry = skillRegistry; - this.sessionService = sessionService; - } + public ChatController(ChatClient chatClient, SkillRegistry skillRegistry, SessionService sessionService) { + this.chatClient = chatClient; + this.skillRegistry = skillRegistry; + this.sessionService = sessionService; + } - /** - * Streaming chat completion — returns SSE events in OpenAI chunk format. Activated - * when {@code request.stream == true}. - */ - @PostMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE) - public Flux> streamChatCompletion(@RequestBody ChatCompletionRequest request) { - log.debug("Stream chat request: model={}, messages={}, conversationId={}, skill={}", request.getModel(), - request.getMessages().size(), request.getConversationId(), request.getSkill()); + /** + * Streaming chat completion — returns SSE events in OpenAI chunk format. Activated + * when {@code request.stream == true}. + */ + @PostMapping(value = "/completions", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public Flux> streamChatCompletion(@RequestBody ChatCompletionRequest request) { + log.debug("Stream chat request: model={}, messages={}, conversationId={}, skill={}", request.getModel(), + request.getMessages().size(), request.getConversationId(), request.getSkill()); - String userMessage = extractLastUserMessage(request); - String conversationId = resolveConversationId(request); - String systemAddition = resolveSkillSystemPrompt(request); + String userMessage = extractLastUserMessage(request); + String conversationId = resolveConversationId(request); + String systemAddition = resolveSkillSystemPrompt(request); - touchSession(conversationId, request); + touchSession(conversationId, request); - var promptSpec = chatClient.prompt() - .user(userMessage) - .advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, conversationId)); - if (systemAddition != null) { - promptSpec = promptSpec.system(systemAddition); - } + var promptSpec = chatClient.prompt() + .user(userMessage) + .advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, conversationId)); + if (systemAddition != null) { + promptSpec = promptSpec.system(systemAddition); + } - Flux contentFlux = promptSpec.stream().content(); + Flux contentFlux = promptSpec.stream().content(); - String chatId = "chatcmpl-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); - long created = Instant.now().getEpochSecond(); - String model = request.getModel() != null ? request.getModel() : "dc3-agentic"; + String chatId = "chatcmpl-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); + long created = Instant.now().getEpochSecond(); + String model = request.getModel() != null ? request.getModel() : "dc3-agentic"; - return contentFlux - .map(chunk -> ServerSentEvent.builder().data(formatChunk(chatId, created, model, chunk)).build()) - .concatWith( - Mono.just(ServerSentEvent.builder().data(formatFinalChunk(chatId, created, model)).build())) - .concatWith(Mono.just(ServerSentEvent.builder().data("[DONE]").build())); - } + return contentFlux + .map(chunk -> ServerSentEvent.builder().data(formatChunk(chatId, created, model, chunk)).build()) + .concatWith( + Mono.just(ServerSentEvent.builder().data(formatFinalChunk(chatId, created, model)).build())) + .concatWith(Mono.just(ServerSentEvent.builder().data("[DONE]").build())); + } - /** - * Non-streaming chat completion — returns a single JSON response. Activated when - * {@code request.stream == false} or omitted. - */ - @PostMapping(value = "/completions", produces = MediaType.APPLICATION_JSON_VALUE) - public Mono chatCompletion(@RequestBody ChatCompletionRequest request) { - log.debug("Chat request: model={}, messages={}, conversationId={}, skill={}", request.getModel(), - request.getMessages().size(), request.getConversationId(), request.getSkill()); + /** + * Non-streaming chat completion — returns a single JSON response. Activated when + * {@code request.stream == false} or omitted. + */ + @PostMapping(value = "/completions", produces = MediaType.APPLICATION_JSON_VALUE) + public Mono chatCompletion(@RequestBody ChatCompletionRequest request) { + log.debug("Chat request: model={}, messages={}, conversationId={}, skill={}", request.getModel(), + request.getMessages().size(), request.getConversationId(), request.getSkill()); - String userMessage = extractLastUserMessage(request); - String conversationId = resolveConversationId(request); - String systemAddition = resolveSkillSystemPrompt(request); + String userMessage = extractLastUserMessage(request); + String conversationId = resolveConversationId(request); + String systemAddition = resolveSkillSystemPrompt(request); - touchSession(conversationId, request); + touchSession(conversationId, request); - return Mono.fromCallable(() -> { - var promptSpec = chatClient.prompt() - .user(userMessage) - .advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, conversationId)); - if (systemAddition != null) { - promptSpec = promptSpec.system(systemAddition); - } + return Mono.fromCallable(() -> { + var promptSpec = chatClient.prompt() + .user(userMessage) + .advisors(advisor -> advisor.param(ChatMemory.CONVERSATION_ID, conversationId)); + if (systemAddition != null) { + promptSpec = promptSpec.system(systemAddition); + } - String content = promptSpec.call().content(); + String content = promptSpec.call().content(); - String chatId = "chatcmpl-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); - return ChatCompletionResponse.builder() - .id(chatId) - .object("chat.completion") - .created(Instant.now().getEpochSecond()) - .model(request.getModel() != null ? request.getModel() : "dc3-agentic") - .choices(List.of(ChatCompletionResponse.Choice.builder() - .index(0) - .message(new ChatCompletionResponse.Message("assistant", content)) - .finishReason("stop") - .build())) - .usage(new ChatCompletionResponse.Usage(0, 0, 0)) - .build(); - }); - } + String chatId = "chatcmpl-" + UUID.randomUUID().toString().replace("-", "").substring(0, 24); + return ChatCompletionResponse.builder() + .id(chatId) + .object("chat.completion") + .created(Instant.now().getEpochSecond()) + .model(request.getModel() != null ? request.getModel() : "dc3-agentic") + .choices(List.of(ChatCompletionResponse.Choice.builder() + .index(0) + .message(new ChatCompletionResponse.Message("assistant", content)) + .finishReason("stop") + .build())) + .usage(new ChatCompletionResponse.Usage(0, 0, 0)) + .build(); + }); + } - private String extractLastUserMessage(ChatCompletionRequest request) { - if (request.getMessages() == null || request.getMessages().isEmpty()) { - return ""; - } - return request.getMessages() - .stream() - .filter(m -> "user".equals(m.getRole())) - .reduce((first, second) -> second) - .map(m -> m.getContent()) - .orElse(""); - } + private String extractLastUserMessage(ChatCompletionRequest request) { + if (request.getMessages() == null || request.getMessages().isEmpty()) { + return ""; + } + return request.getMessages() + .stream() + .filter(m -> "user".equals(m.getRole())) + .reduce((first, second) -> second) + .map(m -> m.getContent()) + .orElse(""); + } - private String resolveConversationId(ChatCompletionRequest request) { - return request.getConversationId() != null ? request.getConversationId() : UUID.randomUUID().toString(); - } + private String resolveConversationId(ChatCompletionRequest request) { + return request.getConversationId() != null ? request.getConversationId() : UUID.randomUUID().toString(); + } - /** - * Resolve the skill-specific system prompt addition for the given request. Returns - * {@code null} when no skill is specified or the skill has no addition. - */ - private String resolveSkillSystemPrompt(ChatCompletionRequest request) { - String skillName = request.getSkill(); - if (skillName == null) { - return null; - } - SkillDefinition skill = skillRegistry.get(skillName); - if (skill == null) { - log.warn("Requested skill '{}' not found in registry", skillName); - return null; - } - log.info("Activating skill: {} — {}", skill.getName(), skill.getDescription()); - return skill.getSystemPromptAddition(); - } + /** + * Resolve the skill-specific system prompt addition for the given request. Returns + * {@code null} when no skill is specified or the skill has no addition. + */ + private String resolveSkillSystemPrompt(ChatCompletionRequest request) { + String skillName = request.getSkill(); + if (skillName == null) { + return null; + } + SkillDefinition skill = skillRegistry.get(skillName); + if (skill == null) { + log.warn("Requested skill '{}' not found in registry", skillName); + return null; + } + log.info("Activating skill: {} — {}", skill.getName(), skill.getDescription()); + return skill.getSystemPromptAddition(); + } - private String formatChunk(String id, long created, String model, String content) { - ChatCompletionChunkResponse chunk = ChatCompletionChunkResponse.builder() - .id(id) - .object("chat.completion.chunk") - .created(created) - .model(model) - .choices(List.of(ChatCompletionChunkResponse.ChunkChoice.builder() - .index(0) - .delta(new ChatCompletionChunkResponse.Delta(null, content)) - .finishReason(null) - .build())) - .build(); - return toJson(chunk); - } + private String formatChunk(String id, long created, String model, String content) { + ChatCompletionChunkResponse chunk = ChatCompletionChunkResponse.builder() + .id(id) + .object("chat.completion.chunk") + .created(created) + .model(model) + .choices(List.of(ChatCompletionChunkResponse.ChunkChoice.builder() + .index(0) + .delta(new ChatCompletionChunkResponse.Delta(null, content)) + .finishReason(null) + .build())) + .build(); + return toJson(chunk); + } - private String formatFinalChunk(String id, long created, String model) { - ChatCompletionChunkResponse chunk = ChatCompletionChunkResponse.builder() - .id(id) - .object("chat.completion.chunk") - .created(created) - .model(model) - .choices(List.of(ChatCompletionChunkResponse.ChunkChoice.builder() - .index(0) - .delta(new ChatCompletionChunkResponse.Delta(null, null)) - .finishReason("stop") - .build())) - .build(); - return toJson(chunk); - } + private String formatFinalChunk(String id, long created, String model) { + ChatCompletionChunkResponse chunk = ChatCompletionChunkResponse.builder() + .id(id) + .object("chat.completion.chunk") + .created(created) + .model(model) + .choices(List.of(ChatCompletionChunkResponse.ChunkChoice.builder() + .index(0) + .delta(new ChatCompletionChunkResponse.Delta(null, null)) + .finishReason("stop") + .build())) + .build(); + return toJson(chunk); + } - private String toJson(Object obj) { - try { - return com.fasterxml.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(obj); - } - catch (Exception e) { - log.error("Failed to serialize response", e); - return "{}"; - } - } + private String toJson(Object obj) { + try { + return com.fasterxml.jackson.databind.json.JsonMapper.builder().build().writeValueAsString(obj); + } catch (Exception e) { + log.error("Failed to serialize response", e); + return "{}"; + } + } - private void touchSession(String conversationId, ChatCompletionRequest request) { - try { - sessionService.touch(conversationId, request.getSkill()); - } - catch (Exception e) { - log.warn("Failed to touch session for {}: {}", conversationId, e.getMessage()); - } - } + private void touchSession(String conversationId, ChatCompletionRequest request) { + try { + sessionService.touch(conversationId, request.getSkill()); + } catch (Exception e) { + log.warn("Failed to touch session for {}: {}", conversationId, e.getMessage()); + } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/SessionController.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/SessionController.java index 99a1adf4d..e893a64f7 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/SessionController.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/controller/SessionController.java @@ -34,52 +34,49 @@ import reactor.core.publisher.Mono; @RequestMapping(AgenticConstant.SESSION_URL_PREFIX) public class SessionController implements BaseController { - private final SessionService sessionService; + private final SessionService sessionService; - private final SessionBuilder sessionBuilder; + private final SessionBuilder sessionBuilder; - public SessionController(SessionService sessionService, SessionBuilder sessionBuilder) { - this.sessionService = sessionService; - this.sessionBuilder = sessionBuilder; - } + public SessionController(SessionService sessionService, SessionBuilder sessionBuilder) { + this.sessionService = sessionService; + this.sessionBuilder = sessionBuilder; + } - @GetMapping - public Mono>> list(SessionQuery query) { - try { - Page page = sessionService.selectByPage(query); - return Mono.just(R.ok(sessionBuilder.buildVOPageByBOPage(page))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping + public Mono>> list(SessionQuery query) { + try { + Page page = sessionService.selectByPage(query); + return Mono.just(R.ok(sessionBuilder.buildVOPageByBOPage(page))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/{conversationId}") - public Mono> get(@PathVariable String conversationId) { - try { - SessionBO session = sessionService.getByConversationId(conversationId); - if (session == null) { - return Mono.just(R.fail("Session not found")); - } - return Mono.just(R.ok(sessionBuilder.buildVOByBO(session))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/{conversationId}") + public Mono> get(@PathVariable String conversationId) { + try { + SessionBO session = sessionService.getByConversationId(conversationId); + if (session == null) { + return Mono.just(R.fail("Session not found")); + } + return Mono.just(R.ok(sessionBuilder.buildVOByBO(session))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @DeleteMapping("/{conversationId}") - public Mono> delete(@PathVariable String conversationId) { - try { - sessionService.removeByConversationId(conversationId); - return Mono.just(R.ok()); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @DeleteMapping("/{conversationId}") + public Mono> delete(@PathVariable String conversationId) { + try { + sessionService.removeByConversationId(conversationId); + return Mono.just(R.ok()); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/bo/SessionBO.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/bo/SessionBO.java index ad1b14b4e..69383026a 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/bo/SessionBO.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/bo/SessionBO.java @@ -28,20 +28,20 @@ import java.time.LocalDateTime; @ToString(callSuper = true) public class SessionBO extends BaseBO { - private String conversationId; + private String conversationId; - private String title; + private String title; - private String skill; + private String skill; - private Byte status; + private Byte status; - private LocalDateTime expireTime; + private LocalDateTime expireTime; - private Long tenantId; + private Long tenantId; - private Long userId; + private Long userId; - private Byte enableFlag; + private Byte enableFlag; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/builder/SessionBuilder.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/builder/SessionBuilder.java index e316c0ee2..f0ae8c323 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/builder/SessionBuilder.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/builder/SessionBuilder.java @@ -26,40 +26,40 @@ import org.mapstruct.Mapping; import java.util.List; -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface SessionBuilder { - SessionBO buildBOByVO(SessionVO entityVO); + SessionBO buildBOByVO(SessionVO entityVO); - List buildBOListByVOList(List entityVOList); + List buildBOListByVOList(List entityVOList); - SessionVO buildVOByBO(SessionBO entityBO); + SessionVO buildVOByBO(SessionBO entityBO); - List buildVOListByBOList(List entityBOList); + List buildVOListByBOList(List entityBOList); - SessionBO buildBOByDO(SessionDO entityDO); + SessionBO buildBOByDO(SessionDO entityDO); - List buildBOListByDOList(List entityDOList); + List buildBOListByDOList(List entityDOList); - @Mapping(target = "deleted", ignore = true) - SessionDO buildDOByBO(SessionBO entityBO); + @Mapping(target = "deleted", ignore = true) + SessionDO buildDOByBO(SessionBO entityBO); - List buildDOListByBOList(List entityBOList); + List buildDOListByBOList(List entityBOList); - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/model/SessionDO.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/model/SessionDO.java index b3be3e3a0..f68d3fd95 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/model/SessionDO.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/model/SessionDO.java @@ -31,59 +31,59 @@ import java.time.LocalDateTime; @TableName("dc3_session") public class SessionDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - @TableField("conversation_id") - private String conversationId; + @TableField("conversation_id") + private String conversationId; - @TableField("title") - private String title; + @TableField("title") + private String title; - @TableField("skill") - private String skill; + @TableField("skill") + private String skill; - @TableField("status") - private Byte status; + @TableField("status") + private Byte status; - @TableField("expire_time") - private LocalDateTime expireTime; + @TableField("expire_time") + private LocalDateTime expireTime; - @TableField("tenant_id") - private Long tenantId; + @TableField("tenant_id") + private Long tenantId; - @TableField("user_id") - private Long userId; + @TableField("user_id") + private Long userId; - @TableField("enable_flag") - private Byte enableFlag; + @TableField("enable_flag") + private Byte enableFlag; - @TableField("remark") - private String remark; + @TableField("remark") + private String remark; - @TableField("creator_id") - private Long creatorId; + @TableField("creator_id") + private Long creatorId; - @TableField("creator_name") - private String creatorName; + @TableField("creator_name") + private String creatorName; - @TableField("create_time") - private LocalDateTime createTime; + @TableField("create_time") + private LocalDateTime createTime; - @TableField("operator_id") - private Long operatorId; + @TableField("operator_id") + private Long operatorId; - @TableField("operator_name") - private String operatorName; + @TableField("operator_name") + private String operatorName; - @TableField("operate_time") - private LocalDateTime operateTime; + @TableField("operate_time") + private LocalDateTime operateTime; - @TableLogic - @TableField("deleted") - private Byte deleted; + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/query/SessionQuery.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/query/SessionQuery.java index 7a4be4873..0f167c52d 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/query/SessionQuery.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/query/SessionQuery.java @@ -30,17 +30,17 @@ import java.io.Serializable; @AllArgsConstructor public class SessionQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - private Long tenantId; + private Long tenantId; - private Long userId; + private Long userId; - private Byte status; + private Byte status; - private String conversationId; + private String conversationId; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatCompletionRequest.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatCompletionRequest.java index 5b5065f7a..693869235 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatCompletionRequest.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatCompletionRequest.java @@ -35,44 +35,44 @@ import java.util.List; @AllArgsConstructor public class ChatCompletionRequest { - /** - * Model identifier (advisory — the actual model is configured server-side). - */ - private String model; + /** + * Model identifier (advisory — the actual model is configured server-side). + */ + private String model; - /** - * Conversation messages in chronological order. - */ - private List messages; + /** + * Conversation messages in chronological order. + */ + private List messages; - /** - * Sampling temperature override (0.0–2.0). Null uses the server default. - */ - private Double temperature; + /** + * Sampling temperature override (0.0–2.0). Null uses the server default. + */ + private Double temperature; - /** - * Maximum tokens to generate. Null uses the server default. - */ - private Integer maxTokens; + /** + * Maximum tokens to generate. Null uses the server default. + */ + private Integer maxTokens; - /** - * Whether to stream the response as SSE events. - */ - private Boolean stream; + /** + * Whether to stream the response as SSE events. + */ + private Boolean stream; - /** - * Conversation ID for chat memory correlation. If omitted, a new conversation is - * started each request. - */ - private String conversationId; + /** + * Conversation ID for chat memory correlation. If omitted, a new conversation is + * started each request. + */ + private String conversationId; - /** - * Skill name to activate for this request. Null = all tools available. - */ - private String skill; + /** + * Skill name to activate for this request. Null = all tools available. + */ + private String skill; - public boolean isStream() { - return Boolean.TRUE.equals(stream); - } + public boolean isStream() { + return Boolean.TRUE.equals(stream); + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatMessageDTO.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatMessageDTO.java index 9e8d77e2a..64a4bb4ab 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatMessageDTO.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/request/ChatMessageDTO.java @@ -30,14 +30,14 @@ import lombok.Setter; @AllArgsConstructor public class ChatMessageDTO { - /** - * Message role: "system", "user", "assistant", or "tool". - */ - private String role; + /** + * Message role: "system", "user", "assistant", or "tool". + */ + private String role; - /** - * Message content text. - */ - private String content; + /** + * Message content text. + */ + private String content; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionChunkResponse.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionChunkResponse.java index 3c2aaf58e..1d3966109 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionChunkResponse.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionChunkResponse.java @@ -36,43 +36,43 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class ChatCompletionChunkResponse { - private String id; + private String id; - private String object; + private String object; - private long created; + private long created; - private String model; + private String model; - private List choices; + private List choices; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - @Builder - public static class ChunkChoice { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class ChunkChoice { - private int index; + private int index; - private Delta delta; + private Delta delta; - @JsonProperty("finish_reason") - private String finishReason; + @JsonProperty("finish_reason") + private String finishReason; - } + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - @JsonInclude(JsonInclude.Include.NON_NULL) - public static class Delta { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @JsonInclude(JsonInclude.Include.NON_NULL) + public static class Delta { - private String role; + private String role; - private String content; + private String content; - } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionResponse.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionResponse.java index cb2725133..556ff060d 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionResponse.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/response/ChatCompletionResponse.java @@ -35,57 +35,57 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class ChatCompletionResponse { - private String id; + private String id; - private String object; + private String object; - private long created; + private long created; - private String model; + private String model; - private List choices; + private List choices; - private Usage usage; + private Usage usage; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - @Builder - public static class Choice { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + @Builder + public static class Choice { - private int index; + private int index; - private Message message; + private Message message; - private String finishReason; + private String finishReason; - } + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Message { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Message { - private String role; + private String role; - private String content; + private String content; - } + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Usage { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Usage { - private int promptTokens; + private int promptTokens; - private int completionTokens; + private int completionTokens; - private int totalTokens; + private int totalTokens; - } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/vo/SessionVO.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/vo/SessionVO.java index 8866365f1..b56a8044f 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/vo/SessionVO.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/entity/vo/SessionVO.java @@ -30,20 +30,20 @@ import java.time.LocalDateTime; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class SessionVO extends BaseVO { - private String conversationId; + private String conversationId; - private String title; + private String title; - private String skill; + private String skill; - private Byte status; + private Byte status; - private LocalDateTime expireTime; + private LocalDateTime expireTime; - private Long tenantId; + private Long tenantId; - private Long userId; + private Long userId; - private Byte enableFlag; + private Byte enableFlag; } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/SessionService.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/SessionService.java index d8dbe72b1..de4431f0a 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/SessionService.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/SessionService.java @@ -22,34 +22,38 @@ import io.github.pnoker.common.agentic.entity.query.SessionQuery; public interface SessionService { - /** - * Create a new session if one does not exist for the given conversation ID. If a - * session already exists, update its operate_time. - * @param conversationId conversation ID - * @param skill active skill name (may be null) - * @return the session BO - */ - SessionBO touch(String conversationId, String skill); + /** + * Create a new session if one does not exist for the given conversation ID. If a + * session already exists, update its operate_time. + * + * @param conversationId conversation ID + * @param skill active skill name (may be null) + * @return the session BO + */ + SessionBO touch(String conversationId, String skill); - /** - * Get session by conversation ID. - * @param conversationId conversation ID - * @return session BO or null - */ - SessionBO getByConversationId(String conversationId); + /** + * Get session by conversation ID. + * + * @param conversationId conversation ID + * @return session BO or null + */ + SessionBO getByConversationId(String conversationId); - /** - * Delete session by conversation ID (logical delete) and clear associated chat - * memory. - * @param conversationId conversation ID - */ - void removeByConversationId(String conversationId); + /** + * Delete session by conversation ID (logical delete) and clear associated chat + * memory. + * + * @param conversationId conversation ID + */ + void removeByConversationId(String conversationId); - /** - * Query sessions with pagination. - * @param query query parameters - * @return paginated results - */ - Page selectByPage(SessionQuery query); + /** + * Query sessions with pagination. + * + * @param query query parameters + * @return paginated results + */ + Page selectByPage(SessionQuery query); } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/impl/SessionServiceImpl.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/impl/SessionServiceImpl.java index 0a873f440..ba7e79655 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/impl/SessionServiceImpl.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/service/impl/SessionServiceImpl.java @@ -38,76 +38,76 @@ import java.util.Objects; @Service public class SessionServiceImpl implements SessionService { - @Resource - private SessionBuilder sessionBuilder; + @Resource + private SessionBuilder sessionBuilder; - @Resource - private SessionManager sessionManager; + @Resource + private SessionManager sessionManager; - @Resource - private ChatMemory agenticChatMemory; + @Resource + private ChatMemory agenticChatMemory; - @Override - public SessionBO touch(String conversationId, String skill) { - SessionDO existing = findByConversationId(conversationId); - if (existing != null) { - if (StringUtils.isNotEmpty(skill)) { - existing.setSkill(skill); - } - sessionManager.updateById(existing); - return sessionBuilder.buildBOByDO(existing); - } + @Override + public SessionBO touch(String conversationId, String skill) { + SessionDO existing = findByConversationId(conversationId); + if (existing != null) { + if (StringUtils.isNotEmpty(skill)) { + existing.setSkill(skill); + } + sessionManager.updateById(existing); + return sessionBuilder.buildBOByDO(existing); + } - SessionDO entityDO = new SessionDO(); - entityDO.setConversationId(conversationId); - entityDO.setTitle("New Conversation"); - entityDO.setSkill(StringUtils.defaultString(skill, "")); - entityDO.setStatus((byte) 0); - entityDO.setEnableFlag((byte) 0); - sessionManager.save(entityDO); - return sessionBuilder.buildBOByDO(entityDO); - } + SessionDO entityDO = new SessionDO(); + entityDO.setConversationId(conversationId); + entityDO.setTitle("New Conversation"); + entityDO.setSkill(StringUtils.defaultString(skill, "")); + entityDO.setStatus((byte) 0); + entityDO.setEnableFlag((byte) 0); + sessionManager.save(entityDO); + return sessionBuilder.buildBOByDO(entityDO); + } - @Override - public SessionBO getByConversationId(String conversationId) { - SessionDO entityDO = findByConversationId(conversationId); - return entityDO != null ? sessionBuilder.buildBOByDO(entityDO) : null; - } + @Override + public SessionBO getByConversationId(String conversationId) { + SessionDO entityDO = findByConversationId(conversationId); + return entityDO != null ? sessionBuilder.buildBOByDO(entityDO) : null; + } - @Override - public void removeByConversationId(String conversationId) { - SessionDO entityDO = findByConversationId(conversationId); - if (entityDO != null) { - sessionManager.removeById(entityDO.getId()); - agenticChatMemory.clear(conversationId); - } - } + @Override + public void removeByConversationId(String conversationId) { + SessionDO entityDO = findByConversationId(conversationId); + if (entityDO != null) { + sessionManager.removeById(entityDO.getId()); + agenticChatMemory.clear(conversationId); + } + } - @Override - public Page selectByPage(SessionQuery query) { - if (Objects.isNull(query.getPage())) { - query.setPage(new io.github.pnoker.common.entity.common.Pages()); - } - Page entityPageDO = sessionManager.page(PageUtil.page(query.getPage()), fuzzyQuery(query)); - return sessionBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(SessionQuery query) { + if (Objects.isNull(query.getPage())) { + query.setPage(new io.github.pnoker.common.entity.common.Pages()); + } + Page entityPageDO = sessionManager.page(PageUtil.page(query.getPage()), fuzzyQuery(query)); + return sessionBuilder.buildBOPageByDOPage(entityPageDO); + } - private SessionDO findByConversationId(String conversationId) { - LambdaQueryWrapper wrapper = Wrappers.query() - .lambda() - .eq(SessionDO::getConversationId, conversationId) - .last("LIMIT 1"); - return sessionManager.getOne(wrapper); - } + private SessionDO findByConversationId(String conversationId) { + LambdaQueryWrapper wrapper = Wrappers.query() + .lambda() + .eq(SessionDO::getConversationId, conversationId) + .last("LIMIT 1"); + return sessionManager.getOne(wrapper); + } - private LambdaQueryWrapper fuzzyQuery(SessionQuery query) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(Objects.nonNull(query.getTenantId()), SessionDO::getTenantId, query.getTenantId()); - wrapper.eq(Objects.nonNull(query.getUserId()), SessionDO::getUserId, query.getUserId()); - wrapper.eq(Objects.nonNull(query.getStatus()), SessionDO::getStatus, query.getStatus()); - wrapper.like(StringUtils.isNotEmpty(query.getConversationId()), SessionDO::getConversationId, - query.getConversationId()); - return wrapper; - } + private LambdaQueryWrapper fuzzyQuery(SessionQuery query) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(Objects.nonNull(query.getTenantId()), SessionDO::getTenantId, query.getTenantId()); + wrapper.eq(Objects.nonNull(query.getUserId()), SessionDO::getUserId, query.getUserId()); + wrapper.eq(Objects.nonNull(query.getStatus()), SessionDO::getStatus, query.getStatus()); + wrapper.like(StringUtils.isNotEmpty(query.getConversationId()), SessionDO::getConversationId, + query.getConversationId()); + return wrapper; + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillDefinition.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillDefinition.java index 7cf3ce8de..8f7b8c68b 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillDefinition.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillDefinition.java @@ -36,55 +36,55 @@ import java.util.List; @AllArgsConstructor public class SkillDefinition { - /** - * Unique skill identifier (matches the YAML filename stem by convention). - */ - private String name; + /** + * Unique skill identifier (matches the YAML filename stem by convention). + */ + private String name; - /** - * Human-readable description of what this skill enables. - */ - private String description; + /** + * Human-readable description of what this skill enables. + */ + private String description; - /** - * Whether the skill is active and should be loaded at startup. - */ - private boolean enabled; + /** + * Whether the skill is active and should be loaded at startup. + */ + private boolean enabled; - /** - * Additional system prompt text injected when this skill is activated. - */ - private String systemPromptAddition; + /** + * Additional system prompt text injected when this skill is activated. + */ + private String systemPromptAddition; - /** - * Names of the Spring AI tools this skill is allowed to use. - */ - private List tools; + /** + * Names of the Spring AI tools this skill is allowed to use. + */ + private List tools; - /** - * Few-shot examples illustrating expected user-assistant interactions. - */ - private List examples; + /** + * Few-shot examples illustrating expected user-assistant interactions. + */ + private List examples; - /** - * A single user-assistant exchange used as a few-shot example. - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class SkillExample { + /** + * A single user-assistant exchange used as a few-shot example. + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class SkillExample { - /** - * Example user message. - */ - private String user; + /** + * Example user message. + */ + private String user; - /** - * Example assistant response. - */ - private String assistant; + /** + * Example assistant response. + */ + private String assistant; - } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillLoader.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillLoader.java index 58833b94a..55748b001 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillLoader.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillLoader.java @@ -39,59 +39,57 @@ import java.util.Map; @Component public class SkillLoader implements ApplicationRunner { - private final SkillRegistry registry; + private final SkillRegistry registry; - public SkillLoader(SkillRegistry registry) { - this.registry = registry; - } + public SkillLoader(SkillRegistry registry) { + this.registry = registry; + } - @Override - public void run(ApplicationArguments args) throws Exception { - PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - Resource[] resources = resolver.getResources("classpath*:skills/*.yml"); + @Override + public void run(ApplicationArguments args) throws Exception { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + Resource[] resources = resolver.getResources("classpath*:skills/*.yml"); - List loaded = new ArrayList<>(); + List loaded = new ArrayList<>(); - Yaml yaml = new Yaml(); - for (Resource resource : resources) { - try (InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) { - Map map = yaml.load(reader); - SkillDefinition skill = mapToSkill(map); - if (skill.isEnabled()) { - registry.register(skill); - loaded.add(skill.getName()); - } - else { - log.debug("Skipping disabled skill: {}", skill.getName()); - } - } - catch (Exception e) { - log.error("Failed to load skill from {}: {}", resource.getDescription(), e.getMessage(), e); - } - } + Yaml yaml = new Yaml(); + for (Resource resource : resources) { + try (InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) { + Map map = yaml.load(reader); + SkillDefinition skill = mapToSkill(map); + if (skill.isEnabled()) { + registry.register(skill); + loaded.add(skill.getName()); + } else { + log.debug("Skipping disabled skill: {}", skill.getName()); + } + } catch (Exception e) { + log.error("Failed to load skill from {}: {}", resource.getDescription(), e.getMessage(), e); + } + } - log.info("Loaded {} skills: {}", loaded.size(), loaded); - } + log.info("Loaded {} skills: {}", loaded.size(), loaded); + } - @SuppressWarnings("unchecked") - private SkillDefinition mapToSkill(Map map) { - SkillDefinition skill = new SkillDefinition(); - skill.setName((String) map.get("name")); - skill.setDescription((String) map.get("description")); - skill.setEnabled(Boolean.TRUE.equals(map.get("enabled"))); - skill.setSystemPromptAddition((String) map.get("system-prompt-addition")); - skill.setTools((List) map.get("tools")); + @SuppressWarnings("unchecked") + private SkillDefinition mapToSkill(Map map) { + SkillDefinition skill = new SkillDefinition(); + skill.setName((String) map.get("name")); + skill.setDescription((String) map.get("description")); + skill.setEnabled(Boolean.TRUE.equals(map.get("enabled"))); + skill.setSystemPromptAddition((String) map.get("system-prompt-addition")); + skill.setTools((List) map.get("tools")); - List> exampleMaps = (List>) map.get("examples"); - if (exampleMaps != null) { - List examples = new ArrayList<>(); - for (Map ex : exampleMaps) { - examples.add(new SkillDefinition.SkillExample(ex.get("user"), ex.get("assistant"))); - } - skill.setExamples(examples); - } + List> exampleMaps = (List>) map.get("examples"); + if (exampleMaps != null) { + List examples = new ArrayList<>(); + for (Map ex : exampleMaps) { + examples.add(new SkillDefinition.SkillExample(ex.get("user"), ex.get("assistant"))); + } + skill.setExamples(examples); + } - return skill; - } + return skill; + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillRegistry.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillRegistry.java index 946bd465d..3d30ecc07 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillRegistry.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/skill/SkillRegistry.java @@ -27,48 +27,52 @@ import java.util.*; @Component public class SkillRegistry { - private final Map skills = new LinkedHashMap<>(); + private final Map skills = new LinkedHashMap<>(); - /** - * Register a skill definition. Overwrites any existing skill with the same name. - * @param skill the skill to register - */ - public void register(SkillDefinition skill) { - skills.put(skill.getName(), skill); - } + /** + * Register a skill definition. Overwrites any existing skill with the same name. + * + * @param skill the skill to register + */ + public void register(SkillDefinition skill) { + skills.put(skill.getName(), skill); + } - /** - * Look up a skill by name. - * @param name the skill name - * @return the matching skill, or {@code null} if not found - */ - public SkillDefinition get(String name) { - return skills.get(name); - } + /** + * Look up a skill by name. + * + * @param name the skill name + * @return the matching skill, or {@code null} if not found + */ + public SkillDefinition get(String name) { + return skills.get(name); + } - /** - * Return all registered skills in insertion order. - * @return unmodifiable collection of all skills - */ - public Collection all() { - return Collections.unmodifiableCollection(skills.values()); - } + /** + * Return all registered skills in insertion order. + * + * @return unmodifiable collection of all skills + */ + public Collection all() { + return Collections.unmodifiableCollection(skills.values()); + } - /** - * Return the tool names associated with the given skill. - *

- * Returns {@code null} (meaning "all tools available") when the skill is not found or - * the skill's tool list is empty. - * @param skillName the skill to look up - * @return list of allowed tool names, or {@code null} for unrestricted - */ - public List getEnabledToolNames(String skillName) { - SkillDefinition skill = skills.get(skillName); - if (skill == null) { - return null; - } - List tools = skill.getTools(); - return (tools == null || tools.isEmpty()) ? null : tools; - } + /** + * Return the tool names associated with the given skill. + *

+ * Returns {@code null} (meaning "all tools available") when the skill is not found or + * the skill's tool list is empty. + * + * @param skillName the skill to look up + * @return list of allowed tool names, or {@code null} for unrestricted + */ + public List getEnabledToolNames(String skillName) { + SkillDefinition skill = skills.get(skillName); + if (skill == null) { + return null; + } + List tools = skill.getTools(); + return (tools == null || tools.isEmpty()) ? null : tools; + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/AuthToolSet.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/AuthToolSet.java index d2c3ee677..6a9bc5f69 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/AuthToolSet.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/AuthToolSet.java @@ -39,51 +39,51 @@ import java.util.Objects; @Component public class AuthToolSet { - private final TenantFacade tenantFacade; + private final TenantFacade tenantFacade; - private final UserFacade userFacade; + private final UserFacade userFacade; - private final UserLoginFacade userLoginFacade; + private final UserLoginFacade userLoginFacade; - public AuthToolSet(TenantFacade tenantFacade, UserFacade userFacade, UserLoginFacade userLoginFacade) { - this.tenantFacade = tenantFacade; - this.userFacade = userFacade; - this.userLoginFacade = userLoginFacade; - } + public AuthToolSet(TenantFacade tenantFacade, UserFacade userFacade, UserLoginFacade userLoginFacade) { + this.tenantFacade = tenantFacade; + this.userFacade = userFacade; + this.userLoginFacade = userLoginFacade; + } - @Tool(description = "Look up a tenant by its unique code. Returns tenant name, code, and enable status.") - public String lookupTenantByCode( - @ToolParam(description = "The unique tenant code, e.g. 'default'") String tenantCode) { - log.debug("Tool: lookupTenantByCode({})", tenantCode); - FacadeTenantBO bo = tenantFacade.selectByCode(tenantCode); - if (Objects.isNull(bo)) { - return "Tenant not found for code: " + tenantCode; - } - return String.format("Tenant: name=%s, code=%s, enabled=%s", bo.getTenantName(), bo.getTenantCode(), - bo.getEnableFlag()); - } + @Tool(description = "Look up a tenant by its unique code. Returns tenant name, code, and enable status.") + public String lookupTenantByCode( + @ToolParam(description = "The unique tenant code, e.g. 'default'") String tenantCode) { + log.debug("Tool: lookupTenantByCode({})", tenantCode); + FacadeTenantBO bo = tenantFacade.selectByCode(tenantCode); + if (Objects.isNull(bo)) { + return "Tenant not found for code: " + tenantCode; + } + return String.format("Tenant: name=%s, code=%s, enabled=%s", bo.getTenantName(), bo.getTenantCode(), + bo.getEnableFlag()); + } - @Tool(description = "Look up a user by their numeric ID. Returns nickname, username, email, and phone.") - public String lookupUserById(@ToolParam(description = "The numeric user ID") Long userId) { - log.debug("Tool: lookupUserById({})", userId); - FacadeUserBO bo = userFacade.selectById(userId); - if (Objects.isNull(bo)) { - return "User not found for ID: " + userId; - } - return String.format("User: nickname=%s, username=%s, phone=%s, email=%s", bo.getNickName(), bo.getUserName(), - bo.getPhone(), bo.getEmail()); - } + @Tool(description = "Look up a user by their numeric ID. Returns nickname, username, email, and phone.") + public String lookupUserById(@ToolParam(description = "The numeric user ID") Long userId) { + log.debug("Tool: lookupUserById({})", userId); + FacadeUserBO bo = userFacade.selectById(userId); + if (Objects.isNull(bo)) { + return "User not found for ID: " + userId; + } + return String.format("User: nickname=%s, username=%s, phone=%s, email=%s", bo.getNickName(), bo.getUserName(), + bo.getPhone(), bo.getEmail()); + } - @Tool(description = "Look up a user login record by login name. Returns the login name, associated user ID, and enable status.") - public String lookupUserLoginByName( - @ToolParam(description = "The login name (username used for authentication)") String loginName) { - log.debug("Tool: lookupUserLoginByName({})", loginName); - FacadeUserLoginBO bo = userLoginFacade.selectByName(loginName); - if (Objects.isNull(bo)) { - return "User login not found for name: " + loginName; - } - return String.format("UserLogin: loginName=%s, userId=%d, enabled=%s", bo.getLoginName(), bo.getUserId(), - bo.getEnableFlag()); - } + @Tool(description = "Look up a user login record by login name. Returns the login name, associated user ID, and enable status.") + public String lookupUserLoginByName( + @ToolParam(description = "The login name (username used for authentication)") String loginName) { + log.debug("Tool: lookupUserLoginByName({})", loginName); + FacadeUserLoginBO bo = userLoginFacade.selectByName(loginName); + if (Objects.isNull(bo)) { + return "User login not found for name: " + loginName; + } + return String.format("UserLogin: loginName=%s, userId=%d, enabled=%s", bo.getLoginName(), bo.getUserId(), + bo.getEnableFlag()); + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/DataToolSet.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/DataToolSet.java index 50b268811..ff7779e83 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/DataToolSet.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/DataToolSet.java @@ -37,84 +37,80 @@ import java.util.List; @Component public class DataToolSet { - private final PointValueFacade pointValueFacade; + private final PointValueFacade pointValueFacade; - private final PointValueCommandFacade pointValueCommandFacade; + private final PointValueCommandFacade pointValueCommandFacade; - public DataToolSet(PointValueFacade pointValueFacade, PointValueCommandFacade pointValueCommandFacade) { - this.pointValueFacade = pointValueFacade; - this.pointValueCommandFacade = pointValueCommandFacade; - } + public DataToolSet(PointValueFacade pointValueFacade, PointValueCommandFacade pointValueCommandFacade) { + this.pointValueFacade = pointValueFacade; + this.pointValueCommandFacade = pointValueCommandFacade; + } - @Tool(description = "Get the latest point value for a specific device and point. Returns the current value.") - public String getLatestPointValue(@ToolParam(description = "The tenant ID") Long tenantId, - @ToolParam(description = "The device ID") Long deviceId, - @ToolParam(description = "The point (metric) ID") Long pointId) { - log.debug("Tool: getLatestPointValue(tenantId={}, deviceId={}, pointId={})", tenantId, deviceId, pointId); - try { - FacadePointValueBO value = pointValueFacade.lastValue(tenantId, deviceId, pointId); - if (value == null) { - return "No latest value found for device " + deviceId + " point " + pointId; - } - return String.format("Device %d / Point %d: value=%s, rawValue=%s, time=%d", value.getDeviceId(), - value.getPointId(), value.getValue(), value.getRawValue(), value.getCreateTime()); - } - catch (Exception e) { - log.error("Failed to get latest point value: {}", e.getMessage()); - return "Error retrieving latest value: " + e.getMessage(); - } - } + @Tool(description = "Get the latest point value for a specific device and point. Returns the current value.") + public String getLatestPointValue(@ToolParam(description = "The tenant ID") Long tenantId, + @ToolParam(description = "The device ID") Long deviceId, + @ToolParam(description = "The point (metric) ID") Long pointId) { + log.debug("Tool: getLatestPointValue(tenantId={}, deviceId={}, pointId={})", tenantId, deviceId, pointId); + try { + FacadePointValueBO value = pointValueFacade.lastValue(tenantId, deviceId, pointId); + if (value == null) { + return "No latest value found for device " + deviceId + " point " + pointId; + } + return String.format("Device %d / Point %d: value=%s, rawValue=%s, time=%d", value.getDeviceId(), + value.getPointId(), value.getValue(), value.getRawValue(), value.getCreateTime()); + } catch (Exception e) { + log.error("Failed to get latest point value: {}", e.getMessage()); + return "Error retrieving latest value: " + e.getMessage(); + } + } - @Tool(description = "Get historical point values for a specific device and point. Returns a list of value strings.") - public String getPointValueHistory(@ToolParam(description = "The tenant ID") Long tenantId, - @ToolParam(description = "The device ID") Long deviceId, - @ToolParam(description = "The point (metric) ID") Long pointId, - @ToolParam(description = "Number of historical records to retrieve") int count) { - log.debug("Tool: getPointValueHistory(tenantId={}, deviceId={}, pointId={}, count={})", tenantId, deviceId, - pointId, count); - try { - List history = pointValueFacade.history(tenantId, deviceId, pointId, count); - if (history == null || history.isEmpty()) { - return "No history data found for device " + deviceId + " point " + pointId; - } - return "History values (" + history.size() + " records): " + String.join(", ", history); - } - catch (Exception e) { - log.error("Failed to get point value history: {}", e.getMessage()); - return "Error retrieving history: " + e.getMessage(); - } - } + @Tool(description = "Get historical point values for a specific device and point. Returns a list of value strings.") + public String getPointValueHistory(@ToolParam(description = "The tenant ID") Long tenantId, + @ToolParam(description = "The device ID") Long deviceId, + @ToolParam(description = "The point (metric) ID") Long pointId, + @ToolParam(description = "Number of historical records to retrieve") int count) { + log.debug("Tool: getPointValueHistory(tenantId={}, deviceId={}, pointId={}, count={})", tenantId, deviceId, + pointId, count); + try { + List history = pointValueFacade.history(tenantId, deviceId, pointId, count); + if (history == null || history.isEmpty()) { + return "No history data found for device " + deviceId + " point " + pointId; + } + return "History values (" + history.size() + " records): " + String.join(", ", history); + } catch (Exception e) { + log.error("Failed to get point value history: {}", e.getMessage()); + return "Error retrieving history: " + e.getMessage(); + } + } - @Tool(description = "Send a read command to a device for a specific point. The driver will read the current value from the physical device.") - public String readPointValue(@ToolParam(description = "The device ID") Long deviceId, - @ToolParam(description = "The point (metric) ID to read") Long pointId) { - log.debug("Tool: readPointValue(deviceId={}, pointId={})", deviceId, pointId); - try { - boolean success = pointValueCommandFacade.read(deviceId, pointId); - return success ? "Read command sent successfully for device " + deviceId + " point " + pointId - : "Read command failed for device " + deviceId + " point " + pointId; - } - catch (Exception e) { - log.error("Failed to send read command: {}", e.getMessage()); - return "Error sending read command: " + e.getMessage(); - } - } + @Tool(description = "Send a read command to a device for a specific point. The driver will read the current value from the physical device.") + public String readPointValue(@ToolParam(description = "The device ID") Long deviceId, + @ToolParam(description = "The point (metric) ID to read") Long pointId) { + log.debug("Tool: readPointValue(deviceId={}, pointId={})", deviceId, pointId); + try { + boolean success = pointValueCommandFacade.read(deviceId, pointId); + return success ? "Read command sent successfully for device " + deviceId + " point " + pointId + : "Read command failed for device " + deviceId + " point " + pointId; + } catch (Exception e) { + log.error("Failed to send read command: {}", e.getMessage()); + return "Error sending read command: " + e.getMessage(); + } + } - @Tool(description = "Send a write command to a device for a specific point. Sets the point to the specified value on the physical device.") - public String writePointValue(@ToolParam(description = "The device ID") Long deviceId, - @ToolParam(description = "The point (metric) ID to write") Long pointId, - @ToolParam(description = "The value to write (as a string)") String value) { - log.debug("Tool: writePointValue(deviceId={}, pointId={}, value={})", deviceId, pointId, value); - try { - boolean success = pointValueCommandFacade.write(deviceId, pointId, value); - return success - ? "Write command sent successfully for device " + deviceId + " point " + pointId + " value=" + value - : "Write command failed for device " + deviceId + " point " + pointId; - } - catch (Exception e) { - log.error("Failed to send write command: {}", e.getMessage()); - return "Error sending write command: " + e.getMessage(); - } - } + @Tool(description = "Send a write command to a device for a specific point. Sets the point to the specified value on the physical device.") + public String writePointValue(@ToolParam(description = "The device ID") Long deviceId, + @ToolParam(description = "The point (metric) ID to write") Long pointId, + @ToolParam(description = "The value to write (as a string)") String value) { + log.debug("Tool: writePointValue(deviceId={}, pointId={}, value={})", deviceId, pointId, value); + try { + boolean success = pointValueCommandFacade.write(deviceId, pointId, value); + return success + ? "Write command sent successfully for device " + deviceId + " point " + pointId + " value=" + value + : "Write command failed for device " + deviceId + " point " + pointId; + } catch (Exception e) { + log.error("Failed to send write command: {}", e.getMessage()); + return "Error sending write command: " + e.getMessage(); + } + } } diff --git a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/ManagerToolSet.java b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/ManagerToolSet.java index a92e08dc5..ff72d4f82 100644 --- a/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/ManagerToolSet.java +++ b/dc3-common/dc3-common-agentic/src/main/java/io/github/pnoker/common/agentic/tool/ManagerToolSet.java @@ -46,189 +46,189 @@ import java.util.stream.Collectors; @Component public class ManagerToolSet { - private final DeviceFacade deviceFacade; + private final DeviceFacade deviceFacade; - private final DriverFacade driverFacade; + private final DriverFacade driverFacade; - private final PointFacade pointFacade; + private final PointFacade pointFacade; - public ManagerToolSet(DeviceFacade deviceFacade, DriverFacade driverFacade, PointFacade pointFacade) { - this.deviceFacade = deviceFacade; - this.driverFacade = driverFacade; - this.pointFacade = pointFacade; - } + public ManagerToolSet(DeviceFacade deviceFacade, DriverFacade driverFacade, PointFacade pointFacade) { + this.deviceFacade = deviceFacade; + this.driverFacade = driverFacade; + this.pointFacade = pointFacade; + } - // ==================== Device Tools ==================== + // ==================== Device Tools ==================== - @Tool(description = "Look up a device by its numeric ID. Returns device name, code, driver ID, enable status, and profile IDs.") - public String lookupDeviceById(@ToolParam(description = "The numeric device ID") Long deviceId) { - log.debug("Tool: lookupDeviceById({})", deviceId); - FacadeDeviceBO bo = deviceFacade.selectById(deviceId); - if (Objects.isNull(bo)) { - return "Device not found for ID: " + deviceId; - } - return formatDevice(bo); - } + @Tool(description = "Look up a device by its numeric ID. Returns device name, code, driver ID, enable status, and profile IDs.") + public String lookupDeviceById(@ToolParam(description = "The numeric device ID") Long deviceId) { + log.debug("Tool: lookupDeviceById({})", deviceId); + FacadeDeviceBO bo = deviceFacade.selectById(deviceId); + if (Objects.isNull(bo)) { + return "Device not found for ID: " + deviceId; + } + return formatDevice(bo); + } - @Tool(description = "Search for devices with optional filters. Supports filtering by device name, code, or driver ID. Returns a paginated list of devices.") - public String searchDevices( - @ToolParam(description = "Device name filter (partial match), or null to skip") String deviceName, - @ToolParam(description = "Device code filter, or null to skip") String deviceCode, - @ToolParam(description = "Driver ID filter, or null to skip") Long driverId, - @ToolParam(description = "Page number (1-based)") int page, - @ToolParam(description = "Page size") int size) { - log.debug("Tool: searchDevices(name={}, code={}, driverId={}, page={}, size={})", deviceName, deviceCode, - driverId, page, size); + @Tool(description = "Search for devices with optional filters. Supports filtering by device name, code, or driver ID. Returns a paginated list of devices.") + public String searchDevices( + @ToolParam(description = "Device name filter (partial match), or null to skip") String deviceName, + @ToolParam(description = "Device code filter, or null to skip") String deviceCode, + @ToolParam(description = "Driver ID filter, or null to skip") Long driverId, + @ToolParam(description = "Page number (1-based)") int page, + @ToolParam(description = "Page size") int size) { + log.debug("Tool: searchDevices(name={}, code={}, driverId={}, page={}, size={})", deviceName, deviceCode, + driverId, page, size); - FacadeDeviceQuery query = new FacadeDeviceQuery(); - query.setDeviceName(deviceName); - query.setDeviceCode(deviceCode); - query.setDriverId(driverId); - Pages p = new Pages(); - p.setCurrent(page); - p.setSize(size); - query.setPage(p); + FacadeDeviceQuery query = new FacadeDeviceQuery(); + query.setDeviceName(deviceName); + query.setDeviceCode(deviceCode); + query.setDriverId(driverId); + Pages p = new Pages(); + p.setCurrent(page); + p.setSize(size); + query.setPage(p); - FacadePage result = deviceFacade.selectByPage(query); - return formatDevicePage(result); - } + FacadePage result = deviceFacade.selectByPage(query); + return formatDevicePage(result); + } - @Tool(description = "List all devices attached to a given driver ID.") - public String listDevicesByDriverId(@ToolParam(description = "The driver ID") Long driverId) { - log.debug("Tool: listDevicesByDriverId({})", driverId); - List devices = deviceFacade.selectByDriverId(driverId); - if (devices.isEmpty()) { - return "No devices found for driver ID: " + driverId; - } - return "Devices for driver " + driverId + ":\n" - + devices.stream().map(this::formatDevice).collect(Collectors.joining("\n")); - } + @Tool(description = "List all devices attached to a given driver ID.") + public String listDevicesByDriverId(@ToolParam(description = "The driver ID") Long driverId) { + log.debug("Tool: listDevicesByDriverId({})", driverId); + List devices = deviceFacade.selectByDriverId(driverId); + if (devices.isEmpty()) { + return "No devices found for driver ID: " + driverId; + } + return "Devices for driver " + driverId + ":\n" + + devices.stream().map(this::formatDevice).collect(Collectors.joining("\n")); + } - @Tool(description = "List all devices that use a given profile (device template) ID.") - public String listDevicesByProfileId(@ToolParam(description = "The profile ID") Long profileId) { - log.debug("Tool: listDevicesByProfileId({})", profileId); - List devices = deviceFacade.selectByProfileId(profileId); - if (devices.isEmpty()) { - return "No devices found for profile ID: " + profileId; - } - return "Devices for profile " + profileId + ":\n" - + devices.stream().map(this::formatDevice).collect(Collectors.joining("\n")); - } + @Tool(description = "List all devices that use a given profile (device template) ID.") + public String listDevicesByProfileId(@ToolParam(description = "The profile ID") Long profileId) { + log.debug("Tool: listDevicesByProfileId({})", profileId); + List devices = deviceFacade.selectByProfileId(profileId); + if (devices.isEmpty()) { + return "No devices found for profile ID: " + profileId; + } + return "Devices for profile " + profileId + ":\n" + + devices.stream().map(this::formatDevice).collect(Collectors.joining("\n")); + } - // ==================== Driver Tools ==================== + // ==================== Driver Tools ==================== - @Tool(description = "Look up a driver by its numeric ID. Returns driver name, code, service name, host, type, and enable status.") - public String lookupDriverById(@ToolParam(description = "The numeric driver ID") Long driverId) { - log.debug("Tool: lookupDriverById({})", driverId); - FacadeDriverBO bo = driverFacade.selectById(driverId); - if (Objects.isNull(bo)) { - return "Driver not found for ID: " + driverId; - } - return formatDriver(bo); - } + @Tool(description = "Look up a driver by its numeric ID. Returns driver name, code, service name, host, type, and enable status.") + public String lookupDriverById(@ToolParam(description = "The numeric driver ID") Long driverId) { + log.debug("Tool: lookupDriverById({})", driverId); + FacadeDriverBO bo = driverFacade.selectById(driverId); + if (Objects.isNull(bo)) { + return "Driver not found for ID: " + driverId; + } + return formatDriver(bo); + } - @Tool(description = "Resolve the driver that owns a given device. Returns the driver details.") - public String lookupDriverByDeviceId(@ToolParam(description = "The device ID") Long deviceId) { - log.debug("Tool: lookupDriverByDeviceId({})", deviceId); - FacadeDriverBO bo = driverFacade.selectByDeviceId(deviceId); - if (Objects.isNull(bo)) { - return "No driver found for device ID: " + deviceId; - } - return formatDriver(bo); - } + @Tool(description = "Resolve the driver that owns a given device. Returns the driver details.") + public String lookupDriverByDeviceId(@ToolParam(description = "The device ID") Long deviceId) { + log.debug("Tool: lookupDriverByDeviceId({})", deviceId); + FacadeDriverBO bo = driverFacade.selectByDeviceId(deviceId); + if (Objects.isNull(bo)) { + return "No driver found for device ID: " + deviceId; + } + return formatDriver(bo); + } - @Tool(description = "Search for drivers with optional name filter. Returns a paginated list.") - public String searchDrivers( - @ToolParam(description = "Driver name filter (partial match), or null to skip") String driverName, - @ToolParam(description = "Page number (1-based)") int page, - @ToolParam(description = "Page size") int size) { - log.debug("Tool: searchDrivers(name={}, page={}, size={})", driverName, page, size); + @Tool(description = "Search for drivers with optional name filter. Returns a paginated list.") + public String searchDrivers( + @ToolParam(description = "Driver name filter (partial match), or null to skip") String driverName, + @ToolParam(description = "Page number (1-based)") int page, + @ToolParam(description = "Page size") int size) { + log.debug("Tool: searchDrivers(name={}, page={}, size={})", driverName, page, size); - FacadeDriverQuery query = new FacadeDriverQuery(); - query.setDriverName(driverName); - Pages p = new Pages(); - p.setCurrent(page); - p.setSize(size); - query.setPage(p); + FacadeDriverQuery query = new FacadeDriverQuery(); + query.setDriverName(driverName); + Pages p = new Pages(); + p.setCurrent(page); + p.setSize(size); + query.setPage(p); - FacadePage result = driverFacade.selectByPage(query); - return formatDriverPage(result); - } + FacadePage result = driverFacade.selectByPage(query); + return formatDriverPage(result); + } - // ==================== Point Tools ==================== + // ==================== Point Tools ==================== - @Tool(description = "Look up a point (data point / metric) by its numeric ID. Returns point name, code, type, read/write flag, unit, base value, and multiplier.") - public String lookupPointById(@ToolParam(description = "The numeric point ID") Long pointId) { - log.debug("Tool: lookupPointById({})", pointId); - FacadePointBO bo = pointFacade.selectById(pointId); - if (Objects.isNull(bo)) { - return "Point not found for ID: " + pointId; - } - return formatPoint(bo); - } + @Tool(description = "Look up a point (data point / metric) by its numeric ID. Returns point name, code, type, read/write flag, unit, base value, and multiplier.") + public String lookupPointById(@ToolParam(description = "The numeric point ID") Long pointId) { + log.debug("Tool: lookupPointById({})", pointId); + FacadePointBO bo = pointFacade.selectById(pointId); + if (Objects.isNull(bo)) { + return "Point not found for ID: " + pointId; + } + return formatPoint(bo); + } - @Tool(description = "Search for points with optional filters. Returns a paginated list.") - public String searchPoints( - @ToolParam(description = "Point name filter (partial match), or null to skip") String pointName, - @ToolParam(description = "Profile ID filter, or null to skip") Long profileId, - @ToolParam(description = "Page number (1-based)") int page, - @ToolParam(description = "Page size") int size) { - log.debug("Tool: searchPoints(name={}, profileId={}, page={}, size={})", pointName, profileId, page, size); + @Tool(description = "Search for points with optional filters. Returns a paginated list.") + public String searchPoints( + @ToolParam(description = "Point name filter (partial match), or null to skip") String pointName, + @ToolParam(description = "Profile ID filter, or null to skip") Long profileId, + @ToolParam(description = "Page number (1-based)") int page, + @ToolParam(description = "Page size") int size) { + log.debug("Tool: searchPoints(name={}, profileId={}, page={}, size={})", pointName, profileId, page, size); - FacadePointQuery query = new FacadePointQuery(); - query.setPointName(pointName); - query.setProfileId(profileId); - Pages p = new Pages(); - p.setCurrent(page); - p.setSize(size); - query.setPage(p); + FacadePointQuery query = new FacadePointQuery(); + query.setPointName(pointName); + query.setProfileId(profileId); + Pages p = new Pages(); + p.setCurrent(page); + p.setSize(size); + query.setPage(p); - FacadePage result = pointFacade.selectByPage(query); - return formatPointPage(result); - } + FacadePage result = pointFacade.selectByPage(query); + return formatPointPage(result); + } - // ==================== Formatting Helpers ==================== + // ==================== Formatting Helpers ==================== - private String formatDevice(FacadeDeviceBO d) { - return String.format("Device[id=%d, name=%s, code=%s, driverId=%d, enabled=%s, profileIds=%s]", d.getId(), - d.getDeviceName(), d.getDeviceCode(), d.getDriverId(), d.getEnableFlag(), d.getProfileIds()); - } + private String formatDevice(FacadeDeviceBO d) { + return String.format("Device[id=%d, name=%s, code=%s, driverId=%d, enabled=%s, profileIds=%s]", d.getId(), + d.getDeviceName(), d.getDeviceCode(), d.getDriverId(), d.getEnableFlag(), d.getProfileIds()); + } - private String formatDevicePage(FacadePage page) { - if (Objects.isNull(page) || page.getRecords().isEmpty()) { - return "No devices found."; - } - String items = page.getRecords().stream().map(this::formatDevice).collect(Collectors.joining("\n")); - return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); - } + private String formatDevicePage(FacadePage page) { + if (Objects.isNull(page) || page.getRecords().isEmpty()) { + return "No devices found."; + } + String items = page.getRecords().stream().map(this::formatDevice).collect(Collectors.joining("\n")); + return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); + } - private String formatDriver(FacadeDriverBO d) { - return String.format("Driver[id=%d, name=%s, code=%s, serviceName=%s, host=%s, type=%s, enabled=%s]", d.getId(), - d.getDriverName(), d.getDriverCode(), d.getServiceName(), d.getServiceHost(), d.getDriverTypeFlag(), - d.getEnableFlag()); - } + private String formatDriver(FacadeDriverBO d) { + return String.format("Driver[id=%d, name=%s, code=%s, serviceName=%s, host=%s, type=%s, enabled=%s]", d.getId(), + d.getDriverName(), d.getDriverCode(), d.getServiceName(), d.getServiceHost(), d.getDriverTypeFlag(), + d.getEnableFlag()); + } - private String formatDriverPage(FacadePage page) { - if (Objects.isNull(page) || page.getRecords().isEmpty()) { - return "No drivers found."; - } - String items = page.getRecords().stream().map(this::formatDriver).collect(Collectors.joining("\n")); - return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); - } + private String formatDriverPage(FacadePage page) { + if (Objects.isNull(page) || page.getRecords().isEmpty()) { + return "No drivers found."; + } + String items = page.getRecords().stream().map(this::formatDriver).collect(Collectors.joining("\n")); + return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); + } - private String formatPoint(FacadePointBO p) { - return String.format( - "Point[id=%d, name=%s, code=%s, type=%s, rw=%s, unit=%s, base=%s, multiple=%s, profileId=%d]", - p.getId(), p.getPointName(), p.getPointCode(), p.getPointTypeFlag(), p.getRwFlag(), p.getUnit(), - p.getBaseValue(), p.getMultiple(), p.getProfileId()); - } + private String formatPoint(FacadePointBO p) { + return String.format( + "Point[id=%d, name=%s, code=%s, type=%s, rw=%s, unit=%s, base=%s, multiple=%s, profileId=%d]", + p.getId(), p.getPointName(), p.getPointCode(), p.getPointTypeFlag(), p.getRwFlag(), p.getUnit(), + p.getBaseValue(), p.getMultiple(), p.getProfileId()); + } - private String formatPointPage(FacadePage page) { - if (Objects.isNull(page) || page.getRecords().isEmpty()) { - return "No points found."; - } - String items = page.getRecords().stream().map(this::formatPoint).collect(Collectors.joining("\n")); - return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); - } + private String formatPointPage(FacadePage page) { + if (Objects.isNull(page) || page.getRecords().isEmpty()) { + return "No points found."; + } + String items = page.getRecords().stream().map(this::formatPoint).collect(Collectors.joining("\n")); + return String.format("Page %d/%d (total %d):\n%s", page.getCurrent(), page.getPages(), page.getTotal(), items); + } } diff --git a/dc3-common/dc3-common-api/README.md b/dc3-common/dc3-common-api/README.md index 3bf02ca90..acd1468c3 100644 --- a/dc3-common/dc3-common-api/README.md +++ b/dc3-common/dc3-common-api/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-api` provides shared gRPC utility classes used across all services in the IoT DC3 platform. It contains builder utilities for constructing gRPC request/response objects +`dc3-common-api` provides shared gRPC utility classes used across all services in the IoT DC3 platform. It contains +builder utilities for constructing gRPC request/response objects from domain model entities. ## Module Information @@ -13,11 +14,13 @@ from domain model entities. ## Key Components -- **`GrpcBuilderUtil`** — Utility class for building common gRPC DTOs from BO/DO entities (e.g., setting pagination, building result wrappers) +- **`GrpcBuilderUtil`** — Utility class for building common gRPC DTOs from BO/DO entities (e.g., setting pagination, + building result wrappers) ## Dependencies -This module is included in any service that imports a `dc3-api-*` module. It bridges domain model objects with generated protobuf classes. +This module is included in any service that imports a `dc3-api-*` module. It bridges domain model objects with generated +protobuf classes. ## Build Instructions diff --git a/dc3-common/dc3-common-api/src/main/java/io/github/pnoker/common/utils/GrpcBuilderUtil.java b/dc3-common/dc3-common-api/src/main/java/io/github/pnoker/common/utils/GrpcBuilderUtil.java index 1afbe825a..77cb27cf5 100644 --- a/dc3-common/dc3-common-api/src/main/java/io/github/pnoker/common/utils/GrpcBuilderUtil.java +++ b/dc3-common/dc3-common-api/src/main/java/io/github/pnoker/common/utils/GrpcBuilderUtil.java @@ -39,132 +39,137 @@ import java.util.Optional; */ public class GrpcBuilderUtil { - private GrpcBuilderUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private GrpcBuilderUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Grpc Page to Pages - * @param page GrpcPage - * @return Pages - */ - public static Pages buildPagesByGrpcPage(GrpcPage page) { - if (Objects.isNull(page)) { - GrpcPage.Builder builder = GrpcPage.newBuilder(); - builder.setCurrent(1); - builder.setPages(DefaultConstant.PAGE_SIZE); - page = builder.build(); - } + /** + * Grpc Page to Pages + * + * @param page GrpcPage + * @return Pages + */ + public static Pages buildPagesByGrpcPage(GrpcPage page) { + if (Objects.isNull(page)) { + GrpcPage.Builder builder = GrpcPage.newBuilder(); + builder.setCurrent(1); + builder.setPages(DefaultConstant.PAGE_SIZE); + page = builder.build(); + } - Pages pages = new Pages(); - long current = page.getCurrent() < 1 ? 1 : page.getCurrent(); - long pageSize = page.getSize() < 1 ? DefaultConstant.PAGE_SIZE : page.getSize(); - pageSize = pageSize > DefaultConstant.MAX_PAGE_SIZE ? DefaultConstant.MAX_PAGE_SIZE : pageSize; - pages.setCurrent(current); - pages.setSize(pageSize); - return pages; - } + Pages pages = new Pages(); + long current = page.getCurrent() < 1 ? 1 : page.getCurrent(); + long pageSize = page.getSize() < 1 ? DefaultConstant.PAGE_SIZE : page.getSize(); + pageSize = pageSize > DefaultConstant.MAX_PAGE_SIZE ? DefaultConstant.MAX_PAGE_SIZE : pageSize; + pages.setCurrent(current); + pages.setSize(pageSize); + return pages; + } - /** - * Entity Base BO to Grpc Base BO - * @param entityBO EntityBO - * @param EntityBO extends BaseBO - * @return GrpcBase - */ - public static GrpcBase buildGrpcBaseByBO(T entityBO) { - if (Objects.isNull(entityBO)) { - return null; - } + /** + * Entity Base BO to Grpc Base BO + * + * @param entityBO EntityBO + * @param EntityBO extends BaseBO + * @return GrpcBase + */ + public static GrpcBase buildGrpcBaseByBO(T entityBO) { + if (Objects.isNull(entityBO)) { + return null; + } - GrpcBase.Builder builder = GrpcBase.newBuilder(); - Optional.ofNullable(entityBO.getId()) - .ifPresentOrElse(builder::setId, () -> builder.setId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getRemark()).ifPresent(builder::setRemark); - Optional.ofNullable(entityBO.getCreatorId()) - .ifPresentOrElse(builder::setCreatorId, () -> builder.setCreatorId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getCreatorName()).ifPresent(builder::setCreatorName); - Optional.ofNullable(entityBO.getCreateTime()) - .ifPresent(value -> builder.setCreateTime(LocalDateTimeUtil.milliSeconds(value))); - Optional.ofNullable(entityBO.getOperatorId()) - .ifPresentOrElse(builder::setOperatorId, () -> builder.setOperatorId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getOperatorName()).ifPresent(builder::setOperatorName); - Optional.ofNullable(entityBO.getOperateTime()) - .ifPresent(value -> builder.setOperateTime(LocalDateTimeUtil.milliSeconds(value))); - return builder.build(); - } + GrpcBase.Builder builder = GrpcBase.newBuilder(); + Optional.ofNullable(entityBO.getId()) + .ifPresentOrElse(builder::setId, () -> builder.setId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getRemark()).ifPresent(builder::setRemark); + Optional.ofNullable(entityBO.getCreatorId()) + .ifPresentOrElse(builder::setCreatorId, () -> builder.setCreatorId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getCreatorName()).ifPresent(builder::setCreatorName); + Optional.ofNullable(entityBO.getCreateTime()) + .ifPresent(value -> builder.setCreateTime(LocalDateTimeUtil.milliSeconds(value))); + Optional.ofNullable(entityBO.getOperatorId()) + .ifPresentOrElse(builder::setOperatorId, () -> builder.setOperatorId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getOperatorName()).ifPresent(builder::setOperatorName); + Optional.ofNullable(entityBO.getOperateTime()) + .ifPresent(value -> builder.setOperateTime(LocalDateTimeUtil.milliSeconds(value))); + return builder.build(); + } - /** - * Grpc Base to Base BO - * @param entityGrpc GrpcBase - * @param entityBO EntityBO - * @param EntityBO extends BaseBO - */ - public static void buildBaseBOByGrpcBase(GrpcBase entityGrpc, T entityBO) { - if (Objects.isNull(entityGrpc)) { - return; - } + /** + * Grpc Base to Base BO + * + * @param entityGrpc GrpcBase + * @param entityBO EntityBO + * @param EntityBO extends BaseBO + */ + public static void buildBaseBOByGrpcBase(GrpcBase entityGrpc, T entityBO) { + if (Objects.isNull(entityGrpc)) { + return; + } - LongOptional.ofNullable(entityGrpc.getId()).ifPresent(entityBO::setId); - StringOptional.ofNullable(entityGrpc.getRemark()).ifPresent(entityBO::setRemark); - LongOptional.ofNullable(entityGrpc.getCreatorId()).ifPresent(entityBO::setCreatorId); - StringOptional.ofNullable(entityGrpc.getCreatorName()).ifPresent(entityBO::setCreatorName); - LongOptional.ofNullable(entityGrpc.getCreateTime()) - .ifPresent(value -> entityBO.setCreateTime(LocalDateTimeUtil.dateTime(value))); - LongOptional.ofNullable(entityGrpc.getOperatorId()).ifPresent(entityBO::setOperatorId); - StringOptional.ofNullable(entityGrpc.getOperatorName()).ifPresent(entityBO::setOperatorName); - LongOptional.ofNullable(entityGrpc.getOperateTime()) - .ifPresent(value -> entityBO.setOperateTime(LocalDateTimeUtil.dateTime(value))); - } + LongOptional.ofNullable(entityGrpc.getId()).ifPresent(entityBO::setId); + StringOptional.ofNullable(entityGrpc.getRemark()).ifPresent(entityBO::setRemark); + LongOptional.ofNullable(entityGrpc.getCreatorId()).ifPresent(entityBO::setCreatorId); + StringOptional.ofNullable(entityGrpc.getCreatorName()).ifPresent(entityBO::setCreatorName); + LongOptional.ofNullable(entityGrpc.getCreateTime()) + .ifPresent(value -> entityBO.setCreateTime(LocalDateTimeUtil.dateTime(value))); + LongOptional.ofNullable(entityGrpc.getOperatorId()).ifPresent(entityBO::setOperatorId); + StringOptional.ofNullable(entityGrpc.getOperatorName()).ifPresent(entityBO::setOperatorName); + LongOptional.ofNullable(entityGrpc.getOperateTime()) + .ifPresent(value -> entityBO.setOperateTime(LocalDateTimeUtil.dateTime(value))); + } - /** - * Entity Base DTO to Grpc Base DTO - * @param entityDTO EntityDTO - * @param EntityDTO extends BaseDTO - * @return GrpcBase - */ - public static GrpcBase buildGrpcBaseByDTO(T entityDTO) { - if (Objects.isNull(entityDTO)) { - return null; - } + /** + * Entity Base DTO to Grpc Base DTO + * + * @param entityDTO EntityDTO + * @param EntityDTO extends BaseDTO + * @return GrpcBase + */ + public static GrpcBase buildGrpcBaseByDTO(T entityDTO) { + if (Objects.isNull(entityDTO)) { + return null; + } - GrpcBase.Builder builder = GrpcBase.newBuilder(); - Optional.ofNullable(entityDTO.getId()) - .ifPresentOrElse(builder::setId, () -> builder.setId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getRemark()).ifPresent(builder::setRemark); - Optional.ofNullable(entityDTO.getCreatorId()) - .ifPresentOrElse(builder::setCreatorId, () -> builder.setCreatorId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getCreatorName()).ifPresent(builder::setCreatorName); - Optional.ofNullable(entityDTO.getCreateTime()) - .ifPresent(value -> builder.setCreateTime(LocalDateTimeUtil.milliSeconds(value))); - Optional.ofNullable(entityDTO.getOperatorId()) - .ifPresentOrElse(builder::setOperatorId, () -> builder.setOperatorId(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getOperatorName()).ifPresent(builder::setOperatorName); - Optional.ofNullable(entityDTO.getOperateTime()) - .ifPresent(time -> builder.setOperateTime(LocalDateTimeUtil.milliSeconds(time))); - return builder.build(); - } + GrpcBase.Builder builder = GrpcBase.newBuilder(); + Optional.ofNullable(entityDTO.getId()) + .ifPresentOrElse(builder::setId, () -> builder.setId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getRemark()).ifPresent(builder::setRemark); + Optional.ofNullable(entityDTO.getCreatorId()) + .ifPresentOrElse(builder::setCreatorId, () -> builder.setCreatorId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getCreatorName()).ifPresent(builder::setCreatorName); + Optional.ofNullable(entityDTO.getCreateTime()) + .ifPresent(value -> builder.setCreateTime(LocalDateTimeUtil.milliSeconds(value))); + Optional.ofNullable(entityDTO.getOperatorId()) + .ifPresentOrElse(builder::setOperatorId, () -> builder.setOperatorId(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getOperatorName()).ifPresent(builder::setOperatorName); + Optional.ofNullable(entityDTO.getOperateTime()) + .ifPresent(time -> builder.setOperateTime(LocalDateTimeUtil.milliSeconds(time))); + return builder.build(); + } - /** - * Grpc Base to Base DTO - * @param entityGrpc GrpcBase - * @param entityDTO EntityDTO - * @param EntityDTO extends GrpcBase - */ - public static void buildBaseDTOByGrpcBase(GrpcBase entityGrpc, T entityDTO) { - if (Objects.isNull(entityGrpc)) { - return; - } + /** + * Grpc Base to Base DTO + * + * @param entityGrpc GrpcBase + * @param entityDTO EntityDTO + * @param EntityDTO extends GrpcBase + */ + public static void buildBaseDTOByGrpcBase(GrpcBase entityGrpc, T entityDTO) { + if (Objects.isNull(entityGrpc)) { + return; + } - LongOptional.ofNullable(entityGrpc.getId()).ifPresent(entityDTO::setId); - StringOptional.ofNullable(entityGrpc.getRemark()).ifPresent(entityDTO::setRemark); - LongOptional.ofNullable(entityGrpc.getCreatorId()).ifPresent(entityDTO::setCreatorId); - StringOptional.ofNullable(entityGrpc.getCreatorName()).ifPresent(entityDTO::setCreatorName); - LongOptional.ofNullable(entityGrpc.getCreateTime()) - .ifPresent(value -> entityDTO.setCreateTime(LocalDateTimeUtil.dateTime(value))); - LongOptional.ofNullable(entityGrpc.getOperatorId()).ifPresent(entityDTO::setOperatorId); - StringOptional.ofNullable(entityGrpc.getOperatorName()).ifPresent(entityDTO::setOperatorName); - LongOptional.ofNullable(entityGrpc.getOperateTime()) - .ifPresent(value -> entityDTO.setOperateTime(LocalDateTimeUtil.dateTime(value))); - } + LongOptional.ofNullable(entityGrpc.getId()).ifPresent(entityDTO::setId); + StringOptional.ofNullable(entityGrpc.getRemark()).ifPresent(entityDTO::setRemark); + LongOptional.ofNullable(entityGrpc.getCreatorId()).ifPresent(entityDTO::setCreatorId); + StringOptional.ofNullable(entityGrpc.getCreatorName()).ifPresent(entityDTO::setCreatorName); + LongOptional.ofNullable(entityGrpc.getCreateTime()) + .ifPresent(value -> entityDTO.setCreateTime(LocalDateTimeUtil.dateTime(value))); + LongOptional.ofNullable(entityGrpc.getOperatorId()).ifPresent(entityDTO::setOperatorId); + StringOptional.ofNullable(entityGrpc.getOperatorName()).ifPresent(entityDTO::setOperatorName); + LongOptional.ofNullable(entityGrpc.getOperateTime()) + .ifPresent(value -> entityDTO.setOperateTime(LocalDateTimeUtil.dateTime(value))); + } } diff --git a/dc3-common/dc3-common-auth/README.md b/dc3-common/dc3-common-auth/README.md index 2ccb67890..cb00c9850 100644 --- a/dc3-common/dc3-common-auth/README.md +++ b/dc3-common/dc3-common-auth/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-auth` is the shared authentication business module of the IoT DC3 platform. It contains all controllers, service implementations, gRPC servers, mappers, and DAL classes +`dc3-common-auth` is the shared authentication business module of the IoT DC3 platform. It contains all controllers, +service implementations, gRPC servers, mappers, and DAL classes that implement the authentication center's functionality. It is wired directly into `dc3-center-auth`. ## Module Information diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/DictionaryForAuthService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/DictionaryForAuthService.java index dd737388d..b5aeb76a1 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/DictionaryForAuthService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/DictionaryForAuthService.java @@ -30,10 +30,11 @@ import java.util.List; */ public interface DictionaryForAuthService { - /** - * Tenant - * @return Dictionary Array - */ - List tenantDictionary(); + /** + * Tenant + * + * @return Dictionary Array + */ + List tenantDictionary(); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/ResourceRegistrySyncService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/ResourceRegistrySyncService.java index e5cf3533f..19b9067ab 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/ResourceRegistrySyncService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/ResourceRegistrySyncService.java @@ -32,28 +32,31 @@ import io.github.pnoker.common.auth.entity.model.MenuDO; */ public interface ResourceRegistrySyncService { - /** - * Perform a three-way diff against the DB state and apply the required mutations - * inside a single transaction guarded by a Postgres advisory lock keyed on - * {@link ResourceRegistrySyncCommand#getServiceName()}. - * @param command the full API inventory for a single service - * @return counters describing what was changed - */ - ResourceRegistrySyncResult sync(ResourceRegistrySyncCommand command); + /** + * Perform a three-way diff against the DB state and apply the required mutations + * inside a single transaction guarded by a Postgres advisory lock keyed on + * {@link ResourceRegistrySyncCommand#getServiceName()}. + * + * @param command the full API inventory for a single service + * @return counters describing what was changed + */ + ResourceRegistrySyncResult sync(ResourceRegistrySyncCommand command); - /** - * Mirror a single menu row into dc3_resource as a MENU-type leaf. Called by - * MenuServiceImpl on save/update so the Resource tree always tracks menu state. - * Idempotent — updates the existing resource row if one already exists for the menu. - * @param menu the menu row that was just inserted or updated - */ - void syncMenuResource(MenuDO menu); + /** + * Mirror a single menu row into dc3_resource as a MENU-type leaf. Called by + * MenuServiceImpl on save/update so the Resource tree always tracks menu state. + * Idempotent — updates the existing resource row if one already exists for the menu. + * + * @param menu the menu row that was just inserted or updated + */ + void syncMenuResource(MenuDO menu); - /** - * Soft-delete the resource row mirroring the given menu, if any. No-op when no mirror - * exists. - * @param menuId the id of the menu being removed - */ - void removeMenuResource(Long menuId); + /** + * Soft-delete the resource row mirroring the given menu, if any. No-op when no mirror + * exists. + * + * @param menuId the id of the menu being removed + */ + void removeMenuResource(Long menuId); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/TokenService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/TokenService.java index 86dc4d9d3..e74330ebd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/TokenService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/TokenService.java @@ -28,29 +28,29 @@ import io.github.pnoker.common.auth.entity.bean.TokenValid; */ public interface TokenService { - /** - * @param loginName Name - * @param tenantCode TenantCode - * @return R of String - */ - String generateSalt(String loginName, String tenantCode); + /** + * @param loginName Name + * @param tenantCode TenantCode + * @return R of String + */ + String generateSalt(String loginName, String tenantCode); - /** - * @param loginName Name - * @param salt User Salt - * @param password User Password - * @param tenantCode TenantCode - * @return R of String - */ - String generateToken(String loginName, String salt, String password, String tenantCode); + /** + * @param loginName Name + * @param salt User Salt + * @param password User Password + * @param tenantCode TenantCode + * @return R of String + */ + String generateToken(String loginName, String salt, String password, String tenantCode); - /** - * @param loginName Name - * @param salt - * @param token Token - * @param tenantCode TenantCode - * @return TokenValid - */ - TokenValid checkValid(String loginName, String salt, String token, String tenantCode); + /** + * @param loginName Name + * @param salt + * @param token Token + * @param tenantCode TenantCode + * @return TokenValid + */ + TokenValid checkValid(String loginName, String salt, String token, String tenantCode); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/DictionaryForAuthServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/DictionaryForAuthServiceImpl.java index cf4e042b6..5747def88 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/DictionaryForAuthServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/DictionaryForAuthServiceImpl.java @@ -39,21 +39,21 @@ import java.util.List; @Service public class DictionaryForAuthServiceImpl implements DictionaryForAuthService { - @Resource - private TenantManager tenantManager; + @Resource + private TenantManager tenantManager; - @Override - public List tenantDictionary() { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantDO::getEnableFlag, EnableFlagEnum.ENABLE); - List entityDOList = tenantManager.list(wrapper); + @Override + public List tenantDictionary() { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantDO::getEnableFlag, EnableFlagEnum.ENABLE); + List entityDOList = tenantManager.list(wrapper); - return entityDOList.stream().map(entityDO -> { - DictionaryBO driverDictionary = new DictionaryBO(); - driverDictionary.setLabel(entityDO.getTenantName()); - driverDictionary.setValue(entityDO.getId().toString()); - return driverDictionary; - }).toList(); - } + return entityDOList.stream().map(entityDO -> { + DictionaryBO driverDictionary = new DictionaryBO(); + driverDictionary.setLabel(entityDO.getTenantName()); + driverDictionary.setValue(entityDO.getId().toString()); + return driverDictionary; + }).toList(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/ResourceRegistrySyncServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/ResourceRegistrySyncServiceImpl.java index 13085ca7a..903495648 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/ResourceRegistrySyncServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/ResourceRegistrySyncServiceImpl.java @@ -52,486 +52,482 @@ import java.util.*; @Service public class ResourceRegistrySyncServiceImpl implements ResourceRegistrySyncService { - /** - * dc3_resource.resource_code prefix for API leaf rows (one per dc3_api row). Other - * resource types should use their own prefixes (e.g. {@code menu:}). - */ - private static final String RESOURCE_CODE_PREFIX = "api:"; + /** + * dc3_resource.resource_code prefix for API leaf rows (one per dc3_api row). Other + * resource types should use their own prefixes (e.g. {@code menu:}). + */ + private static final String RESOURCE_CODE_PREFIX = "api:"; - /** - * Resource code prefix for the virtual service-grouping node — one per serviceName, - * parent = 0, entity_id = 0. Exists only to give the Resource tree a root per - * service. - */ - private static final String SERVICE_NODE_CODE_PREFIX = "api:service:"; + /** + * Resource code prefix for the virtual service-grouping node — one per serviceName, + * parent = 0, entity_id = 0. Exists only to give the Resource tree a root per + * service. + */ + private static final String SERVICE_NODE_CODE_PREFIX = "api:service:"; - /** - * Resource code prefix for the virtual apiGroup-grouping node — one per (serviceName, - * apiGroup) pair, parent = the corresponding service node, entity_id = 0. Clusters - * sibling endpoints under their owning controller. - */ - private static final String GROUP_NODE_CODE_PREFIX = "api:group:"; + /** + * Resource code prefix for the virtual apiGroup-grouping node — one per (serviceName, + * apiGroup) pair, parent = the corresponding service node, entity_id = 0. Clusters + * sibling endpoints under their owning controller. + */ + private static final String GROUP_NODE_CODE_PREFIX = "api:group:"; - /** - * Resource code prefix for MENU-type leaves. Each dc3_menu row owns one dc3_resource - * row; parent_resource_id mirrors the parent menu's resource. - */ - private static final String MENU_RESOURCE_CODE_PREFIX = "menu:"; + /** + * Resource code prefix for MENU-type leaves. Each dc3_menu row owns one dc3_resource + * row; parent_resource_id mirrors the parent menu's resource. + */ + private static final String MENU_RESOURCE_CODE_PREFIX = "menu:"; - @Resource - private ApiManager apiManager; + @Resource + private ApiManager apiManager; - @Resource - private ResourceManager resourceManager; + @Resource + private ResourceManager resourceManager; - @Resource - private ResourceRegistryLockMapper resourceRegistryLockMapper; + @Resource + private ResourceRegistryLockMapper resourceRegistryLockMapper; - private static String apiCodeOf(String serviceName, String method, String path) { - return serviceName + ":" + method.toUpperCase() + ":" + path; - } + private static String apiCodeOf(String serviceName, String method, String path) { + return serviceName + ":" + method.toUpperCase() + ":" + path; + } - private static ApiTypeFlagEnum methodToTypeFlag(String method) { - String m = Objects.requireNonNullElse(method, "").toUpperCase(); - return switch (m) { - case "POST" -> ApiTypeFlagEnum.POST; - case "DELETE" -> ApiTypeFlagEnum.DELETE; - case "PUT" -> ApiTypeFlagEnum.PUT; - case "GET" -> ApiTypeFlagEnum.GET; - default -> throw new IllegalArgumentException("Unsupported HTTP method: " + method); - }; - } + private static ApiTypeFlagEnum methodToTypeFlag(String method) { + String m = Objects.requireNonNullElse(method, "").toUpperCase(); + return switch (m) { + case "POST" -> ApiTypeFlagEnum.POST; + case "DELETE" -> ApiTypeFlagEnum.DELETE; + case "PUT" -> ApiTypeFlagEnum.PUT; + case "GET" -> ApiTypeFlagEnum.GET; + default -> throw new IllegalArgumentException("Unsupported HTTP method: " + method); + }; + } - private static ResourceScopeFlagEnum methodToScopeFlag(Byte apiTypeFlag) { - ApiTypeFlagEnum type = ApiTypeFlagEnum.ofIndex(apiTypeFlag); - if (type == null) { - return ResourceScopeFlagEnum.LIST; - } - return switch (type) { - case POST -> ResourceScopeFlagEnum.ADD; - case DELETE -> ResourceScopeFlagEnum.DELETE; - case PUT -> ResourceScopeFlagEnum.UPDATE; - case GET -> ResourceScopeFlagEnum.LIST; - }; - } + private static ResourceScopeFlagEnum methodToScopeFlag(Byte apiTypeFlag) { + ApiTypeFlagEnum type = ApiTypeFlagEnum.ofIndex(apiTypeFlag); + if (type == null) { + return ResourceScopeFlagEnum.LIST; + } + return switch (type) { + case POST -> ResourceScopeFlagEnum.ADD; + case DELETE -> ResourceScopeFlagEnum.DELETE; + case PUT -> ResourceScopeFlagEnum.UPDATE; + case GET -> ResourceScopeFlagEnum.LIST; + }; + } - @Override - @Transactional(rollbackFor = Exception.class) - public ResourceRegistrySyncResult sync(ResourceRegistrySyncCommand command) { - if (Objects.isNull(command) || StringUtils.isBlank(command.getServiceName())) { - throw new IllegalArgumentException("serviceName is required"); - } - String serviceName = command.getServiceName(); - List scanned = Objects.requireNonNullElse(command.getApis(), List.of()); + @Override + @Transactional(rollbackFor = Exception.class) + public ResourceRegistrySyncResult sync(ResourceRegistrySyncCommand command) { + if (Objects.isNull(command) || StringUtils.isBlank(command.getServiceName())) { + throw new IllegalArgumentException("serviceName is required"); + } + String serviceName = command.getServiceName(); + List scanned = Objects.requireNonNullElse(command.getApis(), List.of()); - resourceRegistryLockMapper.advisoryLock(serviceName); + resourceRegistryLockMapper.advisoryLock(serviceName); - Map existingByCode = loadExisting(serviceName); - Map scannedByCode = indexScanned(scanned, serviceName); + Map existingByCode = loadExisting(serviceName); + Map scannedByCode = indexScanned(scanned, serviceName); - // Ensure the service + apiGroup virtual grouping nodes exist before writing - // leaves, - // so the leaf rows can set parent_resource_id to the right ancestor. - Set targetGroups = new LinkedHashSet<>(); - for (ResourceRegistryScannedApi spec : scannedByCode.values()) { - targetGroups.add(Objects.requireNonNullElse(spec.getApiGroup(), "")); - } - Long serviceNodeId = null; - Map groupNodeIds = Map.of(); - if (!targetGroups.isEmpty()) { - serviceNodeId = ensureServiceNode(serviceName); - groupNodeIds = ensureGroupNodes(serviceName, serviceNodeId, targetGroups); - } + // Ensure the service + apiGroup virtual grouping nodes exist before writing + // leaves, + // so the leaf rows can set parent_resource_id to the right ancestor. + Set targetGroups = new LinkedHashSet<>(); + for (ResourceRegistryScannedApi spec : scannedByCode.values()) { + targetGroups.add(Objects.requireNonNullElse(spec.getApiGroup(), "")); + } + Long serviceNodeId = null; + Map groupNodeIds = Map.of(); + if (!targetGroups.isEmpty()) { + serviceNodeId = ensureServiceNode(serviceName); + groupNodeIds = ensureGroupNodes(serviceName, serviceNodeId, targetGroups); + } - int inserted = 0; - int updated = 0; - int deletedCount = 0; - int unchanged = 0; + int inserted = 0; + int updated = 0; + int deletedCount = 0; + int unchanged = 0; - List apisToInsert = new ArrayList<>(); - List resourcesToInsert = new ArrayList<>(); - List apisToUpdate = new ArrayList<>(); - List resourcesToUpdate = new ArrayList<>(); - List apiIdsToDelete = new ArrayList<>(); + List apisToInsert = new ArrayList<>(); + List resourcesToInsert = new ArrayList<>(); + List apisToUpdate = new ArrayList<>(); + List resourcesToUpdate = new ArrayList<>(); + List apiIdsToDelete = new ArrayList<>(); - for (Map.Entry entry : scannedByCode.entrySet()) { - String apiCode = entry.getKey(); - ResourceRegistryScannedApi spec = entry.getValue(); - ApiDO existing = existingByCode.remove(apiCode); - if (Objects.isNull(existing)) { - ApiDO newApi = buildApiDO(spec, apiCode, serviceName); - apisToInsert.add(newApi); - continue; - } - if (needsUpdate(existing, spec, apiCode, serviceName)) { - applyApiUpdates(existing, spec, apiCode, serviceName); - apisToUpdate.add(existing); - } - else { - unchanged++; - } - } + for (Map.Entry entry : scannedByCode.entrySet()) { + String apiCode = entry.getKey(); + ResourceRegistryScannedApi spec = entry.getValue(); + ApiDO existing = existingByCode.remove(apiCode); + if (Objects.isNull(existing)) { + ApiDO newApi = buildApiDO(spec, apiCode, serviceName); + apisToInsert.add(newApi); + continue; + } + if (needsUpdate(existing, spec, apiCode, serviceName)) { + applyApiUpdates(existing, spec, apiCode, serviceName); + apisToUpdate.add(existing); + } else { + unchanged++; + } + } - if (!apisToInsert.isEmpty()) { - apiManager.saveBatch(apisToInsert); - for (ApiDO api : apisToInsert) { - Long groupNodeId = groupNodeIds.get(Objects.requireNonNullElse(api.getApiGroup(), "")); - resourcesToInsert.add(buildLeafResourceDO(api, groupNodeId)); - } - resourceManager.saveBatch(resourcesToInsert); - inserted = apisToInsert.size(); - } + if (!apisToInsert.isEmpty()) { + apiManager.saveBatch(apisToInsert); + for (ApiDO api : apisToInsert) { + Long groupNodeId = groupNodeIds.get(Objects.requireNonNullElse(api.getApiGroup(), "")); + resourcesToInsert.add(buildLeafResourceDO(api, groupNodeId)); + } + resourceManager.saveBatch(resourcesToInsert); + inserted = apisToInsert.size(); + } - if (!apisToUpdate.isEmpty()) { - apiManager.updateBatchById(apisToUpdate); - Map resourceByEntityId = loadResourcesByEntityIds( - apisToUpdate.stream().map(ApiDO::getId).toList()); - List resourcesToBackfill = new ArrayList<>(); - for (ApiDO api : apisToUpdate) { - Long groupNodeId = groupNodeIds.get(Objects.requireNonNullElse(api.getApiGroup(), "")); - ResourceDO resourceDO = resourceByEntityId.get(api.getId()); - if (Objects.isNull(resourceDO)) { - resourcesToBackfill.add(buildLeafResourceDO(api, groupNodeId)); - } - else { - applyLeafResourceUpdates(resourceDO, api, groupNodeId); - resourcesToUpdate.add(resourceDO); - } - } - if (!resourcesToUpdate.isEmpty()) { - resourceManager.updateBatchById(resourcesToUpdate); - } - if (!resourcesToBackfill.isEmpty()) { - resourceManager.saveBatch(resourcesToBackfill); - } - updated = apisToUpdate.size(); - } + if (!apisToUpdate.isEmpty()) { + apiManager.updateBatchById(apisToUpdate); + Map resourceByEntityId = loadResourcesByEntityIds( + apisToUpdate.stream().map(ApiDO::getId).toList()); + List resourcesToBackfill = new ArrayList<>(); + for (ApiDO api : apisToUpdate) { + Long groupNodeId = groupNodeIds.get(Objects.requireNonNullElse(api.getApiGroup(), "")); + ResourceDO resourceDO = resourceByEntityId.get(api.getId()); + if (Objects.isNull(resourceDO)) { + resourcesToBackfill.add(buildLeafResourceDO(api, groupNodeId)); + } else { + applyLeafResourceUpdates(resourceDO, api, groupNodeId); + resourcesToUpdate.add(resourceDO); + } + } + if (!resourcesToUpdate.isEmpty()) { + resourceManager.updateBatchById(resourcesToUpdate); + } + if (!resourcesToBackfill.isEmpty()) { + resourceManager.saveBatch(resourcesToBackfill); + } + updated = apisToUpdate.size(); + } - if (command.isDeleteMissing() && !existingByCode.isEmpty()) { - for (ApiDO orphan : existingByCode.values()) { - apiIdsToDelete.add(orphan.getId()); - } - apiManager.removeByIds(apiIdsToDelete); - List resourceIds = resourceManager - .list(Wrappers.lambdaQuery() - .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.API.getIndex()) - .in(ResourceDO::getEntityId, apiIdsToDelete)) - .stream() - .map(ResourceDO::getId) - .toList(); - if (!resourceIds.isEmpty()) { - resourceManager.removeByIds(resourceIds); - } - deletedCount = apiIdsToDelete.size(); - } + if (command.isDeleteMissing() && !existingByCode.isEmpty()) { + for (ApiDO orphan : existingByCode.values()) { + apiIdsToDelete.add(orphan.getId()); + } + apiManager.removeByIds(apiIdsToDelete); + List resourceIds = resourceManager + .list(Wrappers.lambdaQuery() + .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.API.getIndex()) + .in(ResourceDO::getEntityId, apiIdsToDelete)) + .stream() + .map(ResourceDO::getId) + .toList(); + if (!resourceIds.isEmpty()) { + resourceManager.removeByIds(resourceIds); + } + deletedCount = apiIdsToDelete.size(); + } - // Sweep orphaned apiGroup / service virtual nodes that no longer cover any leaf. - int removedGroupNodes = cleanupOrphanGroupingNodes(serviceName); + // Sweep orphaned apiGroup / service virtual nodes that no longer cover any leaf. + int removedGroupNodes = cleanupOrphanGroupingNodes(serviceName); - log.info( - "Resource registry sync [{}]: inserted={}, updated={}, deleted={}, unchanged={}, prunedGroupingNodes={}", - serviceName, inserted, updated, deletedCount, unchanged, removedGroupNodes); + log.info( + "Resource registry sync [{}]: inserted={}, updated={}, deleted={}, unchanged={}, prunedGroupingNodes={}", + serviceName, inserted, updated, deletedCount, unchanged, removedGroupNodes); - return ResourceRegistrySyncResult.builder() - .inserted(inserted) - .updated(updated) - .deleted(deletedCount) - .unchanged(unchanged) - .build(); - } + return ResourceRegistrySyncResult.builder() + .inserted(inserted) + .updated(updated) + .deleted(deletedCount) + .unchanged(unchanged) + .build(); + } - private Map loadExisting(String serviceName) { - List existing = apiManager.list(Wrappers.lambdaQuery().eq(ApiDO::getServiceName, serviceName)); - Map map = new HashMap<>(existing.size()); - for (ApiDO api : existing) { - map.put(api.getApiCode(), api); - } - return map; - } + private Map loadExisting(String serviceName) { + List existing = apiManager.list(Wrappers.lambdaQuery().eq(ApiDO::getServiceName, serviceName)); + Map map = new HashMap<>(existing.size()); + for (ApiDO api : existing) { + map.put(api.getApiCode(), api); + } + return map; + } - private Map loadResourcesByEntityIds(List entityIds) { - if (entityIds.isEmpty()) { - return Map.of(); - } - // Exclude grouping nodes (entity_id=0) so the caller only sees real leaves. - List rows = resourceManager.list(Wrappers.lambdaQuery() - .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.API.getIndex()) - .in(ResourceDO::getEntityId, entityIds) - .ne(ResourceDO::getEntityId, 0L)); - Map map = new HashMap<>(rows.size()); - for (ResourceDO row : rows) { - map.put(row.getEntityId(), row); - } - return map; - } + private Map loadResourcesByEntityIds(List entityIds) { + if (entityIds.isEmpty()) { + return Map.of(); + } + // Exclude grouping nodes (entity_id=0) so the caller only sees real leaves. + List rows = resourceManager.list(Wrappers.lambdaQuery() + .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.API.getIndex()) + .in(ResourceDO::getEntityId, entityIds) + .ne(ResourceDO::getEntityId, 0L)); + Map map = new HashMap<>(rows.size()); + for (ResourceDO row : rows) { + map.put(row.getEntityId(), row); + } + return map; + } - private Map indexScanned(List scanned, - String serviceName) { - Map map = new HashMap<>(scanned.size()); - for (ResourceRegistryScannedApi spec : scanned) { - String code = apiCodeOf(serviceName, spec.getMethod(), spec.getPath()); - map.put(code, spec); - } - return map; - } + private Map indexScanned(List scanned, + String serviceName) { + Map map = new HashMap<>(scanned.size()); + for (ResourceRegistryScannedApi spec : scanned) { + String code = apiCodeOf(serviceName, spec.getMethod(), spec.getPath()); + map.put(code, spec); + } + return map; + } - private ApiDO buildApiDO(ResourceRegistryScannedApi spec, String apiCode, String serviceName) { - ApiDO api = new ApiDO(); - api.setServiceName(serviceName); - api.setApiTypeFlag(methodToTypeFlag(spec.getMethod()).getIndex()); - api.setApiName(spec.getApiName()); - api.setApiCode(apiCode); - api.setApiGroup(Objects.requireNonNullElse(spec.getApiGroup(), "")); - api.setApiExt(buildApiExt(spec)); - api.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); - api.setRemark(Objects.requireNonNullElse(spec.getRemark(), "")); - return api; - } + private ApiDO buildApiDO(ResourceRegistryScannedApi spec, String apiCode, String serviceName) { + ApiDO api = new ApiDO(); + api.setServiceName(serviceName); + api.setApiTypeFlag(methodToTypeFlag(spec.getMethod()).getIndex()); + api.setApiName(spec.getApiName()); + api.setApiCode(apiCode); + api.setApiGroup(Objects.requireNonNullElse(spec.getApiGroup(), "")); + api.setApiExt(buildApiExt(spec)); + api.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); + api.setRemark(Objects.requireNonNullElse(spec.getRemark(), "")); + return api; + } - private ResourceDO buildLeafResourceDO(ApiDO api, Long groupNodeId) { - ResourceDO resource = new ResourceDO(); - resource.setParentResourceId(Objects.requireNonNullElse(groupNodeId, 0L)); - resource.setResourceName(api.getApiName()); - resource.setResourceCode(RESOURCE_CODE_PREFIX + api.getApiCode()); - resource.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); - resource.setResourceScopeFlag(methodToScopeFlag(api.getApiTypeFlag()).getIndex()); - resource.setEntityId(api.getId()); - resource.setResourceExt(new JsonExt()); - resource.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); - resource.setRemark(Objects.requireNonNullElse(api.getRemark(), "")); - return resource; - } + private ResourceDO buildLeafResourceDO(ApiDO api, Long groupNodeId) { + ResourceDO resource = new ResourceDO(); + resource.setParentResourceId(Objects.requireNonNullElse(groupNodeId, 0L)); + resource.setResourceName(api.getApiName()); + resource.setResourceCode(RESOURCE_CODE_PREFIX + api.getApiCode()); + resource.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); + resource.setResourceScopeFlag(methodToScopeFlag(api.getApiTypeFlag()).getIndex()); + resource.setEntityId(api.getId()); + resource.setResourceExt(new JsonExt()); + resource.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); + resource.setRemark(Objects.requireNonNullElse(api.getRemark(), "")); + return resource; + } - private boolean needsUpdate(ApiDO existing, ResourceRegistryScannedApi spec, String apiCode, String serviceName) { - byte expectedType = methodToTypeFlag(spec.getMethod()).getIndex(); - if (existing.getApiTypeFlag() == null || existing.getApiTypeFlag() != expectedType) { - return true; - } - if (!Objects.equals(existing.getApiName(), spec.getApiName())) { - return true; - } - if (!Objects.equals(existing.getServiceName(), serviceName)) { - return true; - } - if (!Objects.equals(existing.getApiCode(), apiCode)) { - return true; - } - String expectedGroup = Objects.requireNonNullElse(spec.getApiGroup(), ""); - if (!Objects.equals(Objects.requireNonNullElse(existing.getApiGroup(), ""), expectedGroup)) { - return true; - } - ApiExt.Content expectedContent = buildContent(spec); - ApiExt.Content currentContent = parseContent(existing.getApiExt()); - if (!equalsContent(currentContent, expectedContent)) { - return true; - } - String expectedRemark = Objects.requireNonNullElse(spec.getRemark(), ""); - return !Objects.equals(Objects.requireNonNullElse(existing.getRemark(), ""), expectedRemark); - } + private boolean needsUpdate(ApiDO existing, ResourceRegistryScannedApi spec, String apiCode, String serviceName) { + byte expectedType = methodToTypeFlag(spec.getMethod()).getIndex(); + if (existing.getApiTypeFlag() == null || existing.getApiTypeFlag() != expectedType) { + return true; + } + if (!Objects.equals(existing.getApiName(), spec.getApiName())) { + return true; + } + if (!Objects.equals(existing.getServiceName(), serviceName)) { + return true; + } + if (!Objects.equals(existing.getApiCode(), apiCode)) { + return true; + } + String expectedGroup = Objects.requireNonNullElse(spec.getApiGroup(), ""); + if (!Objects.equals(Objects.requireNonNullElse(existing.getApiGroup(), ""), expectedGroup)) { + return true; + } + ApiExt.Content expectedContent = buildContent(spec); + ApiExt.Content currentContent = parseContent(existing.getApiExt()); + if (!equalsContent(currentContent, expectedContent)) { + return true; + } + String expectedRemark = Objects.requireNonNullElse(spec.getRemark(), ""); + return !Objects.equals(Objects.requireNonNullElse(existing.getRemark(), ""), expectedRemark); + } - private void applyApiUpdates(ApiDO existing, ResourceRegistryScannedApi spec, String apiCode, String serviceName) { - existing.setServiceName(serviceName); - existing.setApiCode(apiCode); - existing.setApiGroup(Objects.requireNonNullElse(spec.getApiGroup(), "")); - existing.setApiTypeFlag(methodToTypeFlag(spec.getMethod()).getIndex()); - existing.setApiName(spec.getApiName()); - existing.setApiExt(buildApiExt(spec)); - existing.setRemark(Objects.requireNonNullElse(spec.getRemark(), "")); - existing.setOperateTime(null); - } + private void applyApiUpdates(ApiDO existing, ResourceRegistryScannedApi spec, String apiCode, String serviceName) { + existing.setServiceName(serviceName); + existing.setApiCode(apiCode); + existing.setApiGroup(Objects.requireNonNullElse(spec.getApiGroup(), "")); + existing.setApiTypeFlag(methodToTypeFlag(spec.getMethod()).getIndex()); + existing.setApiName(spec.getApiName()); + existing.setApiExt(buildApiExt(spec)); + existing.setRemark(Objects.requireNonNullElse(spec.getRemark(), "")); + existing.setOperateTime(null); + } - private void applyLeafResourceUpdates(ResourceDO resource, ApiDO api, Long groupNodeId) { - resource.setParentResourceId(Objects.requireNonNullElse(groupNodeId, 0L)); - resource.setResourceName(api.getApiName()); - resource.setResourceCode(RESOURCE_CODE_PREFIX + api.getApiCode()); - resource.setResourceScopeFlag(methodToScopeFlag(api.getApiTypeFlag()).getIndex()); - resource.setRemark(Objects.requireNonNullElse(api.getRemark(), "")); - resource.setOperateTime(null); - } + private void applyLeafResourceUpdates(ResourceDO resource, ApiDO api, Long groupNodeId) { + resource.setParentResourceId(Objects.requireNonNullElse(groupNodeId, 0L)); + resource.setResourceName(api.getApiName()); + resource.setResourceCode(RESOURCE_CODE_PREFIX + api.getApiCode()); + resource.setResourceScopeFlag(methodToScopeFlag(api.getApiTypeFlag()).getIndex()); + resource.setRemark(Objects.requireNonNullElse(api.getRemark(), "")); + resource.setOperateTime(null); + } - private Long ensureServiceNode(String serviceName) { - String code = SERVICE_NODE_CODE_PREFIX + serviceName; - ResourceDO existing = findByResourceCode(code); - if (existing != null) { - return existing.getId(); - } - ResourceDO node = new ResourceDO(); - node.setParentResourceId(0L); - node.setResourceName(serviceName); - node.setResourceCode(code); - node.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); - node.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); - node.setEntityId(0L); - node.setResourceExt(new JsonExt()); - node.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); - node.setRemark("Service grouping node (auto-registered)"); - resourceManager.save(node); - return node.getId(); - } + private Long ensureServiceNode(String serviceName) { + String code = SERVICE_NODE_CODE_PREFIX + serviceName; + ResourceDO existing = findByResourceCode(code); + if (existing != null) { + return existing.getId(); + } + ResourceDO node = new ResourceDO(); + node.setParentResourceId(0L); + node.setResourceName(serviceName); + node.setResourceCode(code); + node.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); + node.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); + node.setEntityId(0L); + node.setResourceExt(new JsonExt()); + node.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); + node.setRemark("Service grouping node (auto-registered)"); + resourceManager.save(node); + return node.getId(); + } - private Map ensureGroupNodes(String serviceName, Long serviceNodeId, Set targetGroups) { - Map result = new HashMap<>(targetGroups.size()); - for (String group : targetGroups) { - String code = GROUP_NODE_CODE_PREFIX + serviceName + ":" + group; - ResourceDO existing = findByResourceCode(code); - if (existing == null) { - ResourceDO node = new ResourceDO(); - node.setParentResourceId(serviceNodeId); - node.setResourceName(group.isEmpty() ? "(ungrouped)" : group); - node.setResourceCode(code); - node.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); - node.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); - node.setEntityId(0L); - node.setResourceExt(new JsonExt()); - node.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); - node.setRemark("API grouping node (auto-registered)"); - resourceManager.save(node); - result.put(group, node.getId()); - } - else { - if (!Objects.equals(existing.getParentResourceId(), serviceNodeId)) { - existing.setParentResourceId(serviceNodeId); - existing.setOperateTime(null); - resourceManager.updateById(existing); - } - result.put(group, existing.getId()); - } - } - return result; - } + private Map ensureGroupNodes(String serviceName, Long serviceNodeId, Set targetGroups) { + Map result = new HashMap<>(targetGroups.size()); + for (String group : targetGroups) { + String code = GROUP_NODE_CODE_PREFIX + serviceName + ":" + group; + ResourceDO existing = findByResourceCode(code); + if (existing == null) { + ResourceDO node = new ResourceDO(); + node.setParentResourceId(serviceNodeId); + node.setResourceName(group.isEmpty() ? "(ungrouped)" : group); + node.setResourceCode(code); + node.setResourceTypeFlag(ResourceTypeFlagEnum.API.getIndex()); + node.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); + node.setEntityId(0L); + node.setResourceExt(new JsonExt()); + node.setEnableFlag(EnableFlagEnum.ENABLE.getIndex()); + node.setRemark("API grouping node (auto-registered)"); + resourceManager.save(node); + result.put(group, node.getId()); + } else { + if (!Objects.equals(existing.getParentResourceId(), serviceNodeId)) { + existing.setParentResourceId(serviceNodeId); + existing.setOperateTime(null); + resourceManager.updateById(existing); + } + result.put(group, existing.getId()); + } + } + return result; + } - private ResourceDO findByResourceCode(String code) { - return resourceManager - .getOne(Wrappers.lambdaQuery().eq(ResourceDO::getResourceCode, code).last("LIMIT 1")); - } + private ResourceDO findByResourceCode(String code) { + return resourceManager + .getOne(Wrappers.lambdaQuery().eq(ResourceDO::getResourceCode, code).last("LIMIT 1")); + } - /** - * Soft-delete apiGroup nodes that no longer have any leaf, then the service node - * itself if it ends up with no remaining group children. Bounded to the given - * serviceName so concurrent sync of sibling services is unaffected. - */ - private int cleanupOrphanGroupingNodes(String serviceName) { - int removed = 0; - List groupNodes = resourceManager.list(Wrappers.lambdaQuery() - .likeRight(ResourceDO::getResourceCode, GROUP_NODE_CODE_PREFIX + serviceName + ":") - .eq(ResourceDO::getEntityId, 0L)); - List idsToDrop = new ArrayList<>(); - for (ResourceDO node : groupNodes) { - long children = resourceManager - .count(Wrappers.lambdaQuery().eq(ResourceDO::getParentResourceId, node.getId())); - if (children == 0) { - idsToDrop.add(node.getId()); - } - } - if (!idsToDrop.isEmpty()) { - resourceManager.removeByIds(idsToDrop); - removed += idsToDrop.size(); - } - ResourceDO serviceNode = findByResourceCode(SERVICE_NODE_CODE_PREFIX + serviceName); - if (serviceNode != null) { - long children = resourceManager - .count(Wrappers.lambdaQuery().eq(ResourceDO::getParentResourceId, serviceNode.getId())); - if (children == 0) { - resourceManager.removeById(serviceNode.getId()); - removed++; - } - } - return removed; - } + /** + * Soft-delete apiGroup nodes that no longer have any leaf, then the service node + * itself if it ends up with no remaining group children. Bounded to the given + * serviceName so concurrent sync of sibling services is unaffected. + */ + private int cleanupOrphanGroupingNodes(String serviceName) { + int removed = 0; + List groupNodes = resourceManager.list(Wrappers.lambdaQuery() + .likeRight(ResourceDO::getResourceCode, GROUP_NODE_CODE_PREFIX + serviceName + ":") + .eq(ResourceDO::getEntityId, 0L)); + List idsToDrop = new ArrayList<>(); + for (ResourceDO node : groupNodes) { + long children = resourceManager + .count(Wrappers.lambdaQuery().eq(ResourceDO::getParentResourceId, node.getId())); + if (children == 0) { + idsToDrop.add(node.getId()); + } + } + if (!idsToDrop.isEmpty()) { + resourceManager.removeByIds(idsToDrop); + removed += idsToDrop.size(); + } + ResourceDO serviceNode = findByResourceCode(SERVICE_NODE_CODE_PREFIX + serviceName); + if (serviceNode != null) { + long children = resourceManager + .count(Wrappers.lambdaQuery().eq(ResourceDO::getParentResourceId, serviceNode.getId())); + if (children == 0) { + resourceManager.removeById(serviceNode.getId()); + removed++; + } + } + return removed; + } - private JsonExt buildApiExt(ResourceRegistryScannedApi spec) { - JsonExt ext = new JsonExt(); - ext.setVersion(1); - ext.setContent(JsonUtil.toJsonString(buildContent(spec))); - return ext; - } + private JsonExt buildApiExt(ResourceRegistryScannedApi spec) { + JsonExt ext = new JsonExt(); + ext.setVersion(1); + ext.setContent(JsonUtil.toJsonString(buildContent(spec))); + return ext; + } - private ApiExt.Content buildContent(ResourceRegistryScannedApi spec) { - ApiExt.Content content = new ApiExt.Content(); - content.setTitle(spec.getTitle()); - content.setUrl(spec.getPath()); - content.setRemark(spec.getRemark()); - return content; - } + private ApiExt.Content buildContent(ResourceRegistryScannedApi spec) { + ApiExt.Content content = new ApiExt.Content(); + content.setTitle(spec.getTitle()); + content.setUrl(spec.getPath()); + content.setRemark(spec.getRemark()); + return content; + } - private ApiExt.Content parseContent(JsonExt ext) { - if (Objects.isNull(ext) || StringUtils.isBlank(ext.getContent())) { - return null; - } - return JsonUtil.parseObject(ext.getContent(), ApiExt.Content.class); - } + private ApiExt.Content parseContent(JsonExt ext) { + if (Objects.isNull(ext) || StringUtils.isBlank(ext.getContent())) { + return null; + } + return JsonUtil.parseObject(ext.getContent(), ApiExt.Content.class); + } - private boolean equalsContent(ApiExt.Content a, ApiExt.Content b) { - if (a == null || b == null) { - return a == null && b == null; - } - return Objects.equals(a.getTitle(), b.getTitle()) && Objects.equals(a.getUrl(), b.getUrl()) - && Objects.equals(a.getRemark(), b.getRemark()); - } + private boolean equalsContent(ApiExt.Content a, ApiExt.Content b) { + if (a == null || b == null) { + return a == null && b == null; + } + return Objects.equals(a.getTitle(), b.getTitle()) && Objects.equals(a.getUrl(), b.getUrl()) + && Objects.equals(a.getRemark(), b.getRemark()); + } - @Override - @Transactional(rollbackFor = Exception.class) - public void syncMenuResource(MenuDO menu) { - if (menu == null || menu.getId() == null) { - return; - } - String code = MENU_RESOURCE_CODE_PREFIX + Objects.requireNonNullElse(menu.getMenuCode(), ""); - // Prefer lookup by entity_id so a menu_code rename still resolves the mirror. - ResourceDO existing = resourceManager.getOne(Wrappers.lambdaQuery() - .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) - .eq(ResourceDO::getEntityId, menu.getId()) - .last("LIMIT 1")); - Long parentResourceId = resolveMenuParentResourceId(menu.getParentMenuId()); + @Override + @Transactional(rollbackFor = Exception.class) + public void syncMenuResource(MenuDO menu) { + if (menu == null || menu.getId() == null) { + return; + } + String code = MENU_RESOURCE_CODE_PREFIX + Objects.requireNonNullElse(menu.getMenuCode(), ""); + // Prefer lookup by entity_id so a menu_code rename still resolves the mirror. + ResourceDO existing = resourceManager.getOne(Wrappers.lambdaQuery() + .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) + .eq(ResourceDO::getEntityId, menu.getId()) + .last("LIMIT 1")); + Long parentResourceId = resolveMenuParentResourceId(menu.getParentMenuId()); - if (existing == null) { - ResourceDO mirror = new ResourceDO(); - mirror.setParentResourceId(parentResourceId); - mirror.setResourceName(Objects.requireNonNullElse(menu.getMenuName(), "")); - mirror.setResourceCode(code); - mirror.setResourceTypeFlag(ResourceTypeFlagEnum.MENU.getIndex()); - mirror.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); - mirror.setEntityId(menu.getId()); - mirror.setResourceExt(new JsonExt()); - mirror.setEnableFlag(Objects.requireNonNullElse(menu.getEnableFlag(), EnableFlagEnum.ENABLE.getIndex())); - mirror.setRemark(Objects.requireNonNullElse(menu.getRemark(), "")); - resourceManager.save(mirror); - log.info("Menu resource mirror inserted: menuId={}, code={}", menu.getId(), code); - } - else { - existing.setParentResourceId(parentResourceId); - existing.setResourceName(Objects.requireNonNullElse(menu.getMenuName(), "")); - existing.setResourceCode(code); - existing.setEnableFlag(Objects.requireNonNullElse(menu.getEnableFlag(), EnableFlagEnum.ENABLE.getIndex())); - existing.setRemark(Objects.requireNonNullElse(menu.getRemark(), "")); - existing.setOperateTime(null); - resourceManager.updateById(existing); - } - } + if (existing == null) { + ResourceDO mirror = new ResourceDO(); + mirror.setParentResourceId(parentResourceId); + mirror.setResourceName(Objects.requireNonNullElse(menu.getMenuName(), "")); + mirror.setResourceCode(code); + mirror.setResourceTypeFlag(ResourceTypeFlagEnum.MENU.getIndex()); + mirror.setResourceScopeFlag(ResourceScopeFlagEnum.LIST.getIndex()); + mirror.setEntityId(menu.getId()); + mirror.setResourceExt(new JsonExt()); + mirror.setEnableFlag(Objects.requireNonNullElse(menu.getEnableFlag(), EnableFlagEnum.ENABLE.getIndex())); + mirror.setRemark(Objects.requireNonNullElse(menu.getRemark(), "")); + resourceManager.save(mirror); + log.info("Menu resource mirror inserted: menuId={}, code={}", menu.getId(), code); + } else { + existing.setParentResourceId(parentResourceId); + existing.setResourceName(Objects.requireNonNullElse(menu.getMenuName(), "")); + existing.setResourceCode(code); + existing.setEnableFlag(Objects.requireNonNullElse(menu.getEnableFlag(), EnableFlagEnum.ENABLE.getIndex())); + existing.setRemark(Objects.requireNonNullElse(menu.getRemark(), "")); + existing.setOperateTime(null); + resourceManager.updateById(existing); + } + } - @Override - @Transactional(rollbackFor = Exception.class) - public void removeMenuResource(Long menuId) { - if (menuId == null) { - return; - } - ResourceDO existing = resourceManager.getOne(Wrappers.lambdaQuery() - .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) - .eq(ResourceDO::getEntityId, menuId) - .last("LIMIT 1")); - if (existing != null) { - resourceManager.removeById(existing.getId()); - } - } + @Override + @Transactional(rollbackFor = Exception.class) + public void removeMenuResource(Long menuId) { + if (menuId == null) { + return; + } + ResourceDO existing = resourceManager.getOne(Wrappers.lambdaQuery() + .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) + .eq(ResourceDO::getEntityId, menuId) + .last("LIMIT 1")); + if (existing != null) { + resourceManager.removeById(existing.getId()); + } + } - private Long resolveMenuParentResourceId(Long parentMenuId) { - if (parentMenuId == null || parentMenuId == 0L) { - return 0L; - } - ResourceDO parent = resourceManager.getOne(Wrappers.lambdaQuery() - .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) - .eq(ResourceDO::getEntityId, parentMenuId) - .last("LIMIT 1")); - return parent == null ? 0L : parent.getId(); - } + private Long resolveMenuParentResourceId(Long parentMenuId) { + if (parentMenuId == null || parentMenuId == 0L) { + return 0L; + } + ResourceDO parent = resourceManager.getOne(Wrappers.lambdaQuery() + .eq(ResourceDO::getResourceTypeFlag, ResourceTypeFlagEnum.MENU.getIndex()) + .eq(ResourceDO::getEntityId, parentMenuId) + .last("LIMIT 1")); + return parent == null ? 0L : parent.getId(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/TokenServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/TokenServiceImpl.java index 638a0d36c..a96f6d9b6 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/TokenServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/biz/impl/TokenServiceImpl.java @@ -49,77 +49,76 @@ import java.util.UUID; @Service public class TokenServiceImpl implements TokenService { - @Resource - private TenantService tenantService; + @Resource + private TenantService tenantService; - @Resource - private UserLoginService userLoginService; + @Resource + private UserLoginService userLoginService; - @Resource - private UserPasswordService userPasswordService; + @Resource + private UserPasswordService userPasswordService; - @Resource - private TenantBindService tenantBindService; + @Resource + private TenantBindService tenantBindService; - @Override - public String generateSalt(String loginName, String tenantCode) { - TenantBO tenantBO = tenantService.selectByCode(tenantCode); - if (Objects.isNull(tenantBO)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - return UUID.randomUUID().toString(); - } + @Override + public String generateSalt(String loginName, String tenantCode) { + TenantBO tenantBO = tenantService.selectByCode(tenantCode); + if (Objects.isNull(tenantBO)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + return UUID.randomUUID().toString(); + } - @Override - public String generateToken(String loginName, String salt, String password, String tenantCode) { - TenantBO tenantBO = tenantService.selectByCode(tenantCode); - if (Objects.isNull(tenantBO)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - UserLoginBO userLogin = userLoginService.selectByLoginName(loginName, false); - if (Objects.isNull(userLogin)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - TenantBindBO tenantBindBO = tenantBindService.selectByTenantIdAndUserId(tenantBO.getId(), - userLogin.getUserId()); - if (Objects.isNull(tenantBindBO)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - UserPasswordBO userPasswordBO = userPasswordService.selectById(userLogin.getUserPasswordId()); - if (Objects.isNull(userPasswordBO)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - if (StringUtils.isEmpty(salt)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - String md5Password = DecodeUtil.md5(userPasswordBO.getLoginPassword(), salt); - if (!md5Password.equals(password)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } - return KeyUtil.generateToken(loginName, salt, tenantBO.getId()); - } + @Override + public String generateToken(String loginName, String salt, String password, String tenantCode) { + TenantBO tenantBO = tenantService.selectByCode(tenantCode); + if (Objects.isNull(tenantBO)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + UserLoginBO userLogin = userLoginService.selectByLoginName(loginName, false); + if (Objects.isNull(userLogin)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + TenantBindBO tenantBindBO = tenantBindService.selectByTenantIdAndUserId(tenantBO.getId(), + userLogin.getUserId()); + if (Objects.isNull(tenantBindBO)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + UserPasswordBO userPasswordBO = userPasswordService.selectById(userLogin.getUserPasswordId()); + if (Objects.isNull(userPasswordBO)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + if (StringUtils.isEmpty(salt)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + String md5Password = DecodeUtil.md5(userPasswordBO.getLoginPassword(), salt); + if (!md5Password.equals(password)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } + return KeyUtil.generateToken(loginName, salt, tenantBO.getId()); + } - @Override - public TokenValid checkValid(String loginName, String salt, String token, String tenantCode) { - TenantBO tenantBO = tenantService.selectByCode(tenantCode); - if (Objects.isNull(tenantBO)) { - throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); - } + @Override + public TokenValid checkValid(String loginName, String salt, String token, String tenantCode) { + TenantBO tenantBO = tenantService.selectByCode(tenantCode); + if (Objects.isNull(tenantBO)) { + throw new UnAuthorizedException(ExceptionConstant.NO_AVAILABLE_AUTH); + } - TokenValid tokenValid = new TokenValid(false, null); - if (StringUtils.isBlank(token)) { - return tokenValid; - } + TokenValid tokenValid = new TokenValid(false, null); + if (StringUtils.isBlank(token)) { + return tokenValid; + } - try { - Claims claims = KeyUtil.parserToken(loginName, salt, token, tenantBO.getId()); - tokenValid.setValid(true); - tokenValid.setExpireTime(claims.getExpiration()); - return tokenValid; - } - catch (Exception e) { - return tokenValid; - } - } + try { + Claims claims = KeyUtil.parserToken(loginName, salt, token, tenantBO.getId()); + tokenValid.setValid(true); + tokenValid.setExpireTime(claims.getExpiration()); + return tokenValid; + } catch (Exception e) { + return tokenValid; + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ApiController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ApiController.java index ab31a28ed..b862b37b0 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ApiController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ApiController.java @@ -49,80 +49,75 @@ import java.util.Objects; @RequestMapping(AuthConstant.API_URL_PREFIX) public class ApiController implements BaseController { - private final ApiBuilder apiBuilder; + private final ApiBuilder apiBuilder; - private final ApiService apiService; + private final ApiService apiService; - public ApiController(ApiBuilder apiBuilder, ApiService apiService) { - this.apiBuilder = apiBuilder; - this.apiService = apiService; - } + public ApiController(ApiBuilder apiBuilder, ApiService apiService) { + this.apiBuilder = apiBuilder; + this.apiService = apiService; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody ApiVO entityVO) { - try { - ApiBO entityBO = apiBuilder.buildBOByVO(entityVO); - apiService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody ApiVO entityVO) { + try { + ApiBO entityBO = apiBuilder.buildBOByVO(entityVO); + apiService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - apiService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + apiService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody ApiVO entityVO) { - try { - ApiBO entityBO = apiBuilder.buildBOByVO(entityVO); - apiService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody ApiVO entityVO) { + try { + ApiBO entityBO = apiBuilder.buildBOByVO(entityVO); + apiService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - ApiBO entityBO = apiService.selectById(id); - ApiVO entityVO = apiBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + ApiBO entityBO = apiService.selectById(id); + ApiVO entityVO = apiBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) ApiQuery entityQuery) { - try { - if (Objects.isNull(entityQuery)) { - entityQuery = new ApiQuery(); - } - Page entityPageBO = apiService.selectByPage(entityQuery); - Page entityPageVO = apiBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) ApiQuery entityQuery) { + try { + if (Objects.isNull(entityQuery)) { + entityQuery = new ApiQuery(); + } + Page entityPageBO = apiService.selectByPage(entityQuery); + Page entityPageVO = apiBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/DictionaryForAuthController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/DictionaryForAuthController.java index 50775d8cf..46c5db6b4 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/DictionaryForAuthController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/DictionaryForAuthController.java @@ -44,31 +44,31 @@ import java.util.List; @RequestMapping(AuthConstant.DICTIONARY_URL_PREFIX) public class DictionaryForAuthController implements BaseController { - private final DictionaryForAuthBuilder dictionaryForAuthBuilder; + private final DictionaryForAuthBuilder dictionaryForAuthBuilder; - private final DictionaryForAuthService dictionaryForAuthService; + private final DictionaryForAuthService dictionaryForAuthService; - public DictionaryForAuthController(DictionaryForAuthBuilder dictionaryForAuthBuilder, - DictionaryForAuthService dictionaryForAuthService) { - this.dictionaryForAuthBuilder = dictionaryForAuthBuilder; - this.dictionaryForAuthService = dictionaryForAuthService; - } + public DictionaryForAuthController(DictionaryForAuthBuilder dictionaryForAuthBuilder, + DictionaryForAuthService dictionaryForAuthService) { + this.dictionaryForAuthBuilder = dictionaryForAuthBuilder; + this.dictionaryForAuthService = dictionaryForAuthService; + } - /** - * Tenant - * @return - */ - @GetMapping("/tenant") - public Mono>> tenantDictionary() { - try { - List entityBOList = dictionaryForAuthService.tenantDictionary(); - List entityVOList = dictionaryForAuthBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Tenant + * + * @return + */ + @GetMapping("/tenant") + public Mono>> tenantDictionary() { + try { + List entityBOList = dictionaryForAuthService.tenantDictionary(); + List entityVOList = dictionaryForAuthBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/MenuController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/MenuController.java index 44f13399d..8a462566d 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/MenuController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/MenuController.java @@ -53,135 +53,129 @@ import java.util.Objects; @RequestMapping(AuthConstant.MENU_URL_PREFIX) public class MenuController implements BaseController { - private final MenuBuilder menuBuilder; + private final MenuBuilder menuBuilder; - private final MenuService menuService; + private final MenuService menuService; - public MenuController(MenuBuilder menuBuilder, MenuService menuService) { - this.menuBuilder = menuBuilder; - this.menuService = menuService; - } + public MenuController(MenuBuilder menuBuilder, MenuService menuService) { + this.menuBuilder = menuBuilder; + this.menuService = menuService; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody MenuVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - MenuBO entityBO = menuBuilder.buildBOByVO(entityVO); - entityBO.setCreatorId(header.getUserId()); - entityBO.setCreatorName(header.getNickName()); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - menuService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody MenuVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + MenuBO entityBO = menuBuilder.buildBOByVO(entityVO); + entityBO.setCreatorId(header.getUserId()); + entityBO.setCreatorName(header.getNickName()); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + menuService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - menuService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + menuService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody MenuVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - MenuBO entityBO = menuBuilder.buildBOByVO(entityVO); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - menuService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody MenuVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + MenuBO entityBO = menuBuilder.buildBOByVO(entityVO); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + menuService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - MenuBO entityBO = menuService.selectById(id); - MenuVO entityVO = menuBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + MenuBO entityBO = menuService.selectById(id); + MenuVO entityVO = menuBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) MenuQuery entityQuery) { - try { - if (Objects.isNull(entityQuery)) { - entityQuery = new MenuQuery(); - } - Page entityPageBO = menuService.selectByPage(entityQuery); - Page entityPageVO = menuBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) MenuQuery entityQuery) { + try { + if (Objects.isNull(entityQuery)) { + entityQuery = new MenuQuery(); + } + Page entityPageBO = menuService.selectByPage(entityQuery); + Page entityPageVO = menuBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/tree") - public Mono>> tree(@RequestBody(required = false) MenuQuery entityQuery) { - try { - List entityBOList = menuService.selectTree(entityQuery); - List entityVOList = new ArrayList<>(entityBOList.size()); - for (MenuTreeBO node : entityBOList) { - entityVOList.add(toTreeVO(node)); - } - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/tree") + public Mono>> tree(@RequestBody(required = false) MenuQuery entityQuery) { + try { + List entityBOList = menuService.selectTree(entityQuery); + List entityVOList = new ArrayList<>(entityBOList.size()); + for (MenuTreeBO node : entityBOList) { + entityVOList.add(toTreeVO(node)); + } + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - private MenuTreeVO toTreeVO(MenuTreeBO node) { - MenuVO flat = menuBuilder.buildVOByBO(node); - MenuTreeVO out = new MenuTreeVO(); - out.setId(flat.getId()); - out.setParentMenuId(flat.getParentMenuId()); - out.setMenuTypeFlag(flat.getMenuTypeFlag()); - out.setMenuName(flat.getMenuName()); - out.setMenuCode(flat.getMenuCode()); - out.setMenuLevel(flat.getMenuLevel()); - out.setMenuIndex(flat.getMenuIndex()); - out.setMenuExt(flat.getMenuExt()); - out.setEnableFlag(flat.getEnableFlag()); - out.setRemark(flat.getRemark()); - out.setCreatorId(flat.getCreatorId()); - out.setCreatorName(flat.getCreatorName()); - out.setCreateTime(flat.getCreateTime()); - out.setOperatorId(flat.getOperatorId()); - out.setOperatorName(flat.getOperatorName()); - out.setOperateTime(flat.getOperateTime()); - if (node.getChildren() != null) { - List childVOs = new ArrayList<>(node.getChildren().size()); - for (MenuTreeBO child : node.getChildren()) { - childVOs.add(toTreeVO(child)); - } - out.setChildren(childVOs); - } - return out; - } + private MenuTreeVO toTreeVO(MenuTreeBO node) { + MenuVO flat = menuBuilder.buildVOByBO(node); + MenuTreeVO out = new MenuTreeVO(); + out.setId(flat.getId()); + out.setParentMenuId(flat.getParentMenuId()); + out.setMenuTypeFlag(flat.getMenuTypeFlag()); + out.setMenuName(flat.getMenuName()); + out.setMenuCode(flat.getMenuCode()); + out.setMenuLevel(flat.getMenuLevel()); + out.setMenuIndex(flat.getMenuIndex()); + out.setMenuExt(flat.getMenuExt()); + out.setEnableFlag(flat.getEnableFlag()); + out.setRemark(flat.getRemark()); + out.setCreatorId(flat.getCreatorId()); + out.setCreatorName(flat.getCreatorName()); + out.setCreateTime(flat.getCreateTime()); + out.setOperatorId(flat.getOperatorId()); + out.setOperatorName(flat.getOperatorName()); + out.setOperateTime(flat.getOperateTime()); + if (node.getChildren() != null) { + List childVOs = new ArrayList<>(node.getChildren().size()); + for (MenuTreeBO child : node.getChildren()) { + childVOs.add(toTreeVO(child)); + } + out.setChildren(childVOs); + } + return out; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ResourceController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ResourceController.java index a1e0cc95d..bc0249d46 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ResourceController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/ResourceController.java @@ -53,135 +53,129 @@ import java.util.Objects; @RequestMapping(AuthConstant.RESOURCE_URL_PREFIX) public class ResourceController implements BaseController { - private final ResourceBuilder resourceBuilder; + private final ResourceBuilder resourceBuilder; - private final ResourceService resourceService; + private final ResourceService resourceService; - public ResourceController(ResourceBuilder resourceBuilder, ResourceService resourceService) { - this.resourceBuilder = resourceBuilder; - this.resourceService = resourceService; - } + public ResourceController(ResourceBuilder resourceBuilder, ResourceService resourceService) { + this.resourceBuilder = resourceBuilder; + this.resourceService = resourceService; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody ResourceVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - ResourceBO entityBO = resourceBuilder.buildBOByVO(entityVO); - entityBO.setCreatorId(header.getUserId()); - entityBO.setCreatorName(header.getNickName()); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - resourceService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody ResourceVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + ResourceBO entityBO = resourceBuilder.buildBOByVO(entityVO); + entityBO.setCreatorId(header.getUserId()); + entityBO.setCreatorName(header.getNickName()); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + resourceService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - resourceService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + resourceService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody ResourceVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - ResourceBO entityBO = resourceBuilder.buildBOByVO(entityVO); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - resourceService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody ResourceVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + ResourceBO entityBO = resourceBuilder.buildBOByVO(entityVO); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + resourceService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - ResourceBO entityBO = resourceService.selectById(id); - ResourceVO entityVO = resourceBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + ResourceBO entityBO = resourceService.selectById(id); + ResourceVO entityVO = resourceBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) ResourceQuery entityQuery) { - try { - if (Objects.isNull(entityQuery)) { - entityQuery = new ResourceQuery(); - } - Page entityPageBO = resourceService.selectByPage(entityQuery); - Page entityPageVO = resourceBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) ResourceQuery entityQuery) { + try { + if (Objects.isNull(entityQuery)) { + entityQuery = new ResourceQuery(); + } + Page entityPageBO = resourceService.selectByPage(entityQuery); + Page entityPageVO = resourceBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/tree") - public Mono>> tree(@RequestBody(required = false) ResourceQuery entityQuery) { - try { - List entityBOList = resourceService.selectTree(entityQuery); - List entityVOList = new ArrayList<>(entityBOList.size()); - for (ResourceTreeBO node : entityBOList) { - entityVOList.add(toTreeVO(node)); - } - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/tree") + public Mono>> tree(@RequestBody(required = false) ResourceQuery entityQuery) { + try { + List entityBOList = resourceService.selectTree(entityQuery); + List entityVOList = new ArrayList<>(entityBOList.size()); + for (ResourceTreeBO node : entityBOList) { + entityVOList.add(toTreeVO(node)); + } + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - private ResourceTreeVO toTreeVO(ResourceTreeBO node) { - ResourceVO flat = resourceBuilder.buildVOByBO(node); - ResourceTreeVO out = new ResourceTreeVO(); - out.setId(flat.getId()); - out.setParentResourceId(flat.getParentResourceId()); - out.setResourceName(flat.getResourceName()); - out.setResourceCode(flat.getResourceCode()); - out.setResourceTypeFlag(flat.getResourceTypeFlag()); - out.setResourceScopeFlag(flat.getResourceScopeFlag()); - out.setEntityId(flat.getEntityId()); - out.setResourceExt(flat.getResourceExt()); - out.setEnableFlag(flat.getEnableFlag()); - out.setRemark(flat.getRemark()); - out.setCreatorId(flat.getCreatorId()); - out.setCreatorName(flat.getCreatorName()); - out.setCreateTime(flat.getCreateTime()); - out.setOperatorId(flat.getOperatorId()); - out.setOperatorName(flat.getOperatorName()); - out.setOperateTime(flat.getOperateTime()); - if (node.getChildren() != null) { - List childVOs = new ArrayList<>(node.getChildren().size()); - for (ResourceTreeBO child : node.getChildren()) { - childVOs.add(toTreeVO(child)); - } - out.setChildren(childVOs); - } - return out; - } + private ResourceTreeVO toTreeVO(ResourceTreeBO node) { + ResourceVO flat = resourceBuilder.buildVOByBO(node); + ResourceTreeVO out = new ResourceTreeVO(); + out.setId(flat.getId()); + out.setParentResourceId(flat.getParentResourceId()); + out.setResourceName(flat.getResourceName()); + out.setResourceCode(flat.getResourceCode()); + out.setResourceTypeFlag(flat.getResourceTypeFlag()); + out.setResourceScopeFlag(flat.getResourceScopeFlag()); + out.setEntityId(flat.getEntityId()); + out.setResourceExt(flat.getResourceExt()); + out.setEnableFlag(flat.getEnableFlag()); + out.setRemark(flat.getRemark()); + out.setCreatorId(flat.getCreatorId()); + out.setCreatorName(flat.getCreatorName()); + out.setCreateTime(flat.getCreateTime()); + out.setOperatorId(flat.getOperatorId()); + out.setOperatorName(flat.getOperatorName()); + out.setOperateTime(flat.getOperateTime()); + if (node.getChildren() != null) { + List childVOs = new ArrayList<>(node.getChildren().size()); + for (ResourceTreeBO child : node.getChildren()) { + childVOs.add(toTreeVO(child)); + } + out.setChildren(childVOs); + } + return out; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleController.java index 034ecab42..faa718852 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleController.java @@ -53,139 +53,133 @@ import java.util.Objects; @RequestMapping(AuthConstant.ROLE_URL_PREFIX) public class RoleController implements BaseController { - private final RoleBuilder roleBuilder; + private final RoleBuilder roleBuilder; - private final RoleService roleService; + private final RoleService roleService; - public RoleController(RoleBuilder roleBuilder, RoleService roleService) { - this.roleBuilder = roleBuilder; - this.roleService = roleService; - } + public RoleController(RoleBuilder roleBuilder, RoleService roleService) { + this.roleBuilder = roleBuilder; + this.roleService = roleService; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody RoleVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - RoleBO entityBO = roleBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(header.getTenantId()); - entityBO.setCreatorId(header.getUserId()); - entityBO.setCreatorName(header.getNickName()); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - roleService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody RoleVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + RoleBO entityBO = roleBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(header.getTenantId()); + entityBO.setCreatorId(header.getUserId()); + entityBO.setCreatorName(header.getNickName()); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + roleService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - roleService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + roleService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody RoleVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - RoleBO entityBO = roleBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(header.getTenantId()); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - roleService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody RoleVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + RoleBO entityBO = roleBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(header.getTenantId()); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + roleService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - RoleBO entityBO = roleService.selectById(id); - RoleVO entityVO = roleBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + RoleBO entityBO = roleService.selectById(id); + RoleVO entityVO = roleBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) RoleQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - RoleQuery query = Objects.isNull(entityQuery) ? new RoleQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = roleService.selectByPage(query); - Page entityPageVO = roleBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) RoleQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + RoleQuery query = Objects.isNull(entityQuery) ? new RoleQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = roleService.selectByPage(query); + Page entityPageVO = roleBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/tree") - public Mono>> tree(@RequestBody(required = false) RoleQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - RoleQuery query = Objects.isNull(entityQuery) ? new RoleQuery() : entityQuery; - query.setTenantId(tenantId); - List entityBOList = roleService.selectTree(query); - List entityVOList = new ArrayList<>(entityBOList.size()); - for (RoleTreeBO node : entityBOList) { - entityVOList.add(toTreeVO(node)); - } - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/tree") + public Mono>> tree(@RequestBody(required = false) RoleQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + RoleQuery query = Objects.isNull(entityQuery) ? new RoleQuery() : entityQuery; + query.setTenantId(tenantId); + List entityBOList = roleService.selectTree(query); + List entityVOList = new ArrayList<>(entityBOList.size()); + for (RoleTreeBO node : entityBOList) { + entityVOList.add(toTreeVO(node)); + } + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - private RoleTreeVO toTreeVO(RoleTreeBO node) { - RoleVO flat = roleBuilder.buildVOByBO(node); - RoleTreeVO out = new RoleTreeVO(); - out.setId(flat.getId()); - out.setParentRoleId(flat.getParentRoleId()); - out.setRoleName(flat.getRoleName()); - out.setRoleCode(flat.getRoleCode()); - out.setRoleExt(flat.getRoleExt()); - out.setEnableFlag(flat.getEnableFlag()); - out.setRemark(flat.getRemark()); - out.setCreatorId(flat.getCreatorId()); - out.setCreatorName(flat.getCreatorName()); - out.setCreateTime(flat.getCreateTime()); - out.setOperatorId(flat.getOperatorId()); - out.setOperatorName(flat.getOperatorName()); - out.setOperateTime(flat.getOperateTime()); - if (node.getChildren() != null) { - List childVOs = new ArrayList<>(node.getChildren().size()); - for (RoleTreeBO child : node.getChildren()) { - childVOs.add(toTreeVO(child)); - } - out.setChildren(childVOs); - } - return out; - } + private RoleTreeVO toTreeVO(RoleTreeBO node) { + RoleVO flat = roleBuilder.buildVOByBO(node); + RoleTreeVO out = new RoleTreeVO(); + out.setId(flat.getId()); + out.setParentRoleId(flat.getParentRoleId()); + out.setRoleName(flat.getRoleName()); + out.setRoleCode(flat.getRoleCode()); + out.setRoleExt(flat.getRoleExt()); + out.setEnableFlag(flat.getEnableFlag()); + out.setRemark(flat.getRemark()); + out.setCreatorId(flat.getCreatorId()); + out.setCreatorName(flat.getCreatorName()); + out.setCreateTime(flat.getCreateTime()); + out.setOperatorId(flat.getOperatorId()); + out.setOperatorName(flat.getOperatorName()); + out.setOperateTime(flat.getOperateTime()); + if (node.getChildren() != null) { + List childVOs = new ArrayList<>(node.getChildren().size()); + for (RoleTreeBO child : node.getChildren()) { + childVOs.add(toTreeVO(child)); + } + out.setChildren(childVOs); + } + return out; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleResourceBindController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleResourceBindController.java index 4343f3fa7..eaae23c7f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleResourceBindController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleResourceBindController.java @@ -55,106 +55,100 @@ import java.util.Objects; @RequestMapping(AuthConstant.ROLE_RESOURCE_URL_PREFIX) public class RoleResourceBindController implements BaseController { - private final RoleResourceBindBuilder roleResourceBindBuilder; + private final RoleResourceBindBuilder roleResourceBindBuilder; - private final RoleResourceBindService roleResourceBindService; + private final RoleResourceBindService roleResourceBindService; - private final ResourceBuilder resourceBuilder; + private final ResourceBuilder resourceBuilder; - private final RoleBuilder roleBuilder; + private final RoleBuilder roleBuilder; - public RoleResourceBindController(RoleResourceBindBuilder roleResourceBindBuilder, - RoleResourceBindService roleResourceBindService, ResourceBuilder resourceBuilder, RoleBuilder roleBuilder) { - this.roleResourceBindBuilder = roleResourceBindBuilder; - this.roleResourceBindService = roleResourceBindService; - this.resourceBuilder = resourceBuilder; - this.roleBuilder = roleBuilder; - } + public RoleResourceBindController(RoleResourceBindBuilder roleResourceBindBuilder, + RoleResourceBindService roleResourceBindService, ResourceBuilder resourceBuilder, RoleBuilder roleBuilder) { + this.roleResourceBindBuilder = roleResourceBindBuilder; + this.roleResourceBindService = roleResourceBindService; + this.resourceBuilder = resourceBuilder; + this.roleBuilder = roleBuilder; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody RoleResourceBindVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - RoleResourceBindBO entityBO = roleResourceBindBuilder.buildBOByVO(entityVO); - roleResourceBindService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody RoleResourceBindVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + RoleResourceBindBO entityBO = roleResourceBindBuilder.buildBOByVO(entityVO); + roleResourceBindService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - roleResourceBindService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + roleResourceBindService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) RoleResourceBindQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - RoleResourceBindQuery query = Objects.isNull(entityQuery) ? new RoleResourceBindQuery() : entityQuery; - Page entityPageBO = roleResourceBindService.selectByPage(query, tenantId); - Page entityPageVO = roleResourceBindBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) RoleResourceBindQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + RoleResourceBindQuery query = Objects.isNull(entityQuery) ? new RoleResourceBindQuery() : entityQuery; + Page entityPageBO = roleResourceBindService.selectByPage(query, tenantId); + Page entityPageVO = roleResourceBindBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/list-resource-by-role/{roleId}") - public Mono>> listResourceByRole(@NotNull @PathVariable(value = "roleId") Long roleId) { - try { - List entityBOList = roleResourceBindService.listResourceByRoleId(roleId); - List entityVOList = resourceBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/list-resource-by-role/{roleId}") + public Mono>> listResourceByRole(@NotNull @PathVariable(value = "roleId") Long roleId) { + try { + List entityBOList = roleResourceBindService.listResourceByRoleId(roleId); + List entityVOList = resourceBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/list-resource-by-user/{userId}") - public Mono>> listResourceByUser(@NotNull @PathVariable(value = "userId") Long userId) { - return getTenantId().flatMap(tenantId -> { - try { - List entityBOList = roleResourceBindService.listResourceByUserId(userId, tenantId); - List entityVOList = resourceBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/list-resource-by-user/{userId}") + public Mono>> listResourceByUser(@NotNull @PathVariable(value = "userId") Long userId) { + return getTenantId().flatMap(tenantId -> { + try { + List entityBOList = roleResourceBindService.listResourceByUserId(userId, tenantId); + List entityVOList = resourceBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/list-role-by-resource/{resourceId}") - public Mono>> listRoleByResource(@NotNull @PathVariable(value = "resourceId") Long resourceId) { - return getTenantId().flatMap(tenantId -> { - try { - List entityBOList = roleResourceBindService.listRoleByResourceId(resourceId, tenantId); - List entityVOList = roleBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/list-role-by-resource/{resourceId}") + public Mono>> listRoleByResource(@NotNull @PathVariable(value = "resourceId") Long resourceId) { + return getTenantId().flatMap(tenantId -> { + try { + List entityBOList = roleResourceBindService.listRoleByResourceId(resourceId, tenantId); + List entityVOList = roleBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleUserBindController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleUserBindController.java index 8b4e2b9a4..0f4922cdd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleUserBindController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/RoleUserBindController.java @@ -55,90 +55,85 @@ import java.util.Objects; @RequestMapping(AuthConstant.ROLE_USER_URL_PREFIX) public class RoleUserBindController implements BaseController { - private final RoleUserBindBuilder roleUserBindBuilder; + private final RoleUserBindBuilder roleUserBindBuilder; - private final RoleUserBindService roleUserBindService; + private final RoleUserBindService roleUserBindService; - private final RoleBuilder roleBuilder; + private final RoleBuilder roleBuilder; - private final UserBuilder userBuilder; + private final UserBuilder userBuilder; - public RoleUserBindController(RoleUserBindBuilder roleUserBindBuilder, RoleUserBindService roleUserBindService, - RoleBuilder roleBuilder, UserBuilder userBuilder) { - this.roleUserBindBuilder = roleUserBindBuilder; - this.roleUserBindService = roleUserBindService; - this.roleBuilder = roleBuilder; - this.userBuilder = userBuilder; - } + public RoleUserBindController(RoleUserBindBuilder roleUserBindBuilder, RoleUserBindService roleUserBindService, + RoleBuilder roleBuilder, UserBuilder userBuilder) { + this.roleUserBindBuilder = roleUserBindBuilder; + this.roleUserBindService = roleUserBindService; + this.roleBuilder = roleBuilder; + this.userBuilder = userBuilder; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody RoleUserBindVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - RoleUserBindBO entityBO = roleUserBindBuilder.buildBOByVO(entityVO); - roleUserBindService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody RoleUserBindVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + RoleUserBindBO entityBO = roleUserBindBuilder.buildBOByVO(entityVO); + roleUserBindService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - roleUserBindService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + roleUserBindService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) RoleUserBindQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - RoleUserBindQuery query = Objects.isNull(entityQuery) ? new RoleUserBindQuery() : entityQuery; - Page entityPageBO = roleUserBindService.selectByPage(query, tenantId); - Page entityPageVO = roleUserBindBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) RoleUserBindQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + RoleUserBindQuery query = Objects.isNull(entityQuery) ? new RoleUserBindQuery() : entityQuery; + Page entityPageBO = roleUserBindService.selectByPage(query, tenantId); + Page entityPageVO = roleUserBindBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/list-role-by-user/{userId}") - public Mono>> listRoleByUser(@NotNull @PathVariable(value = "userId") Long userId, - @RequestParam(value = "tenantId", required = false) Long tenantId) { - try { - List entityBOList = roleUserBindService.listRoleByTenantIdAndUserId(tenantId, userId); - List entityVOList = roleBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/list-role-by-user/{userId}") + public Mono>> listRoleByUser(@NotNull @PathVariable(value = "userId") Long userId, + @RequestParam(value = "tenantId", required = false) Long tenantId) { + try { + List entityBOList = roleUserBindService.listRoleByTenantIdAndUserId(tenantId, userId); + List entityVOList = roleBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/list-user-by-role/{roleId}") - public Mono>> listUserByRole(@NotNull @PathVariable(value = "roleId") Long roleId) { - try { - List entityBOList = roleUserBindService.listUserByRoleId(roleId); - List entityVOList = userBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/list-user-by-role/{roleId}") + public Mono>> listUserByRole(@NotNull @PathVariable(value = "roleId") Long roleId) { + try { + List entityBOList = roleUserBindService.listUserByRoleId(roleId); + List entityVOList = userBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TenantController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TenantController.java index ad0db6d6c..9d8abb9fa 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TenantController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TenantController.java @@ -49,129 +49,129 @@ import java.util.Objects; @RequestMapping(AuthConstant.TENANT_URL_PREFIX) public class TenantController implements BaseController { - private final TenantBuilder tenantBuilder; + private final TenantBuilder tenantBuilder; - private final TenantService tenantService; + private final TenantService tenantService; - public TenantController(TenantBuilder tenantBuilder, TenantService tenantService) { - this.tenantBuilder = tenantBuilder; - this.tenantService = tenantService; - } + public TenantController(TenantBuilder tenantBuilder, TenantService tenantService) { + this.tenantBuilder = tenantBuilder; + this.tenantService = tenantService; + } - /** - * Tenant - * @param entityVO {@link TenantVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody TenantVO entityVO) { - try { - TenantBO entityBO = tenantBuilder.buildBOByVO(entityVO); - tenantService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Tenant + * + * @param entityVO {@link TenantVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody TenantVO entityVO) { + try { + TenantBO entityBO = tenantBuilder.buildBOByVO(entityVO); + tenantService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Tenant - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - tenantService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Tenant + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + tenantService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Tenant - *

    - *
  1. : Enable
  2. - *
  3. : Name
  4. - *
- * @param entityVO {@link TenantVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody TenantVO entityVO) { - try { - TenantBO entityBO = tenantBuilder.buildBOByVO(entityVO); - tenantService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Tenant + *
    + *
  1. : Enable
  2. + *
  3. : Name
  4. + *
+ * + * @param entityVO {@link TenantVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody TenantVO entityVO) { + try { + TenantBO entityBO = tenantBuilder.buildBOByVO(entityVO); + tenantService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Tenant - * @param id ID - * @return TenantVO {@link TenantVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - TenantBO entityBO = tenantService.selectById(id); - TenantVO entityVO = tenantBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Tenant + * + * @param id ID + * @return TenantVO {@link TenantVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + TenantBO entityBO = tenantService.selectById(id); + TenantVO entityVO = tenantBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Code Tenant - * @param code TenantCode - * @return {@link TenantBO} - */ - @GetMapping("/code/{code}") - public Mono> selectByCode(@NotNull @PathVariable(value = "code") String code) { - try { - TenantBO select = tenantService.selectByCode(code); - if (Objects.nonNull(select)) { - return Mono.just(R.ok(select)); - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - return Mono.just(R.fail(ResponseEnum.NO_RESOURCE.getText())); - } + /** + * Code Tenant + * + * @param code TenantCode + * @return {@link TenantBO} + */ + @GetMapping("/code/{code}") + public Mono> selectByCode(@NotNull @PathVariable(value = "code") String code) { + try { + TenantBO select = tenantService.selectByCode(code); + if (Objects.nonNull(select)) { + return Mono.just(R.ok(select)); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + return Mono.just(R.fail(ResponseEnum.NO_RESOURCE.getText())); + } - /** - * Tenant - * @param entityQuery Tenant - * @return {@link TenantBO} - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) TenantQuery entityQuery) { - try { - if (Objects.isNull(entityQuery)) { - entityQuery = new TenantQuery(); - } - Page entityPageBO = tenantService.selectByPage(entityQuery); - Page entityPageVO = tenantBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Tenant + * + * @param entityQuery Tenant + * @return {@link TenantBO} + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) TenantQuery entityQuery) { + try { + if (Objects.isNull(entityQuery)) { + entityQuery = new TenantQuery(); + } + Page entityPageBO = tenantService.selectByPage(entityQuery); + Page entityPageVO = tenantBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TokenController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TokenController.java index daddf3e22..f0931d055 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TokenController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/TokenController.java @@ -46,57 +46,58 @@ import java.util.Objects; @RequestMapping(AuthConstant.TOKEN_URL_PREFIX) public class TokenController implements BaseController { - private final TokenService tokenService; + private final TokenService tokenService; - public TokenController(TokenService tokenService) { - this.tokenService = tokenService; - } + public TokenController(TokenService tokenService) { + this.tokenService = tokenService; + } - /** - * @param entityVO {@link TokenQuery} - * @return - */ - @PostMapping("/salt") - public Mono> generateSalt(@Validated @RequestBody TokenQuery entityVO) { - String salt = tokenService.generateSalt(entityVO.getName(), entityVO.getTenant()); - return Objects.nonNull(salt) ? Mono.just(R.ok(salt, "The salt will expire in 5 minutes")) : Mono.just(R.fail()); - } + /** + * @param entityVO {@link TokenQuery} + * @return + */ + @PostMapping("/salt") + public Mono> generateSalt(@Validated @RequestBody TokenQuery entityVO) { + String salt = tokenService.generateSalt(entityVO.getName(), entityVO.getTenant()); + return Objects.nonNull(salt) ? Mono.just(R.ok(salt, "The salt will expire in 5 minutes")) : Mono.just(R.fail()); + } - /** - * Token - * @param entityVO {@link TokenQuery} - * @return Token - */ - @PostMapping("/generate") - public Mono> generateToken(@Validated @RequestBody TokenQuery entityVO) { - String token = tokenService.generateToken(entityVO.getName(), entityVO.getSalt(), entityVO.getPassword(), - entityVO.getTenant()); - return Objects.nonNull(token) ? Mono.just(R.ok(token, "The token will expire in 12 hours.")) - : Mono.just(R.fail()); - } + /** + * Token + * + * @param entityVO {@link TokenQuery} + * @return Token + */ + @PostMapping("/generate") + public Mono> generateToken(@Validated @RequestBody TokenQuery entityVO) { + String token = tokenService.generateToken(entityVO.getName(), entityVO.getSalt(), entityVO.getPassword(), + entityVO.getTenant()); + return Objects.nonNull(token) ? Mono.just(R.ok(token, "The token will expire in 12 hours.")) + : Mono.just(R.fail()); + } - /** - * Token - * @param entityVO {@link TokenQuery} - * @return , - */ - @PostMapping("/check") - public Mono> checkValid(@Validated @RequestBody TokenQuery entityVO) { - TokenValid tokenValid = tokenService.checkValid(entityVO.getName(), entityVO.getSalt(), entityVO.getToken(), - entityVO.getTenant()); + /** + * Token + * + * @param entityVO {@link TokenQuery} + * @return , + */ + @PostMapping("/check") + public Mono> checkValid(@Validated @RequestBody TokenQuery entityVO) { + TokenValid tokenValid = tokenService.checkValid(entityVO.getName(), entityVO.getSalt(), entityVO.getToken(), + entityVO.getTenant()); - boolean valid = tokenValid.isValid(); - String message = "The token has expired"; - if (valid && Objects.nonNull(tokenValid.getExpireTime())) { - String expireTime = TimeUtil.completeFormat(tokenValid.getExpireTime()); - message = "The token will expire in " + expireTime; - } - else if (!valid && Objects.nonNull(tokenValid.getExpireTime())) { - String expireTime = TimeUtil.completeFormat(tokenValid.getExpireTime()); - message = "The token has expired in " + expireTime; - } + boolean valid = tokenValid.isValid(); + String message = "The token has expired"; + if (valid && Objects.nonNull(tokenValid.getExpireTime())) { + String expireTime = TimeUtil.completeFormat(tokenValid.getExpireTime()); + message = "The token will expire in " + expireTime; + } else if (!valid && Objects.nonNull(tokenValid.getExpireTime())) { + String expireTime = TimeUtil.completeFormat(tokenValid.getExpireTime()); + message = "The token has expired in " + expireTime; + } - return Mono.just(R.ok(valid, message)); - } + return Mono.just(R.ok(valid, message)); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserController.java index 0e5cc9545..24c6a2b63 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserController.java @@ -49,109 +49,103 @@ import java.util.Objects; @RequestMapping(AuthConstant.USER_PROFILE_URL_PREFIX) public class UserController implements BaseController { - private final UserBuilder userBuilder; + private final UserBuilder userBuilder; - private final UserService userService; + private final UserService userService; - public UserController(UserBuilder userBuilder, UserService userService) { - this.userBuilder = userBuilder; - this.userService = userService; - } + public UserController(UserBuilder userBuilder, UserService userService) { + this.userBuilder = userBuilder; + this.userService = userService; + } - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody UserVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - UserBO entityBO = userBuilder.buildBOByVO(entityVO); - entityBO.setCreatorId(header.getUserId()); - entityBO.setCreatorName(header.getNickName()); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - userService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody UserVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + UserBO entityBO = userBuilder.buildBOByVO(entityVO); + entityBO.setCreatorId(header.getUserId()); + entityBO.setCreatorName(header.getNickName()); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + userService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - userService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + userService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody UserVO entityVO) { - return getUserHeader().flatMap(header -> { - try { - UserBO entityBO = userBuilder.buildBOByVO(entityVO); - entityBO.setOperatorId(header.getUserId()); - entityBO.setOperatorName(header.getNickName()); - userService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody UserVO entityVO) { + return getUserHeader().flatMap(header -> { + try { + UserBO entityBO = userBuilder.buildBOByVO(entityVO); + entityBO.setOperatorId(header.getUserId()); + entityBO.setOperatorName(header.getNickName()); + userService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - UserBO entityBO = userService.selectById(id); - UserVO entityVO = userBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + UserBO entityBO = userService.selectById(id); + UserVO entityVO = userBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/name/{name}") - public Mono> selectByName(@NotNull @PathVariable(value = "name") String name) { - try { - UserBO entityBO = userService.selectByUserName(name, false); - if (Objects.isNull(entityBO)) { - return Mono.just(R.fail(ResponseEnum.NO_RESOURCE.getText())); - } - UserVO entityVO = userBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/name/{name}") + public Mono> selectByName(@NotNull @PathVariable(value = "name") String name) { + try { + UserBO entityBO = userService.selectByUserName(name, false); + if (Objects.isNull(entityBO)) { + return Mono.just(R.fail(ResponseEnum.NO_RESOURCE.getText())); + } + UserVO entityVO = userBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) UserQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - UserQuery query = Objects.isNull(entityQuery) ? new UserQuery() : entityQuery; - // Overwrite whatever the client sent. Tenant scope is a hard - // boundary, not a filter — a caller cannot reach across tenants. - query.setTenantId(tenantId); - Page entityPageBO = userService.selectByPage(query); - Page entityPageVO = userBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) UserQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + UserQuery query = Objects.isNull(entityQuery) ? new UserQuery() : entityQuery; + // Overwrite whatever the client sent. Tenant scope is a hard + // boundary, not a filter — a caller cannot reach across tenants. + query.setTenantId(tenantId); + Page entityPageBO = userService.selectByPage(query); + Page entityPageVO = userBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserLoginController.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserLoginController.java index fc608e691..69164bf65 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserLoginController.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/controller/UserLoginController.java @@ -50,164 +50,163 @@ import java.util.Objects; @RequestMapping(AuthConstant.USER_URL_PREFIX) public class UserLoginController implements BaseController { - private final UserLoginBuilder userLoginBuilder; + private final UserLoginBuilder userLoginBuilder; - private final UserLoginService userLoginService; + private final UserLoginService userLoginService; - private final UserPasswordService userPasswordService; + private final UserPasswordService userPasswordService; - public UserLoginController(UserLoginBuilder userLoginBuilder, UserLoginService userLoginService, - UserPasswordService userPasswordService) { - this.userLoginBuilder = userLoginBuilder; - this.userLoginService = userLoginService; - this.userPasswordService = userPasswordService; - } + public UserLoginController(UserLoginBuilder userLoginBuilder, UserLoginService userLoginService, + UserPasswordService userPasswordService) { + this.userLoginBuilder = userLoginBuilder; + this.userLoginService = userLoginService; + this.userPasswordService = userPasswordService; + } - /** - * @param entityVO {@link UserLoginVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody UserLoginVO entityVO) { - try { - UserLoginBO entityBO = userLoginBuilder.buildBOByVO(entityVO); - userLoginService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param entityVO {@link UserLoginVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody UserLoginVO entityVO) { + try { + UserLoginBO entityBO = userLoginBuilder.buildBOByVO(entityVO); + userLoginService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - userLoginService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + userLoginService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * - *
    - *
  1. : Enable,Password
  2. - *
  3. : Name
  4. - *
- * @param entityVO {@link UserLoginVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody UserLoginVO entityVO) { - try { - UserLoginBO entityBO = userLoginBuilder.buildBOByVO(entityVO); - userLoginService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * + *
    + *
  1. : Enable,Password
  2. + *
  3. : Name
  4. + *
+ * + * @param entityVO {@link UserLoginVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody UserLoginVO entityVO) { + try { + UserLoginBO entityBO = userLoginBuilder.buildBOByVO(entityVO); + userLoginService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID - * @param id ID - * @return - */ - @PostMapping("/reset/{id}") - public Mono> restPassword(@NotNull @PathVariable(value = "id") Long id) { - try { - userPasswordService.restPassword(id); - return Mono.just(R.ok()); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID + * + * @param id ID + * @return + */ + @PostMapping("/reset/{id}") + public Mono> restPassword(@NotNull @PathVariable(value = "id") Long id) { + try { + userPasswordService.restPassword(id); + return Mono.just(R.ok()); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID - * @param id ID - * @return UserLoginVO {@link UserLoginVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - UserLoginBO entityBO = userLoginService.selectById(id); - UserLoginVO entityVO = userLoginBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID + * + * @param id ID + * @return UserLoginVO {@link UserLoginVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + UserLoginBO entityBO = userLoginService.selectById(id); + UserLoginVO entityVO = userLoginBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Name User - * @param name Name - * @return {@link UserLoginBO} - */ - @GetMapping("/name/{name}") - public Mono> selectByName(@NotNull @PathVariable(value = "name") String name) { - try { - UserLoginBO entityBO = userLoginService.selectByLoginName(name, false); - UserLoginVO entityVO = userLoginBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Name User + * + * @param name Name + * @return {@link UserLoginBO} + */ + @GetMapping("/name/{name}") + public Mono> selectByName(@NotNull @PathVariable(value = "name") String name) { + try { + UserLoginBO entityBO = userLoginService.selectByLoginName(name, false); + UserLoginVO entityVO = userLoginBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * User - * @param entityQuery - * @return {@link UserLoginBO} - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) UserLoginQuery entityQuery) { - try { - if (Objects.isNull(entityQuery)) { - entityQuery = new UserLoginQuery(); - } - Page entityPageBO = userLoginService.selectByPage(entityQuery); - Page entityPageVO = userLoginBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * User + * + * @param entityQuery + * @return {@link UserLoginBO} + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) UserLoginQuery entityQuery) { + try { + if (Objects.isNull(entityQuery)) { + entityQuery = new UserLoginQuery(); + } + Page entityPageBO = userLoginService.selectByPage(entityQuery); + Page entityPageVO = userLoginBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Name - * @param name Name - * @return - */ - @GetMapping("/check/{name}") - public Mono> checkLoginNameValid(@NotNull @PathVariable(value = "name") String name) { - try { - return Boolean.TRUE.equals(userLoginService.checkLoginNameValid(name)) ? Mono.just(R.ok()) - : Mono.just(R.fail()); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Name + * + * @param name Name + * @return + */ + @GetMapping("/check/{name}") + public Mono> checkLoginNameValid(@NotNull @PathVariable(value = "name") String name) { + try { + return Boolean.TRUE.equals(userLoginService.checkLoginNameValid(name)) ? Mono.just(R.ok()) + : Mono.just(R.fail()); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/DriverTokenManagerImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/DriverTokenManagerImpl.java index 2db2da44c..424e8dec3 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/DriverTokenManagerImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/DriverTokenManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class DriverTokenManagerImpl extends ServiceImpl - implements DriverTokenManager { + implements DriverTokenManager { } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleResourceBindManagerImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleResourceBindManagerImpl.java index 2f05ad3d5..21e1c63cb 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleResourceBindManagerImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleResourceBindManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class RoleResourceBindManagerImpl extends ServiceImpl - implements RoleResourceBindManager { + implements RoleResourceBindManager { } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleUserBindManagerImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleUserBindManagerImpl.java index 10478ba91..d4f82657d 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleUserBindManagerImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/RoleUserBindManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class RoleUserBindManagerImpl extends ServiceImpl - implements RoleUserBindManager { + implements RoleUserBindManager { } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/UserPasswordManagerImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/UserPasswordManagerImpl.java index 6341dcb53..7193c8e7c 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/UserPasswordManagerImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/dal/impl/UserPasswordManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class UserPasswordManagerImpl extends ServiceImpl - implements UserPasswordManager { + implements UserPasswordManager { } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/AuthHeader.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/AuthHeader.java index a2f92cd6f..53aa3ae74 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/AuthHeader.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/AuthHeader.java @@ -34,13 +34,13 @@ import java.io.Serializable; @AllArgsConstructor public class AuthHeader implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String user; + private String user; - private String salt; + private String salt; - private String token; + private String token; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/Login.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/Login.java index 0b41bc37f..1adc26953 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/Login.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/Login.java @@ -40,22 +40,22 @@ import java.io.Serializable; @AllArgsConstructor public class Login implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @NotBlank(message = "租户不能为空", groups = { Auth.class }) - private String tenant; + @NotBlank(message = "租户不能为空", groups = {Auth.class}) + private String tenant; - @NotBlank(message = "名称不能为空", groups = { Check.class, Auth.class, Update.class }) - private String name; + @NotBlank(message = "名称不能为空", groups = {Check.class, Auth.class, Update.class}) + private String name; - @NotBlank(message = "盐值不能为空", groups = { Check.class, Auth.class }) - private String salt; + @NotBlank(message = "盐值不能为空", groups = {Check.class, Auth.class}) + private String salt; - @NotBlank(message = "密码不能为空", groups = { Auth.class }) - private String password; + @NotBlank(message = "密码不能为空", groups = {Auth.class}) + private String password; - @NotBlank(message = "令牌不能为空", groups = { Check.class }) - private String token; + @NotBlank(message = "令牌不能为空", groups = {Check.class}) + private String token; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/TokenValid.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/TokenValid.java index 62863da17..e5f6871b6 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/TokenValid.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bean/TokenValid.java @@ -35,11 +35,11 @@ import java.util.Date; @AllArgsConstructor public class TokenValid implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private boolean valid; + private boolean valid; - private Date expireTime; + private Date expireTime; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ApiBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ApiBO.java index e86ff4041..9e8efbc09 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ApiBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ApiBO.java @@ -37,39 +37,39 @@ import lombok.*; @ToString(callSuper = true) public class ApiBO extends BaseBO { - /** - * Owning service name, populated by resource registrar - */ - private String serviceName; + /** + * Owning service name, populated by resource registrar + */ + private String serviceName; - /** - * ApiType - */ - private ApiTypeFlagEnum apiTypeFlag; + /** + * ApiType + */ + private ApiTypeFlagEnum apiTypeFlag; - /** - * ApiName - */ - private String apiName; + /** + * ApiName + */ + private String apiName; - /** - * ApiCode, URLMD5 - */ - private String apiCode; + /** + * ApiCode, URLMD5 + */ + private String apiCode; - /** - * API grouping, usually the owning controller simple class name - */ - private String apiGroup; + /** + * API grouping, usually the owning controller simple class name + */ + private String apiGroup; - /** - * Api - */ - private ApiExt apiExt; + /** + * Api + */ + private ApiExt apiExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/DriverTokenBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/DriverTokenBO.java index 1b2c4f2f9..d30310edb 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/DriverTokenBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/DriverTokenBO.java @@ -38,39 +38,39 @@ import java.time.LocalDateTime; @ToString(callSuper = true) public class DriverTokenBO extends BaseBO { - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * AppID - */ - private String driverAppId; + /** + * AppID + */ + private String driverAppId; - /** - * AppKey - */ - private String driverAppKey; + /** + * AppKey + */ + private String driverAppKey; - /** - * - */ - private ExpireFlagEnum expireFlag; + /** + * + */ + private ExpireFlagEnum expireFlag; - /** - * - */ - private LocalDateTime expireTime; + /** + * + */ + private LocalDateTime expireTime; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuBO.java index f7fb50127..0f56550e7 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuBO.java @@ -38,44 +38,44 @@ import lombok.*; @ToString(callSuper = true) public class MenuBO extends BaseBO { - /** - * ID - */ - private Long parentMenuId; + /** + * ID + */ + private Long parentMenuId; - /** - * Type - */ - private MenuTypeFlagEnum menuTypeFlag; + /** + * Type + */ + private MenuTypeFlagEnum menuTypeFlag; - /** - * Name - */ - private String menuName; + /** + * Name + */ + private String menuName; - /** - * Code, URLMD5 - */ - private String menuCode; + /** + * Code, URLMD5 + */ + private String menuCode; - /** - * - */ - private MenuLevelFlagEnum menuLevel; + /** + * + */ + private MenuLevelFlagEnum menuLevel; - /** - * - */ - private Integer menuIndex; + /** + * + */ + private Integer menuIndex; - /** - * - */ - private MenuExt menuExt; + /** + * + */ + private MenuExt menuExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuTreeBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuTreeBO.java index 12b234daa..6a36dd32e 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuTreeBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/MenuTreeBO.java @@ -36,34 +36,34 @@ import java.util.List; @EqualsAndHashCode(callSuper = true) public class MenuTreeBO extends MenuBO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); - public static MenuTreeBO fromBO(MenuBO source) { - MenuTreeBO node = new MenuTreeBO(); - node.setId(source.getId()); - node.setParentMenuId(source.getParentMenuId()); - node.setMenuTypeFlag(source.getMenuTypeFlag()); - node.setMenuName(source.getMenuName()); - node.setMenuCode(source.getMenuCode()); - node.setMenuLevel(source.getMenuLevel()); - node.setMenuIndex(source.getMenuIndex()); - node.setMenuExt(source.getMenuExt()); - node.setEnableFlag(source.getEnableFlag()); - node.setRemark(source.getRemark()); - node.setCreatorId(source.getCreatorId()); - node.setCreatorName(source.getCreatorName()); - node.setCreateTime(source.getCreateTime()); - node.setOperatorId(source.getOperatorId()); - node.setOperatorName(source.getOperatorName()); - node.setOperateTime(source.getOperateTime()); - return node; - } + public static MenuTreeBO fromBO(MenuBO source) { + MenuTreeBO node = new MenuTreeBO(); + node.setId(source.getId()); + node.setParentMenuId(source.getParentMenuId()); + node.setMenuTypeFlag(source.getMenuTypeFlag()); + node.setMenuName(source.getMenuName()); + node.setMenuCode(source.getMenuCode()); + node.setMenuLevel(source.getMenuLevel()); + node.setMenuIndex(source.getMenuIndex()); + node.setMenuExt(source.getMenuExt()); + node.setEnableFlag(source.getEnableFlag()); + node.setRemark(source.getRemark()); + node.setCreatorId(source.getCreatorId()); + node.setCreatorName(source.getCreatorName()); + node.setCreateTime(source.getCreateTime()); + node.setOperatorId(source.getOperatorId()); + node.setOperatorName(source.getOperatorName()); + node.setOperateTime(source.getOperateTime()); + return node; + } - public void addChild(MenuTreeBO child) { - if (children == null) { - children = new ArrayList<>(); - } - children.add(child); - } + public void addChild(MenuTreeBO child) { + if (children == null) { + children = new ArrayList<>(); + } + children.add(child); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceBO.java index 3b6ef53e0..8f4a6ead8 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceBO.java @@ -38,51 +38,51 @@ import lombok.*; @ToString(callSuper = true) public class ResourceBO extends BaseBO { - /** - * ID - */ - private Long parentResourceId; + /** + * ID + */ + private Long parentResourceId; - /** - * Name - */ - private String resourceName; + /** + * Name + */ + private String resourceName; - /** - * Code - */ - private String resourceCode; + /** + * Code + */ + private String resourceCode; - /** - * Type - */ - private ResourceTypeFlagEnum resourceTypeFlag; + /** + * Type + */ + private ResourceTypeFlagEnum resourceTypeFlag; - /** - * , : ResourceScopeFlagEnum - *
    - *
  • 0x01:
  • - *
  • 0x02:
  • - *
  • 0x04:
  • - *
  • 0x08:
  • - *
- * - */ - private ResourceScopeFlagEnum resourceScopeFlag; + /** + * , : ResourceScopeFlagEnum + *
    + *
  • 0x01:
  • + *
  • 0x02:
  • + *
  • 0x04:
  • + *
  • 0x08:
  • + *
+ * + */ + private ResourceScopeFlagEnum resourceScopeFlag; - /** - * Entity ID - */ - private Long entityId; + /** + * Entity ID + */ + private Long entityId; - /** - * - */ - private ResourceExt resourceExt; + /** + * + */ + private ResourceExt resourceExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistryScannedApi.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistryScannedApi.java index df36949aa..66bb12d6f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistryScannedApi.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistryScannedApi.java @@ -34,36 +34,36 @@ import lombok.*; @AllArgsConstructor public class ResourceRegistryScannedApi { - /** - * HTTP method: GET / POST / PUT / DELETE. - */ - private String method; + /** + * HTTP method: GET / POST / PUT / DELETE. + */ + private String method; - /** - * Full path (post gateway strip), e.g. /device/add. - */ - private String path; + /** + * Full path (post gateway strip), e.g. /device/add. + */ + private String path; - /** - * Human-readable name, typically ClassSimpleName.methodName. - */ - private String apiName; + /** + * Human-readable name, typically ClassSimpleName.methodName. + */ + private String apiName; - /** - * Short title, usually the controller method name. - */ - private String title; + /** + * Short title, usually the controller method name. + */ + private String title; - /** - * Optional description. - */ - private String remark; + /** + * Optional description. + */ + private String remark; - /** - * API grouping label — usually the owning controller's simple class name, e.g. - * "ApiController". Endpoints sharing the same apiGroup become siblings under the same - * resource-tree node. - */ - private String apiGroup; + /** + * API grouping label — usually the owning controller's simple class name, e.g. + * "ApiController". Endpoints sharing the same apiGroup become siblings under the same + * resource-tree node. + */ + private String apiGroup; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncCommand.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncCommand.java index 9632de32d..5cba94fd0 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncCommand.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncCommand.java @@ -36,20 +36,20 @@ import java.util.List; @AllArgsConstructor public class ResourceRegistrySyncCommand { - /** - * Owning service name, e.g. dc3-center-manager. - */ - private String serviceName; + /** + * Owning service name, e.g. dc3-center-manager. + */ + private String serviceName; - /** - * When true, endpoints that exist in the DB but are absent from the current scan are - * soft-deleted. When false, such endpoints are left untouched. - */ - private boolean deleteMissing; + /** + * When true, endpoints that exist in the DB but are absent from the current scan are + * soft-deleted. When false, such endpoints are left untouched. + */ + private boolean deleteMissing; - /** - * Complete list of endpoints discovered by the registrar on the calling service. - */ - private List apis; + /** + * Complete list of endpoints discovered by the registrar on the calling service. + */ + private List apis; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncResult.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncResult.java index 5dd8c7a78..8195c42fd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncResult.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceRegistrySyncResult.java @@ -34,12 +34,12 @@ import lombok.*; @AllArgsConstructor public class ResourceRegistrySyncResult { - private int inserted; + private int inserted; - private int updated; + private int updated; - private int deleted; + private int deleted; - private int unchanged; + private int unchanged; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceTreeBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceTreeBO.java index bee8bfb85..2a374fb7d 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceTreeBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/ResourceTreeBO.java @@ -37,37 +37,37 @@ import java.util.List; @EqualsAndHashCode(callSuper = true) public class ResourceTreeBO extends ResourceBO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); - /** - * Copy shared fields from a flat {@link ResourceBO} into a new tree node. - */ - public static ResourceTreeBO fromBO(ResourceBO source) { - ResourceTreeBO node = new ResourceTreeBO(); - node.setId(source.getId()); - node.setParentResourceId(source.getParentResourceId()); - node.setResourceName(source.getResourceName()); - node.setResourceCode(source.getResourceCode()); - node.setResourceTypeFlag(source.getResourceTypeFlag()); - node.setResourceScopeFlag(source.getResourceScopeFlag()); - node.setEntityId(source.getEntityId()); - node.setResourceExt(source.getResourceExt()); - node.setEnableFlag(source.getEnableFlag()); - node.setRemark(source.getRemark()); - node.setCreatorId(source.getCreatorId()); - node.setCreatorName(source.getCreatorName()); - node.setCreateTime(source.getCreateTime()); - node.setOperatorId(source.getOperatorId()); - node.setOperatorName(source.getOperatorName()); - node.setOperateTime(source.getOperateTime()); - return node; - } + /** + * Copy shared fields from a flat {@link ResourceBO} into a new tree node. + */ + public static ResourceTreeBO fromBO(ResourceBO source) { + ResourceTreeBO node = new ResourceTreeBO(); + node.setId(source.getId()); + node.setParentResourceId(source.getParentResourceId()); + node.setResourceName(source.getResourceName()); + node.setResourceCode(source.getResourceCode()); + node.setResourceTypeFlag(source.getResourceTypeFlag()); + node.setResourceScopeFlag(source.getResourceScopeFlag()); + node.setEntityId(source.getEntityId()); + node.setResourceExt(source.getResourceExt()); + node.setEnableFlag(source.getEnableFlag()); + node.setRemark(source.getRemark()); + node.setCreatorId(source.getCreatorId()); + node.setCreatorName(source.getCreatorName()); + node.setCreateTime(source.getCreateTime()); + node.setOperatorId(source.getOperatorId()); + node.setOperatorName(source.getOperatorName()); + node.setOperateTime(source.getOperateTime()); + return node; + } - public void addChild(ResourceTreeBO child) { - if (children == null) { - children = new ArrayList<>(); - } - children.add(child); - } + public void addChild(ResourceTreeBO child) { + if (children == null) { + children = new ArrayList<>(); + } + children.add(child); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleBO.java index 75e8234cc..6c7bb2841 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleBO.java @@ -36,34 +36,34 @@ import lombok.*; @ToString(callSuper = true) public class RoleBO extends BaseBO { - /** - * ID - */ - private String parentRoleId; + /** + * ID + */ + private String parentRoleId; - /** - * Name - */ - private String roleName; + /** + * Name + */ + private String roleName; - /** - * Code - */ - private String roleCode; + /** + * Code + */ + private String roleCode; - /** - * - */ - private RoleExt roleExt; + /** + * + */ + private RoleExt roleExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleResourceBindBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleResourceBindBO.java index 9bfad956c..126051862 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleResourceBindBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleResourceBindBO.java @@ -34,14 +34,14 @@ import lombok.*; @ToString(callSuper = true) public class RoleResourceBindBO extends BaseBO { - /** - * ID - */ - private Long roleId; + /** + * ID + */ + private Long roleId; - /** - * ID - */ - private Long resourceId; + /** + * ID + */ + private Long resourceId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleTreeBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleTreeBO.java index 116a1de0d..8cc578e5b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleTreeBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleTreeBO.java @@ -38,35 +38,35 @@ import java.util.List; @EqualsAndHashCode(callSuper = true) public class RoleTreeBO extends RoleBO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); - /** - * Copy shared fields from a flat {@link RoleBO} into a new tree node. - */ - public static RoleTreeBO fromBO(RoleBO source) { - RoleTreeBO node = new RoleTreeBO(); - node.setId(source.getId()); - node.setParentRoleId(source.getParentRoleId()); - node.setRoleName(source.getRoleName()); - node.setRoleCode(source.getRoleCode()); - node.setRoleExt(source.getRoleExt()); - node.setEnableFlag(source.getEnableFlag()); - node.setTenantId(source.getTenantId()); - node.setRemark(source.getRemark()); - node.setCreatorId(source.getCreatorId()); - node.setCreatorName(source.getCreatorName()); - node.setCreateTime(source.getCreateTime()); - node.setOperatorId(source.getOperatorId()); - node.setOperatorName(source.getOperatorName()); - node.setOperateTime(source.getOperateTime()); - return node; - } + /** + * Copy shared fields from a flat {@link RoleBO} into a new tree node. + */ + public static RoleTreeBO fromBO(RoleBO source) { + RoleTreeBO node = new RoleTreeBO(); + node.setId(source.getId()); + node.setParentRoleId(source.getParentRoleId()); + node.setRoleName(source.getRoleName()); + node.setRoleCode(source.getRoleCode()); + node.setRoleExt(source.getRoleExt()); + node.setEnableFlag(source.getEnableFlag()); + node.setTenantId(source.getTenantId()); + node.setRemark(source.getRemark()); + node.setCreatorId(source.getCreatorId()); + node.setCreatorName(source.getCreatorName()); + node.setCreateTime(source.getCreateTime()); + node.setOperatorId(source.getOperatorId()); + node.setOperatorName(source.getOperatorName()); + node.setOperateTime(source.getOperateTime()); + return node; + } - public void addChild(RoleTreeBO child) { - if (children == null) { - children = new ArrayList<>(); - } - children.add(child); - } + public void addChild(RoleTreeBO child) { + if (children == null) { + children = new ArrayList<>(); + } + children.add(child); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleUserBindBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleUserBindBO.java index 8fb674b7f..38a41a92f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleUserBindBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/RoleUserBindBO.java @@ -34,14 +34,14 @@ import lombok.*; @ToString(callSuper = true) public class RoleUserBindBO extends BaseBO { - /** - * ID - */ - private Long roleId; + /** + * ID + */ + private Long roleId; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBO.java index 60fa775e8..062526c7f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBO.java @@ -36,24 +36,24 @@ import lombok.*; @ToString(callSuper = true) public class TenantBO extends BaseBO { - /** - * TenantName - */ - private String tenantName; + /** + * TenantName + */ + private String tenantName; - /** - * TenantCode - */ - private String tenantCode; + /** + * TenantCode + */ + private String tenantCode; - /** - * Tenant - */ - private TenantExt tenantExt; + /** + * Tenant + */ + private TenantExt tenantExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBindBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBindBO.java index 25d78e752..dbf072f17 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBindBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/TenantBindBO.java @@ -34,14 +34,14 @@ import lombok.*; @ToString(callSuper = true) public class TenantBindBO extends BaseBO { - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserBO.java index 454a4d19f..1c702b6d6 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserBO.java @@ -36,39 +36,39 @@ import lombok.*; @ToString(callSuper = true) public class UserBO extends BaseBO { - /** - * - */ - private String nickName; + /** + * + */ + private String nickName; - /** - * Name - */ - private String userName; + /** + * Name + */ + private String userName; - /** - * - */ - private String phone; + /** + * + */ + private String phone; - /** - * - */ - private String email; + /** + * + */ + private String email; - /** - * - */ - private UserSocialExt socialExt; + /** + * + */ + private UserSocialExt socialExt; - /** - * - */ - private UserIdentityExt identityExt; + /** + * + */ + private UserIdentityExt identityExt; - /** - * Enable flag, 0:, 1:Disable - */ - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + private Byte enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserLoginBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserLoginBO.java index 78169abb0..289a8ae2f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserLoginBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserLoginBO.java @@ -35,24 +35,24 @@ import lombok.*; @ToString(callSuper = true) public class UserLoginBO extends BaseBO { - /** - * Name - */ - private String loginName; + /** + * Name + */ + private String loginName; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; - /** - * ID - */ - private Long userPasswordId; + /** + * ID + */ + private Long userPasswordId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserPasswordBO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserPasswordBO.java index 2e3f107ec..66d5533d4 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserPasswordBO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/bo/UserPasswordBO.java @@ -34,9 +34,9 @@ import lombok.*; @ToString(callSuper = true) public class UserPasswordBO extends BaseBO { - /** - * - */ - private String loginPassword; + /** + * + */ + private String loginPassword; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ApiBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ApiBuilder.java index 4df9546e5..2a62710f3 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ApiBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ApiBuilder.java @@ -45,146 +45,156 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface ApiBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - ApiBO buildBOByVO(ApiVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + ApiBO buildBOByVO(ApiVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "apiExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "apiTypeFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - ApiDO buildDOByBO(ApiBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "apiExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "apiTypeFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + ApiDO buildDOByBO(ApiBO entityBO); - @AfterMapping - default void afterProcess(ApiBO entityBO, @MappingTarget ApiDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getApiCode())) { - entityDO.setApiCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(ApiBO entityBO, @MappingTarget ApiDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getApiCode())) { + entityDO.setApiCode(CodeUtil.getCode()); + } - // Json Ext - ApiExt entityExt = entityBO.getApiExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setApiExt(ext); + // Json Ext + ApiExt entityExt = entityBO.getApiExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setApiExt(ext); - // ApiType Flag - ApiTypeFlagEnum apiTypeFlag = entityBO.getApiTypeFlag(); - entityDO.setApiTypeFlag(apiTypeFlag.getIndex()); - Optional.ofNullable(apiTypeFlag).ifPresent(value -> entityDO.setApiTypeFlag(value.getIndex())); + // ApiType Flag + ApiTypeFlagEnum apiTypeFlag = entityBO.getApiTypeFlag(); + entityDO.setApiTypeFlag(apiTypeFlag.getIndex()); + Optional.ofNullable(apiTypeFlag).ifPresent(value -> entityDO.setApiTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "apiExt", ignore = true) - @Mapping(target = "apiTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - ApiBO buildBOByDO(ApiDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "apiExt", ignore = true) + @Mapping(target = "apiTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + ApiBO buildBOByDO(ApiDO entityDO); - @AfterMapping - default void afterProcess(ApiDO entityDO, @MappingTarget ApiBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getApiExt(); - if (Objects.nonNull(entityExt)) { - ApiExt ext = new ApiExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ApiExt.Content.class)); - entityBO.setApiExt(ext); - } + @AfterMapping + default void afterProcess(ApiDO entityDO, @MappingTarget ApiBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getApiExt(); + if (Objects.nonNull(entityExt)) { + ApiExt ext = new ApiExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ApiExt.Content.class)); + entityBO.setApiExt(ext); + } - // ApiType Flag - Byte apiTypeFlag = entityDO.getApiTypeFlag(); - entityBO.setApiTypeFlag(ApiTypeFlagEnum.ofIndex(apiTypeFlag)); + // ApiType Flag + Byte apiTypeFlag = entityDO.getApiTypeFlag(); + entityBO.setApiTypeFlag(ApiTypeFlagEnum.ofIndex(apiTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - ApiVO buildVOByBO(ApiBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + ApiVO buildVOByBO(ApiBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/DictionaryForAuthBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/DictionaryForAuthBuilder.java index 9c0220a62..2668630bc 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/DictionaryForAuthBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/DictionaryForAuthBuilder.java @@ -33,55 +33,59 @@ import org.mapstruct.Mapping; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DictionaryForAuthBuilder extends DictionaryBuilder { - // Tenant + // Tenant - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByTenantBO(TenantBO entityBO) { - return DictionaryBO.builder().label(entityBO.getTenantName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByTenantBO(TenantBO entityBO) { + return DictionaryBO.builder().label(entityBO.getTenantName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByTenantBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByTenantBOPage(Page entityPageBO); - // + // - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByUserLoginBO(UserLoginBO entityBO) { - return DictionaryBO.builder().label(entityBO.getLoginName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByUserLoginBO(UserLoginBO entityBO) { + return DictionaryBO.builder().label(entityBO.getLoginName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByUserLoginBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByUserLoginBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/MenuBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/MenuBuilder.java index b108cbae5..8905d8a42 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/MenuBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/MenuBuilder.java @@ -46,155 +46,165 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface MenuBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - MenuBO buildBOByVO(MenuVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + MenuBO buildBOByVO(MenuVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "menuExt", ignore = true) - @Mapping(target = "menuTypeFlag", ignore = true) - @Mapping(target = "menuLevel", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - MenuDO buildDOByBO(MenuBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "menuExt", ignore = true) + @Mapping(target = "menuTypeFlag", ignore = true) + @Mapping(target = "menuLevel", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + MenuDO buildDOByBO(MenuBO entityBO); - @AfterMapping - default void afterProcess(MenuBO entityBO, @MappingTarget MenuDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getMenuCode())) { - entityDO.setMenuCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(MenuBO entityBO, @MappingTarget MenuDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getMenuCode())) { + entityDO.setMenuCode(CodeUtil.getCode()); + } - // Json Ext - MenuExt entityExt = entityBO.getMenuExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setMenuExt(ext); + // Json Ext + MenuExt entityExt = entityBO.getMenuExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setMenuExt(ext); - // MenuType Flag - MenuTypeFlagEnum menuTypeFlag = entityBO.getMenuTypeFlag(); - Optional.ofNullable(menuTypeFlag).ifPresent(value -> entityDO.setMenuTypeFlag(value.getIndex())); + // MenuType Flag + MenuTypeFlagEnum menuTypeFlag = entityBO.getMenuTypeFlag(); + Optional.ofNullable(menuTypeFlag).ifPresent(value -> entityDO.setMenuTypeFlag(value.getIndex())); - // MenuLevel Flag - MenuLevelFlagEnum menuLevel = entityBO.getMenuLevel(); - Optional.ofNullable(menuLevel).ifPresent(value -> entityDO.setMenuLevel(value.getIndex())); + // MenuLevel Flag + MenuLevelFlagEnum menuLevel = entityBO.getMenuLevel(); + Optional.ofNullable(menuLevel).ifPresent(value -> entityDO.setMenuLevel(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "menuExt", ignore = true) - @Mapping(target = "menuTypeFlag", ignore = true) - @Mapping(target = "menuLevel", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - MenuBO buildBOByDO(MenuDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "menuExt", ignore = true) + @Mapping(target = "menuTypeFlag", ignore = true) + @Mapping(target = "menuLevel", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + MenuBO buildBOByDO(MenuDO entityDO); - @AfterMapping - default void afterProcess(MenuDO entityDO, @MappingTarget MenuBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getMenuExt(); - if (Objects.nonNull(entityExt)) { - MenuExt ext = new MenuExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), MenuExt.Content.class)); - entityBO.setMenuExt(ext); - } + @AfterMapping + default void afterProcess(MenuDO entityDO, @MappingTarget MenuBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getMenuExt(); + if (Objects.nonNull(entityExt)) { + MenuExt ext = new MenuExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), MenuExt.Content.class)); + entityBO.setMenuExt(ext); + } - // MenuType Flag - Byte menuTypeFlag = entityDO.getMenuTypeFlag(); - entityBO.setMenuTypeFlag(MenuTypeFlagEnum.ofIndex(menuTypeFlag)); + // MenuType Flag + Byte menuTypeFlag = entityDO.getMenuTypeFlag(); + entityBO.setMenuTypeFlag(MenuTypeFlagEnum.ofIndex(menuTypeFlag)); - // MenuLevel Flag - Byte menuLevel = entityDO.getMenuLevel(); - entityBO.setMenuLevel(MenuLevelFlagEnum.ofIndex(menuLevel)); + // MenuLevel Flag + Byte menuLevel = entityDO.getMenuLevel(); + entityBO.setMenuLevel(MenuLevelFlagEnum.ofIndex(menuLevel)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - MenuVO buildVOByBO(MenuBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + MenuVO buildVOByBO(MenuBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ResourceBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ResourceBuilder.java index 871a39626..012ea1caf 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ResourceBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/ResourceBuilder.java @@ -46,155 +46,165 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface ResourceBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - ResourceBO buildBOByVO(ResourceVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + ResourceBO buildBOByVO(ResourceVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "resourceExt", ignore = true) - @Mapping(target = "resourceTypeFlag", ignore = true) - @Mapping(target = "resourceScopeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - ResourceDO buildDOByBO(ResourceBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "resourceExt", ignore = true) + @Mapping(target = "resourceTypeFlag", ignore = true) + @Mapping(target = "resourceScopeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + ResourceDO buildDOByBO(ResourceBO entityBO); - @AfterMapping - default void afterProcess(ResourceBO entityBO, @MappingTarget ResourceDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getResourceCode())) { - entityDO.setResourceCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(ResourceBO entityBO, @MappingTarget ResourceDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getResourceCode())) { + entityDO.setResourceCode(CodeUtil.getCode()); + } - // Json Ext - ResourceExt entityExt = entityBO.getResourceExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setResourceExt(ext); + // Json Ext + ResourceExt entityExt = entityBO.getResourceExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setResourceExt(ext); - // ResourceType Flag - ResourceTypeFlagEnum resourceTypeFlag = entityBO.getResourceTypeFlag(); - Optional.ofNullable(resourceTypeFlag).ifPresent(value -> entityDO.setResourceTypeFlag(value.getIndex())); + // ResourceType Flag + ResourceTypeFlagEnum resourceTypeFlag = entityBO.getResourceTypeFlag(); + Optional.ofNullable(resourceTypeFlag).ifPresent(value -> entityDO.setResourceTypeFlag(value.getIndex())); - // ResourceScope Flag - ResourceScopeFlagEnum resourceScopeFlag = entityBO.getResourceScopeFlag(); - Optional.ofNullable(resourceScopeFlag).ifPresent(value -> entityDO.setResourceScopeFlag(value.getIndex())); + // ResourceScope Flag + ResourceScopeFlagEnum resourceScopeFlag = entityBO.getResourceScopeFlag(); + Optional.ofNullable(resourceScopeFlag).ifPresent(value -> entityDO.setResourceScopeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "resourceExt", ignore = true) - @Mapping(target = "resourceTypeFlag", ignore = true) - @Mapping(target = "resourceScopeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - ResourceBO buildBOByDO(ResourceDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "resourceExt", ignore = true) + @Mapping(target = "resourceTypeFlag", ignore = true) + @Mapping(target = "resourceScopeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + ResourceBO buildBOByDO(ResourceDO entityDO); - @AfterMapping - default void afterProcess(ResourceDO entityDO, @MappingTarget ResourceBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getResourceExt(); - if (Objects.nonNull(entityExt)) { - ResourceExt ext = new ResourceExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ResourceExt.Content.class)); - entityBO.setResourceExt(ext); - } + @AfterMapping + default void afterProcess(ResourceDO entityDO, @MappingTarget ResourceBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getResourceExt(); + if (Objects.nonNull(entityExt)) { + ResourceExt ext = new ResourceExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ResourceExt.Content.class)); + entityBO.setResourceExt(ext); + } - // ResourceType Flag - Byte resourceTypeFlag = entityDO.getResourceTypeFlag(); - entityBO.setResourceTypeFlag(ResourceTypeFlagEnum.ofIndex(resourceTypeFlag)); + // ResourceType Flag + Byte resourceTypeFlag = entityDO.getResourceTypeFlag(); + entityBO.setResourceTypeFlag(ResourceTypeFlagEnum.ofIndex(resourceTypeFlag)); - // ResourceScope Flag - Byte resourceScopeFlag = entityDO.getResourceScopeFlag(); - entityBO.setResourceScopeFlag(ResourceScopeFlagEnum.ofIndex(resourceScopeFlag)); + // ResourceScope Flag + Byte resourceScopeFlag = entityDO.getResourceScopeFlag(); + entityBO.setResourceScopeFlag(ResourceScopeFlagEnum.ofIndex(resourceScopeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - ResourceVO buildVOByBO(ResourceBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + ResourceVO buildVOByBO(ResourceBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleBuilder.java index 6921ca534..29a7e4e51 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleBuilder.java @@ -44,136 +44,146 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface RoleBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - RoleBO buildBOByVO(RoleVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + RoleBO buildBOByVO(RoleVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "roleExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - RoleDO buildDOByBO(RoleBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "roleExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + RoleDO buildDOByBO(RoleBO entityBO); - @AfterMapping - default void afterProcess(RoleBO entityBO, @MappingTarget RoleDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getRoleCode())) { - entityDO.setRoleCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(RoleBO entityBO, @MappingTarget RoleDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getRoleCode())) { + entityDO.setRoleCode(CodeUtil.getCode()); + } - // Json Ext - RoleExt entityExt = entityBO.getRoleExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setRoleExt(ext); + // Json Ext + RoleExt entityExt = entityBO.getRoleExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setRoleExt(ext); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "roleExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - RoleBO buildBOByDO(RoleDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "roleExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + RoleBO buildBOByDO(RoleDO entityDO); - @AfterMapping - default void afterProcess(RoleDO entityDO, @MappingTarget RoleBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getRoleExt(); - if (Objects.nonNull(entityExt)) { - RoleExt ext = new RoleExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), RoleExt.Content.class)); - entityBO.setRoleExt(ext); - } + @AfterMapping + default void afterProcess(RoleDO entityDO, @MappingTarget RoleBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getRoleExt(); + if (Objects.nonNull(entityExt)) { + RoleExt ext = new RoleExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), RoleExt.Content.class)); + entityBO.setRoleExt(ext); + } - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - RoleVO buildVOByBO(RoleBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + RoleVO buildVOByBO(RoleBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleResourceBindBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleResourceBindBuilder.java index dfd6ce1b8..2fd2c1ab4 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleResourceBindBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleResourceBindBuilder.java @@ -34,90 +34,100 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface RoleResourceBindBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - RoleResourceBindBO buildBOByVO(RoleResourceBindVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + RoleResourceBindBO buildBOByVO(RoleResourceBindVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deleted", ignore = true) - RoleResourceBindDO buildDOByBO(RoleResourceBindBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deleted", ignore = true) + RoleResourceBindDO buildDOByBO(RoleResourceBindBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - RoleResourceBindBO buildBOByDO(RoleResourceBindDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + RoleResourceBindBO buildBOByDO(RoleResourceBindDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - RoleResourceBindVO buildVOByBO(RoleResourceBindBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + RoleResourceBindVO buildVOByBO(RoleResourceBindBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleUserBindBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleUserBindBuilder.java index f8a75b63d..768786232 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleUserBindBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/RoleUserBindBuilder.java @@ -34,90 +34,100 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface RoleUserBindBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - RoleUserBindBO buildBOByVO(RoleUserBindVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + RoleUserBindBO buildBOByVO(RoleUserBindVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deleted", ignore = true) - RoleUserBindDO buildDOByBO(RoleUserBindBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deleted", ignore = true) + RoleUserBindDO buildDOByBO(RoleUserBindBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - RoleUserBindBO buildBOByDO(RoleUserBindDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + RoleUserBindBO buildBOByDO(RoleUserBindDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - RoleUserBindVO buildVOByBO(RoleUserBindBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + RoleUserBindVO buildVOByBO(RoleUserBindBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBindBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBindBuilder.java index 1c7f3f3e4..8663f8106 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBindBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBindBuilder.java @@ -34,90 +34,100 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface TenantBindBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - TenantBindBO buildBOByVO(TenantBindVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + TenantBindBO buildBOByVO(TenantBindVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deleted", ignore = true) - TenantBindDO buildDOByBO(TenantBindBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deleted", ignore = true) + TenantBindDO buildDOByBO(TenantBindBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - TenantBindBO buildBOByDO(TenantBindDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + TenantBindBO buildBOByDO(TenantBindDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - TenantBindVO buildVOByBO(TenantBindBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + TenantBindVO buildVOByBO(TenantBindBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBuilder.java index 0d337b36b..fa56e10e0 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/TenantBuilder.java @@ -44,135 +44,145 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface TenantBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - TenantBO buildBOByVO(TenantVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + TenantBO buildBOByVO(TenantVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "tenantExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - TenantDO buildDOByBO(TenantBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "tenantExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + TenantDO buildDOByBO(TenantBO entityBO); - @AfterMapping - default void afterProcess(TenantBO entityBO, @MappingTarget TenantDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getTenantCode())) { - entityDO.setTenantCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(TenantBO entityBO, @MappingTarget TenantDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getTenantCode())) { + entityDO.setTenantCode(CodeUtil.getCode()); + } - // Json Ext - TenantExt entityExt = entityBO.getTenantExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setTenantExt(ext); + // Json Ext + TenantExt entityExt = entityBO.getTenantExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setTenantExt(ext); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "tenantExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - TenantBO buildBOByDO(TenantDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "tenantExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + TenantBO buildBOByDO(TenantDO entityDO); - @AfterMapping - default void afterProcess(TenantDO entityDO, @MappingTarget TenantBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getTenantExt(); - if (Objects.nonNull(entityExt)) { - TenantExt ext = new TenantExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), TenantExt.Content.class)); - entityBO.setTenantExt(ext); - } + @AfterMapping + default void afterProcess(TenantDO entityDO, @MappingTarget TenantBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getTenantExt(); + if (Objects.nonNull(entityExt)) { + TenantExt ext = new TenantExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), TenantExt.Content.class)); + entityBO.setTenantExt(ext); + } - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - TenantVO buildVOByBO(TenantBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + TenantVO buildVOByBO(TenantBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserBuilder.java index d25a5d797..ec61bc1ae 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserBuilder.java @@ -41,146 +41,156 @@ import java.util.Objects; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface UserBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - UserBO buildBOByVO(UserVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + UserBO buildBOByVO(UserVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "socialExt", ignore = true) - @Mapping(target = "identityExt", ignore = true) - @Mapping(target = "deleted", ignore = true) - UserDO buildDOByBO(UserBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "socialExt", ignore = true) + @Mapping(target = "identityExt", ignore = true) + @Mapping(target = "deleted", ignore = true) + UserDO buildDOByBO(UserBO entityBO); - @AfterMapping - default void afterProcess(UserBO entityBO, @MappingTarget UserDO entityDO) { + @AfterMapping + default void afterProcess(UserBO entityBO, @MappingTarget UserDO entityDO) { - // Json Ext - UserSocialExt entitySocialExt = entityBO.getSocialExt(); - JsonExt socialExt = new JsonExt(); - if (Objects.nonNull(entitySocialExt)) { - socialExt.setType(entitySocialExt.getType()); - socialExt.setVersion(entitySocialExt.getVersion()); - socialExt.setVersion(entitySocialExt.getVersion()); - socialExt.setRemark(entitySocialExt.getRemark()); - socialExt.setContent(JsonUtil.toJsonString(entitySocialExt.getContent())); - } - entityDO.setSocialExt(socialExt); + // Json Ext + UserSocialExt entitySocialExt = entityBO.getSocialExt(); + JsonExt socialExt = new JsonExt(); + if (Objects.nonNull(entitySocialExt)) { + socialExt.setType(entitySocialExt.getType()); + socialExt.setVersion(entitySocialExt.getVersion()); + socialExt.setVersion(entitySocialExt.getVersion()); + socialExt.setRemark(entitySocialExt.getRemark()); + socialExt.setContent(JsonUtil.toJsonString(entitySocialExt.getContent())); + } + entityDO.setSocialExt(socialExt); - UserIdentityExt entityIdentityExt = entityBO.getIdentityExt(); - JsonExt identityExt = new JsonExt(); - if (Objects.nonNull(entityIdentityExt)) { - identityExt.setType(entityIdentityExt.getType()); - identityExt.setVersion(entityIdentityExt.getVersion()); - identityExt.setVersion(entityIdentityExt.getVersion()); - identityExt.setRemark(entityIdentityExt.getRemark()); - identityExt.setContent(JsonUtil.toJsonString(entityIdentityExt.getContent())); - } - entityDO.setIdentityExt(identityExt); - } + UserIdentityExt entityIdentityExt = entityBO.getIdentityExt(); + JsonExt identityExt = new JsonExt(); + if (Objects.nonNull(entityIdentityExt)) { + identityExt.setType(entityIdentityExt.getType()); + identityExt.setVersion(entityIdentityExt.getVersion()); + identityExt.setVersion(entityIdentityExt.getVersion()); + identityExt.setRemark(entityIdentityExt.getRemark()); + identityExt.setContent(JsonUtil.toJsonString(entityIdentityExt.getContent())); + } + entityDO.setIdentityExt(identityExt); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "socialExt", ignore = true) - @Mapping(target = "identityExt", ignore = true) - UserBO buildBOByDO(UserDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "socialExt", ignore = true) + @Mapping(target = "identityExt", ignore = true) + UserBO buildBOByDO(UserDO entityDO); - @AfterMapping - default void afterProcess(UserDO entityDO, @MappingTarget UserBO entityBO) { - JsonExt entitySocialExt = entityDO.getSocialExt(); - if (Objects.nonNull(entitySocialExt)) { - UserSocialExt ext = new UserSocialExt(); - ext.setType(entitySocialExt.getType()); - ext.setVersion(entitySocialExt.getVersion()); - ext.setVersion(entitySocialExt.getVersion()); - ext.setRemark(entitySocialExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entitySocialExt.getContent(), UserSocialExt.Content.class)); - entityBO.setSocialExt(ext); - } + @AfterMapping + default void afterProcess(UserDO entityDO, @MappingTarget UserBO entityBO) { + JsonExt entitySocialExt = entityDO.getSocialExt(); + if (Objects.nonNull(entitySocialExt)) { + UserSocialExt ext = new UserSocialExt(); + ext.setType(entitySocialExt.getType()); + ext.setVersion(entitySocialExt.getVersion()); + ext.setVersion(entitySocialExt.getVersion()); + ext.setRemark(entitySocialExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entitySocialExt.getContent(), UserSocialExt.Content.class)); + entityBO.setSocialExt(ext); + } - JsonExt entityIdentityExt = entityDO.getIdentityExt(); - if (Objects.nonNull(entityIdentityExt)) { - UserIdentityExt ext = new UserIdentityExt(); - ext.setType(entityIdentityExt.getType()); - ext.setVersion(entityIdentityExt.getVersion()); - ext.setVersion(entityIdentityExt.getVersion()); - ext.setRemark(entityIdentityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityIdentityExt.getContent(), UserIdentityExt.Content.class)); - entityBO.setIdentityExt(ext); - } - } + JsonExt entityIdentityExt = entityDO.getIdentityExt(); + if (Objects.nonNull(entityIdentityExt)) { + UserIdentityExt ext = new UserIdentityExt(); + ext.setType(entityIdentityExt.getType()); + ext.setVersion(entityIdentityExt.getVersion()); + ext.setVersion(entityIdentityExt.getVersion()); + ext.setRemark(entityIdentityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityIdentityExt.getContent(), UserIdentityExt.Content.class)); + entityBO.setIdentityExt(ext); + } + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - UserVO buildVOByBO(UserBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + UserVO buildVOByBO(UserBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserLoginBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserLoginBuilder.java index 9563e5a1a..ed6065bdd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserLoginBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserLoginBuilder.java @@ -38,106 +38,116 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface UserLoginBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - UserLoginBO buildBOByVO(UserLoginVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + UserLoginBO buildBOByVO(UserLoginVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - UserLoginDO buildDOByBO(UserLoginBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + UserLoginDO buildDOByBO(UserLoginBO entityBO); - @AfterMapping - default void afterProcess(UserLoginBO entityBO, @MappingTarget UserLoginDO entityDO) { - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + @AfterMapping + default void afterProcess(UserLoginBO entityBO, @MappingTarget UserLoginDO entityDO) { + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO collection - * @return EntityDO collection - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO collection + * @return EntityDO collection + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "enableFlag", ignore = true) - UserLoginBO buildBOByDO(UserLoginDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "enableFlag", ignore = true) + UserLoginBO buildBOByDO(UserLoginDO entityDO); - @AfterMapping - default void afterProcess(UserLoginDO entityDO, @MappingTarget UserLoginBO entityBO) { - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + @AfterMapping + default void afterProcess(UserLoginDO entityDO, @MappingTarget UserLoginBO entityBO) { + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO collection - * @return EntityBO collection - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO collection + * @return EntityBO collection + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - UserLoginVO buildVOByBO(UserLoginBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + UserLoginVO buildVOByBO(UserLoginBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserPasswordBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserPasswordBuilder.java index 605931b7a..1102788ce 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserPasswordBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/builder/UserPasswordBuilder.java @@ -34,90 +34,100 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface UserPasswordBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - UserPasswordBO buildBOByVO(UserPasswordVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + UserPasswordBO buildBOByVO(UserPasswordVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deleted", ignore = true) - UserPasswordDO buildDOByBO(UserPasswordBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deleted", ignore = true) + UserPasswordDO buildDOByBO(UserPasswordBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - UserPasswordBO buildBOByDO(UserPasswordDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + UserPasswordBO buildBOByDO(UserPasswordDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - UserPasswordVO buildVOByBO(UserPasswordBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + UserPasswordVO buildVOByBO(UserPasswordBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ApiDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ApiDO.java index 492bbedc4..855bce00a 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ApiDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ApiDO.java @@ -43,104 +43,104 @@ import java.time.LocalDateTime; @TableName(value = "dc3_api", autoResultMap = true) public class ApiDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Owning service name, populated by resource registrar - */ - @TableField("service_name") - private String serviceName; + /** + * Owning service name, populated by resource registrar + */ + @TableField("service_name") + private String serviceName; - /** - * Type - */ - @TableField("api_type_flag") - private Byte apiTypeFlag; + /** + * Type + */ + @TableField("api_type_flag") + private Byte apiTypeFlag; - /** - * Name - */ - @TableField("api_name") - private String apiName; + /** + * Name + */ + @TableField("api_name") + private String apiName; - /** - * Code - */ - @TableField("api_code") - private String apiCode; + /** + * Code + */ + @TableField("api_code") + private String apiCode; - /** - * API grouping, usually the owning controller simple class name - */ - @TableField("api_group") - private String apiGroup; + /** + * API grouping, usually the owning controller simple class name + */ + @TableField("api_group") + private String apiGroup; - /** - * - */ - @TableField(value = "api_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt apiExt; + /** + * + */ + @TableField(value = "api_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt apiExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/DriverTokenDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/DriverTokenDO.java index d56943afe..a22e21b91 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/DriverTokenDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/DriverTokenDO.java @@ -41,104 +41,104 @@ import java.time.LocalDateTime; @TableName("dc3_driver_token") public class DriverTokenDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Driver ID - */ - @TableField("driver_code") - private String driverCode; + /** + * Driver ID + */ + @TableField("driver_code") + private String driverCode; - /** - * AppID - */ - @TableField("driver_app_id") - private String driverAppId; + /** + * AppID + */ + @TableField("driver_app_id") + private String driverAppId; - /** - * AppKey - */ - @TableField("driver_app_key") - private String driverAppKey; + /** + * AppKey + */ + @TableField("driver_app_key") + private String driverAppKey; - /** - * - */ - @TableField("expire_flag") - private Byte expireFlag; + /** + * + */ + @TableField("expire_flag") + private Byte expireFlag; - /** - * - */ - @TableField("expire_time") - private LocalDateTime expireTime; + /** + * + */ + @TableField("expire_time") + private LocalDateTime expireTime; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/MenuDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/MenuDO.java index a788a7401..3fe9b9640 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/MenuDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/MenuDO.java @@ -43,110 +43,110 @@ import java.time.LocalDateTime; @TableName(value = "dc3_menu", autoResultMap = true) public class MenuDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("parent_menu_id") - private Long parentMenuId; + /** + * ID + */ + @TableField("parent_menu_id") + private Long parentMenuId; - /** - * Type - */ - @TableField("menu_type_flag") - private Byte menuTypeFlag; + /** + * Type + */ + @TableField("menu_type_flag") + private Byte menuTypeFlag; - /** - * Name - */ - @TableField("menu_name") - private String menuName; + /** + * Name + */ + @TableField("menu_name") + private String menuName; - /** - * Code - */ - @TableField("menu_code") - private String menuCode; + /** + * Code + */ + @TableField("menu_code") + private String menuCode; - /** - * - */ - @TableField("menu_level") - private Byte menuLevel; + /** + * + */ + @TableField("menu_level") + private Byte menuLevel; - /** - * - */ - @TableField("menu_index") - private Byte menuIndex; + /** + * + */ + @TableField("menu_index") + private Byte menuIndex; - /** - * - */ - @TableField(value = "menu_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt menuExt; + /** + * + */ + @TableField(value = "menu_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt menuExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ResourceDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ResourceDO.java index 657f20fa8..10327551b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ResourceDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/ResourceDO.java @@ -43,110 +43,110 @@ import java.time.LocalDateTime; @TableName(value = "dc3_resource", autoResultMap = true) public class ResourceDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("parent_resource_id") - private Long parentResourceId; + /** + * ID + */ + @TableField("parent_resource_id") + private Long parentResourceId; - /** - * Name - */ - @TableField("resource_name") - private String resourceName; + /** + * Name + */ + @TableField("resource_name") + private String resourceName; - /** - * Code - */ - @TableField("resource_code") - private String resourceCode; + /** + * Code + */ + @TableField("resource_code") + private String resourceCode; - /** - * Type - */ - @TableField("resource_type_flag") - private Byte resourceTypeFlag; + /** + * Type + */ + @TableField("resource_type_flag") + private Byte resourceTypeFlag; - /** - * - */ - @TableField("resource_scope_flag") - private Byte resourceScopeFlag; + /** + * + */ + @TableField("resource_scope_flag") + private Byte resourceScopeFlag; - /** - * Entity ID - */ - @TableField("entity_id") - private Long entityId; + /** + * Entity ID + */ + @TableField("entity_id") + private Long entityId; - /** - * - */ - @TableField(value = "resource_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt resourceExt; + /** + * + */ + @TableField(value = "resource_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt resourceExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleDO.java index 38337f80b..353088d7b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleDO.java @@ -43,98 +43,98 @@ import java.time.LocalDateTime; @TableName(value = "dc3_role", autoResultMap = true) public class RoleDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("parent_role_id") - private Long parentRoleId; + /** + * ID + */ + @TableField("parent_role_id") + private Long parentRoleId; - /** - * Name - */ - @TableField("role_name") - private String roleName; + /** + * Name + */ + @TableField("role_name") + private String roleName; - /** - * Code - */ - @TableField("role_code") - private String roleCode; + /** + * Code + */ + @TableField("role_code") + private String roleCode; - /** - * - */ - @TableField(value = "role_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt roleExt; + /** + * + */ + @TableField(value = "role_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt roleExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleResourceBindDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleResourceBindDO.java index 935294a73..8237f5b82 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleResourceBindDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleResourceBindDO.java @@ -41,74 +41,74 @@ import java.time.LocalDateTime; @TableName("dc3_role_resource_bind") public class RoleResourceBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("role_id") - private Long roleId; + /** + * ID + */ + @TableField("role_id") + private Long roleId; - /** - * ID - */ - @TableField("resource_id") - private Long resourceId; + /** + * ID + */ + @TableField("resource_id") + private Long resourceId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleUserBindDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleUserBindDO.java index 2983db62b..39c4181b9 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleUserBindDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/RoleUserBindDO.java @@ -41,74 +41,74 @@ import java.time.LocalDateTime; @TableName("dc3_role_user_bind") public class RoleUserBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("role_id") - private Long roleId; + /** + * ID + */ + @TableField("role_id") + private Long roleId; - /** - * ID - */ - @TableField("user_id") - private Long userId; + /** + * ID + */ + @TableField("user_id") + private Long userId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantBindDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantBindDO.java index 95cc484b4..0a0658a28 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantBindDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantBindDO.java @@ -41,74 +41,74 @@ import java.time.LocalDateTime; @TableName("dc3_tenant_bind") public class TenantBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * ID - */ - @TableField("user_id") - private Long userId; + /** + * ID + */ + @TableField("user_id") + private Long userId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantDO.java index b9c03e81e..ddf946a3b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/TenantDO.java @@ -43,86 +43,86 @@ import java.time.LocalDateTime; @TableName(value = "dc3_tenant", autoResultMap = true) public class TenantDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * TenantName - */ - @TableField("tenant_name") - private String tenantName; + /** + * TenantName + */ + @TableField("tenant_name") + private String tenantName; - /** - * TenantCode - */ - @TableField("tenant_code") - private String tenantCode; + /** + * TenantCode + */ + @TableField("tenant_code") + private String tenantCode; - /** - * Tenant - */ - @TableField(value = "tenant_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt tenantExt; + /** + * Tenant + */ + @TableField(value = "tenant_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt tenantExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserDO.java index d094f0d87..7bf4ef1a3 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserDO.java @@ -43,104 +43,104 @@ import java.time.LocalDateTime; @TableName(value = "dc3_user", autoResultMap = true) public class UserDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID. - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID. + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Username. - */ - @TableField("user_name") - private String userName; + /** + * Username. + */ + @TableField("user_name") + private String userName; - /** - * User nickname. - */ - @TableField("nick_name") - private String nickName; + /** + * User nickname. + */ + @TableField("nick_name") + private String nickName; - /** - * Phone number. - */ - @TableField("phone") - private String phone; + /** + * Phone number. + */ + @TableField("phone") + private String phone; - /** - * Email address. - */ - @TableField("email") - private String email; + /** + * Email address. + */ + @TableField("email") + private String email; - /** - * Social-related extension information. - */ - @TableField(value = "social_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt socialExt; + /** + * Social-related extension information. + */ + @TableField(value = "social_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt socialExt; - /** - * Identity-related extension information. - */ - @TableField(value = "identity_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt identityExt; + /** + * Identity-related extension information. + */ + @TableField(value = "identity_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt identityExt; - /** - * Enable flag, {@code 0} for enabled, {@code 1} for disabled. - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, {@code 0} for enabled, {@code 1} for disabled. + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Remark or description. - */ - @TableField("remark") - private String remark; + /** + * Remark or description. + */ + @TableField("remark") + private String remark; - /** - * Creator ID. - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID. + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator name. - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator name. + */ + @TableField("creator_name") + private String creatorName; - /** - * Creation time. - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Creation time. + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID. - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID. + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator name. - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator name. + */ + @TableField("operator_name") + private String operatorName; - /** - * Operation time. - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operation time. + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserLoginDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserLoginDO.java index 6c94b3ca7..941552a05 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserLoginDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserLoginDO.java @@ -41,86 +41,86 @@ import java.time.LocalDateTime; @TableName("dc3_user_login") public class UserLoginDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name, - */ - @TableField("login_name") - private String loginName; + /** + * Name, + */ + @TableField("login_name") + private String loginName; - /** - * ID - */ - @TableField("user_id") - private Long userId; + /** + * ID + */ + @TableField("user_id") + private Long userId; - /** - * ID - */ - @TableField("user_password_id") - private Long userPasswordId; + /** + * ID + */ + @TableField("user_password_id") + private Long userPasswordId; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserPasswordDO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserPasswordDO.java index 8f1cbc71e..10ae3c49f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserPasswordDO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/model/UserPasswordDO.java @@ -41,68 +41,68 @@ import java.time.LocalDateTime; @TableName("dc3_user_password") public class UserPasswordDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * - */ - @TableField("login_password") - private String loginPassword; + /** + * + */ + @TableField("login_password") + private String loginPassword; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ApiQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ApiQuery.java index 843fe3f45..d3288c043 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ApiQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ApiQuery.java @@ -38,41 +38,41 @@ import java.io.Serializable; @AllArgsConstructor public class ApiQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * Owning service name, populated by resource registrar - */ - private String serviceName; + /** + * Owning service name, populated by resource registrar + */ + private String serviceName; - /** - * ApiType - */ - private ApiTypeFlagEnum apiTypeFlag; + /** + * ApiType + */ + private ApiTypeFlagEnum apiTypeFlag; - /** - * ApiName - */ - private String apiName; + /** + * ApiName + */ + private String apiName; - /** - * ApiCode, URLMD5 - */ - private String apiCode; + /** + * ApiCode, URLMD5 + */ + private String apiCode; - /** - * API grouping, usually the owning controller simple class name - */ - private String apiGroup; + /** + * API grouping, usually the owning controller simple class name + */ + private String apiGroup; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/DriverTokenQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/DriverTokenQuery.java index a96469b71..61269dcc2 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/DriverTokenQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/DriverTokenQuery.java @@ -40,36 +40,36 @@ import java.io.Serializable; @AllArgsConstructor public class DriverTokenQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * AppID - */ - private String driverAppId; + /** + * AppID + */ + private String driverAppId; - /** - * - */ - private ExpireFlagEnum expireFlag; + /** + * + */ + private ExpireFlagEnum expireFlag; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/MenuQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/MenuQuery.java index ff8333e63..1443f5714 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/MenuQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/MenuQuery.java @@ -38,36 +38,36 @@ import java.io.Serializable; @AllArgsConstructor public class MenuQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * Parent menu id filter (optional). - */ - private Long parentMenuId; + /** + * Parent menu id filter (optional). + */ + private Long parentMenuId; - /** - * Type - */ - private MenuTypeFlagEnum menuTypeFlag; + /** + * Type + */ + private MenuTypeFlagEnum menuTypeFlag; - /** - * Name - */ - private String menuName; + /** + * Name + */ + private String menuName; - /** - * Code, URLMD5 - */ - private String menuCode; + /** + * Code, URLMD5 + */ + private String menuCode; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ResourceQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ResourceQuery.java index eb90a7535..0210c5fbd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ResourceQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/ResourceQuery.java @@ -40,59 +40,59 @@ import java.util.List; @AllArgsConstructor public class ResourceQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * Name - */ - private String resourceName; + /** + * Name + */ + private String resourceName; - /** - * Code - */ - private String resourceCode; + /** + * Code + */ + private String resourceCode; - /** - * Type - */ - private ResourceTypeFlagEnum resourceTypeFlag; + /** + * Type + */ + private ResourceTypeFlagEnum resourceTypeFlag; - /** - * Type multi-select — takes precedence over {@link #resourceTypeFlag} when non-empty. - */ - private List resourceTypeFlags; + /** + * Type multi-select — takes precedence over {@link #resourceTypeFlag} when non-empty. + */ + private List resourceTypeFlags; - /** - * , : ResourceScopeFlagEnum - *
    - *
  • 0x01:
  • - *
  • 0x02:
  • - *
  • 0x04:
  • - *
  • 0x08:
  • - *
- * - */ - private Byte resourceScopeFlag; + /** + * , : ResourceScopeFlagEnum + *
    + *
  • 0x01:
  • + *
  • 0x02:
  • + *
  • 0x04:
  • + *
  • 0x08:
  • + *
+ * + */ + private Byte resourceScopeFlag; - /** - * Scope multi-select — takes precedence over {@link #resourceScopeFlag} when - * non-empty. - */ - private List resourceScopeFlags; + /** + * Scope multi-select — takes precedence over {@link #resourceScopeFlag} when + * non-empty. + */ + private List resourceScopeFlags; - /** - * Parent resource id filter (optional). - */ - private Long parentResourceId; + /** + * Parent resource id filter (optional). + */ + private Long parentResourceId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleQuery.java index 15f4366f2..78c5855bc 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleQuery.java @@ -37,31 +37,31 @@ import java.io.Serializable; @AllArgsConstructor public class RoleQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String roleName; + /** + * Name + */ + private String roleName; - /** - * Code - */ - private String roleCode; + /** + * Code + */ + private String roleCode; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleResourceBindQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleResourceBindQuery.java index 241045685..4ffe75872 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleResourceBindQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleResourceBindQuery.java @@ -36,21 +36,21 @@ import java.io.Serializable; @AllArgsConstructor public class RoleResourceBindQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * ID - */ - private Long roleId; + /** + * ID + */ + private Long roleId; - /** - * ID - */ - private Long resourceId; + /** + * ID + */ + private Long resourceId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleUserBindQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleUserBindQuery.java index ad064c304..248a5df05 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleUserBindQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/RoleUserBindQuery.java @@ -36,21 +36,21 @@ import java.io.Serializable; @AllArgsConstructor public class RoleUserBindQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * ID - */ - private Long roleId; + /** + * ID + */ + private Long roleId; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantBindQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantBindQuery.java index 308dfb100..53ae32450 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantBindQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantBindQuery.java @@ -38,21 +38,21 @@ import java.io.Serializable; @AllArgsConstructor public class TenantBindQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantQuery.java index c26c21100..036d4a8c9 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TenantQuery.java @@ -39,26 +39,26 @@ import java.io.Serializable; @AllArgsConstructor public class TenantQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * TenantName - */ - private String tenantName; + /** + * TenantName + */ + private String tenantName; - /** - * TenantCode - */ - private String tenantCode; + /** + * TenantCode + */ + private String tenantCode; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TokenQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TokenQuery.java index 840a74182..ab709c557 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TokenQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/TokenQuery.java @@ -38,31 +38,31 @@ import lombok.Setter; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class TokenQuery { - /** - * Tenant - */ - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的租户编号") - private String tenant; + /** + * Tenant + */ + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的租户编号") + private String tenant; - /** - * - */ - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的用户登录名") - private String name; + /** + * + */ + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的用户登录名") + private String name; - /** - * - */ - private String salt; + /** + * + */ + private String salt; - /** - * - */ - private String password; + /** + * + */ + private String password; - /** - * - */ - private String token; + /** + * + */ + private String token; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserLoginQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserLoginQuery.java index 10ed72d5c..c123732df 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserLoginQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserLoginQuery.java @@ -39,31 +39,31 @@ import java.io.Serializable; @AllArgsConstructor public class UserLoginQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * Name - */ - private String loginName; + /** + * Name + */ + private String loginName; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; - /** - * ID - */ - private Long userPasswordId; + /** + * ID + */ + private Long userPasswordId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserPasswordQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserPasswordQuery.java index a48230bf3..23e04fc2c 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserPasswordQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserPasswordQuery.java @@ -38,16 +38,16 @@ import java.io.Serializable; @AllArgsConstructor public class UserPasswordQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - // + // - /** - * - */ - private String loginPassword; + /** + * + */ + private String loginPassword; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserQuery.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserQuery.java index cfee08ab7..acac7ebbd 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserQuery.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/query/UserQuery.java @@ -38,40 +38,40 @@ import java.io.Serializable; @AllArgsConstructor public class UserQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant scope. Populated by the controller from the request context; any value - * supplied by the client is overwritten so a caller cannot reach across tenants. - */ - private Long tenantId; + /** + * Tenant scope. Populated by the controller from the request context; any value + * supplied by the client is overwritten so a caller cannot reach across tenants. + */ + private Long tenantId; - /** - * - */ - private String nickName; + /** + * + */ + private String nickName; - /** - * Name - */ - private String userName; + /** + * Name + */ + private String userName; - /** - * - */ - private String phone; + /** + * + */ + private String phone; - /** - * - */ - private String email; + /** + * + */ + private String email; - /** - * Enable flag, 0 enabled, 1 disabled - */ - private Byte enableFlag; + /** + * Enable flag, 0 enabled, 1 disabled + */ + private Byte enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ApiVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ApiVO.java index d2dcc082e..315ff8f07 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ApiVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ApiVO.java @@ -44,41 +44,41 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ApiVO extends BaseVO { - /** - * Owning service name, populated by resource registrar - */ - private String serviceName; + /** + * Owning service name, populated by resource registrar + */ + private String serviceName; - /** - * ApiType - */ - private ApiTypeFlagEnum apiTypeFlag; + /** + * ApiType + */ + private ApiTypeFlagEnum apiTypeFlag; - /** - * ApiName - */ - @NotBlank(message = "Api接口名称不能为空", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效接口名称", groups = { Add.class, Update.class }) - private String apiName; + /** + * ApiName + */ + @NotBlank(message = "Api接口名称不能为空", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效接口名称", groups = {Add.class, Update.class}) + private String apiName; - /** - * ApiCode, URLMD5 - */ - private String apiCode; + /** + * ApiCode, URLMD5 + */ + private String apiCode; - /** - * API grouping, usually the owning controller simple class name - */ - private String apiGroup; + /** + * API grouping, usually the owning controller simple class name + */ + private String apiGroup; - /** - * Api - */ - private ApiExt apiExt; + /** + * Api + */ + private ApiExt apiExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/DriverTokenVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/DriverTokenVO.java index 4b6784e23..674491468 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/DriverTokenVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/DriverTokenVO.java @@ -40,34 +40,34 @@ import java.time.LocalDateTime; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DriverTokenVO extends BaseVO { - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * AppID - */ - private String driverAppId; + /** + * AppID + */ + private String driverAppId; - /** - * AppKey - */ - private String driverAppKey; + /** + * AppKey + */ + private String driverAppKey; - /** - * - */ - private ExpireFlagEnum expireFlag; + /** + * + */ + private ExpireFlagEnum expireFlag; - /** - * - */ - private LocalDateTime expireTime; + /** + * + */ + private LocalDateTime expireTime; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuTreeVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuTreeVO.java index 99dc9f01d..81d8e3cea 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuTreeVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuTreeVO.java @@ -39,6 +39,6 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class MenuTreeVO extends MenuVO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuVO.java index f622d6fc9..4b3ebe457 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/MenuVO.java @@ -45,48 +45,48 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class MenuVO extends BaseVO { - /** - * ID - */ - @NotBlank(message = "Menu parent id can't be empty", groups = { Add.class, Update.class }) - private Long parentMenuId; + /** + * ID + */ + @NotBlank(message = "Menu parent id can't be empty", groups = {Add.class, Update.class}) + private Long parentMenuId; - /** - * Type - */ - private MenuTypeFlagEnum menuTypeFlag; + /** + * Type + */ + private MenuTypeFlagEnum menuTypeFlag; - /** - * Name - */ - @NotBlank(message = "Menu name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid menu name", - groups = { Add.class, Update.class }) - private String menuName; + /** + * Name + */ + @NotBlank(message = "Menu name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid menu name", + groups = {Add.class, Update.class}) + private String menuName; - /** - * Code, URLMD5 - */ - private String menuCode; + /** + * Code, URLMD5 + */ + private String menuCode; - /** - * - */ - private MenuLevelFlagEnum menuLevel; + /** + * + */ + private MenuLevelFlagEnum menuLevel; - /** - * - */ - private Integer menuIndex; + /** + * + */ + private Integer menuIndex; - /** - * - */ - private MenuExt menuExt; + /** + * + */ + private MenuExt menuExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceTreeVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceTreeVO.java index f18256fbd..895290ff3 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceTreeVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceTreeVO.java @@ -39,6 +39,6 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ResourceTreeVO extends ResourceVO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceVO.java index ce622cf9c..b640781fc 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/ResourceVO.java @@ -46,56 +46,56 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ResourceVO extends BaseVO { - /** - * ID - */ - @NotBlank(message = "Resource parent id can't be empty", groups = { Add.class, Update.class }) - private Long parentResourceId; + /** + * ID + */ + @NotBlank(message = "Resource parent id can't be empty", groups = {Add.class, Update.class}) + private Long parentResourceId; - /** - * Name - */ - @NotBlank(message = "Role name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid role name", - groups = { Add.class, Update.class }) - private String resourceName; + /** + * Name + */ + @NotBlank(message = "Role name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid role name", + groups = {Add.class, Update.class}) + private String resourceName; - /** - * Code - */ - private String resourceCode; + /** + * Code + */ + private String resourceCode; - /** - * Type - */ - private ResourceTypeFlagEnum resourceTypeFlag; + /** + * Type + */ + private ResourceTypeFlagEnum resourceTypeFlag; - /** - * , : ResourceScopeFlagEnum - *
    - *
  • 0x01:
  • - *
  • 0x02:
  • - *
  • 0x04:
  • - *
  • 0x08:
  • - *
- * - */ - private ResourceScopeFlagEnum resourceScopeFlag; + /** + * , : ResourceScopeFlagEnum + *
    + *
  • 0x01:
  • + *
  • 0x02:
  • + *
  • 0x04:
  • + *
  • 0x08:
  • + *
+ * + */ + private ResourceScopeFlagEnum resourceScopeFlag; - /** - * Entity ID - */ - @NotNull(message = "实体ID不能为空", groups = { Add.class, Update.class }) - private Long entityId; + /** + * Entity ID + */ + @NotNull(message = "实体ID不能为空", groups = {Add.class, Update.class}) + private Long entityId; - /** - * - */ - private ResourceExt resourceExt; + /** + * + */ + private ResourceExt resourceExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleResourceBindVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleResourceBindVO.java index 9c082a80e..3f01d5545 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleResourceBindVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleResourceBindVO.java @@ -39,16 +39,16 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RoleResourceBindVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "Role id can't be empty", groups = { Add.class, Update.class }) - private Long roleId; + /** + * ID + */ + @NotNull(message = "Role id can't be empty", groups = {Add.class, Update.class}) + private Long roleId; - /** - * ID - */ - @NotNull(message = "Resource id can't be empty", groups = { Add.class, Update.class }) - private Long resourceId; + /** + * ID + */ + @NotNull(message = "Resource id can't be empty", groups = {Add.class, Update.class}) + private Long resourceId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleTreeVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleTreeVO.java index 4f410ba12..65e82042a 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleTreeVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleTreeVO.java @@ -39,6 +39,6 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RoleTreeVO extends RoleVO { - private List children = new ArrayList<>(); + private List children = new ArrayList<>(); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleUserBindVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleUserBindVO.java index 3fd379d6d..31568237f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleUserBindVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleUserBindVO.java @@ -39,16 +39,16 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RoleUserBindVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "Role id can't be empty", groups = { Add.class, Update.class }) - private Long roleId; + /** + * ID + */ + @NotNull(message = "Role id can't be empty", groups = {Add.class, Update.class}) + private Long roleId; - /** - * ID - */ - @NotNull(message = "User id can't be empty", groups = { Add.class, Update.class }) - private Long userId; + /** + * ID + */ + @NotNull(message = "User id can't be empty", groups = {Add.class, Update.class}) + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleVO.java index b66bf80e4..3523fd406 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/RoleVO.java @@ -44,33 +44,33 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RoleVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "Role parent id can't be empty", groups = { Add.class, Update.class }) - private Long parentRoleId; + /** + * ID + */ + @NotNull(message = "Role parent id can't be empty", groups = {Add.class, Update.class}) + private Long parentRoleId; - /** - * Name - */ - @NotBlank(message = "Role name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid role name", - groups = { Add.class, Update.class }) - private String roleName; + /** + * Name + */ + @NotBlank(message = "Role name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid role name", + groups = {Add.class, Update.class}) + private String roleName; - /** - * Code - */ - private String roleCode; + /** + * Code + */ + private String roleCode; - /** - * - */ - private RoleExt roleExt; + /** + * + */ + private RoleExt roleExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantBindVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantBindVO.java index d23cce1b2..17ad14c50 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantBindVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantBindVO.java @@ -39,16 +39,16 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class TenantBindVO extends BaseVO { - /** - * Tenant ID - */ - @NotNull(message = "Tenant id can't be empty", groups = { Add.class, Update.class }) - private Long tenantId; + /** + * Tenant ID + */ + @NotNull(message = "Tenant id can't be empty", groups = {Add.class, Update.class}) + private Long tenantId; - /** - * ID - */ - @NotNull(message = "User id can't be empty", groups = { Add.class, Update.class }) - private Long userId; + /** + * ID + */ + @NotNull(message = "User id can't be empty", groups = {Add.class, Update.class}) + private Long userId; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantVO.java index 920bf093e..f6ad1d4d4 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/TenantVO.java @@ -43,30 +43,30 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class TenantVO extends BaseVO { - /** - * TenantName - */ - @NotBlank(message = "Tenant name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", - message = "Invalid tenant name", groups = { Add.class, Update.class }) - private String tenantName; + /** + * TenantName + */ + @NotBlank(message = "Tenant name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", + message = "Invalid tenant name", groups = {Add.class, Update.class}) + private String tenantName; - /** - * TenantCode - */ - @NotBlank(message = "Tenant code can't be empty", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid tenant code", - groups = { Add.class, Update.class }) - private String tenantCode; + /** + * TenantCode + */ + @NotBlank(message = "Tenant code can't be empty", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid tenant code", + groups = {Add.class, Update.class}) + private String tenantCode; - /** - * Tenant - */ - private TenantExt tenantExt; + /** + * Tenant + */ + private TenantExt tenantExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserLoginVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserLoginVO.java index 90fe2620e..5bf3ef77a 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserLoginVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserLoginVO.java @@ -37,24 +37,24 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class UserLoginVO extends BaseVO { - /** - * Name - */ - private String loginName; + /** + * Name + */ + private String loginName; - /** - * ID - */ - private Long userId; + /** + * ID + */ + private Long userId; - /** - * ID - */ - private String userPasswordId; + /** + * ID + */ + private String userPasswordId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserPasswordVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserPasswordVO.java index 7b3b4747d..5b5356096 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserPasswordVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserPasswordVO.java @@ -41,11 +41,11 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class UserPasswordVO extends BaseVO { - /** - * - */ - @NotBlank(message = "Login password can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[a-zA-Z]\\w{7,15}$", message = "Invalid login password", groups = { Add.class, Update.class }) - private String loginPassword; + /** + * + */ + @NotBlank(message = "Login password can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[a-zA-Z]\\w{7,15}$", message = "Invalid login password", groups = {Add.class, Update.class}) + private String loginPassword; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserVO.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserVO.java index 02d5c3ffb..07f568608 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserVO.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/entity/vo/UserVO.java @@ -43,48 +43,48 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class UserVO extends BaseVO { - /** - * - */ - @NotBlank(message = "Nick name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", - message = "Invalid nick name", groups = { Add.class, Update.class }) - private String nickName; + /** + * + */ + @NotBlank(message = "Nick name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", + message = "Invalid nick name", groups = {Add.class, Update.class}) + private String nickName; - /** - * Name - */ - @NotBlank(message = "User name can't be empty", groups = { Add.class, Auth.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid user name", - groups = { Add.class, Update.class }) - private String userName; + /** + * Name + */ + @NotBlank(message = "User name can't be empty", groups = {Add.class, Auth.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "Invalid user name", + groups = {Add.class, Update.class}) + private String userName; - /** - * - */ - @Pattern(regexp = "^1([3-9])\\d{9}$", message = "Invalid phone", groups = { Add.class, Update.class }) - private String phone; + /** + * + */ + @Pattern(regexp = "^1([3-9])\\d{9}$", message = "Invalid phone", groups = {Add.class, Update.class}) + private String phone; - /** - * - */ - @Pattern(regexp = "^[A-Za-z0-9_.-]+@[A-Za-z0-9]+\\.[A-Za-z0-9]+$", message = "Invalid email", - groups = { Add.class, Update.class }) - private String email; + /** + * + */ + @Pattern(regexp = "^[A-Za-z0-9_.-]+@[A-Za-z0-9]+\\.[A-Za-z0-9]+$", message = "Invalid email", + groups = {Add.class, Update.class}) + private String email; - /** - * - */ - private UserSocialExt socialExt; + /** + * + */ + private UserSocialExt socialExt; - /** - * - */ - private UserIdentityExt identityExt; + /** + * + */ + private UserIdentityExt identityExt; - /** - * Enable flag, 0:, 1:Disable - */ - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + private Byte enableFlag; } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/generator/MybatisGenerator.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/generator/MybatisGenerator.java index 3ae4579a9..8ec0a19fc 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/generator/MybatisGenerator.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/generator/MybatisGenerator.java @@ -35,29 +35,29 @@ import io.github.pnoker.common.utils.MybatisUtil; */ public class MybatisGenerator { - public static void main(String[] args) { - generator(); - } + public static void main(String[] args) { + generator(); + } - public static void generator() { - String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-auth/src/main"; - MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_auth", "dc3", "dc3dc3dc3") - .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) - .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) - .packageConfig(builder -> builder.parent("io.github.pnoker.common.auth") - .entity("entity.model") - .service("dal") - .serviceImpl("dal.impl") - .mapper("mapper") - .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/auth/dal", - OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/auth/dal/impl", OutputFile.xml, - path + "/resources/mapping"))) - .templateEngine(new FreemarkerTemplateEngine()) - .strategyConfig(MybatisUtil::defaultStrategyConfig) - .strategyConfig(builder -> builder.addInclude("dc3_api", "dc3_menu", "dc3_resource", "dc3_role", - "dc3_role_resource_bind", "dc3_role_user_bind", "dc3_driver_token", "dc3_tenant", "dc3_tenant_bind", - "dc3_user", "dc3_user_login", "dc3_user_password")) - .execute(); - } + public static void generator() { + String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-auth/src/main"; + MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_auth", "dc3", "dc3dc3dc3") + .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) + .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) + .packageConfig(builder -> builder.parent("io.github.pnoker.common.auth") + .entity("entity.model") + .service("dal") + .serviceImpl("dal.impl") + .mapper("mapper") + .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/auth/dal", + OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/auth/dal/impl", OutputFile.xml, + path + "/resources/mapping"))) + .templateEngine(new FreemarkerTemplateEngine()) + .strategyConfig(MybatisUtil::defaultStrategyConfig) + .strategyConfig(builder -> builder.addInclude("dc3_api", "dc3_menu", "dc3_resource", "dc3_role", + "dc3_role_resource_bind", "dc3_role_user_bind", "dc3_driver_token", "dc3_tenant", "dc3_tenant_bind", + "dc3_user", "dc3_user_login", "dc3_user_password")) + .execute(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/ResourceRegistryServer.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/ResourceRegistryServer.java index ffa4c1f7f..258d6568b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/ResourceRegistryServer.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/ResourceRegistryServer.java @@ -43,55 +43,54 @@ import java.util.List; @Service public class ResourceRegistryServer extends ResourceRegistryApiGrpc.ResourceRegistryApiImplBase { - @Resource - private ResourceRegistrySyncService resourceRegistrySyncService; + @Resource + private ResourceRegistrySyncService resourceRegistrySyncService; - private static List toScannedApis(List dtos) { - List apis = new ArrayList<>(dtos.size()); - for (GrpcScannedApiDTO dto : dtos) { - apis.add(ResourceRegistryScannedApi.builder() - .method(dto.getMethod()) - .path(dto.getPath()) - .apiName(dto.getApiName()) - .title(dto.getTitle()) - .remark(dto.getRemark()) - .apiGroup(dto.getApiGroup()) - .build()); - } - return apis; - } + private static List toScannedApis(List dtos) { + List apis = new ArrayList<>(dtos.size()); + for (GrpcScannedApiDTO dto : dtos) { + apis.add(ResourceRegistryScannedApi.builder() + .method(dto.getMethod()) + .path(dto.getPath()) + .apiName(dto.getApiName()) + .title(dto.getTitle()) + .remark(dto.getRemark()) + .apiGroup(dto.getApiGroup()) + .build()); + } + return apis; + } - @Override - public void sync(GrpcSyncRequest request, StreamObserver responseObserver) { - GrpcRSyncResult.Builder builder = GrpcRSyncResult.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); - try { - ResourceRegistrySyncCommand command = ResourceRegistrySyncCommand.builder() - .serviceName(request.getServiceName()) - .deleteMissing(request.getDeleteMissing()) - .apis(toScannedApis(request.getApisList())) - .build(); - ResourceRegistrySyncResult result = resourceRegistrySyncService.sync(command); + @Override + public void sync(GrpcSyncRequest request, StreamObserver responseObserver) { + GrpcRSyncResult.Builder builder = GrpcRSyncResult.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); + try { + ResourceRegistrySyncCommand command = ResourceRegistrySyncCommand.builder() + .serviceName(request.getServiceName()) + .deleteMissing(request.getDeleteMissing()) + .apis(toScannedApis(request.getApisList())) + .build(); + ResourceRegistrySyncResult result = resourceRegistrySyncService.sync(command); - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(GrpcSyncResultDTO.newBuilder() - .setInserted(result.getInserted()) - .setUpdated(result.getUpdated()) - .setDeleted(result.getDeleted()) - .setUnchanged(result.getUnchanged()) - .build()); - } - catch (Exception e) { - log.error("Resource registry sync failed for service [{}]", request.getServiceName(), e); - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.FAILURE.getCode()); - rBuilder.setMessage(e.getMessage() != null ? e.getMessage() : ResponseEnum.FAILURE.getText()); - } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); + builder.setData(GrpcSyncResultDTO.newBuilder() + .setInserted(result.getInserted()) + .setUpdated(result.getUpdated()) + .setDeleted(result.getDeleted()) + .setUnchanged(result.getUnchanged()) + .build()); + } catch (Exception e) { + log.error("Resource registry sync failed for service [{}]", request.getServiceName(), e); + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.FAILURE.getCode()); + rBuilder.setMessage(e.getMessage() != null ? e.getMessage() : ResponseEnum.FAILURE.getText()); + } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TenantServer.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TenantServer.java index 0856bf4d2..c19cfaf26 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TenantServer.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TenantServer.java @@ -43,34 +43,33 @@ import java.util.Objects; @Service public class TenantServer extends TenantApiGrpc.TenantApiImplBase { - @Resource - private GrpcTenantBuilder grpcTenantBuilder; + @Resource + private GrpcTenantBuilder grpcTenantBuilder; - @Resource - private TenantService tenantService; + @Resource + private TenantService tenantService; - @Override - public void selectByCode(GrpcCodeQuery request, StreamObserver responseObserver) { - GrpcRTenantDTO.Builder builder = GrpcRTenantDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByCode(GrpcCodeQuery request, StreamObserver responseObserver) { + GrpcRTenantDTO.Builder builder = GrpcRTenantDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - TenantBO entityBO = tenantService.selectByCode(request.getCode()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + TenantBO entityBO = tenantService.selectByCode(request.getCode()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcTenantBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcTenantBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TokenServer.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TokenServer.java index ddee5cde5..451d5af36 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TokenServer.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/TokenServer.java @@ -43,37 +43,35 @@ import java.util.Objects; @Service public class TokenServer extends TokenApiGrpc.TokenApiImplBase { - @Resource - private TokenService tokenService; + @Resource + private TokenService tokenService; - @Override - public void checkValid(GrpcLoginQuery request, StreamObserver responseObserver) { - GrpcRTokenDTO.Builder builder = GrpcRTokenDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void checkValid(GrpcLoginQuery request, StreamObserver responseObserver) { + GrpcRTokenDTO.Builder builder = GrpcRTokenDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - TokenValid entity = tokenService.checkValid(request.getName(), request.getSalt(), request.getToken(), - request.getTenant()); - if (Objects.isNull(entity)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else if (!entity.isValid()) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.TOKEN_INVALID.getCode()); - rBuilder.setMessage(ResponseEnum.TOKEN_INVALID.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + TokenValid entity = tokenService.checkValid(request.getName(), request.getSalt(), request.getToken(), + request.getTenant()); + if (Objects.isNull(entity)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else if (!entity.isValid()) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.TOKEN_INVALID.getCode()); + rBuilder.setMessage(ResponseEnum.TOKEN_INVALID.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(TimeUtil.completeFormat(entity.getExpireTime())); - } + builder.setData(TimeUtil.completeFormat(entity.getExpireTime())); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserLoginServer.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserLoginServer.java index 07b212f13..4ec0ce27f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserLoginServer.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserLoginServer.java @@ -43,34 +43,33 @@ import java.util.Objects; @Service public class UserLoginServer extends UserLoginApiGrpc.UserLoginApiImplBase { - @Resource - private GrpcUserLoginBuilder grpcUserLoginBuilder; + @Resource + private GrpcUserLoginBuilder grpcUserLoginBuilder; - @Resource - private UserLoginService userLoginService; + @Resource + private UserLoginService userLoginService; - @Override - public void selectByName(GrpcNameQuery request, StreamObserver responseObserver) { - GrpcRUserLoginDTO.Builder builder = GrpcRUserLoginDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByName(GrpcNameQuery request, StreamObserver responseObserver) { + GrpcRUserLoginDTO.Builder builder = GrpcRUserLoginDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - UserLoginBO entityBO = userLoginService.selectByLoginName(request.getName(), false); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + UserLoginBO entityBO = userLoginService.selectByLoginName(request.getName(), false); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcUserLoginBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcUserLoginBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserServer.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserServer.java index 892032221..cdd1d8317 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserServer.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/UserServer.java @@ -43,34 +43,33 @@ import java.util.Objects; @Service public class UserServer extends UserApiGrpc.UserApiImplBase { - @Resource - private GrpcUserBuilder grpcUserBuilder; + @Resource + private GrpcUserBuilder grpcUserBuilder; - @Resource - private UserService userService; + @Resource + private UserService userService; - @Override - public void selectById(GrpcIdQuery request, StreamObserver responseObserver) { - GrpcRUserDTO.Builder builder = GrpcRUserDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectById(GrpcIdQuery request, StreamObserver responseObserver) { + GrpcRUserDTO.Builder builder = GrpcRUserDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - UserBO entityBO = userService.selectById(request.getId()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + UserBO entityBO = userService.selectById(request.getId()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcUserBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcUserBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcTenantBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcTenantBuilder.java index ab06654e0..277713099 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcTenantBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcTenantBuilder.java @@ -37,35 +37,36 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcTenantBuilder { - /** - * BO to Grpc DTO - * @param entityBO TenantBO - * @return GrpcTenantDTO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "tenantNameBytes", ignore = true) - @Mapping(target = "tenantCodeBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcTenantDTO buildGrpcDTOByBO(TenantBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO TenantBO + * @return GrpcTenantDTO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "tenantNameBytes", ignore = true) + @Mapping(target = "tenantCodeBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcTenantDTO buildGrpcDTOByBO(TenantBO entityBO); - @AfterMapping - default void afterProcess(TenantBO entityBO, @MappingTarget GrpcTenantDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(TenantBO entityBO, @MappingTarget GrpcTenantDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserBuilder.java index 80d72d2a3..bb8a088fa 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserBuilder.java @@ -37,41 +37,42 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcUserBuilder { - /** - * BO to Grpc DTO - * @param entityBO UserBO - * @return GrpcUserDTO - */ - @Mapping(target = "socialExt", ignore = true) - @Mapping(target = "identityExt", ignore = true) - @Mapping(target = "nickNameBytes", ignore = true) - @Mapping(target = "userNameBytes", ignore = true) - @Mapping(target = "phoneBytes", ignore = true) - @Mapping(target = "emailBytes", ignore = true) - @Mapping(target = "socialExtBytes", ignore = true) - @Mapping(target = "identityExtBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcUserDTO buildGrpcDTOByBO(UserBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO UserBO + * @return GrpcUserDTO + */ + @Mapping(target = "socialExt", ignore = true) + @Mapping(target = "identityExt", ignore = true) + @Mapping(target = "nickNameBytes", ignore = true) + @Mapping(target = "userNameBytes", ignore = true) + @Mapping(target = "phoneBytes", ignore = true) + @Mapping(target = "emailBytes", ignore = true) + @Mapping(target = "socialExtBytes", ignore = true) + @Mapping(target = "identityExtBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcUserDTO buildGrpcDTOByBO(UserBO entityBO); - @AfterMapping - default void afterProcess(UserBO entityBO, @MappingTarget GrpcUserDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(UserBO entityBO, @MappingTarget GrpcUserDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getSocialExt()) - .ifPresent(value -> entityGrpc.setSocialExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getIdentityExt()) - .ifPresent(value -> entityGrpc.setIdentityExt(JsonUtil.toJsonString(value))); - } + Optional.ofNullable(entityBO.getSocialExt()) + .ifPresent(value -> entityGrpc.setSocialExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getIdentityExt()) + .ifPresent(value -> entityGrpc.setIdentityExt(JsonUtil.toJsonString(value))); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserLoginBuilder.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserLoginBuilder.java index 946fdb014..aff18e2d5 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserLoginBuilder.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/grpc/builder/GrpcUserLoginBuilder.java @@ -37,34 +37,35 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcUserLoginBuilder { - /** - * BO to Grpc DTO - * @param entityBO UserLoginBO - * @return GrpcUserLoginDTO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "loginNameBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcUserLoginDTO buildGrpcDTOByBO(UserLoginBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO UserLoginBO + * @return GrpcUserLoginDTO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "loginNameBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcUserLoginDTO buildGrpcDTOByBO(UserLoginBO entityBO); - @AfterMapping - default void afterProcess(UserLoginBO entityBO, @MappingTarget GrpcUserLoginDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(UserLoginBO entityBO, @MappingTarget GrpcUserLoginDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/mapper/ResourceRegistryLockMapper.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/mapper/ResourceRegistryLockMapper.java index b59e6b546..508e467a7 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/mapper/ResourceRegistryLockMapper.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/mapper/ResourceRegistryLockMapper.java @@ -31,17 +31,17 @@ import org.apache.ibatis.annotations.Param; @Mapper public interface ResourceRegistryLockMapper { - /** - * Acquire a transaction-scoped advisory lock keyed by the given string. The lock is - * automatically released when the enclosing transaction ends. - * - *

- * SQL lives in {@code resources/mapping/ResourceRegistryLockMapper.xml}. The return - * value is an empty string and is intentionally discarded by callers; it only exists - * so MyBatis can map the ResultSet produced by the {@code SELECT} statement. - * PostgreSQL's {@code pg_advisory_xact_lock} returns {@code void}, which is cast to - * {@code text} in the XML mapping to satisfy MyBatis' result-mapping contract. - */ - String advisoryLock(@Param("key") String key); + /** + * Acquire a transaction-scoped advisory lock keyed by the given string. The lock is + * automatically released when the enclosing transaction ends. + * + *

+ * SQL lives in {@code resources/mapping/ResourceRegistryLockMapper.xml}. The return + * value is an empty string and is intentionally discarded by callers; it only exists + * so MyBatis can map the ResultSet produced by the {@code SELECT} statement. + * PostgreSQL's {@code pg_advisory_xact_lock} returns {@code void}, which is cast to + * {@code text} in the XML mapping to satisfy MyBatis' result-mapping contract. + */ + String advisoryLock(@Param("key") String key); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/MenuService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/MenuService.java index 8a546d3b7..90045ad1e 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/MenuService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/MenuService.java @@ -33,12 +33,13 @@ import java.util.List; */ public interface MenuService extends BaseService { - /** - * Return menus matching the filter, assembled into a parent/child tree ordered by - * menuIndex. - * @param entityQuery filter conditions; null disables filtering - * @return tree roots - */ - List selectTree(MenuQuery entityQuery); + /** + * Return menus matching the filter, assembled into a parent/child tree ordered by + * menuIndex. + * + * @param entityQuery filter conditions; null disables filtering + * @return tree roots + */ + List selectTree(MenuQuery entityQuery); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/ResourceService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/ResourceService.java index db8ee7bc6..90daee280 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/ResourceService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/ResourceService.java @@ -33,11 +33,12 @@ import java.util.List; */ public interface ResourceService extends BaseService { - /** - * Returns all resources matching the filter assembled into a parent/child tree. - * @param entityQuery filter conditions; null disables filtering - * @return tree roots, children nested under each parent - */ - List selectTree(ResourceQuery entityQuery); + /** + * Returns all resources matching the filter assembled into a parent/child tree. + * + * @param entityQuery filter conditions; null disables filtering + * @return tree roots, children nested under each parent + */ + List selectTree(ResourceQuery entityQuery); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleResourceBindService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleResourceBindService.java index 20f3e83f8..7fca45dad 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleResourceBindService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleResourceBindService.java @@ -35,38 +35,42 @@ import java.util.List; */ public interface RoleResourceBindService extends BaseService { - /** - * Paginated query filtered by tenant: only bindings whose role belongs to the given - * tenant. - * @param entityQuery Query conditions - * @param tenantId Tenant ID, null means no tenant filtering - * @return Paginated bindings - */ - Page selectByPage(RoleResourceBindQuery entityQuery, Long tenantId); + /** + * Paginated query filtered by tenant: only bindings whose role belongs to the given + * tenant. + * + * @param entityQuery Query conditions + * @param tenantId Tenant ID, null means no tenant filtering + * @return Paginated bindings + */ + Page selectByPage(RoleResourceBindQuery entityQuery, Long tenantId); - /** - * TenantIdUserId - * @param roleId id - * @return - */ - List listResourceByRoleId(Long roleId); + /** + * TenantIdUserId + * + * @param roleId id + * @return + */ + List listResourceByRoleId(Long roleId); - /** - * List resources reachable by the given user, via dc3_role_user_bind joined onto - * dc3_role_resource_bind. Disabled resources are filtered out. - * @param userId target user - * @param tenantId tenant scope (constrains the user's roles) - * @return distinct enabled resources, empty list if the user has no roles - */ - List listResourceByUserId(Long userId, Long tenantId); + /** + * List resources reachable by the given user, via dc3_role_user_bind joined onto + * dc3_role_resource_bind. Disabled resources are filtered out. + * + * @param userId target user + * @param tenantId tenant scope (constrains the user's roles) + * @return distinct enabled resources, empty list if the user has no roles + */ + List listResourceByUserId(Long userId, Long tenantId); - /** - * Reverse of {@link #listResourceByRoleId} — given a resource, list the enabled roles - * that currently grant it. Used by the resource detail page's "Assigned Roles" tab. - * @param resourceId target resource - * @param tenantId tenant scope (constrains which roles are returned) - * @return enabled roles within the tenant; empty list if none - */ - List listRoleByResourceId(Long resourceId, Long tenantId); + /** + * Reverse of {@link #listResourceByRoleId} — given a resource, list the enabled roles + * that currently grant it. Used by the resource detail page's "Assigned Roles" tab. + * + * @param resourceId target resource + * @param tenantId tenant scope (constrains which roles are returned) + * @return enabled roles within the tenant; empty list if none + */ + List listRoleByResourceId(Long resourceId, Long tenantId); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleService.java index 192525f18..5c170687b 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleService.java @@ -33,12 +33,13 @@ import java.util.List; */ public interface RoleService extends BaseService { - /** - * Assemble the tenant's role hierarchy as a single nested tree. Top-level roles - * (parent_role_id == 0 or null) land at the root. - * @param entityQuery optional filters (tenantId is populated by the controller) - * @return root nodes, each node carrying its children - */ - List selectTree(RoleQuery entityQuery); + /** + * Assemble the tenant's role hierarchy as a single nested tree. Top-level roles + * (parent_role_id == 0 or null) land at the root. + * + * @param entityQuery optional filters (tenantId is populated by the controller) + * @return root nodes, each node carrying its children + */ + List selectTree(RoleQuery entityQuery); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleUserBindService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleUserBindService.java index e4843b451..7674dbd57 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleUserBindService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/RoleUserBindService.java @@ -35,30 +35,33 @@ import java.util.List; */ public interface RoleUserBindService extends BaseService { - /** - * Paginated query filtered by tenant: only bindings whose role belongs to the given - * tenant. - * @param entityQuery Query conditions - * @param tenantId Tenant ID, null means no tenant filtering - * @return Paginated bindings - */ - Page selectByPage(RoleUserBindQuery entityQuery, Long tenantId); + /** + * Paginated query filtered by tenant: only bindings whose role belongs to the given + * tenant. + * + * @param entityQuery Query conditions + * @param tenantId Tenant ID, null means no tenant filtering + * @return Paginated bindings + */ + Page selectByPage(RoleUserBindQuery entityQuery, Long tenantId); - /** - * Tenantid id - * @param tenantId Tenantid - * @param userId id - * @return Role list - */ - List listRoleByTenantIdAndUserId(Long tenantId, Long userId); + /** + * Tenantid id + * + * @param tenantId Tenantid + * @param userId id + * @return Role list + */ + List listRoleByTenantIdAndUserId(Long tenantId, Long userId); - /** - * List enabled users bound to the given role. Mirror of - * {@link #listRoleByTenantIdAndUserId}: look up user_ids via dc3_role_user_bind, then - * fetch + enable-filter users. - * @param roleId role scope - * @return users bound to the role; empty list if none - */ - List listUserByRoleId(Long roleId); + /** + * List enabled users bound to the given role. Mirror of + * {@link #listRoleByTenantIdAndUserId}: look up user_ids via dc3_role_user_bind, then + * fetch + enable-filter users. + * + * @param roleId role scope + * @return users bound to the role; empty list if none + */ + List listUserByRoleId(Long roleId); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantBindService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantBindService.java index 48d714e00..0f53458c9 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantBindService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantBindService.java @@ -32,19 +32,21 @@ import java.util.List; */ public interface TenantBindService extends BaseService { - /** - * Tenant ID ID - * @param tenantId Tenant ID - * @param userId User ID - * @return TenantBind - */ - TenantBindBO selectByTenantIdAndUserId(Long tenantId, Long userId); + /** + * Tenant ID ID + * + * @param tenantId Tenant ID + * @param userId User ID + * @return TenantBind + */ + TenantBindBO selectByTenantIdAndUserId(Long tenantId, Long userId); - /** - * List active user IDs bound to the given tenant. - * @param tenantId tenant scope; must be non-null - * @return user IDs (empty if the tenant has no members yet) - */ - List listUserIdsByTenantId(Long tenantId); + /** + * List active user IDs bound to the given tenant. + * + * @param tenantId tenant scope; must be non-null + * @return user IDs (empty if the tenant has no members yet) + */ + List listUserIdsByTenantId(Long tenantId); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantService.java index 3db02bbbd..bd698a041 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/TenantService.java @@ -30,11 +30,12 @@ import io.github.pnoker.common.base.service.BaseService; */ public interface TenantService extends BaseService { - /** - * TenantCodeTenant - * @param code TenantCode - * @return {@link TenantBO} - */ - TenantBO selectByCode(String code); + /** + * TenantCodeTenant + * + * @param code TenantCode + * @return {@link TenantBO} + */ + TenantBO selectByCode(String code); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserLoginService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserLoginService.java index 11fda5cde..0765618db 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserLoginService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserLoginService.java @@ -30,19 +30,21 @@ import io.github.pnoker.common.base.service.BaseService; */ public interface UserLoginService extends BaseService { - /** - * Name - * @param loginName Name - * @param throwException Throw Exception - * @return User - */ - UserLoginBO selectByLoginName(String loginName, boolean throwException); + /** + * Name + * + * @param loginName Name + * @param throwException Throw Exception + * @return User + */ + UserLoginBO selectByLoginName(String loginName, boolean throwException); - /** - * Name - * @param loginName Name - * @return Boolean - */ - boolean checkLoginNameValid(String loginName); + /** + * Name + * + * @param loginName Name + * @return Boolean + */ + boolean checkLoginNameValid(String loginName); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserPasswordService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserPasswordService.java index 2425905c8..61b990d08 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserPasswordService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserPasswordService.java @@ -30,9 +30,9 @@ import io.github.pnoker.common.base.service.BaseService; */ public interface UserPasswordService extends BaseService { - /** - * @param id ID - */ - void restPassword(Long id); + /** + * @param id ID + */ + void restPassword(Long id); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserService.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserService.java index 47a03ac42..691cfd779 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserService.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/UserService.java @@ -30,31 +30,34 @@ import io.github.pnoker.common.base.service.BaseService; */ public interface UserService extends BaseService { - /** - * Get user by username. - * @param userName username - * @param throwException whether to throw exception when user does not exist - * @return {@link UserBO} or {@code null} when not found and {@code throwException} is - * false - */ - UserBO selectByUserName(String userName, boolean throwException); + /** + * Get user by username. + * + * @param userName username + * @param throwException whether to throw exception when user does not exist + * @return {@link UserBO} or {@code null} when not found and {@code throwException} is + * false + */ + UserBO selectByUserName(String userName, boolean throwException); - /** - * Get user by phone number. - * @param phone phone number - * @param throwException whether to throw exception when user does not exist - * @return {@link UserBO} or {@code null} when not found and {@code throwException} is - * false - */ - UserBO selectByPhone(String phone, boolean throwException); + /** + * Get user by phone number. + * + * @param phone phone number + * @param throwException whether to throw exception when user does not exist + * @return {@link UserBO} or {@code null} when not found and {@code throwException} is + * false + */ + UserBO selectByPhone(String phone, boolean throwException); - /** - * Get user by email. - * @param email email address - * @param throwException whether to throw exception when user does not exist - * @return {@link UserBO} or {@code null} when not found and {@code throwException} is - * false - */ - UserBO selectByEmail(String email, boolean throwException); + /** + * Get user by email. + * + * @param email email address + * @param throwException whether to throw exception when user does not exist + * @return {@link UserBO} or {@code null} when not found and {@code throwException} is + * false + */ + UserBO selectByEmail(String email, boolean throwException); } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ApiServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ApiServiceImpl.java index 53705d81c..92d70b9c7 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ApiServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ApiServiceImpl.java @@ -50,109 +50,110 @@ import java.util.Objects; @Service public class ApiServiceImpl implements ApiService { - @Resource - private ApiBuilder apiBuilder; + @Resource + private ApiBuilder apiBuilder; - @Resource - private ApiManager apiManager; + @Resource + private ApiManager apiManager; - @Override - public void save(ApiBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(ApiBO entityBO) { + checkDuplicate(entityBO, false, true); - ApiDO entityDO = apiBuilder.buildDOByBO(entityBO); - if (!apiManager.save(entityDO)) { - throw new AddException("Failed to create api"); - } - } + ApiDO entityDO = apiBuilder.buildDOByBO(entityBO); + if (!apiManager.save(entityDO)) { + throw new AddException("Failed to create api"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!apiManager.removeById(id)) { - throw new DeleteException("Failed to remove api"); - } - } + if (!apiManager.removeById(id)) { + throw new DeleteException("Failed to remove api"); + } + } - @Override - public void update(ApiBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(ApiBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - ApiDO entityDO = apiBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!apiManager.updateById(entityDO)) { - throw new UpdateException("Failed to update api"); - } - } + ApiDO entityDO = apiBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!apiManager.updateById(entityDO)) { + throw new UpdateException("Failed to update api"); + } + } - @Override - public ApiBO selectById(Long id) { - ApiDO entityDO = getDOById(id, true); - return apiBuilder.buildBOByDO(entityDO); - } + @Override + public ApiBO selectById(Long id) { + ApiDO entityDO = getDOById(id, true); + return apiBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(ApiQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = apiManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return apiBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(ApiQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = apiManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return apiBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link ApiQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(ApiQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getApiName()), ApiDO::getApiName, entityQuery.getApiName()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getApiCode()), ApiDO::getApiCode, entityQuery.getApiCode()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceName()), ApiDO::getServiceName, - entityQuery.getServiceName()); - wrapper.eq(Objects.nonNull(entityQuery.getApiTypeFlag()), ApiDO::getApiTypeFlag, entityQuery.getApiTypeFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), ApiDO::getEnableFlag, entityQuery.getEnableFlag()); - return wrapper; - } + /** + * @param entityQuery {@link ApiQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(ApiQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getApiName()), ApiDO::getApiName, entityQuery.getApiName()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getApiCode()), ApiDO::getApiCode, entityQuery.getApiCode()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceName()), ApiDO::getServiceName, + entityQuery.getServiceName()); + wrapper.eq(Objects.nonNull(entityQuery.getApiTypeFlag()), ApiDO::getApiTypeFlag, entityQuery.getApiTypeFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), ApiDO::getEnableFlag, entityQuery.getEnableFlag()); + return wrapper; + } - /** - * @param entityBO {@link ApiBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(ApiBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ApiDO::getApiTypeFlag, entityBO.getApiTypeFlag()); - wrapper.eq(ApiDO::getApiName, entityBO.getApiName()); - wrapper.eq(ApiDO::getApiCode, entityBO.getApiCode()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - ApiDO one = apiManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Api has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link ApiBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(ApiBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ApiDO::getApiTypeFlag, entityBO.getApiTypeFlag()); + wrapper.eq(ApiDO::getApiName, entityBO.getApiName()); + wrapper.eq(ApiDO::getApiCode, entityBO.getApiCode()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + ApiDO one = apiManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Api has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link ApiDO} - */ - private ApiDO getDOById(Long id, boolean throwException) { - ApiDO entityDO = apiManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Api does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link ApiDO} + */ + private ApiDO getDOById(Long id, boolean throwException) { + ApiDO entityDO = apiManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Api does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/MenuServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/MenuServiceImpl.java index cb356b758..a408649b9 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/MenuServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/MenuServiceImpl.java @@ -55,173 +55,173 @@ import java.util.*; @Service public class MenuServiceImpl implements MenuService { - @Resource - private MenuBuilder menuBuilder; + @Resource + private MenuBuilder menuBuilder; - @Resource - private MenuManager menuManager; + @Resource + private MenuManager menuManager; - @Resource - private ResourceRegistrySyncService resourceRegistrySyncService; + @Resource + private ResourceRegistrySyncService resourceRegistrySyncService; - @Override - @Transactional(rollbackFor = Exception.class) - public void save(MenuBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + @Transactional(rollbackFor = Exception.class) + public void save(MenuBO entityBO) { + checkDuplicate(entityBO, false, true); - MenuDO entityDO = menuBuilder.buildDOByBO(entityBO); - if (!menuManager.save(entityDO)) { - throw new AddException("Failed to create menu"); - } - resourceRegistrySyncService.syncMenuResource(entityDO); - } + MenuDO entityDO = menuBuilder.buildDOByBO(entityBO); + if (!menuManager.save(entityDO)) { + throw new AddException("Failed to create menu"); + } + resourceRegistrySyncService.syncMenuResource(entityDO); + } - @Override - @Transactional(rollbackFor = Exception.class) - public void remove(Long id) { - getDOById(id, true); + @Override + @Transactional(rollbackFor = Exception.class) + public void remove(Long id) { + getDOById(id, true); - // - LambdaQueryChainWrapper wrapper = menuManager.lambdaQuery().eq(MenuDO::getParentMenuId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove menu: some sub menus exists in the menu"); - } + // + LambdaQueryChainWrapper wrapper = menuManager.lambdaQuery().eq(MenuDO::getParentMenuId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove menu: some sub menus exists in the menu"); + } - if (!menuManager.removeById(id)) { - throw new DeleteException("Failed to remove menu"); - } - resourceRegistrySyncService.removeMenuResource(id); - } + if (!menuManager.removeById(id)) { + throw new DeleteException("Failed to remove menu"); + } + resourceRegistrySyncService.removeMenuResource(id); + } - @Override - @Transactional(rollbackFor = Exception.class) - public void update(MenuBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + @Transactional(rollbackFor = Exception.class) + public void update(MenuBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - MenuDO entityDO = menuBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!menuManager.updateById(entityDO)) { - throw new UpdateException("Failed to update menu"); - } - // Re-read to pick up any DB-side mutations (trigger-updated operate_time, etc). - MenuDO latest = menuManager.getById(entityBO.getId()); - resourceRegistrySyncService.syncMenuResource(latest != null ? latest : entityDO); - } + MenuDO entityDO = menuBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!menuManager.updateById(entityDO)) { + throw new UpdateException("Failed to update menu"); + } + // Re-read to pick up any DB-side mutations (trigger-updated operate_time, etc). + MenuDO latest = menuManager.getById(entityBO.getId()); + resourceRegistrySyncService.syncMenuResource(latest != null ? latest : entityDO); + } - @Override - public MenuBO selectById(Long id) { - MenuDO entityDO = getDOById(id, true); - return menuBuilder.buildBOByDO(entityDO); - } + @Override + public MenuBO selectById(Long id) { + MenuDO entityDO = getDOById(id, true); + return menuBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(MenuQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = menuManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return menuBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(MenuQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = menuManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return menuBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link MenuQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(MenuQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getMenuName()), MenuDO::getMenuName, entityQuery.getMenuName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getMenuCode()), MenuDO::getMenuCode, entityQuery.getMenuCode()); - wrapper.eq(Objects.nonNull(entityQuery.getMenuTypeFlag()), MenuDO::getMenuTypeFlag, - entityQuery.getMenuTypeFlag() == null ? null : entityQuery.getMenuTypeFlag().getIndex()); - wrapper.eq(Objects.nonNull(entityQuery.getParentMenuId()), MenuDO::getParentMenuId, - entityQuery.getParentMenuId()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), MenuDO::getEnableFlag, - entityQuery.getEnableFlag() == null ? null : entityQuery.getEnableFlag().getIndex()); - return wrapper; - } + /** + * @param entityQuery {@link MenuQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(MenuQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getMenuName()), MenuDO::getMenuName, entityQuery.getMenuName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getMenuCode()), MenuDO::getMenuCode, entityQuery.getMenuCode()); + wrapper.eq(Objects.nonNull(entityQuery.getMenuTypeFlag()), MenuDO::getMenuTypeFlag, + entityQuery.getMenuTypeFlag() == null ? null : entityQuery.getMenuTypeFlag().getIndex()); + wrapper.eq(Objects.nonNull(entityQuery.getParentMenuId()), MenuDO::getParentMenuId, + entityQuery.getParentMenuId()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), MenuDO::getEnableFlag, + entityQuery.getEnableFlag() == null ? null : entityQuery.getEnableFlag().getIndex()); + return wrapper; + } - @Override - public List selectTree(MenuQuery entityQuery) { - MenuQuery effective = Objects.requireNonNullElseGet(entityQuery, MenuQuery::new); - List rows = menuManager.list(fuzzyQuery(effective)); - return assembleTree(rows); - } + @Override + public List selectTree(MenuQuery entityQuery) { + MenuQuery effective = Objects.requireNonNullElseGet(entityQuery, MenuQuery::new); + List rows = menuManager.list(fuzzyQuery(effective)); + return assembleTree(rows); + } - private List assembleTree(List rows) { - if (CollectionUtils.isEmpty(rows)) { - return List.of(); - } - Map byId = new HashMap<>(rows.size()); - for (MenuDO row : rows) { - byId.put(row.getId(), MenuTreeBO.fromBO(menuBuilder.buildBOByDO(row))); - } - List roots = new ArrayList<>(); - for (MenuTreeBO node : byId.values()) { - Long parentId = node.getParentMenuId(); - MenuTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); - if (parent == null) { - roots.add(node); - } - else { - parent.addChild(node); - } - } - Comparator order = Comparator - .comparing(MenuTreeBO::getMenuIndex, Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(MenuTreeBO::getMenuName, Comparator.nullsLast(Comparator.naturalOrder())); - sortRecursive(roots, order); - return roots; - } + private List assembleTree(List rows) { + if (CollectionUtils.isEmpty(rows)) { + return List.of(); + } + Map byId = new HashMap<>(rows.size()); + for (MenuDO row : rows) { + byId.put(row.getId(), MenuTreeBO.fromBO(menuBuilder.buildBOByDO(row))); + } + List roots = new ArrayList<>(); + for (MenuTreeBO node : byId.values()) { + Long parentId = node.getParentMenuId(); + MenuTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); + if (parent == null) { + roots.add(node); + } else { + parent.addChild(node); + } + } + Comparator order = Comparator + .comparing(MenuTreeBO::getMenuIndex, Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(MenuTreeBO::getMenuName, Comparator.nullsLast(Comparator.naturalOrder())); + sortRecursive(roots, order); + return roots; + } - private void sortRecursive(List nodes, Comparator order) { - if (CollectionUtils.isEmpty(nodes)) { - return; - } - nodes.sort(order); - for (MenuTreeBO node : nodes) { - sortRecursive(node.getChildren(), order); - } - } + private void sortRecursive(List nodes, Comparator order) { + if (CollectionUtils.isEmpty(nodes)) { + return; + } + nodes.sort(order); + for (MenuTreeBO node : nodes) { + sortRecursive(node.getChildren(), order); + } + } - /** - * @param entityBO {@link MenuBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(MenuBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(MenuDO::getParentMenuId, entityBO.getParentMenuId()); - wrapper.eq(MenuDO::getMenuTypeFlag, entityBO.getMenuTypeFlag()); - wrapper.eq(MenuDO::getMenuName, entityBO.getMenuName()); - wrapper.eq(MenuDO::getMenuCode, entityBO.getMenuCode()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - MenuDO one = menuManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Menu has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link MenuBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(MenuBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(MenuDO::getParentMenuId, entityBO.getParentMenuId()); + wrapper.eq(MenuDO::getMenuTypeFlag, entityBO.getMenuTypeFlag()); + wrapper.eq(MenuDO::getMenuName, entityBO.getMenuName()); + wrapper.eq(MenuDO::getMenuCode, entityBO.getMenuCode()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + MenuDO one = menuManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Menu has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link MenuDO} - */ - private MenuDO getDOById(Long id, boolean throwException) { - MenuDO entityDO = menuManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Menu does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link MenuDO} + */ + private MenuDO getDOById(Long id, boolean throwException) { + MenuDO entityDO = menuManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Menu does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ResourceServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ResourceServiceImpl.java index fd455c6fe..69d1d31a8 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ResourceServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/ResourceServiceImpl.java @@ -50,188 +50,186 @@ import java.util.*; @Service public class ResourceServiceImpl implements ResourceService { - @Resource - private ResourceBuilder resourceBuilder; + @Resource + private ResourceBuilder resourceBuilder; - @Resource - private ResourceManager resourceManager; + @Resource + private ResourceManager resourceManager; - @Override - public void save(ResourceBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException("Failed to create resource: resource has been duplicated"); - } + @Override + public void save(ResourceBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException("Failed to create resource: resource has been duplicated"); + } - ResourceDO entityDO = resourceBuilder.buildDOByBO(entityBO); - if (!resourceManager.save(entityDO)) { - throw new AddException("Failed to create resource"); - } - } + ResourceDO entityDO = resourceBuilder.buildDOByBO(entityBO); + if (!resourceManager.save(entityDO)) { + throw new AddException("Failed to create resource"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!resourceManager.removeById(id)) { - throw new DeleteException("Failed to remove resource"); - } - } + if (!resourceManager.removeById(id)) { + throw new DeleteException("Failed to remove resource"); + } + } - @Override - public void update(ResourceBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(ResourceBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException("Failed to update resource: resource has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException("Failed to update resource: resource has been duplicated"); + } - ResourceDO entityDO = resourceBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!resourceManager.updateById(entityDO)) { - throw new UpdateException("Failed to update resource"); - } - } + ResourceDO entityDO = resourceBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!resourceManager.updateById(entityDO)) { + throw new UpdateException("Failed to update resource"); + } + } - @Override - public ResourceBO selectById(Long id) { - ResourceDO entityDO = getDOById(id, true); - return resourceBuilder.buildBOByDO(entityDO); - } + @Override + public ResourceBO selectById(Long id) { + ResourceDO entityDO = getDOById(id, true); + return resourceBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(ResourceQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = resourceManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return resourceBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(ResourceQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = resourceManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return resourceBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link ResourceQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(ResourceQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getResourceName()), ResourceDO::getResourceName, - entityQuery.getResourceName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getResourceCode()), ResourceDO::getResourceCode, - entityQuery.getResourceCode()); - // Type: multi-select wins when present; fall back to single value. - if (CollectionUtils.isNotEmpty(entityQuery.getResourceTypeFlags())) { - List typeIndexes = entityQuery.getResourceTypeFlags() - .stream() - .filter(Objects::nonNull) - .map(ResourceTypeFlagEnum::getIndex) - .toList(); - if (!typeIndexes.isEmpty()) { - wrapper.in(ResourceDO::getResourceTypeFlag, typeIndexes); - } - } - else if (Objects.nonNull(entityQuery.getResourceTypeFlag())) { - wrapper.eq(ResourceDO::getResourceTypeFlag, entityQuery.getResourceTypeFlag().getIndex()); - } - // Scope: multi-select wins when present; fall back to single value. - if (CollectionUtils.isNotEmpty(entityQuery.getResourceScopeFlags())) { - List scopeIndexes = entityQuery.getResourceScopeFlags() - .stream() - .filter(Objects::nonNull) - .map(ResourceScopeFlagEnum::getIndex) - .toList(); - if (!scopeIndexes.isEmpty()) { - wrapper.in(ResourceDO::getResourceScopeFlag, scopeIndexes); - } - } - else if (Objects.nonNull(entityQuery.getResourceScopeFlag())) { - wrapper.eq(ResourceDO::getResourceScopeFlag, entityQuery.getResourceScopeFlag()); - } - wrapper.eq(Objects.nonNull(entityQuery.getParentResourceId()), ResourceDO::getParentResourceId, - entityQuery.getParentResourceId()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), ResourceDO::getEnableFlag, - entityQuery.getEnableFlag()); - return wrapper; - } + /** + * @param entityQuery {@link ResourceQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(ResourceQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getResourceName()), ResourceDO::getResourceName, + entityQuery.getResourceName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getResourceCode()), ResourceDO::getResourceCode, + entityQuery.getResourceCode()); + // Type: multi-select wins when present; fall back to single value. + if (CollectionUtils.isNotEmpty(entityQuery.getResourceTypeFlags())) { + List typeIndexes = entityQuery.getResourceTypeFlags() + .stream() + .filter(Objects::nonNull) + .map(ResourceTypeFlagEnum::getIndex) + .toList(); + if (!typeIndexes.isEmpty()) { + wrapper.in(ResourceDO::getResourceTypeFlag, typeIndexes); + } + } else if (Objects.nonNull(entityQuery.getResourceTypeFlag())) { + wrapper.eq(ResourceDO::getResourceTypeFlag, entityQuery.getResourceTypeFlag().getIndex()); + } + // Scope: multi-select wins when present; fall back to single value. + if (CollectionUtils.isNotEmpty(entityQuery.getResourceScopeFlags())) { + List scopeIndexes = entityQuery.getResourceScopeFlags() + .stream() + .filter(Objects::nonNull) + .map(ResourceScopeFlagEnum::getIndex) + .toList(); + if (!scopeIndexes.isEmpty()) { + wrapper.in(ResourceDO::getResourceScopeFlag, scopeIndexes); + } + } else if (Objects.nonNull(entityQuery.getResourceScopeFlag())) { + wrapper.eq(ResourceDO::getResourceScopeFlag, entityQuery.getResourceScopeFlag()); + } + wrapper.eq(Objects.nonNull(entityQuery.getParentResourceId()), ResourceDO::getParentResourceId, + entityQuery.getParentResourceId()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), ResourceDO::getEnableFlag, + entityQuery.getEnableFlag()); + return wrapper; + } - @Override - public List selectTree(ResourceQuery entityQuery) { - ResourceQuery effective = Objects.requireNonNullElseGet(entityQuery, ResourceQuery::new); - LambdaQueryWrapper wrapper = fuzzyQuery(effective); - // Load everything that matches, then assemble in memory by parent_resource_id. - List rows = resourceManager.list(wrapper); - return assembleTree(rows); - } + @Override + public List selectTree(ResourceQuery entityQuery) { + ResourceQuery effective = Objects.requireNonNullElseGet(entityQuery, ResourceQuery::new); + LambdaQueryWrapper wrapper = fuzzyQuery(effective); + // Load everything that matches, then assemble in memory by parent_resource_id. + List rows = resourceManager.list(wrapper); + return assembleTree(rows); + } - private List assembleTree(List rows) { - if (CollectionUtils.isEmpty(rows)) { - return List.of(); - } - Map byId = new HashMap<>(rows.size()); - for (ResourceDO row : rows) { - ResourceTreeBO node = ResourceTreeBO.fromBO(resourceBuilder.buildBOByDO(row)); - byId.put(node.getId(), node); - } - List roots = new ArrayList<>(); - for (ResourceTreeBO node : byId.values()) { - Long parentId = node.getParentResourceId(); - ResourceTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); - if (parent == null) { - roots.add(node); - } - else { - parent.addChild(node); - } - } - Comparator order = Comparator - .comparing(ResourceTreeBO::getResourceTypeFlag, Comparator.nullsLast(Comparator.naturalOrder())) - .thenComparing(ResourceTreeBO::getResourceName, Comparator.nullsLast(Comparator.naturalOrder())); - sortRecursive(roots, order); - return roots; - } + private List assembleTree(List rows) { + if (CollectionUtils.isEmpty(rows)) { + return List.of(); + } + Map byId = new HashMap<>(rows.size()); + for (ResourceDO row : rows) { + ResourceTreeBO node = ResourceTreeBO.fromBO(resourceBuilder.buildBOByDO(row)); + byId.put(node.getId(), node); + } + List roots = new ArrayList<>(); + for (ResourceTreeBO node : byId.values()) { + Long parentId = node.getParentResourceId(); + ResourceTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); + if (parent == null) { + roots.add(node); + } else { + parent.addChild(node); + } + } + Comparator order = Comparator + .comparing(ResourceTreeBO::getResourceTypeFlag, Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparing(ResourceTreeBO::getResourceName, Comparator.nullsLast(Comparator.naturalOrder())); + sortRecursive(roots, order); + return roots; + } - private void sortRecursive(List nodes, Comparator order) { - if (CollectionUtils.isEmpty(nodes)) { - return; - } - nodes.sort(order); - for (ResourceTreeBO node : nodes) { - sortRecursive(node.getChildren(), order); - } - } + private void sortRecursive(List nodes, Comparator order) { + if (CollectionUtils.isEmpty(nodes)) { + return; + } + nodes.sort(order); + for (ResourceTreeBO node : nodes) { + sortRecursive(node.getChildren(), order); + } + } - /** - * @param entityBO {@link ResourceBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(ResourceBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ResourceDO::getParentResourceId, entityBO.getParentResourceId()); - wrapper.eq(ResourceDO::getResourceName, entityBO.getResourceName()); - wrapper.eq(ResourceDO::getResourceCode, entityBO.getResourceCode()); - wrapper.eq(ResourceDO::getResourceTypeFlag, entityBO.getResourceTypeFlag()); - wrapper.eq(ResourceDO::getResourceScopeFlag, entityBO.getResourceScopeFlag()); - wrapper.eq(ResourceDO::getEntityId, entityBO.getEntityId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - ResourceDO one = resourceManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link ResourceBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(ResourceBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ResourceDO::getParentResourceId, entityBO.getParentResourceId()); + wrapper.eq(ResourceDO::getResourceName, entityBO.getResourceName()); + wrapper.eq(ResourceDO::getResourceCode, entityBO.getResourceCode()); + wrapper.eq(ResourceDO::getResourceTypeFlag, entityBO.getResourceTypeFlag()); + wrapper.eq(ResourceDO::getResourceScopeFlag, entityBO.getResourceScopeFlag()); + wrapper.eq(ResourceDO::getEntityId, entityBO.getEntityId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + ResourceDO one = resourceManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link ResourceDO} - */ - private ResourceDO getDOById(Long id, boolean throwException) { - ResourceDO entityDO = resourceManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Resource does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link ResourceDO} + */ + private ResourceDO getDOById(Long id, boolean throwException) { + ResourceDO entityDO = resourceManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Resource does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleResourceBindServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleResourceBindServiceImpl.java index e6bf55d2c..aaa049cca 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleResourceBindServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleResourceBindServiceImpl.java @@ -60,222 +60,222 @@ import java.util.Objects; @Service public class RoleResourceBindServiceImpl implements RoleResourceBindService { - @Resource - private ResourceBuilder resourceBuilder; + @Resource + private ResourceBuilder resourceBuilder; - @Resource - private RoleBuilder roleBuilder; + @Resource + private RoleBuilder roleBuilder; - @Resource - private RoleResourceBindBuilder roleResourceBindBuilder; + @Resource + private RoleResourceBindBuilder roleResourceBindBuilder; - @Resource - private RoleResourceBindManager roleResourceBindManager; + @Resource + private RoleResourceBindManager roleResourceBindManager; - @Resource - private ResourceManager resourceManager; + @Resource + private ResourceManager resourceManager; - @Resource - private RoleManager roleManager; + @Resource + private RoleManager roleManager; - @Resource - private RoleUserBindManager roleUserBindManager; + @Resource + private RoleUserBindManager roleUserBindManager; - @Override - public void save(RoleResourceBindBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException("Failed to create role resource bind: role resource bind has been duplicated"); - } + @Override + public void save(RoleResourceBindBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException("Failed to create role resource bind: role resource bind has been duplicated"); + } - RoleResourceBindDO entityDO = roleResourceBindBuilder.buildDOByBO(entityBO); - if (!roleResourceBindManager.save(entityDO)) { - throw new AddException("Failed to create role resource bind"); - } - } + RoleResourceBindDO entityDO = roleResourceBindBuilder.buildDOByBO(entityBO); + if (!roleResourceBindManager.save(entityDO)) { + throw new AddException("Failed to create role resource bind"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!roleResourceBindManager.removeById(id)) { - throw new DeleteException("Failed to remove role resource bind"); - } - } + if (!roleResourceBindManager.removeById(id)) { + throw new DeleteException("Failed to remove role resource bind"); + } + } - @Override - public void update(RoleResourceBindBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(RoleResourceBindBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException("Failed to update role resource bind: role resource bind has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException("Failed to update role resource bind: role resource bind has been duplicated"); + } - RoleResourceBindDO entityDO = roleResourceBindBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!roleResourceBindManager.updateById(entityDO)) { - throw new UpdateException("Failed to update role resource bind"); - } - } + RoleResourceBindDO entityDO = roleResourceBindBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!roleResourceBindManager.updateById(entityDO)) { + throw new UpdateException("Failed to update role resource bind"); + } + } - @Override - public RoleResourceBindBO selectById(Long id) { - RoleResourceBindDO entityDO = getDOById(id, true); - return roleResourceBindBuilder.buildBOByDO(entityDO); - } + @Override + public RoleResourceBindBO selectById(Long id) { + RoleResourceBindDO entityDO = getDOById(id, true); + return roleResourceBindBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(RoleResourceBindQuery entityQuery) { - return selectByPage(entityQuery, null); - } + @Override + public Page selectByPage(RoleResourceBindQuery entityQuery) { + return selectByPage(entityQuery, null); + } - @Override - public Page selectByPage(RoleResourceBindQuery entityQuery, Long tenantId) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = roleResourceBindManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery, tenantId)); - return roleResourceBindBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(RoleResourceBindQuery entityQuery, Long tenantId) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = roleResourceBindManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery, tenantId)); + return roleResourceBindBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public List listResourceByUserId(Long userId, Long tenantId) { - if (Objects.isNull(userId)) { - return Collections.emptyList(); - } - // Step 1: roles the user is bound to. - LambdaQueryWrapper userWrapper = Wrappers.query().lambda(); - userWrapper.eq(RoleUserBindDO::getUserId, userId); - userWrapper.select(RoleUserBindDO::getRoleId); - List roleIds = roleUserBindManager.listObjs(userWrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(roleIds)) { - return Collections.emptyList(); - } - // Step 2: narrow to the caller's tenant so a stale cross-tenant binding - // cannot leak resources outside the current scope. - if (Objects.nonNull(tenantId)) { - LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); - roleWrapper.in(RoleDO::getId, roleIds); - roleWrapper.eq(RoleDO::getTenantId, tenantId); - roleWrapper.select(RoleDO::getId); - roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(roleIds)) { - return Collections.emptyList(); - } - } - // Step 3: role -> resource bindings. - LambdaQueryWrapper bindWrapper = Wrappers.query().lambda(); - bindWrapper.in(RoleResourceBindDO::getRoleId, roleIds); - bindWrapper.select(RoleResourceBindDO::getResourceId); - List resourceIds = roleResourceBindManager.listObjs(bindWrapper, o -> (Long) o) - .stream() - .distinct() - .toList(); - if (CollectionUtils.isEmpty(resourceIds)) { - return Collections.emptyList(); - } - // Step 4: fetch resources and drop disabled ones (same rule as - // listResourceByRoleId). - List resourceDOList = resourceManager.listByIds(resourceIds) - .stream() - .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) - .toList(); - return resourceBuilder.buildBOListByDOList(resourceDOList); - } + @Override + public List listResourceByUserId(Long userId, Long tenantId) { + if (Objects.isNull(userId)) { + return Collections.emptyList(); + } + // Step 1: roles the user is bound to. + LambdaQueryWrapper userWrapper = Wrappers.query().lambda(); + userWrapper.eq(RoleUserBindDO::getUserId, userId); + userWrapper.select(RoleUserBindDO::getRoleId); + List roleIds = roleUserBindManager.listObjs(userWrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(roleIds)) { + return Collections.emptyList(); + } + // Step 2: narrow to the caller's tenant so a stale cross-tenant binding + // cannot leak resources outside the current scope. + if (Objects.nonNull(tenantId)) { + LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); + roleWrapper.in(RoleDO::getId, roleIds); + roleWrapper.eq(RoleDO::getTenantId, tenantId); + roleWrapper.select(RoleDO::getId); + roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(roleIds)) { + return Collections.emptyList(); + } + } + // Step 3: role -> resource bindings. + LambdaQueryWrapper bindWrapper = Wrappers.query().lambda(); + bindWrapper.in(RoleResourceBindDO::getRoleId, roleIds); + bindWrapper.select(RoleResourceBindDO::getResourceId); + List resourceIds = roleResourceBindManager.listObjs(bindWrapper, o -> (Long) o) + .stream() + .distinct() + .toList(); + if (CollectionUtils.isEmpty(resourceIds)) { + return Collections.emptyList(); + } + // Step 4: fetch resources and drop disabled ones (same rule as + // listResourceByRoleId). + List resourceDOList = resourceManager.listByIds(resourceIds) + .stream() + .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) + .toList(); + return resourceBuilder.buildBOListByDOList(resourceDOList); + } - @Override - public List listRoleByResourceId(Long resourceId, Long tenantId) { - if (Objects.isNull(resourceId)) { - return Collections.emptyList(); - } - // Step 1: role_ids currently bound to this resource. - LambdaQueryWrapper bindWrapper = Wrappers.query().lambda(); - bindWrapper.eq(RoleResourceBindDO::getResourceId, resourceId); - bindWrapper.select(RoleResourceBindDO::getRoleId); - List roleIds = roleResourceBindManager.listObjs(bindWrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(roleIds)) { - return Collections.emptyList(); - } - // Step 2: fetch roles; filter by tenant (caller-scoped) and enabled flag. - List enabled = roleManager.listByIds(roleIds) - .stream() - .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag()) - && (Objects.isNull(tenantId) || tenantId.equals(e.getTenantId()))) - .toList(); - return roleBuilder.buildBOListByDOList(enabled); - } + @Override + public List listRoleByResourceId(Long resourceId, Long tenantId) { + if (Objects.isNull(resourceId)) { + return Collections.emptyList(); + } + // Step 1: role_ids currently bound to this resource. + LambdaQueryWrapper bindWrapper = Wrappers.query().lambda(); + bindWrapper.eq(RoleResourceBindDO::getResourceId, resourceId); + bindWrapper.select(RoleResourceBindDO::getRoleId); + List roleIds = roleResourceBindManager.listObjs(bindWrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(roleIds)) { + return Collections.emptyList(); + } + // Step 2: fetch roles; filter by tenant (caller-scoped) and enabled flag. + List enabled = roleManager.listByIds(roleIds) + .stream() + .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag()) + && (Objects.isNull(tenantId) || tenantId.equals(e.getTenantId()))) + .toList(); + return roleBuilder.buildBOListByDOList(enabled); + } - @Override - public List listResourceByRoleId(Long roleId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleResourceBindDO::getRoleId, roleId); - List entityDOList = roleResourceBindManager.list(wrapper); - if (CollectionUtils.isNotEmpty(entityDOList)) { - List resourceDOList = resourceManager - .listByIds(entityDOList.stream().map(RoleResourceBindDO::getResourceId).toList()); - List collect = resourceDOList.stream() - .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) - .toList(); - return resourceBuilder.buildBOListByDOList(collect); - } + @Override + public List listResourceByRoleId(Long roleId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleResourceBindDO::getRoleId, roleId); + List entityDOList = roleResourceBindManager.list(wrapper); + if (CollectionUtils.isNotEmpty(entityDOList)) { + List resourceDOList = resourceManager + .listByIds(entityDOList.stream().map(RoleResourceBindDO::getResourceId).toList()); + List collect = resourceDOList.stream() + .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) + .toList(); + return resourceBuilder.buildBOListByDOList(collect); + } - return null; - } + return null; + } - /** - * @param entityQuery {@link RoleResourceBindQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(RoleResourceBindQuery entityQuery, Long tenantId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getRoleId()), RoleResourceBindDO::getRoleId, - entityQuery.getRoleId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getResourceId()), RoleResourceBindDO::getResourceId, - entityQuery.getResourceId()); - if (Objects.nonNull(tenantId)) { - LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); - roleWrapper.eq(RoleDO::getTenantId, tenantId); - roleWrapper.select(RoleDO::getId); - List roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(roleIds)) { - wrapper.apply("1 = 0"); - } - else { - wrapper.in(RoleResourceBindDO::getRoleId, roleIds); - } - } - return wrapper; - } + /** + * @param entityQuery {@link RoleResourceBindQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(RoleResourceBindQuery entityQuery, Long tenantId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getRoleId()), RoleResourceBindDO::getRoleId, + entityQuery.getRoleId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getResourceId()), RoleResourceBindDO::getResourceId, + entityQuery.getResourceId()); + if (Objects.nonNull(tenantId)) { + LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); + roleWrapper.eq(RoleDO::getTenantId, tenantId); + roleWrapper.select(RoleDO::getId); + List roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(roleIds)) { + wrapper.apply("1 = 0"); + } else { + wrapper.in(RoleResourceBindDO::getRoleId, roleIds); + } + } + return wrapper; + } - /** - * @param entityBO {@link RoleResourceBindBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(RoleResourceBindBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleResourceBindDO::getRoleId, entityBO.getRoleId()); - wrapper.eq(RoleResourceBindDO::getResourceId, entityBO.getResourceId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - RoleResourceBindDO one = roleResourceBindManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link RoleResourceBindBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(RoleResourceBindBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleResourceBindDO::getRoleId, entityBO.getRoleId()); + wrapper.eq(RoleResourceBindDO::getResourceId, entityBO.getResourceId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + RoleResourceBindDO one = roleResourceBindManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link RoleResourceBindDO} - */ - private RoleResourceBindDO getDOById(Long id, boolean throwException) { - RoleResourceBindDO entityDO = roleResourceBindManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Role resource bind does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link RoleResourceBindDO} + */ + private RoleResourceBindDO getDOById(Long id, boolean throwException) { + RoleResourceBindDO entityDO = roleResourceBindManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Role resource bind does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleServiceImpl.java index 2d79641e6..7d75e2d77 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleServiceImpl.java @@ -53,164 +53,164 @@ import java.util.*; @Service public class RoleServiceImpl implements RoleService { - @Resource - private RoleBuilder roleBuilder; + @Resource + private RoleBuilder roleBuilder; - @Resource - private RoleManager roleManager; + @Resource + private RoleManager roleManager; - @Override - public void save(RoleBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(RoleBO entityBO) { + checkDuplicate(entityBO, false, true); - RoleDO entityDO = roleBuilder.buildDOByBO(entityBO); - if (!roleManager.save(entityDO)) { - throw new AddException("Failed to create role"); - } - } + RoleDO entityDO = roleBuilder.buildDOByBO(entityBO); + if (!roleManager.save(entityDO)) { + throw new AddException("Failed to create role"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // - LambdaQueryChainWrapper wrapper = roleManager.lambdaQuery().eq(RoleDO::getParentRoleId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove role: some sub roles exists in the role"); - } + // + LambdaQueryChainWrapper wrapper = roleManager.lambdaQuery().eq(RoleDO::getParentRoleId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove role: some sub roles exists in the role"); + } - if (!roleManager.removeById(id)) { - throw new DeleteException("Failed to remove role"); - } - } + if (!roleManager.removeById(id)) { + throw new DeleteException("Failed to remove role"); + } + } - @Override - public void update(RoleBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(RoleBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - RoleDO entityDO = roleBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!roleManager.updateById(entityDO)) { - throw new UpdateException("Failed to update role"); - } - } + RoleDO entityDO = roleBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!roleManager.updateById(entityDO)) { + throw new UpdateException("Failed to update role"); + } + } - @Override - public RoleBO selectById(Long id) { - RoleDO entityDO = getDOById(id, true); - return roleBuilder.buildBOByDO(entityDO); - } + @Override + public RoleBO selectById(Long id) { + RoleDO entityDO = getDOById(id, true); + return roleBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(RoleQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = roleManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return roleBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(RoleQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = roleManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return roleBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public List selectTree(RoleQuery entityQuery) { - RoleQuery effective = Objects.requireNonNullElseGet(entityQuery, RoleQuery::new); - List rows = roleManager.list(fuzzyQuery(effective)); - return assembleTree(rows); - } + @Override + public List selectTree(RoleQuery entityQuery) { + RoleQuery effective = Objects.requireNonNullElseGet(entityQuery, RoleQuery::new); + List rows = roleManager.list(fuzzyQuery(effective)); + return assembleTree(rows); + } - /** - * Build the role hierarchy from a flat list of DOs. Roles with {@code parent_role_id} - * null or 0 become roots; children are linked by their {@code parent_role_id}, and - * each level is ordered by role name. - */ - private List assembleTree(List rows) { - if (CollectionUtils.isEmpty(rows)) { - return new ArrayList<>(); - } - Map byId = new HashMap<>(rows.size()); - Map parentByChild = new HashMap<>(rows.size()); - for (RoleDO row : rows) { - RoleTreeBO node = RoleTreeBO.fromBO(roleBuilder.buildBOByDO(row)); - byId.put(row.getId(), node); - parentByChild.put(row.getId(), row.getParentRoleId()); - } - List roots = new ArrayList<>(); - for (Map.Entry e : byId.entrySet()) { - Long parentId = parentByChild.get(e.getKey()); - RoleTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); - if (parent == null) { - roots.add(e.getValue()); - } - else { - parent.addChild(e.getValue()); - } - } - Comparator order = Comparator.comparing(RoleTreeBO::getRoleName, - Comparator.nullsLast(Comparator.naturalOrder())); - sortRecursive(roots, order); - return roots; - } + /** + * Build the role hierarchy from a flat list of DOs. Roles with {@code parent_role_id} + * null or 0 become roots; children are linked by their {@code parent_role_id}, and + * each level is ordered by role name. + */ + private List assembleTree(List rows) { + if (CollectionUtils.isEmpty(rows)) { + return new ArrayList<>(); + } + Map byId = new HashMap<>(rows.size()); + Map parentByChild = new HashMap<>(rows.size()); + for (RoleDO row : rows) { + RoleTreeBO node = RoleTreeBO.fromBO(roleBuilder.buildBOByDO(row)); + byId.put(row.getId(), node); + parentByChild.put(row.getId(), row.getParentRoleId()); + } + List roots = new ArrayList<>(); + for (Map.Entry e : byId.entrySet()) { + Long parentId = parentByChild.get(e.getKey()); + RoleTreeBO parent = parentId == null || parentId == 0L ? null : byId.get(parentId); + if (parent == null) { + roots.add(e.getValue()); + } else { + parent.addChild(e.getValue()); + } + } + Comparator order = Comparator.comparing(RoleTreeBO::getRoleName, + Comparator.nullsLast(Comparator.naturalOrder())); + sortRecursive(roots, order); + return roots; + } - private void sortRecursive(List nodes, Comparator order) { - if (CollectionUtils.isEmpty(nodes)) { - return; - } - nodes.sort(order); - for (RoleTreeBO node : nodes) { - sortRecursive(node.getChildren(), order); - } - } + private void sortRecursive(List nodes, Comparator order) { + if (CollectionUtils.isEmpty(nodes)) { + return; + } + nodes.sort(order); + for (RoleTreeBO node : nodes) { + sortRecursive(node.getChildren(), order); + } + } - /** - * @param entityQuery {@link RoleQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(RoleQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getRoleName()), RoleDO::getRoleName, entityQuery.getRoleName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getRoleCode()), RoleDO::getRoleCode, entityQuery.getRoleCode()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), RoleDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link RoleQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(RoleQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getRoleName()), RoleDO::getRoleName, entityQuery.getRoleName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getRoleCode()), RoleDO::getRoleCode, entityQuery.getRoleCode()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), RoleDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link RoleBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(RoleBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleDO::getParentRoleId, entityBO.getParentRoleId()); - wrapper.eq(RoleDO::getRoleName, entityBO.getRoleName()); - wrapper.eq(RoleDO::getRoleCode, entityBO.getRoleCode()); - wrapper.eq(RoleDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - RoleDO one = roleManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Role has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link RoleBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(RoleBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleDO::getParentRoleId, entityBO.getParentRoleId()); + wrapper.eq(RoleDO::getRoleName, entityBO.getRoleName()); + wrapper.eq(RoleDO::getRoleCode, entityBO.getRoleCode()); + wrapper.eq(RoleDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + RoleDO one = roleManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Role has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link RoleDO} - */ - private RoleDO getDOById(Long id, boolean throwException) { - RoleDO entityDO = roleManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Role does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link RoleDO} + */ + private RoleDO getDOById(Long id, boolean throwException) { + RoleDO entityDO = roleManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Role does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleUserBindServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleUserBindServiceImpl.java index 7c46f9eca..ce5798213 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleUserBindServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/RoleUserBindServiceImpl.java @@ -58,173 +58,173 @@ import java.util.Objects; @Service public class RoleUserBindServiceImpl implements RoleUserBindService { - @Resource - private RoleUserBindBuilder roleUserBindBuilder; + @Resource + private RoleUserBindBuilder roleUserBindBuilder; - @Resource - private RoleBuilder roleBuilder; + @Resource + private RoleBuilder roleBuilder; - @Resource - private UserBuilder userBuilder; + @Resource + private UserBuilder userBuilder; - @Resource - private RoleUserBindManager roleUserBindManager; + @Resource + private RoleUserBindManager roleUserBindManager; - @Resource - private RoleManager roleManager; + @Resource + private RoleManager roleManager; - @Resource - private UserManager userManager; + @Resource + private UserManager userManager; - @Override - public void save(RoleUserBindBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(RoleUserBindBO entityBO) { + checkDuplicate(entityBO, false, true); - RoleUserBindDO entityDO = roleUserBindBuilder.buildDOByBO(entityBO); - if (!roleUserBindManager.save(entityDO)) { - throw new AddException("Failed to create role user bind"); - } - } + RoleUserBindDO entityDO = roleUserBindBuilder.buildDOByBO(entityBO); + if (!roleUserBindManager.save(entityDO)) { + throw new AddException("Failed to create role user bind"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!roleUserBindManager.removeById(id)) { - throw new DeleteException("Failed to remove role user bind"); - } - } + if (!roleUserBindManager.removeById(id)) { + throw new DeleteException("Failed to remove role user bind"); + } + } - @Override - public void update(RoleUserBindBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(RoleUserBindBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - RoleUserBindDO entityDO = roleUserBindBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!roleUserBindManager.updateById(entityDO)) { - throw new UpdateException("The role user bind update failed"); - } - } + RoleUserBindDO entityDO = roleUserBindBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!roleUserBindManager.updateById(entityDO)) { + throw new UpdateException("The role user bind update failed"); + } + } - @Override - public RoleUserBindBO selectById(Long id) { - RoleUserBindDO entityDO = getDOById(id, true); - return roleUserBindBuilder.buildBOByDO(entityDO); - } + @Override + public RoleUserBindBO selectById(Long id) { + RoleUserBindDO entityDO = getDOById(id, true); + return roleUserBindBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(RoleUserBindQuery entityQuery) { - return selectByPage(entityQuery, null); - } + @Override + public Page selectByPage(RoleUserBindQuery entityQuery) { + return selectByPage(entityQuery, null); + } - @Override - public Page selectByPage(RoleUserBindQuery entityQuery, Long tenantId) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = roleUserBindManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery, tenantId)); - return roleUserBindBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(RoleUserBindQuery entityQuery, Long tenantId) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = roleUserBindManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery, tenantId)); + return roleUserBindBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public List listUserByRoleId(Long roleId) { - if (Objects.isNull(roleId)) { - return Collections.emptyList(); - } - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleUserBindDO::getRoleId, roleId); - wrapper.select(RoleUserBindDO::getUserId); - List userIds = roleUserBindManager.listObjs(wrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(userIds)) { - return Collections.emptyList(); - } - List enabled = userManager.listByIds(userIds) - .stream() - .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) - .toList(); - return userBuilder.buildBOListByDOList(enabled); - } + @Override + public List listUserByRoleId(Long roleId) { + if (Objects.isNull(roleId)) { + return Collections.emptyList(); + } + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleUserBindDO::getRoleId, roleId); + wrapper.select(RoleUserBindDO::getUserId); + List userIds = roleUserBindManager.listObjs(wrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(userIds)) { + return Collections.emptyList(); + } + List enabled = userManager.listByIds(userIds) + .stream() + .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag())) + .toList(); + return userBuilder.buildBOListByDOList(enabled); + } - @Override - public List listRoleByTenantIdAndUserId(Long tenantId, Long userId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleUserBindDO::getUserId, userId); - List roleUserBindBOList = roleUserBindManager.list(wrapper); - if (CollectionUtils.isNotEmpty(roleUserBindBOList)) { - List roleBOList = roleManager - .listByIds(roleUserBindBOList.stream().map(RoleUserBindDO::getRoleId).toList()); - List collect = roleBOList.stream() - .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag()) - && (Objects.isNull(tenantId) || tenantId.equals(e.getTenantId()))) - .toList(); - return roleBuilder.buildBOListByDOList(collect); - } + @Override + public List listRoleByTenantIdAndUserId(Long tenantId, Long userId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleUserBindDO::getUserId, userId); + List roleUserBindBOList = roleUserBindManager.list(wrapper); + if (CollectionUtils.isNotEmpty(roleUserBindBOList)) { + List roleBOList = roleManager + .listByIds(roleUserBindBOList.stream().map(RoleUserBindDO::getRoleId).toList()); + List collect = roleBOList.stream() + .filter(e -> EnableFlagEnum.ENABLE.getIndex().equals(e.getEnableFlag()) + && (Objects.isNull(tenantId) || tenantId.equals(e.getTenantId()))) + .toList(); + return roleBuilder.buildBOListByDOList(collect); + } - return null; - } + return null; + } - /** - * @param entityQuery {@link RoleUserBindQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(RoleUserBindQuery entityQuery, Long tenantId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getUserId()), RoleUserBindDO::getUserId, - entityQuery.getUserId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getRoleId()), RoleUserBindDO::getRoleId, - entityQuery.getRoleId()); - if (Objects.nonNull(tenantId)) { - LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); - roleWrapper.eq(RoleDO::getTenantId, tenantId); - roleWrapper.select(RoleDO::getId); - List roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); - if (CollectionUtils.isEmpty(roleIds)) { - wrapper.apply("1 = 0"); - } - else { - wrapper.in(RoleUserBindDO::getRoleId, roleIds); - } - } - return wrapper; - } + /** + * @param entityQuery {@link RoleUserBindQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(RoleUserBindQuery entityQuery, Long tenantId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getUserId()), RoleUserBindDO::getUserId, + entityQuery.getUserId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getRoleId()), RoleUserBindDO::getRoleId, + entityQuery.getRoleId()); + if (Objects.nonNull(tenantId)) { + LambdaQueryWrapper roleWrapper = Wrappers.query().lambda(); + roleWrapper.eq(RoleDO::getTenantId, tenantId); + roleWrapper.select(RoleDO::getId); + List roleIds = roleManager.listObjs(roleWrapper, o -> (Long) o); + if (CollectionUtils.isEmpty(roleIds)) { + wrapper.apply("1 = 0"); + } else { + wrapper.in(RoleUserBindDO::getRoleId, roleIds); + } + } + return wrapper; + } - /** - * @param entityBO {@link RoleUserBindBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(RoleUserBindBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RoleUserBindDO::getRoleId, entityBO.getRoleId()); - wrapper.eq(RoleUserBindDO::getUserId, entityBO.getUserId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - RoleUserBindDO one = roleUserBindManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Role user bind has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link RoleUserBindBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(RoleUserBindBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RoleUserBindDO::getRoleId, entityBO.getRoleId()); + wrapper.eq(RoleUserBindDO::getUserId, entityBO.getUserId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + RoleUserBindDO one = roleUserBindManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Role user bind has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link RoleUserBindDO} - */ - private RoleUserBindDO getDOById(Long id, boolean throwException) { - RoleUserBindDO entityDO = roleUserBindManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Role user bind does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link RoleUserBindDO} + */ + private RoleUserBindDO getDOById(Long id, boolean throwException) { + RoleUserBindDO entityDO = roleUserBindManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Role user bind does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantBindServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantBindServiceImpl.java index a589b7213..2a5153f67 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantBindServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantBindServiceImpl.java @@ -50,127 +50,128 @@ import java.util.Objects; @Service public class TenantBindServiceImpl implements TenantBindService { - @Resource - private TenantBindBuilder tenantBindBuilder; + @Resource + private TenantBindBuilder tenantBindBuilder; - @Resource - private TenantBindManager tenantBindManager; + @Resource + private TenantBindManager tenantBindManager; - @Override - public void save(TenantBindBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(TenantBindBO entityBO) { + checkDuplicate(entityBO, false, true); - TenantBindDO entityDO = tenantBindBuilder.buildDOByBO(entityBO); - if (!tenantBindManager.save(entityDO)) { - throw new AddException("Failed to create tenant bind"); - } - } + TenantBindDO entityDO = tenantBindBuilder.buildDOByBO(entityBO); + if (!tenantBindManager.save(entityDO)) { + throw new AddException("Failed to create tenant bind"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!tenantBindManager.removeById(id)) { - throw new DeleteException("Failed to remove tenant bind"); - } - } + if (!tenantBindManager.removeById(id)) { + throw new DeleteException("Failed to remove tenant bind"); + } + } - @Override - public void update(TenantBindBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(TenantBindBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - TenantBindDO entityDO = tenantBindBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!tenantBindManager.updateById(entityDO)) { - throw new UpdateException("The tenant bind update failed"); - } - } + TenantBindDO entityDO = tenantBindBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!tenantBindManager.updateById(entityDO)) { + throw new UpdateException("The tenant bind update failed"); + } + } - @Override - public TenantBindBO selectById(Long id) { - TenantBindDO entityDO = getDOById(id, true); - return tenantBindBuilder.buildBOByDO(entityDO); - } + @Override + public TenantBindBO selectById(Long id) { + TenantBindDO entityDO = getDOById(id, true); + return tenantBindBuilder.buildBOByDO(entityDO); + } - @Override - public TenantBindBO selectByTenantIdAndUserId(Long tenantId, Long userId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantBindDO::getTenantId, tenantId); - wrapper.eq(TenantBindDO::getUserId, userId); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - TenantBindDO entityDO = tenantBindManager.getOne(wrapper); - return tenantBindBuilder.buildBOByDO(entityDO); - } + @Override + public TenantBindBO selectByTenantIdAndUserId(Long tenantId, Long userId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantBindDO::getTenantId, tenantId); + wrapper.eq(TenantBindDO::getUserId, userId); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + TenantBindDO entityDO = tenantBindManager.getOne(wrapper); + return tenantBindBuilder.buildBOByDO(entityDO); + } - @Override - public List listUserIdsByTenantId(Long tenantId) { - if (Objects.isNull(tenantId)) { - return Collections.emptyList(); - } - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantBindDO::getTenantId, tenantId); - wrapper.select(TenantBindDO::getUserId); - return tenantBindManager.listObjs(wrapper, o -> (Long) o); - } + @Override + public List listUserIdsByTenantId(Long tenantId) { + if (Objects.isNull(tenantId)) { + return Collections.emptyList(); + } + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantBindDO::getTenantId, tenantId); + wrapper.select(TenantBindDO::getUserId); + return tenantBindManager.listObjs(wrapper, o -> (Long) o); + } - @Override - public Page selectByPage(TenantBindQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = tenantBindManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return tenantBindBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(TenantBindQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = tenantBindManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return tenantBindBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link TenantBindQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(TenantBindQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getTenantId()), TenantBindDO::getTenantId, - entityQuery.getTenantId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getUserId()), TenantBindDO::getUserId, entityQuery.getUserId()); - return wrapper; - } + /** + * @param entityQuery {@link TenantBindQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(TenantBindQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getTenantId()), TenantBindDO::getTenantId, + entityQuery.getTenantId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getUserId()), TenantBindDO::getUserId, entityQuery.getUserId()); + return wrapper; + } - /** - * @param entityBO {@link TenantBindBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(TenantBindBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantBindDO::getTenantId, entityBO.getTenantId()); - wrapper.eq(TenantBindDO::getUserId, entityBO.getUserId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - TenantBindDO one = tenantBindManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Tenant has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link TenantBindBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(TenantBindBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantBindDO::getTenantId, entityBO.getTenantId()); + wrapper.eq(TenantBindDO::getUserId, entityBO.getUserId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + TenantBindDO one = tenantBindManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Tenant has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link TenantBindDO} - */ - private TenantBindDO getDOById(Long id, boolean throwException) { - TenantBindDO entityDO = tenantBindManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Tenant bind does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link TenantBindDO} + */ + private TenantBindDO getDOById(Long id, boolean throwException) { + TenantBindDO entityDO = tenantBindManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Tenant bind does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantServiceImpl.java index 06a3ee2d9..0c1bf3f42 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/TenantServiceImpl.java @@ -49,114 +49,115 @@ import java.util.Objects; @Service public class TenantServiceImpl implements TenantService { - @Resource - private TenantBuilder tenantBuilder; + @Resource + private TenantBuilder tenantBuilder; - @Resource - private TenantManager tenantManager; + @Resource + private TenantManager tenantManager; - @Override - public void save(TenantBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(TenantBO entityBO) { + checkDuplicate(entityBO, false, true); - TenantDO entityDO = tenantBuilder.buildDOByBO(entityBO); - if (!tenantManager.save(entityDO)) { - throw new AddException("Failed to create tenant: {}", entityBO.getTenantName()); - } - } + TenantDO entityDO = tenantBuilder.buildDOByBO(entityBO); + if (!tenantManager.save(entityDO)) { + throw new AddException("Failed to create tenant: {}", entityBO.getTenantName()); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!tenantManager.removeById(id)) { - throw new DeleteException("Failed to remove tenant"); - } - } + if (!tenantManager.removeById(id)) { + throw new DeleteException("Failed to remove tenant"); + } + } - @Override - public void update(TenantBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(TenantBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - TenantDO entityDO = tenantBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!tenantManager.updateById(entityDO)) { - throw new UpdateException("Failed to update tenant"); - } - } + TenantDO entityDO = tenantBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!tenantManager.updateById(entityDO)) { + throw new UpdateException("Failed to update tenant"); + } + } - @Override - public TenantBO selectById(Long id) { - TenantDO entityDO = getDOById(id, true); - return tenantBuilder.buildBOByDO(entityDO); - } + @Override + public TenantBO selectById(Long id) { + TenantDO entityDO = getDOById(id, true); + return tenantBuilder.buildBOByDO(entityDO); + } - @Override - public TenantBO selectByCode(String code) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantDO::getTenantCode, code); - wrapper.eq(TenantDO::getEnableFlag, EnableFlagEnum.ENABLE); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - TenantDO entityDO = tenantManager.getOne(wrapper); - return tenantBuilder.buildBOByDO(entityDO); - } + @Override + public TenantBO selectByCode(String code) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantDO::getTenantCode, code); + wrapper.eq(TenantDO::getEnableFlag, EnableFlagEnum.ENABLE); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + TenantDO entityDO = tenantManager.getOne(wrapper); + return tenantBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(TenantQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = tenantManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return tenantBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(TenantQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = tenantManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return tenantBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link TenantQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(TenantQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getTenantName()), TenantDO::getTenantName, - entityQuery.getTenantName()); - return wrapper; - } + /** + * @param entityQuery {@link TenantQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(TenantQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getTenantName()), TenantDO::getTenantName, + entityQuery.getTenantName()); + return wrapper; + } - /** - * @param entityBO {@link TenantBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(TenantBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(TenantDO::getTenantName, entityBO.getTenantName()); - wrapper.eq(TenantDO::getTenantCode, entityBO.getTenantCode()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - TenantDO one = tenantManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Tenant has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link TenantBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(TenantBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(TenantDO::getTenantName, entityBO.getTenantName()); + wrapper.eq(TenantDO::getTenantCode, entityBO.getTenantCode()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + TenantDO one = tenantManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Tenant has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link TenantDO} - */ - private TenantDO getDOById(Long id, boolean throwException) { - TenantDO entityDO = tenantManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("租户"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link TenantDO} + */ + private TenantDO getDOById(Long id, boolean throwException) { + TenantDO entityDO = tenantManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("租户"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserLoginServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserLoginServiceImpl.java index 108a3cfb6..257019f5a 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserLoginServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserLoginServiceImpl.java @@ -47,135 +47,136 @@ import java.util.Objects; @Service public class UserLoginServiceImpl implements UserLoginService { - @Resource - private UserLoginBuilder userLoginBuilder; + @Resource + private UserLoginBuilder userLoginBuilder; - @Resource - private UserLoginManager userLoginManager; + @Resource + private UserLoginManager userLoginManager; - @Override - public void save(UserLoginBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(UserLoginBO entityBO) { + checkDuplicate(entityBO, false, true); - UserLoginDO entityDO = userLoginBuilder.buildDOByBO(entityBO); - if (!userLoginManager.save(entityDO)) { - throw new AddException("Failed to create user: {}", entityBO.toString()); - } - } + UserLoginDO entityDO = userLoginBuilder.buildDOByBO(entityBO); + if (!userLoginManager.save(entityDO)) { + throw new AddException("Failed to create user: {}", entityBO.toString()); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!userLoginManager.removeById(id)) { - throw new DeleteException("Failed to remove user login"); - } - } + if (!userLoginManager.removeById(id)) { + throw new DeleteException("Failed to remove user login"); + } + } - @Override - public void update(UserLoginBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(UserLoginBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - UserLoginDO entityDO = userLoginBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!userLoginManager.updateById(entityDO)) { - throw new UpdateException("The user login update failed"); - } - } + UserLoginDO entityDO = userLoginBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!userLoginManager.updateById(entityDO)) { + throw new UpdateException("The user login update failed"); + } + } - @Override - public UserLoginBO selectById(Long id) { - UserLoginDO entityDO = getDOById(id, true); - return userLoginBuilder.buildBOByDO(entityDO); - } + @Override + public UserLoginBO selectById(Long id) { + UserLoginDO entityDO = getDOById(id, true); + return userLoginBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(UserLoginQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageBO = userLoginManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return userLoginBuilder.buildBOPageByDOPage(entityPageBO); - } + @Override + public Page selectByPage(UserLoginQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageBO = userLoginManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return userLoginBuilder.buildBOPageByDOPage(entityPageBO); + } - @Override - public UserLoginBO selectByLoginName(String loginName, boolean throwException) { - if (StringUtils.isEmpty(loginName)) { - if (throwException) { - throw new EmptyException("The login name is empty"); - } - return null; - } + @Override + public UserLoginBO selectByLoginName(String loginName, boolean throwException) { + if (StringUtils.isEmpty(loginName)) { + if (throwException) { + throw new EmptyException("The login name is empty"); + } + return null; + } - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(UserLoginDO::getLoginName, loginName); - wrapper.eq(UserLoginDO::getEnableFlag, EnableFlagEnum.ENABLE); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - UserLoginDO userLogin = userLoginManager.getOne(wrapper); - if (Objects.isNull(userLogin)) { - throw new NotFoundException(); - } - return userLoginBuilder.buildBOByDO(userLogin); - } + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(UserLoginDO::getLoginName, loginName); + wrapper.eq(UserLoginDO::getEnableFlag, EnableFlagEnum.ENABLE); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + UserLoginDO userLogin = userLoginManager.getOne(wrapper); + if (Objects.isNull(userLogin)) { + throw new NotFoundException(); + } + return userLoginBuilder.buildBOByDO(userLogin); + } - @Override - public boolean checkLoginNameValid(String loginName) { - UserLoginBO userLogin = selectByLoginName(loginName, false); - if (Objects.nonNull(userLogin)) { - return EnableFlagEnum.ENABLE.equals(userLogin.getEnableFlag()); - } + @Override + public boolean checkLoginNameValid(String loginName) { + UserLoginBO userLogin = selectByLoginName(loginName, false); + if (Objects.nonNull(userLogin)) { + return EnableFlagEnum.ENABLE.equals(userLogin.getEnableFlag()); + } - return false; - } + return false; + } - /** - * @param entityQuery {@link UserLoginQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(UserLoginQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getLoginName()), UserLoginDO::getLoginName, - entityQuery.getLoginName()); - return wrapper; - } + /** + * @param entityQuery {@link UserLoginQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(UserLoginQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getLoginName()), UserLoginDO::getLoginName, + entityQuery.getLoginName()); + return wrapper; + } - /** - * @param entityBO {@link UserLoginBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(UserLoginBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(UserLoginDO::getLoginName, entityBO.getLoginName()); - wrapper.eq(UserLoginDO::getUserId, entityBO.getUserId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - UserLoginDO one = userLoginManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("User login has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link UserLoginBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(UserLoginBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(UserLoginDO::getLoginName, entityBO.getLoginName()); + wrapper.eq(UserLoginDO::getUserId, entityBO.getUserId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + UserLoginDO one = userLoginManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("User login has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link UserLoginDO} - */ - private UserLoginDO getDOById(Long id, boolean throwException) { - UserLoginDO entityDO = userLoginManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("User login does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link UserLoginDO} + */ + private UserLoginDO getDOById(Long id, boolean throwException) { + UserLoginDO entityDO = userLoginManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("User login does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserPasswordServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserPasswordServiceImpl.java index 7ae8a85b6..04d8cd809 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserPasswordServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserPasswordServiceImpl.java @@ -47,112 +47,113 @@ import java.util.Objects; @Service public class UserPasswordServiceImpl implements UserPasswordService { - @Resource - private UserPasswordBuilder userPasswordBuilder; + @Resource + private UserPasswordBuilder userPasswordBuilder; - @Resource - private UserPasswordManager userPasswordManager; + @Resource + private UserPasswordManager userPasswordManager; - @Override - public void save(UserPasswordBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(UserPasswordBO entityBO) { + checkDuplicate(entityBO, false, true); - UserPasswordDO entityDO = userPasswordBuilder.buildDOByBO(entityBO); - entityDO.setLoginPassword(DecodeUtil.md5(entityDO.getLoginPassword())); - if (!userPasswordManager.save(entityDO)) { - throw new AddException("Failed to create user password: {}", entityBO.toString()); - } - } + UserPasswordDO entityDO = userPasswordBuilder.buildDOByBO(entityBO); + entityDO.setLoginPassword(DecodeUtil.md5(entityDO.getLoginPassword())); + if (!userPasswordManager.save(entityDO)) { + throw new AddException("Failed to create user password: {}", entityBO.toString()); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!userPasswordManager.removeById(id)) { - throw new DeleteException("Failed to remove user password"); - } - } + if (!userPasswordManager.removeById(id)) { + throw new DeleteException("Failed to remove user password"); + } + } - @Override - public void update(UserPasswordBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(UserPasswordBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - UserPasswordDO entityDO = userPasswordBuilder.buildDOByBO(entityBO); - entityDO.setLoginPassword(DecodeUtil.md5(entityDO.getLoginPassword())); - entityDO.setOperateTime(null); - if (!userPasswordManager.updateById(entityDO)) { - throw new UpdateException("The user password update failed"); - } - } + UserPasswordDO entityDO = userPasswordBuilder.buildDOByBO(entityBO); + entityDO.setLoginPassword(DecodeUtil.md5(entityDO.getLoginPassword())); + entityDO.setOperateTime(null); + if (!userPasswordManager.updateById(entityDO)) { + throw new UpdateException("The user password update failed"); + } + } - @Override - public UserPasswordBO selectById(Long id) { - UserPasswordDO entityDO = getDOById(id, true); - return userPasswordBuilder.buildBOByDO(entityDO); - } + @Override + public UserPasswordBO selectById(Long id) { + UserPasswordDO entityDO = getDOById(id, true); + return userPasswordBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(UserPasswordQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = userPasswordManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return userPasswordBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(UserPasswordQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = userPasswordManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return userPasswordBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public void restPassword(Long id) { - UserPasswordBO userPasswordBO = selectById(id); - if (Objects.nonNull(userPasswordBO)) { - userPasswordBO.setLoginPassword(DecodeUtil.md5(AlgorithmConstant.DEFAULT_PASSWORD)); - update(userPasswordBO); - } - } + @Override + public void restPassword(Long id) { + UserPasswordBO userPasswordBO = selectById(id); + if (Objects.nonNull(userPasswordBO)) { + userPasswordBO.setLoginPassword(DecodeUtil.md5(AlgorithmConstant.DEFAULT_PASSWORD)); + update(userPasswordBO); + } + } - /** - * @param entityQuery {@link UserPasswordQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(UserPasswordQuery entityQuery) { - return Wrappers.query().lambda(); - } + /** + * @param entityQuery {@link UserPasswordQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(UserPasswordQuery entityQuery) { + return Wrappers.query().lambda(); + } - /** - * @param entityBO {@link UserPasswordBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(UserPasswordBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(UserPasswordDO::getLoginPassword, entityBO.getLoginPassword()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - UserPasswordDO one = userPasswordManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("User password has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link UserPasswordBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(UserPasswordBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(UserPasswordDO::getLoginPassword, entityBO.getLoginPassword()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + UserPasswordDO one = userPasswordManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("User password has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link UserPasswordDO} - */ - private UserPasswordDO getDOById(Long id, boolean throwException) { - UserPasswordDO entityDO = userPasswordManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("User password does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link UserPasswordDO} + */ + private UserPasswordDO getDOById(Long id, boolean throwException) { + UserPasswordDO entityDO = userPasswordManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("User password does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserServiceImpl.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserServiceImpl.java index bb9f934ec..d3b737e1f 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserServiceImpl.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/auth/service/impl/UserServiceImpl.java @@ -56,209 +56,211 @@ import java.util.Objects; @Service public class UserServiceImpl implements UserService { - @Resource - private UserBuilder userBuilder; + @Resource + private UserBuilder userBuilder; - @Resource - private UserManager userManager; + @Resource + private UserManager userManager; - @Resource - private TenantBindService tenantBindService; + @Resource + private TenantBindService tenantBindService; - @Override - public void save(UserBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(UserBO entityBO) { + checkDuplicate(entityBO, false, true); - // When phone number is present, check whether it is already occupied. - if (StringUtils.isNotEmpty(entityBO.getPhone())) { - UserBO selectByPhone = selectByPhone(entityBO.getPhone(), false); - if (Objects.nonNull(selectByPhone)) { - throw new DuplicateException("The user already exists with phone: {}", entityBO.getPhone()); - } - } + // When phone number is present, check whether it is already occupied. + if (StringUtils.isNotEmpty(entityBO.getPhone())) { + UserBO selectByPhone = selectByPhone(entityBO.getPhone(), false); + if (Objects.nonNull(selectByPhone)) { + throw new DuplicateException("The user already exists with phone: {}", entityBO.getPhone()); + } + } - // When email is present, check whether it is already occupied. - if (StringUtils.isNotEmpty(entityBO.getEmail())) { - UserBO selectByEmail = selectByEmail(entityBO.getEmail(), false); - if (Objects.nonNull(selectByEmail)) { - throw new DuplicateException("The user already exists with email: {}", entityBO.getEmail()); - } - } + // When email is present, check whether it is already occupied. + if (StringUtils.isNotEmpty(entityBO.getEmail())) { + UserBO selectByEmail = selectByEmail(entityBO.getEmail(), false); + if (Objects.nonNull(selectByEmail)) { + throw new DuplicateException("The user already exists with email: {}", entityBO.getEmail()); + } + } - UserDO entityDO = userBuilder.buildDOByBO(entityBO); - if (!userManager.save(entityDO)) { - throw new AddException("Failed to create user: {}", entityBO.toString()); - } - } + UserDO entityDO = userBuilder.buildDOByBO(entityBO); + if (!userManager.save(entityDO)) { + throw new AddException("Failed to create user: {}", entityBO.toString()); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!userManager.removeById(id)) { - throw new DeleteException("Failed to remove user"); - } - } + if (!userManager.removeById(id)) { + throw new DeleteException("Failed to remove user"); + } + } - @Override - public void update(UserBO entityBO) { - UserDO selectById = getDOById(entityBO.getId(), true); + @Override + public void update(UserBO entityBO) { + UserDO selectById = getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - // Check whether phone number is updated. - if (StringUtils.isNotEmpty(entityBO.getPhone())) { - if (!entityBO.getPhone().equals(selectById.getPhone())) { - UserBO selectByPhone = selectByPhone(entityBO.getPhone(), false); - if (Objects.nonNull(selectByPhone)) { - throw new DuplicateException("The user already exists with phone {}", entityBO.getPhone()); - } - } - } + // Check whether phone number is updated. + if (StringUtils.isNotEmpty(entityBO.getPhone())) { + if (!entityBO.getPhone().equals(selectById.getPhone())) { + UserBO selectByPhone = selectByPhone(entityBO.getPhone(), false); + if (Objects.nonNull(selectByPhone)) { + throw new DuplicateException("The user already exists with phone {}", entityBO.getPhone()); + } + } + } - // Check whether email is updated. - if (StringUtils.isNotEmpty(entityBO.getEmail())) { - if (!entityBO.getEmail().equals(selectById.getEmail())) { - UserBO selectByEmail = selectByEmail(entityBO.getEmail(), false); - if (Objects.nonNull(selectByEmail)) { - throw new DuplicateException("The user already exists with email {}", entityBO.getEmail()); - } - } - } + // Check whether email is updated. + if (StringUtils.isNotEmpty(entityBO.getEmail())) { + if (!entityBO.getEmail().equals(selectById.getEmail())) { + UserBO selectByEmail = selectByEmail(entityBO.getEmail(), false); + if (Objects.nonNull(selectByEmail)) { + throw new DuplicateException("The user already exists with email {}", entityBO.getEmail()); + } + } + } - UserDO entityDO = userBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!userManager.updateById(entityDO)) { - throw new UpdateException("The user update failed"); - } - } + UserDO entityDO = userBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!userManager.updateById(entityDO)) { + throw new UpdateException("The user update failed"); + } + } - @Override - public UserBO selectById(Long id) { - UserDO entityDO = getDOById(id, true); - return userBuilder.buildBOByDO(entityDO); - } + @Override + public UserBO selectById(Long id) { + UserDO entityDO = getDOById(id, true); + return userBuilder.buildBOByDO(entityDO); + } - public UserBO selectByUserName(String userName, boolean throwException) { - if (StringUtils.isEmpty(userName)) { - if (throwException) { - throw new EmptyException("The name is empty"); - } - return null; - } + public UserBO selectByUserName(String userName, boolean throwException) { + if (StringUtils.isEmpty(userName)) { + if (throwException) { + throw new EmptyException("The name is empty"); + } + return null; + } - return selectByKey(UserDO::getUserName, userName, throwException); - } + return selectByKey(UserDO::getUserName, userName, throwException); + } - @Override - public UserBO selectByPhone(String phone, boolean throwException) { - if (StringUtils.isEmpty(phone)) { - if (throwException) { - throw new EmptyException("The phone is empty"); - } - return null; - } + @Override + public UserBO selectByPhone(String phone, boolean throwException) { + if (StringUtils.isEmpty(phone)) { + if (throwException) { + throw new EmptyException("The phone is empty"); + } + return null; + } - return selectByKey(UserDO::getPhone, phone, throwException); - } + return selectByKey(UserDO::getPhone, phone, throwException); + } - @Override - public UserBO selectByEmail(String email, boolean throwException) { - if (StringUtils.isEmpty(email)) { - if (throwException) { - throw new EmptyException("The phone is empty"); - } - return null; - } + @Override + public UserBO selectByEmail(String email, boolean throwException) { + if (StringUtils.isEmpty(email)) { + if (throwException) { + throw new EmptyException("The phone is empty"); + } + return null; + } - return selectByKey(UserDO::getEmail, email, throwException); - } + return selectByKey(UserDO::getEmail, email, throwException); + } - @Override - public Page selectByPage(UserQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page page = userManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return userBuilder.buildBOPageByDOPage(page); - } + @Override + public Page selectByPage(UserQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page page = userManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return userBuilder.buildBOPageByDOPage(page); + } - /** - * Build fuzzy query wrapper for user search. - * @param entityQuery {@link UserQuery} query parameters - * @return {@link LambdaQueryWrapper} for {@link UserDO} - */ - private LambdaQueryWrapper fuzzyQuery(UserQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getNickName()), UserDO::getNickName, entityQuery.getNickName()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getUserName()), UserDO::getUserName, entityQuery.getUserName()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getPhone()), UserDO::getPhone, entityQuery.getPhone()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getEmail()), UserDO::getEmail, entityQuery.getEmail()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), UserDO::getEnableFlag, entityQuery.getEnableFlag()); - // Tenant scope. Users have no tenant_id column — they're associated with - // tenants through dc3_tenant_bind. Resolve the bound user_ids for the - // controller-supplied tenant and constrain the list to that set. - if (Objects.nonNull(entityQuery.getTenantId())) { - List userIds = tenantBindService.listUserIdsByTenantId(entityQuery.getTenantId()); - if (CollectionUtils.isEmpty(userIds)) { - wrapper.apply("1 = 0"); - } - else { - wrapper.in(UserDO::getId, userIds); - } - } - return wrapper; - } + /** + * Build fuzzy query wrapper for user search. + * + * @param entityQuery {@link UserQuery} query parameters + * @return {@link LambdaQueryWrapper} for {@link UserDO} + */ + private LambdaQueryWrapper fuzzyQuery(UserQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getNickName()), UserDO::getNickName, entityQuery.getNickName()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getUserName()), UserDO::getUserName, entityQuery.getUserName()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getPhone()), UserDO::getPhone, entityQuery.getPhone()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getEmail()), UserDO::getEmail, entityQuery.getEmail()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), UserDO::getEnableFlag, entityQuery.getEnableFlag()); + // Tenant scope. Users have no tenant_id column — they're associated with + // tenants through dc3_tenant_bind. Resolve the bound user_ids for the + // controller-supplied tenant and constrain the list to that set. + if (Objects.nonNull(entityQuery.getTenantId())) { + List userIds = tenantBindService.listUserIdsByTenantId(entityQuery.getTenantId()); + if (CollectionUtils.isEmpty(userIds)) { + wrapper.apply("1 = 0"); + } else { + wrapper.in(UserDO::getId, userIds); + } + } + return wrapper; + } - private UserBO selectByKey(SFunction key, String value, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(key, value); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - UserDO userDO = userManager.getOne(wrapper); - if (Objects.isNull(userDO)) { - if (throwException) { - throw new NotFoundException(); - } - return null; - } - return userBuilder.buildBOByDO(userDO); - } + private UserBO selectByKey(SFunction key, String value, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(key, value); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + UserDO userDO = userManager.getOne(wrapper); + if (Objects.isNull(userDO)) { + if (throwException) { + throw new NotFoundException(); + } + return null; + } + return userBuilder.buildBOByDO(userDO); + } - /** - * Check whether a user is duplicated by username. - * @param entityBO {@link UserBO} to be validated - * @param isUpdate whether the operation is an update (true) or create (false) - * @param throwException whether to throw {@link DuplicateException} when duplicated - * @return {@code true} if duplicated, otherwise {@code false} - */ - private boolean checkDuplicate(UserBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(UserDO::getUserName, entityBO.getUserName()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - UserDO one = userManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("User has been duplicated"); - } - return duplicate; - } + /** + * Check whether a user is duplicated by username. + * + * @param entityBO {@link UserBO} to be validated + * @param isUpdate whether the operation is an update (true) or create (false) + * @param throwException whether to throw {@link DuplicateException} when duplicated + * @return {@code true} if duplicated, otherwise {@code false} + */ + private boolean checkDuplicate(UserBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(UserDO::getUserName, entityBO.getUserName()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + UserDO one = userManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("User has been duplicated"); + } + return duplicate; + } - /** - * Get user data object by primary key ID. - * @param id primary key ID - * @param throwException whether to throw {@link NotFoundException} when not found - * @return {@link UserDO} if found, otherwise {@code null} when {@code throwException} - * is false - */ - private UserDO getDOById(Long id, boolean throwException) { - UserDO entityDO = userManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("User does not exist"); - } - return entityDO; - } + /** + * Get user data object by primary key ID. + * + * @param id primary key ID + * @param throwException whether to throw {@link NotFoundException} when not found + * @return {@link UserDO} if found, otherwise {@code null} when {@code throwException} + * is false + */ + private UserDO getDOById(Long id, boolean throwException) { + UserDO entityDO = userManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("User does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/config/ActiveAuthProfileConfig.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/config/ActiveAuthProfileConfig.java index 427d58564..249f8e0bc 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/config/ActiveAuthProfileConfig.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/config/ActiveAuthProfileConfig.java @@ -37,9 +37,9 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveAuthProfileConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("auth"); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("auth"); + } } diff --git a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/init/AuthInitRunner.java b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/init/AuthInitRunner.java index 0b9b40ad9..bbe5be0ea 100644 --- a/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/init/AuthInitRunner.java +++ b/dc3-common/dc3-common-auth/src/main/java/io/github/pnoker/common/init/AuthInitRunner.java @@ -35,14 +35,14 @@ import org.springframework.context.annotation.Configuration; */ @Slf4j @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.auth" }) -@MapperScan(basePackages = { "io.github.pnoker.common.auth.mapper" }) +@ComponentScan(basePackages = {"io.github.pnoker.common.auth"}) +@MapperScan(basePackages = {"io.github.pnoker.common.auth.mapper"}) public class AuthInitRunner implements ApplicationRunner { - @Override - public void run(ApplicationArguments args) throws Exception { - // Currently no initialization tasks are required - // This method can be extended to add future authentication initialization logic - } + @Override + public void run(ApplicationArguments args) throws Exception { + // Currently no initialization tasks are required + // This method can be extended to add future authentication initialization logic + } } diff --git a/dc3-common/dc3-common-constant/README.md b/dc3-common/dc3-common-constant/README.md index d1ef10753..50a4ad5a6 100644 --- a/dc3-common/dc3-common-constant/README.md +++ b/dc3-common/dc3-common-constant/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-constant` is the shared constants and enumerations module of the IoT DC3 platform. It defines all platform-wide constants, routing keys, service names, URL prefixes, +`dc3-common-constant` is the shared constants and enumerations module of the IoT DC3 platform. It defines all +platform-wide constants, routing keys, service names, URL prefixes, and enumeration types used across services, drivers, and common modules. ## Module Information @@ -36,7 +37,8 @@ and enumeration types used across services, drivers, and common modules. | `ROUTING_DRIVER_METADATA_PREFIX` | `dc3.r.metadata.driver.` | | `ROUTING_POINT_VALUE_PREFIX` | `dc3.r.value.point.` | -> **Important**: RabbitMQ routing keys are suffixed with the driver's service name. These constants must not be renamed without updating all consumers. +> **Important**: RabbitMQ routing keys are suffixed with the driver's service name. These constants must not be renamed +> without updating all consumers. ### Common Constants diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/cache/TimeoutConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/cache/TimeoutConstant.java index da7be792d..7d9d2e73c 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/cache/TimeoutConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/cache/TimeoutConstant.java @@ -28,23 +28,23 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class TimeoutConstant { - /** - * salt cache timeout, minutes - */ - public static final int SALT_CACHE_TIMEOUT = 5; + /** + * salt cache timeout, minutes + */ + public static final int SALT_CACHE_TIMEOUT = 5; - /** - * user login limit timeout, minutes - */ - public static final int USER_LIMIT_TIMEOUT = 5; + /** + * user login limit timeout, minutes + */ + public static final int USER_LIMIT_TIMEOUT = 5; - /** - * token cache timeout, hours - */ - public static final int TOKEN_CACHE_TIMEOUT = 12; + /** + * token cache timeout, hours + */ + public static final int TOKEN_CACHE_TIMEOUT = 12; - private TimeoutConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private TimeoutConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/AlgorithmConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/AlgorithmConstant.java index 262cd9abe..02198ddfc 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/AlgorithmConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/AlgorithmConstant.java @@ -30,48 +30,48 @@ package io.github.pnoker.common.constant.common; */ public class AlgorithmConstant { - /** - * Default encryption key - */ - public static final String DEFAULT_KEY = "io.github.pnoker.dc3"; + /** + * Default encryption key + */ + public static final String DEFAULT_KEY = "io.github.pnoker.dc3"; - /** - * Default password - */ - public static final String DEFAULT_PASSWORD = "dc3dc3dc3"; + /** + * Default password + */ + public static final String DEFAULT_PASSWORD = "dc3dc3dc3"; - /** - * Symmetric encryption algorithm: AES - */ - public static final String ALGORITHM_AES = "AES"; + /** + * Symmetric encryption algorithm: AES + */ + public static final String ALGORITHM_AES = "AES"; - /** - * Asymmetric encryption algorithm: RSA - */ - public static final String ALGORITHM_RSA = "RSA"; + /** + * Asymmetric encryption algorithm: RSA + */ + public static final String ALGORITHM_RSA = "RSA"; - /** - * Encryption algorithm: SHA256withRSA - */ - public static final String ALGORITHM_SHA256_RSA = "SHA256withRSA"; + /** + * Encryption algorithm: SHA256withRSA + */ + public static final String ALGORITHM_SHA256_RSA = "SHA256withRSA"; - /** - * Certificate type: X.509 - */ - public static final String CERTIFICATE_X509 = "X.509"; + /** + * Certificate type: X.509 + */ + public static final String CERTIFICATE_X509 = "X.509"; - /** - * Certificate type: PKCS12 - */ - public static final String CERTIFICATE_PKCS12 = "PKCS12"; + /** + * Certificate type: PKCS12 + */ + public static final String CERTIFICATE_PKCS12 = "PKCS12"; - /** - * Certificate type: JKS (Java KeyStore) - */ - public static final String CERTIFICATE_JKS = "jks"; + /** + * Certificate type: JKS (Java KeyStore) + */ + public static final String CERTIFICATE_JKS = "jks"; - private AlgorithmConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private AlgorithmConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/DefaultConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/DefaultConstant.java index aa069ad60..e1366a14d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/DefaultConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/DefaultConstant.java @@ -26,48 +26,48 @@ package io.github.pnoker.common.constant.common; */ public class DefaultConstant { - /** - * Default {@link Integer} null value: {@code -1}. - */ - public static final Integer NULL_INT = -1; + /** + * Default {@link Integer} null value: {@code -1}. + */ + public static final Integer NULL_INT = -1; - /** - * Default {@link Integer} zero value: {@code 0}. - */ - public static final Integer DEFAULT_INT = 0; + /** + * Default {@link Integer} zero value: {@code 0}. + */ + public static final Integer DEFAULT_INT = 0; - /** - * Zero constant: {@code 0}. - */ - public static final Integer ZERO = 0; + /** + * Zero constant: {@code 0}. + */ + public static final Integer ZERO = 0; - /** - * One constant: {@code 1}. - */ - public static final Integer ONE = 1; + /** + * One constant: {@code 1}. + */ + public static final Integer ONE = 1; - /** - * Default username. - */ - public static final String USER_NAME = "pnoker"; + /** + * Default username. + */ + public static final String USER_NAME = "pnoker"; - /** - * Default {@link String} null value: {@code "nil"}. - */ - public static final String NULL_STRING = "nil"; + /** + * Default {@link String} null value: {@code "nil"}. + */ + public static final String NULL_STRING = "nil"; - /** - * Default page size. - */ - public static final Integer PAGE_SIZE = 20; + /** + * Default page size. + */ + public static final Integer PAGE_SIZE = 20; - /** - * Default maximum page size. - */ - public static final Integer MAX_PAGE_SIZE = 100; + /** + * Default maximum page size. + */ + public static final Integer MAX_PAGE_SIZE = 100; - private DefaultConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private DefaultConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/EnvironmentConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/EnvironmentConstant.java index 235e0f294..2d2702799 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/EnvironmentConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/EnvironmentConstant.java @@ -30,94 +30,94 @@ package io.github.pnoker.common.constant.common; */ public class EnvironmentConstant { - /** - * Development environment: "dev" - */ - public static final String ENV_DEV = "dev"; + /** + * Development environment: "dev" + */ + public static final String ENV_DEV = "dev"; - /** - * Test environment: "test" - */ - public static final String ENV_TEST = "test"; + /** + * Test environment: "test" + */ + public static final String ENV_TEST = "test"; - /** - * Pre-production environment: "pre" - */ - public static final String ENV_PRE = "pre"; + /** + * Pre-production environment: "pre" + */ + public static final String ENV_PRE = "pre"; - /** - * Production environment: "pro" - */ - public static final String ENV_PRO = "pro"; + /** + * Production environment: "pro" + */ + public static final String ENV_PRO = "pro"; - /** - * Eureka TLS enable configuration key: "eureka.client.tls.enabled" - */ - public static final String EUREKA_TLS_ENABLE = "eureka.client.tls.enabled"; + /** + * Eureka TLS enable configuration key: "eureka.client.tls.enabled" + */ + public static final String EUREKA_TLS_ENABLE = "eureka.client.tls.enabled"; - /** - * Eureka service registry URL configuration key: - * "eureka.client.service-url.defaultZone" - */ - public static final String EUREKA_SERVICE_URL = "eureka.client.service-url.defaultZone"; + /** + * Eureka service registry URL configuration key: + * "eureka.client.service-url.defaultZone" + */ + public static final String EUREKA_SERVICE_URL = "eureka.client.service-url.defaultZone"; - /** - * Current environment type configuration key: "spring.env" - */ - public static final String SPRING_ENV = "spring.env"; + /** + * Current environment type configuration key: "spring.env" + */ + public static final String SPRING_ENV = "spring.env"; - /** - * Current group configuration key: "spring.group" - */ - public static final String SPRING_GROUP = "spring.group"; + /** + * Current group configuration key: "spring.group" + */ + public static final String SPRING_GROUP = "spring.group"; - /** - * Application name configuration key: "spring.application.name" - */ - public static final String SPRING_APPLICATION_NAME = "spring.application.name"; + /** + * Application name configuration key: "spring.application.name" + */ + public static final String SPRING_APPLICATION_NAME = "spring.application.name"; - /** - * Driver tenant name configuration key: "driver.tenant" - */ - public static final String DRIVER_TENANT = "driver.tenant"; + /** + * Driver tenant name configuration key: "driver.tenant" + */ + public static final String DRIVER_TENANT = "driver.tenant"; - /** - * Driver node configuration key: "driver.node" - */ - public static final String DRIVER_NODE = "driver.node"; + /** + * Driver node configuration key: "driver.node" + */ + public static final String DRIVER_NODE = "driver.node"; - /** - * Driver service configuration key: "driver.service" - */ - public static final String DRIVER_SERVICE = "driver.service"; + /** + * Driver service configuration key: "driver.service" + */ + public static final String DRIVER_SERVICE = "driver.service"; - /** - * Driver host configuration key: "driver.host" - */ - public static final String DRIVER_HOST = "driver.host"; + /** + * Driver host configuration key: "driver.host" + */ + public static final String DRIVER_HOST = "driver.host"; - /** - * Driver client name configuration key: "driver.client" - */ - public static final String DRIVER_CLIENT = "driver.client"; + /** + * Driver client name configuration key: "driver.client" + */ + public static final String DRIVER_CLIENT = "driver.client"; - /** - * Driver port configuration key: "driver.port" - */ - public static final String DRIVER_PORT = "driver.port"; + /** + * Driver port configuration key: "driver.port" + */ + public static final String DRIVER_PORT = "driver.port"; - /** - * Driver MQTT client name configuration key: "driver.mqtt.client" - */ - public static final String MQTT_CLIENT = "driver.mqtt.client"; + /** + * Driver MQTT client name configuration key: "driver.mqtt.client" + */ + public static final String MQTT_CLIENT = "driver.mqtt.client"; - /** - * Driver MQTT topic prefix configuration key: "driver.mqtt.topic-prefix" - */ - public static final String MQTT_PREFIX = "driver.mqtt.topic-prefix"; + /** + * Driver MQTT topic prefix configuration key: "driver.mqtt.topic-prefix" + */ + public static final String MQTT_PREFIX = "driver.mqtt.topic-prefix"; - private EnvironmentConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private EnvironmentConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/FolderConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/FolderConstant.java index 77db80044..362842f57 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/FolderConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/FolderConstant.java @@ -29,18 +29,18 @@ package io.github.pnoker.common.constant.common; */ public class FolderConstant { - /** - * User home directory path: "{user.home}/.dc3/" - */ - public static final String USER_HOME_PATH = System.getProperty("user.home") + "/.dc3/"; + /** + * User home directory path: "{user.home}/.dc3/" + */ + public static final String USER_HOME_PATH = System.getProperty("user.home") + "/.dc3/"; - /** - * Default temporary file upload cache location: "{java.io.tmpdir}/dc3/upload/" - */ - public static final String TEMP_FILE_PATH = System.getProperty("java.io.tmpdir") + "/dc3/upload/"; + /** + * Default temporary file upload cache location: "{java.io.tmpdir}/dc3/upload/" + */ + public static final String TEMP_FILE_PATH = System.getProperty("java.io.tmpdir") + "/dc3/upload/"; - private FolderConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private FolderConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/PrefixConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/PrefixConstant.java index d0c081289..8d2ba3985 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/PrefixConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/PrefixConstant.java @@ -30,128 +30,128 @@ package io.github.pnoker.common.constant.common; */ public class PrefixConstant { - /** - * HTTP protocol prefix: "http" - */ - public static final String HTTP = "http"; + /** + * HTTP protocol prefix: "http" + */ + public static final String HTTP = "http"; - /** - * HTTPS protocol prefix: "https" - */ - public static final String HTTPS = "https"; + /** + * HTTPS protocol prefix: "https" + */ + public static final String HTTPS = "https"; - /** - * Add operation prefix: "add" - */ - public static final String ADD = "add"; + /** + * Add operation prefix: "add" + */ + public static final String ADD = "add"; - /** - * Delete operation prefix: "delete" - */ - public static final String DELETE = "delete"; + /** + * Delete operation prefix: "delete" + */ + public static final String DELETE = "delete"; - /** - * Update operation prefix: "update" - */ - public static final String UPDATE = "update"; + /** + * Update operation prefix: "update" + */ + public static final String UPDATE = "update"; - /** - * Tenant prefix: "tenant" - */ - public static final String TENANT = "tenant"; + /** + * Tenant prefix: "tenant" + */ + public static final String TENANT = "tenant"; - /** - * Tenant bind prefix: "tenant_bind" - */ - public static final String TENANT_BIND = "tenant_bind"; + /** + * Tenant bind prefix: "tenant_bind" + */ + public static final String TENANT_BIND = "tenant_bind"; - /** - * User prefix: "user" - */ - public static final String USER = "user"; + /** + * User prefix: "user" + */ + public static final String USER = "user"; - /** - * Driver prefix: "driver" - */ - public static final String DRIVER = "driver"; + /** + * Driver prefix: "driver" + */ + public static final String DRIVER = "driver"; - /** - * Driver attribute prefix: "driver_attribute" - */ - public static final String DRIVER_ATTRIBUTE = "driver_attribute"; + /** + * Driver attribute prefix: "driver_attribute" + */ + public static final String DRIVER_ATTRIBUTE = "driver_attribute"; - /** - * Driver attribute config prefix: "driver_attribute_config" - */ - public static final String DRIVER_ATTRIBUTE_CONFIG = "driver_attribute_config"; + /** + * Driver attribute config prefix: "driver_attribute_config" + */ + public static final String DRIVER_ATTRIBUTE_CONFIG = "driver_attribute_config"; - /** - * Profile prefix: "profile" - */ - public static final String PROFILE = "profile"; + /** + * Profile prefix: "profile" + */ + public static final String PROFILE = "profile"; - /** - * Profile bind prefix: "profile_bind" - */ - public static final String PROFILE_BIND = "profile_bind"; + /** + * Profile bind prefix: "profile_bind" + */ + public static final String PROFILE_BIND = "profile_bind"; - /** - * Point prefix: "point" - */ - public static final String POINT = "point"; + /** + * Point prefix: "point" + */ + public static final String POINT = "point"; - /** - * Point attribute prefix: "point_attribute" - */ - public static final String POINT_ATTRIBUTE = "point_attribute"; + /** + * Point attribute prefix: "point_attribute" + */ + public static final String POINT_ATTRIBUTE = "point_attribute"; - /** - * Point attribute config prefix: "point_attribute_config" - */ - public static final String POINT_ATTRIBUTE_CONFIG = "point_attribute_config"; + /** + * Point attribute config prefix: "point_attribute_config" + */ + public static final String POINT_ATTRIBUTE_CONFIG = "point_attribute_config"; - /** - * Device prefix: "device" - */ - public static final String DEVICE = "device"; + /** + * Device prefix: "device" + */ + public static final String DEVICE = "device"; - /** - * Group prefix: "group" - */ - public static final String GROUP = "group"; + /** + * Group prefix: "group" + */ + public static final String GROUP = "group"; - /** - * Label prefix: "label" - */ - public static final String LABEL = "label"; + /** + * Label prefix: "label" + */ + public static final String LABEL = "label"; - /** - * Label bind prefix: "label_bind" - */ - public static final String LABEL_BIND = "label_bind"; + /** + * Label bind prefix: "label_bind" + */ + public static final String LABEL_BIND = "label_bind"; - /** - * Data statistics prefix: "data_statistics" - */ - public static final String DATA_STATISTICS = "data_statistics"; + /** + * Data statistics prefix: "data_statistics" + */ + public static final String DATA_STATISTICS = "data_statistics"; - /** - * Real-time value cache key prefix: "point_value:" - */ - public static final String REAL_TIME_VALUE_KEY_PREFIX = POINT + SuffixConstant.VALUE + SymbolConstant.COLON; + /** + * Real-time value cache key prefix: "point_value:" + */ + public static final String REAL_TIME_VALUE_KEY_PREFIX = POINT + SuffixConstant.VALUE + SymbolConstant.COLON; - /** - * Driver status cache key prefix: "driver_status:" - */ - public static final String DRIVER_STATUS_KEY_PREFIX = DRIVER + SuffixConstant.STATUS + SymbolConstant.COLON; + /** + * Driver status cache key prefix: "driver_status:" + */ + public static final String DRIVER_STATUS_KEY_PREFIX = DRIVER + SuffixConstant.STATUS + SymbolConstant.COLON; - /** - * Device status cache key prefix: "device_status:" - */ - public static final String DEVICE_STATUS_KEY_PREFIX = DEVICE + SuffixConstant.STATUS + SymbolConstant.COLON; + /** + * Device status cache key prefix: "device_status:" + */ + public static final String DEVICE_STATUS_KEY_PREFIX = DEVICE + SuffixConstant.STATUS + SymbolConstant.COLON; - private PrefixConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private PrefixConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/QueryWrapperConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/QueryWrapperConstant.java index cdf03434b..0f5baeaf6 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/QueryWrapperConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/QueryWrapperConstant.java @@ -29,13 +29,13 @@ package io.github.pnoker.common.constant.common; */ public class QueryWrapperConstant { - /** - * SQL LIMIT clause for single record: "LIMIT 1" - */ - public static final String LIMIT_ONE = "LIMIT 1"; + /** + * SQL LIMIT clause for single record: "LIMIT 1" + */ + public static final String LIMIT_ONE = "LIMIT 1"; - private QueryWrapperConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private QueryWrapperConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/RequestConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/RequestConstant.java index 1ee44ab81..6c00d929d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/RequestConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/RequestConstant.java @@ -26,89 +26,89 @@ package io.github.pnoker.common.constant.common; */ public class RequestConstant { - /** - * Default maximum request count limit. - */ - public static final int DEFAULT_MAX_REQUEST_SIZE = 100; + /** + * Default maximum request count limit. + */ + public static final int DEFAULT_MAX_REQUEST_SIZE = 100; - private RequestConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private RequestConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Custom request header related constants. - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Header { + /** + * Custom request header related constants. + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Header { - /** - * Custom tenant code request header, used by frontend requests. - */ - public static final String X_AUTH_TENANT = "X-Auth-Tenant"; + /** + * Custom tenant code request header, used by frontend requests. + */ + public static final String X_AUTH_TENANT = "X-Auth-Tenant"; - /** - * Custom user login name request header, used by frontend requests. - */ - public static final String X_AUTH_LOGIN = "X-Auth-Login"; + /** + * Custom user login name request header, used by frontend requests. + */ + public static final String X_AUTH_LOGIN = "X-Auth-Login"; - /** - * Custom token request header, used by frontend requests. - */ - public static final String X_AUTH_TOKEN = "X-Auth-Token"; + /** + * Custom token request header, used by frontend requests. + */ + public static final String X_AUTH_TOKEN = "X-Auth-Token"; - /** - * Custom user request header. Used to pass user information to other services, - * including tenant ID, user ID, user nickname, and username. - */ - public static final String X_AUTH_USER = "X-Auth-User"; + /** + * Custom user request header. Used to pass user information to other services, + * including tenant ID, user ID, user nickname, and username. + */ + public static final String X_AUTH_USER = "X-Auth-User"; - private Header() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Header() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Custom request message related constants. - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Message { + /** + * Custom request message related constants. + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Message { - /** - * Invalid authorization request header message. - */ - public static final String INVALID_REQUEST = "Invalid request auth header"; + /** + * Invalid authorization request header message. + */ + public static final String INVALID_REQUEST = "Invalid request auth header"; - private Message() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Message() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Custom request key related constants. - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Key { + /** + * Custom request key related constants. + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Key { - /** - * User request header key used in context. - */ - public static final String USER_HEADER = "USER_HEADER_KEY"; + /** + * User request header key used in context. + */ + public static final String USER_HEADER = "USER_HEADER_KEY"; - private Key() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Key() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SuffixConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SuffixConstant.java index 74e8f2ea2..746c122bd 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SuffixConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SuffixConstant.java @@ -30,168 +30,168 @@ package io.github.pnoker.common.constant.common; */ public class SuffixConstant { - /** - * ID suffix: "_id" - */ - public static final String ID = "_id"; + /** + * ID suffix: "_id" + */ + public static final String ID = "_id"; - /** - * Tenant ID suffix: "_tenant_id" - */ - public static final String TENANT_ID = "_tenant_id"; + /** + * Tenant ID suffix: "_tenant_id" + */ + public static final String TENANT_ID = "_tenant_id"; - /** - * User ID suffix: "_user_id" - */ - public static final String USER_ID = "_user_id"; + /** + * User ID suffix: "_user_id" + */ + public static final String USER_ID = "_user_id"; - /** - * Driver ID suffix: "_driver_id" - */ - public static final String DRIVER_ID = "_driver_id"; + /** + * Driver ID suffix: "_driver_id" + */ + public static final String DRIVER_ID = "_driver_id"; - /** - * Group ID suffix: "_group_id" - */ - public static final String GROUP_ID = "_group_id"; + /** + * Group ID suffix: "_group_id" + */ + public static final String GROUP_ID = "_group_id"; - /** - * Profile ID suffix: "_profile_id" - */ - public static final String PROFILE_ID = "_profile_id"; + /** + * Profile ID suffix: "_profile_id" + */ + public static final String PROFILE_ID = "_profile_id"; - /** - * Point ID suffix: "_point_id" - */ - public static final String POINT_ID = "_point_id"; + /** + * Point ID suffix: "_point_id" + */ + public static final String POINT_ID = "_point_id"; - /** - * Device ID suffix: "_device_id" - */ - public static final String DEVICE_ID = "_device_id"; + /** + * Device ID suffix: "_device_id" + */ + public static final String DEVICE_ID = "_device_id"; - /** - * Attribute ID suffix: "_attribute_id" - */ - public static final String ATTRIBUTE_ID = "_attribute_id"; + /** + * Attribute ID suffix: "_attribute_id" + */ + public static final String ATTRIBUTE_ID = "_attribute_id"; - /** - * Entity ID suffix: "_entity_id" - */ - public static final String ENTITY_ID = "_entity_id"; + /** + * Entity ID suffix: "_entity_id" + */ + public static final String ENTITY_ID = "_entity_id"; - /** - * Device suffix: "_device" - */ - public static final String DEVICE = "_device"; + /** + * Device suffix: "_device" + */ + public static final String DEVICE = "_device"; - /** - * Profile suffix: "_profile" - */ - public static final String PROFILE = "_profile"; + /** + * Profile suffix: "_profile" + */ + public static final String PROFILE = "_profile"; - /** - * Point suffix: "_point" - */ - public static final String POINT = "_point"; + /** + * Point suffix: "_point" + */ + public static final String POINT = "_point"; - /** - * Driver attribute config suffix: "_driver_attribute_config" - */ - public static final String DRIVER_ATTRIBUTE_CONFIG = "_driver_attribute_config"; + /** + * Driver attribute config suffix: "_driver_attribute_config" + */ + public static final String DRIVER_ATTRIBUTE_CONFIG = "_driver_attribute_config"; - /** - * Point attribute config suffix: "_point_attribute_config" - */ - public static final String POINT_ATTRIBUTE_CONFIG = "_point_attribute_config"; + /** + * Point attribute config suffix: "_point_attribute_config" + */ + public static final String POINT_ATTRIBUTE_CONFIG = "_point_attribute_config"; - /** - * Name suffix: "_name" - */ - public static final String NAME = "_name"; + /** + * Name suffix: "_name" + */ + public static final String NAME = "_name"; - /** - * Phone suffix: "_phone" - */ - public static final String PHONE = "_phone"; + /** + * Phone suffix: "_phone" + */ + public static final String PHONE = "_phone"; - /** - * Email suffix: "_email" - */ - public static final String EMAIL = "_email"; + /** + * Email suffix: "_email" + */ + public static final String EMAIL = "_email"; - /** - * Salt suffix: "_salt" - */ - public static final String SALT = "_salt"; + /** + * Salt suffix: "_salt" + */ + public static final String SALT = "_salt"; - /** - * Token suffix: "_token" - */ - public static final String TOKEN = "_token"; + /** + * Token suffix: "_token" + */ + public static final String TOKEN = "_token"; - /** - * Limit suffix: "_limit" - */ - public static final String LIMIT = "_limit"; + /** + * Limit suffix: "_limit" + */ + public static final String LIMIT = "_limit"; - /** - * Value suffix: "_value" - */ - public static final String VALUE = "_value"; + /** + * Value suffix: "_value" + */ + public static final String VALUE = "_value"; - /** - * Status suffix: "_status" - */ - public static final String STATUS = "_status"; + /** + * Status suffix: "_status" + */ + public static final String STATUS = "_status"; - /** - * Type suffix: "_type" - */ - public static final String TYPE = "_type"; + /** + * Type suffix: "_type" + */ + public static final String TYPE = "_type"; - /** - * Unit suffix: "_unit" - */ - public static final String UNIT = "_unit"; + /** + * Unit suffix: "_unit" + */ + public static final String UNIT = "_unit"; - /** - * IP suffix: "_ip" - */ - public static final String IP = "_ip"; + /** + * IP suffix: "_ip" + */ + public static final String IP = "_ip"; - /** - * Host port suffix: "_host_port" - */ - public static final String HOST_PORT = "_host_port"; + /** + * Host port suffix: "_host_port" + */ + public static final String HOST_PORT = "_host_port"; - /** - * Service name suffix: "_service_name" - */ - public static final String SERVICE_NAME = "_service_name"; + /** + * Service name suffix: "_service_name" + */ + public static final String SERVICE_NAME = "_service_name"; - /** - * List suffix: "_list" - */ - public static final String LIST = "_list"; + /** + * List suffix: "_list" + */ + public static final String LIST = "_list"; - /** - * Dictionary suffix: "_dic" - */ - public static final String DIC = "_dic"; + /** + * Dictionary suffix: "_dic" + */ + public static final String DIC = "_dic"; - /** - * Role suffix: "_role" - */ - public static final String ROLE = "_role"; + /** + * Role suffix: "_role" + */ + public static final String ROLE = "_role"; - /** - * Resource suffix: "_resource" - */ - public static final String RESOURCE = "_resource"; + /** + * Resource suffix: "_resource" + */ + public static final String RESOURCE = "_resource"; - private SuffixConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private SuffixConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SymbolConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SymbolConstant.java index f57048aae..0ab884b09 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SymbolConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/SymbolConstant.java @@ -29,53 +29,53 @@ package io.github.pnoker.common.constant.common; */ public class SymbolConstant { - /** - * Dot symbol: "." - */ - public static final String DOT = "."; + /** + * Dot symbol: "." + */ + public static final String DOT = "."; - /** - * Underscore symbol: "_" - */ - public static final String UNDERSCORE = "_"; + /** + * Underscore symbol: "_" + */ + public static final String UNDERSCORE = "_"; - /** - * Hyphen symbol: "-" - */ - public static final String HYPHEN = "-"; + /** + * Hyphen symbol: "-" + */ + public static final String HYPHEN = "-"; - /** - * Asterisk symbol: "*" - */ - public static final String ASTERISK = "*"; + /** + * Asterisk symbol: "*" + */ + public static final String ASTERISK = "*"; - /** - * Hashtag symbol: "#" - */ - public static final String HASHTAG = "#"; + /** + * Hashtag symbol: "#" + */ + public static final String HASHTAG = "#"; - /** - * Colon symbol: ":" - */ - public static final String COLON = ":"; + /** + * Colon symbol: ":" + */ + public static final String COLON = ":"; - /** - * Double colon symbol: "::" - */ - public static final String DOUBLE_COLON = "::"; + /** + * Double colon symbol: "::" + */ + public static final String DOUBLE_COLON = "::"; - /** - * Slash symbol: "/" - */ - public static final String SLASH = "/"; + /** + * Slash symbol: "/" + */ + public static final String SLASH = "/"; - /** - * Double slash symbol: "//" - */ - public static final String DOUBLE_SLASH = "//"; + /** + * Double slash symbol: "//" + */ + public static final String DOUBLE_SLASH = "//"; - private SymbolConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private SymbolConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/TimeConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/TimeConstant.java index 785f56329..43a3e3900 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/TimeConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/common/TimeConstant.java @@ -28,29 +28,29 @@ import java.time.ZoneId; */ public class TimeConstant { - /** - * Default time zone ID, default is {@code Asia/Shanghai}. - */ - public static final String DEFAULT_TIMEZONE = "Asia/Shanghai"; + /** + * Default time zone ID, default is {@code Asia/Shanghai}. + */ + public static final String DEFAULT_TIMEZONE = "Asia/Shanghai"; - /** - * Default {@link ZoneId}, default is {@code Asia/Shanghai}. - */ - public static final ZoneId DEFAULT_ZONEID = ZoneId.of(DEFAULT_TIMEZONE); + /** + * Default {@link ZoneId}, default is {@code Asia/Shanghai}. + */ + public static final ZoneId DEFAULT_ZONEID = ZoneId.of(DEFAULT_TIMEZONE); - /** - * Date and time format patterns. - */ - public static final String DAY_DATE_FORMAT1 = "yyyy.MM.dd"; + /** + * Date and time format patterns. + */ + public static final String DAY_DATE_FORMAT1 = "yyyy.MM.dd"; - public static final String DAY_DATE_FORMAT2 = "yyyy-MM-dd"; + public static final String DAY_DATE_FORMAT2 = "yyyy-MM-dd"; - public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; - public static final String COMPLETE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; + public static final String COMPLETE_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; - private TimeConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private TimeConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/EventConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/EventConstant.java index 7ebcad9d7..1d083d74d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/EventConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/EventConstant.java @@ -28,62 +28,62 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class EventConstant { - private EventConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private EventConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Driver event related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Driver { + /** + * Driver event related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Driver { - /** - * Driver status event, used to send the current status of the driver to - * dc3-center-manager - */ - public static final String STATUS = "driver_status"; + /** + * Driver status event, used to send the current status of the driver to + * dc3-center-manager + */ + public static final String STATUS = "driver_status"; - /** - * Driver registration event, used to register driver configuration information to - * dc3-center-manager - */ - public static final String REGISTER = "driver_register"; + /** + * Driver registration event, used to register driver configuration information to + * dc3-center-manager + */ + public static final String REGISTER = "driver_register"; - public static final String REGISTER_BACK = "driver_register_back"; + public static final String REGISTER_BACK = "driver_register_back"; - private Driver() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Driver() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Device event related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Device { + /** + * Device event related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Device { - /** - * Device status event - */ - public static final String STATUS = "device_status"; + /** + * Device status event + */ + public static final String STATUS = "device_status"; - /** - * Used to record error event type - */ - public static final String ERROR = "device_error"; + /** + * Used to record error event type + */ + public static final String ERROR = "device_error"; - private Device() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Device() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/MetadataConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/MetadataConstant.java index 7a08ed1fe..b5000acc6 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/MetadataConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/MetadataConstant.java @@ -30,113 +30,113 @@ import io.github.pnoker.common.constant.common.SuffixConstant; */ public class MetadataConstant { - private MetadataConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private MetadataConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Profile metadata related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Profile { + /** + * Profile metadata related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Profile { - public static final String ADD = PrefixConstant.ADD + SuffixConstant.PROFILE; + public static final String ADD = PrefixConstant.ADD + SuffixConstant.PROFILE; - public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.PROFILE; + public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.PROFILE; - public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.PROFILE; + public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.PROFILE; - private Profile() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Profile() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Point metadata related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Point { + /** + * Point metadata related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Point { - public static final String ADD = PrefixConstant.ADD + SuffixConstant.POINT; + public static final String ADD = PrefixConstant.ADD + SuffixConstant.POINT; - public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.POINT; + public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.POINT; - public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.POINT; + public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.POINT; - private Point() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Point() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Device metadata related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Device { + /** + * Device metadata related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Device { - public static final String ADD = PrefixConstant.ADD + SuffixConstant.DEVICE; + public static final String ADD = PrefixConstant.ADD + SuffixConstant.DEVICE; - public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.DEVICE; + public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.DEVICE; - public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.DEVICE; + public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.DEVICE; - private Device() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Device() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Driver configuration metadata related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class DriverConfig { + /** + * Driver configuration metadata related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class DriverConfig { - public static final String ADD = PrefixConstant.ADD + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; + public static final String ADD = PrefixConstant.ADD + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; - public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; + public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; - public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; + public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.DRIVER_ATTRIBUTE_CONFIG; - private DriverConfig() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private DriverConfig() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } - /** - * Point configuration metadata related constants - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class PointConfig { + /** + * Point configuration metadata related constants + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class PointConfig { - public static final String ADD = PrefixConstant.ADD + SuffixConstant.POINT_ATTRIBUTE_CONFIG; + public static final String ADD = PrefixConstant.ADD + SuffixConstant.POINT_ATTRIBUTE_CONFIG; - public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.POINT_ATTRIBUTE_CONFIG; + public static final String DELETE = PrefixConstant.DELETE + SuffixConstant.POINT_ATTRIBUTE_CONFIG; - public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.POINT_ATTRIBUTE_CONFIG; + public static final String UPDATE = PrefixConstant.UPDATE + SuffixConstant.POINT_ATTRIBUTE_CONFIG; - private PointConfig() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private PointConfig() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/RabbitConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/RabbitConstant.java index 37fa11b0e..ee16dd65c 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/RabbitConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/RabbitConstant.java @@ -28,68 +28,68 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class RabbitConstant { - // Arguments - public static final String MESSAGE_TTL = "x-message-ttl"; + // Arguments + public static final String MESSAGE_TTL = "x-message-ttl"; - public static final String AUTO_DELETE = "x-auto-delete"; + public static final String AUTO_DELETE = "x-auto-delete"; - // Routing - public static final String ROUTING_REGISTER_UP_PREFIX = "dc3.r.register.up."; + // Routing + public static final String ROUTING_REGISTER_UP_PREFIX = "dc3.r.register.up."; - public static final String ROUTING_REGISTER_DOWN_PREFIX = "dc3.r.register.down."; + public static final String ROUTING_REGISTER_DOWN_PREFIX = "dc3.r.register.down."; - public static final String ROUTING_DRIVER_EVENT_PREFIX = "dc3.r.event.driver."; + public static final String ROUTING_DRIVER_EVENT_PREFIX = "dc3.r.event.driver."; - public static final String ROUTING_DEVICE_EVENT_PREFIX = "dc3.r.event.device."; + public static final String ROUTING_DEVICE_EVENT_PREFIX = "dc3.r.event.device."; - public static final String ROUTING_DRIVER_METADATA_PREFIX = "dc3.r.metadata.driver."; + public static final String ROUTING_DRIVER_METADATA_PREFIX = "dc3.r.metadata.driver."; - public static final String ROUTING_DRIVER_COMMAND_PREFIX = "dc3.r.command.driver."; + public static final String ROUTING_DRIVER_COMMAND_PREFIX = "dc3.r.command.driver."; - public static final String ROUTING_DEVICE_COMMAND_PREFIX = "dc3.r.command.device."; + public static final String ROUTING_DEVICE_COMMAND_PREFIX = "dc3.r.command.device."; - public static final String ROUTING_POINT_VALUE_PREFIX = "dc3.r.value.point."; + public static final String ROUTING_POINT_VALUE_PREFIX = "dc3.r.value.point."; - public static final String ROUTING_MQTT_PREFIX = "dc3.r.mqtt."; + public static final String ROUTING_MQTT_PREFIX = "dc3.r.mqtt."; - // Register - public static String TOPIC_EXCHANGE_REGISTER = "dc3.e.register"; + // Register + public static String TOPIC_EXCHANGE_REGISTER = "dc3.e.register"; - public static String QUEUE_REGISTER_UP = "dc3.q.register.up"; + public static String QUEUE_REGISTER_UP = "dc3.q.register.up"; - public static String QUEUE_REGISTER_DOWN_PREFIX = "dc3.q.register.down."; + public static String QUEUE_REGISTER_DOWN_PREFIX = "dc3.q.register.down."; - // Event - public static String TOPIC_EXCHANGE_EVENT = "dc3.e.event"; + // Event + public static String TOPIC_EXCHANGE_EVENT = "dc3.e.event"; - public static String QUEUE_DRIVER_EVENT = "dc3.q.event.driver"; + public static String QUEUE_DRIVER_EVENT = "dc3.q.event.driver"; - public static String QUEUE_DEVICE_EVENT = "dc3.q.event.device"; + public static String QUEUE_DEVICE_EVENT = "dc3.q.event.device"; - // Metadata - public static String TOPIC_EXCHANGE_METADATA = "dc3.e.metadata"; + // Metadata + public static String TOPIC_EXCHANGE_METADATA = "dc3.e.metadata"; - public static String QUEUE_DRIVER_METADATA_PREFIX = "dc3.q.metadata.driver."; + public static String QUEUE_DRIVER_METADATA_PREFIX = "dc3.q.metadata.driver."; - // Command - public static String TOPIC_EXCHANGE_COMMAND = "dc3.e.command"; + // Command + public static String TOPIC_EXCHANGE_COMMAND = "dc3.e.command"; - public static String QUEUE_DRIVER_COMMAND_PREFIX = "dc3.q.command.driver."; + public static String QUEUE_DRIVER_COMMAND_PREFIX = "dc3.q.command.driver."; - public static String QUEUE_DEVICE_COMMAND_PREFIX = "dc3.q.command.device."; + public static String QUEUE_DEVICE_COMMAND_PREFIX = "dc3.q.command.device."; - // Value - public static String TOPIC_EXCHANGE_VALUE = "dc3.e.value"; + // Value + public static String TOPIC_EXCHANGE_VALUE = "dc3.e.value"; - public static String QUEUE_POINT_VALUE = "dc3.q.value.point"; + public static String QUEUE_POINT_VALUE = "dc3.q.value.point"; - // Mqtt - public static String TOPIC_EXCHANGE_MQTT = "dc3.e.mqtt"; + // Mqtt + public static String TOPIC_EXCHANGE_MQTT = "dc3.e.mqtt"; - public static String QUEUE_MQTT = "dc3.q.mqtt"; + public static String QUEUE_MQTT = "dc3.q.mqtt"; - private RabbitConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private RabbitConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/ScheduleConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/ScheduleConstant.java index 48f3f699f..5969950c8 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/ScheduleConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/ScheduleConstant.java @@ -28,43 +28,43 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class ScheduleConstant { - /** - * Driver schedule group - */ - public static final String DRIVER_SCHEDULE_GROUP = "driver-schedule-group"; + /** + * Driver schedule group + */ + public static final String DRIVER_SCHEDULE_GROUP = "driver-schedule-group"; - /** - * Driver read schedule job - */ - public static final String DRIVER_READ_SCHEDULE_JOB = "read-schedule-job"; + /** + * Driver read schedule job + */ + public static final String DRIVER_READ_SCHEDULE_JOB = "read-schedule-job"; - /** - * Driver custom schedule job - */ - public static final String DRIVER_CUSTOM_SCHEDULE_JOB = "customs-chedule-job"; + /** + * Driver custom schedule job + */ + public static final String DRIVER_CUSTOM_SCHEDULE_JOB = "customs-chedule-job"; - /** - * Driver status schedule job - */ - public static final String DRIVER_STATUS_SCHEDULE_JOB = "status-schedule-job"; + /** + * Driver status schedule job + */ + public static final String DRIVER_STATUS_SCHEDULE_JOB = "status-schedule-job"; - /** - * Driver status schedule cron - */ - public static final String DRIVER_STATUS_SCHEDULE_CRON = "0/15 * * * * ?"; + /** + * Driver status schedule cron + */ + public static final String DRIVER_STATUS_SCHEDULE_CRON = "0/15 * * * * ?"; - /** - * Data schedule group - */ - public static final String DATA_SCHEDULE_GROUP = "data-schedule-group"; + /** + * Data schedule group + */ + public static final String DATA_SCHEDULE_GROUP = "data-schedule-group"; - /** - * Manager schedule group - */ - public static final String MANAGER_SCHEDULE_GROUP = "manager-schedule-group"; + /** + * Manager schedule group + */ + public static final String MANAGER_SCHEDULE_GROUP = "manager-schedule-group"; - private ScheduleConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ScheduleConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StorageConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StorageConstant.java index 7052a317c..ea48b43ed 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StorageConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StorageConstant.java @@ -31,14 +31,14 @@ import io.github.pnoker.common.constant.common.SymbolConstant; */ public class StorageConstant { - /** - * Point value prefix - */ - public static final String POINT_VALUE_PREFIX = PrefixConstant.POINT + SuffixConstant.VALUE - + SymbolConstant.UNDERSCORE; + /** + * Point value prefix + */ + public static final String POINT_VALUE_PREFIX = PrefixConstant.POINT + SuffixConstant.VALUE + + SymbolConstant.UNDERSCORE; - private StorageConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private StorageConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StrategyConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StrategyConstant.java index 163dc8b4b..d27a78231 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StrategyConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/driver/StrategyConstant.java @@ -29,37 +29,37 @@ import io.github.pnoker.common.constant.common.SymbolConstant; */ public class StrategyConstant { - private StrategyConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private StrategyConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Storage strategy constant - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - public static class Storage { + /** + * Storage strategy constant + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + public static class Storage { - public static final String REPOSITORY_PREFIX = "repository" + SymbolConstant.COLON; + public static final String REPOSITORY_PREFIX = "repository" + SymbolConstant.COLON; - public static final String POSTGRES = "postgres"; + public static final String POSTGRES = "postgres"; - public static final String INFLUXDB = "influxdb"; + public static final String INFLUXDB = "influxdb"; - public static final String TDENGINE = "tdengine"; + public static final String TDENGINE = "tdengine"; - public static final String OPENTSDB = "opentsdb"; + public static final String OPENTSDB = "opentsdb"; - public static final String MONGODB = "mongodb"; + public static final String MONGODB = "mongodb"; - public static final String ELASTICSEARCH = "elasticsearch"; + public static final String ELASTICSEARCH = "elasticsearch"; - private Storage() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Storage() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/AuthConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/AuthConstant.java index 932c6c546..80a7c41f2 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/AuthConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/AuthConstant.java @@ -28,35 +28,35 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class AuthConstant { - /** - * Service name registered in service discovery. - */ - public static final String SERVICE_NAME = "dc3-center-auth"; + /** + * Service name registered in service discovery. + */ + public static final String SERVICE_NAME = "dc3-center-auth"; - public static final String USER_URL_PREFIX = "/user"; + public static final String USER_URL_PREFIX = "/user"; - public static final String USER_PROFILE_URL_PREFIX = "/user-profile"; + public static final String USER_PROFILE_URL_PREFIX = "/user-profile"; - public static final String TENANT_URL_PREFIX = "/tenant"; + public static final String TENANT_URL_PREFIX = "/tenant"; - public static final String TOKEN_URL_PREFIX = "/token"; + public static final String TOKEN_URL_PREFIX = "/token"; - public static final String DICTIONARY_URL_PREFIX = "/dictionary"; + public static final String DICTIONARY_URL_PREFIX = "/dictionary"; - public static final String ROLE_URL_PREFIX = "/role"; + public static final String ROLE_URL_PREFIX = "/role"; - public static final String RESOURCE_URL_PREFIX = "/resource"; + public static final String RESOURCE_URL_PREFIX = "/resource"; - public static final String ROLE_USER_URL_PREFIX = "/role-user"; + public static final String ROLE_USER_URL_PREFIX = "/role-user"; - public static final String ROLE_RESOURCE_URL_PREFIX = "/role-resource"; + public static final String ROLE_RESOURCE_URL_PREFIX = "/role-resource"; - public static final String API_URL_PREFIX = "/api"; + public static final String API_URL_PREFIX = "/api"; - public static final String MENU_URL_PREFIX = "/menu"; + public static final String MENU_URL_PREFIX = "/menu"; - private AuthConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private AuthConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DataConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DataConstant.java index 3a7e344ba..90b948d4f 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DataConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DataConstant.java @@ -28,43 +28,43 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class DataConstant { - /** - * Service name - */ - public static final String SERVICE_NAME = "dc3-center-data"; + /** + * Service name + */ + public static final String SERVICE_NAME = "dc3-center-data"; - public static final String POINT_VALUE_URL_PREFIX = "/point_value"; + public static final String POINT_VALUE_URL_PREFIX = "/point_value"; - public static final String POINT_VALUE_COMMAND_URL_PREFIX = "/point_value_command"; + public static final String POINT_VALUE_COMMAND_URL_PREFIX = "/point_value_command"; - public static final String DASHBOARD_URL_PREFIX = "/dashboard"; + public static final String DASHBOARD_URL_PREFIX = "/dashboard"; - public static final String DRIVER_STATUS_URL_PREFIX = "/driver/status"; + public static final String DRIVER_STATUS_URL_PREFIX = "/driver/status"; - public static final String DRIVER_EVENT_URL_PREFIX = "/driver/event"; + public static final String DRIVER_EVENT_URL_PREFIX = "/driver/event"; - public static final String DEVICE_STATUS_URL_PREFIX = "/device/status"; + public static final String DEVICE_STATUS_URL_PREFIX = "/device/status"; - public static final String DEVICE_EVENT_URL_PREFIX = "/device/event"; + public static final String DEVICE_EVENT_URL_PREFIX = "/device/event"; - public static final String RABBITMQ_CONNECTION_URL_PREFIX = "/rabbitmq/connection"; + public static final String RABBITMQ_CONNECTION_URL_PREFIX = "/rabbitmq/connection"; - public static final String RABBITMQ_MESSAGE_URL_PREFIX = "/rabbitmq/message"; + public static final String RABBITMQ_MESSAGE_URL_PREFIX = "/rabbitmq/message"; - public static final String RABBITMQ_PUBLISHER_URL_PREFIX = "/rabbitmq/publisher"; + public static final String RABBITMQ_PUBLISHER_URL_PREFIX = "/rabbitmq/publisher"; - public static final String RABBITMQ_QUEUE_URL_PREFIX = "/rabbitmq/queue"; + public static final String RABBITMQ_QUEUE_URL_PREFIX = "/rabbitmq/queue"; - public static final String RABBITMQ_CONSUMER_URL_PREFIX = "/rabbitmq/consumer"; + public static final String RABBITMQ_CONSUMER_URL_PREFIX = "/rabbitmq/consumer"; - public static final String RABBITMQ_CHANNEL_URL_PREFIX = "/rabbitmq/channel"; + public static final String RABBITMQ_CHANNEL_URL_PREFIX = "/rabbitmq/channel"; - public static final String RABBITMQ_NODE_URL_PREFIX = "/rabbitmq/node"; + public static final String RABBITMQ_NODE_URL_PREFIX = "/rabbitmq/node"; - public static final String RABBITMQ_CLUSTER_URL_PREFIX = "/rabbitmq/cluster"; + public static final String RABBITMQ_CLUSTER_URL_PREFIX = "/rabbitmq/cluster"; - private DataConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private DataConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DriverConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DriverConstant.java index 55bebd8b6..3a347d9dc 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DriverConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/DriverConstant.java @@ -28,15 +28,15 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class DriverConstant { - /** - * Service name - */ - public static final String SERVICE_NAME = "dc3-driver"; + /** + * Service name + */ + public static final String SERVICE_NAME = "dc3-driver"; - public static final String COMMAND_URL_PREFIX = "/command"; + public static final String COMMAND_URL_PREFIX = "/command"; - private DriverConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private DriverConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/ManagerConstant.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/ManagerConstant.java index c9c5ae37a..8a708196c 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/ManagerConstant.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/constant/service/ManagerConstant.java @@ -28,43 +28,43 @@ import io.github.pnoker.common.constant.common.ExceptionConstant; */ public class ManagerConstant { - /** - * Service name - */ - public static final String SERVICE_NAME = "dc3-center-manager"; + /** + * Service name + */ + public static final String SERVICE_NAME = "dc3-center-manager"; - public static final String DRIVER_URL_PREFIX = "/driver"; + public static final String DRIVER_URL_PREFIX = "/driver"; - public static final String BATCH_URL_PREFIX = "/batch"; + public static final String BATCH_URL_PREFIX = "/batch"; - public static final String DRIVER_ATTRIBUTE_URL_PREFIX = "/driver_attribute"; + public static final String DRIVER_ATTRIBUTE_URL_PREFIX = "/driver_attribute"; - public static final String POINT_ATTRIBUTE_URL_PREFIX = "/point_attribute"; + public static final String POINT_ATTRIBUTE_URL_PREFIX = "/point_attribute"; - public static final String PROFILE_URL_PREFIX = "/profile"; + public static final String PROFILE_URL_PREFIX = "/profile"; - public static final String POINT_URL_PREFIX = "/point"; + public static final String POINT_URL_PREFIX = "/point"; - public static final String GROUP_URL_PREFIX = "/group"; + public static final String GROUP_URL_PREFIX = "/group"; - public static final String DEVICE_URL_PREFIX = "/device"; + public static final String DEVICE_URL_PREFIX = "/device"; - public static final String DASHBOARD_URL_PREFIX = "/dashboard"; + public static final String DASHBOARD_URL_PREFIX = "/dashboard"; - public static final String AUTO_URL_PREFIX = "/auto"; + public static final String AUTO_URL_PREFIX = "/auto"; - public static final String POINT_ATTRIBUTE_CONFIG_URL_PREFIX = "/point_attribute_config"; + public static final String POINT_ATTRIBUTE_CONFIG_URL_PREFIX = "/point_attribute_config"; - public static final String DRIVER_ATTRIBUTE_CONFIG_URL_PREFIX = "/driver_attribute_config"; + public static final String DRIVER_ATTRIBUTE_CONFIG_URL_PREFIX = "/driver_attribute_config"; - public static final String LABEL_URL_PREFIX = "/label"; + public static final String LABEL_URL_PREFIX = "/label"; - public static final String DICTIONARY_URL_PREFIX = "/dictionary"; + public static final String DICTIONARY_URL_PREFIX = "/dictionary"; - public static final String TOPIC_URL_PREFIX = "/topic"; + public static final String TOPIC_URL_PREFIX = "/topic"; - private ManagerConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ManagerConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AccrueFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AccrueFlagEnum.java index 2a35987a6..031749519 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AccrueFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AccrueFlagEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum AccrueFlagEnum { - /** - * None - */ - NONE((byte) 0, "none", "None"), + /** + * None + */ + NONE((byte) 0, "none", "None"), - /** - * Increment - */ - INCREMENT((byte) 1, "increment", "Increment"), + /** + * Increment + */ + INCREMENT((byte) 1, "increment", "Increment"), - /** - * Decrement - */ - DECREMENT((byte) 2, "decrement", "Decrement"),; + /** + * Decrement + */ + DECREMENT((byte) 2, "decrement", "Decrement"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link AccrueFlagEnum} - */ - public static AccrueFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(AccrueFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link AccrueFlagEnum} + */ + public static AccrueFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(AccrueFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link AccrueFlagEnum} - */ - public static AccrueFlagEnum ofCode(String code) { - Optional any = Arrays.stream(AccrueFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link AccrueFlagEnum} + */ + public static AccrueFlagEnum ofCode(String code) { + Optional any = Arrays.stream(AccrueFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link AccrueFlagEnum} - */ - public static AccrueFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link AccrueFlagEnum} + */ + public static AccrueFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmMessageLevelFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmMessageLevelFlagEnum.java index f059e3ea6..95aa5b8f6 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmMessageLevelFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmMessageLevelFlagEnum.java @@ -35,78 +35,81 @@ import java.util.Optional; @AllArgsConstructor public enum AlarmMessageLevelFlagEnum { - /** - * P0 - */ - P0((byte) 0, "p0", "P0"), + /** + * P0 + */ + P0((byte) 0, "p0", "P0"), - /** - * P1 - */ - P1((byte) 1, "p1", "P1"), + /** + * P1 + */ + P1((byte) 1, "p1", "P1"), - /** - * P2 - */ - P2((byte) 2, "p2", "P2"), + /** + * P2 + */ + P2((byte) 2, "p2", "P2"), - /** - * P3 - */ - P3((byte) 3, "p3", "P3"),; + /** + * P3 + */ + P3((byte) 3, "p3", "P3"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link AlarmMessageLevelFlagEnum} - */ - public static AlarmMessageLevelFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(AlarmMessageLevelFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link AlarmMessageLevelFlagEnum} + */ + public static AlarmMessageLevelFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(AlarmMessageLevelFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link AlarmMessageLevelFlagEnum} - */ - public static AlarmMessageLevelFlagEnum ofCode(String code) { - Optional any = Arrays.stream(AlarmMessageLevelFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link AlarmMessageLevelFlagEnum} + */ + public static AlarmMessageLevelFlagEnum ofCode(String code) { + Optional any = Arrays.stream(AlarmMessageLevelFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link AlarmMessageLevelFlagEnum} - */ - public static AlarmMessageLevelFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link AlarmMessageLevelFlagEnum} + */ + public static AlarmMessageLevelFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmTypeFlagEnum.java index 815063b34..7d75312f0 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AlarmTypeFlagEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum AlarmTypeFlagEnum { - /** - * Point - */ - POINT((byte) 0, "point", "Point"), + /** + * Point + */ + POINT((byte) 0, "point", "Point"), - /** - * Device - */ - DEVICE((byte) 1, "device", "Device"), + /** + * Device + */ + DEVICE((byte) 1, "device", "Device"), - /** - * Driver - */ - DRIVER((byte) 2, "driver", "Driver"),; + /** + * Driver + */ + DRIVER((byte) 2, "driver", "Driver"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link AlarmTypeFlagEnum} - */ - public static AlarmTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(AlarmTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link AlarmTypeFlagEnum} + */ + public static AlarmTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(AlarmTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link AlarmTypeFlagEnum} - */ - public static AlarmTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(AlarmTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link AlarmTypeFlagEnum} + */ + public static AlarmTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(AlarmTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link AlarmTypeFlagEnum} - */ - public static AlarmTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link AlarmTypeFlagEnum} + */ + public static AlarmTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ApiTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ApiTypeFlagEnum.java index 38689a42c..ad6165f1d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ApiTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ApiTypeFlagEnum.java @@ -35,78 +35,81 @@ import java.util.Optional; @AllArgsConstructor public enum ApiTypeFlagEnum { - /** - * POST - */ - POST((byte) 0, "post", "POST"), + /** + * POST + */ + POST((byte) 0, "post", "POST"), - /** - * DELETE - */ - DELETE((byte) 1, "delete", "DELETE"), + /** + * DELETE + */ + DELETE((byte) 1, "delete", "DELETE"), - /** - * PUT - */ - PUT((byte) 2, "put", "PUT"), + /** + * PUT + */ + PUT((byte) 2, "put", "PUT"), - /** - * GET - */ - GET((byte) 3, "get", "GET"),; + /** + * GET + */ + GET((byte) 3, "get", "GET"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link ApiTypeFlagEnum} - */ - public static ApiTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ApiTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ApiTypeFlagEnum} + */ + public static ApiTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ApiTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ApiTypeFlagEnum} - */ - public static ApiTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ApiTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ApiTypeFlagEnum} + */ + public static ApiTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ApiTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ApiTypeFlagEnum} - */ - public static ApiTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ApiTypeFlagEnum} + */ + public static ApiTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AttributeTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AttributeTypeFlagEnum.java index ba2dafede..d51c1b2ed 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AttributeTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AttributeTypeFlagEnum.java @@ -35,98 +35,101 @@ import java.util.Optional; @AllArgsConstructor public enum AttributeTypeFlagEnum { - /** - * String - */ - STRING((byte) 0, "string", "String"), + /** + * String + */ + STRING((byte) 0, "string", "String"), - /** - * Byte - */ - BYTE((byte) 1, "byte", "Byte"), + /** + * Byte + */ + BYTE((byte) 1, "byte", "Byte"), - /** - * Short - */ - SHORT((byte) 2, "short", "Short"), + /** + * Short + */ + SHORT((byte) 2, "short", "Short"), - /** - * Int - */ - INT((byte) 3, "int", "Int"), + /** + * Int + */ + INT((byte) 3, "int", "Int"), - /** - * Long - */ - LONG((byte) 4, "long", "Long"), + /** + * Long + */ + LONG((byte) 4, "long", "Long"), - /** - * Float - */ - FLOAT((byte) 5, "float", "Float"), + /** + * Float + */ + FLOAT((byte) 5, "float", "Float"), - /** - * Double - */ - DOUBLE((byte) 6, "double", "Double"), + /** + * Double + */ + DOUBLE((byte) 6, "double", "Double"), - /** - * Boolean - */ - BOOLEAN((byte) 7, "boolean", "Boolean"),; + /** + * Boolean + */ + BOOLEAN((byte) 7, "boolean", "Boolean"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link AttributeTypeFlagEnum} - */ - public static AttributeTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(AttributeTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link AttributeTypeFlagEnum} + */ + public static AttributeTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(AttributeTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link AttributeTypeFlagEnum} - */ - public static AttributeTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(AttributeTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link AttributeTypeFlagEnum} + */ + public static AttributeTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(AttributeTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link AttributeTypeFlagEnum} - */ - public static AttributeTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link AttributeTypeFlagEnum} + */ + public static AttributeTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AutoConfirmFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AutoConfirmFlagEnum.java index 8e2ec5153..7402955f2 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AutoConfirmFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/AutoConfirmFlagEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum AutoConfirmFlagEnum { - /** - * Auto - */ - AUTO((byte) 0, "auto", "Auto"), + /** + * Auto + */ + AUTO((byte) 0, "auto", "Auto"), - /** - * Manual - */ - MANUAL((byte) 1, "manual", "Manual"),; + /** + * Manual + */ + MANUAL((byte) 1, "manual", "Manual"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link AutoConfirmFlagEnum} - */ - public static AutoConfirmFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(AutoConfirmFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link AutoConfirmFlagEnum} + */ + public static AutoConfirmFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(AutoConfirmFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link AutoConfirmFlagEnum} - */ - public static AutoConfirmFlagEnum ofCode(String code) { - Optional any = Arrays.stream(AutoConfirmFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link AutoConfirmFlagEnum} + */ + public static AutoConfirmFlagEnum ofCode(String code) { + Optional any = Arrays.stream(AutoConfirmFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link AutoConfirmFlagEnum} - */ - public static AutoConfirmFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link AutoConfirmFlagEnum} + */ + public static AutoConfirmFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceCommandTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceCommandTypeEnum.java index 5b65cb0f2..579df4848 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceCommandTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceCommandTypeEnum.java @@ -35,83 +35,86 @@ import java.util.Optional; @AllArgsConstructor public enum DeviceCommandTypeEnum { - /** - * Read point value command - */ - READ((byte) 0, "read", "Read point value command"), + /** + * Read point value command + */ + READ((byte) 0, "read", "Read point value command"), - /** - * Read point value batch command - */ - READ_BATCH((byte) 1, "read_batch", "Read point value batch command"), + /** + * Read point value batch command + */ + READ_BATCH((byte) 1, "read_batch", "Read point value batch command"), - /** - * Write point value command - */ - WRITE((byte) 2, "write", "Write point value command"), + /** + * Write point value command + */ + WRITE((byte) 2, "write", "Write point value command"), - /** - * Write point value batch command - */ - WRITE_BATCH((byte) 3, "write_batch", "Write point value batch command"), + /** + * Write point value batch command + */ + WRITE_BATCH((byte) 3, "write_batch", "Write point value batch command"), - /** - * Config device command - */ - CONFIG((byte) 4, "config", "Config device command"),; + /** + * Config device command + */ + CONFIG((byte) 4, "config", "Config device command"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link DeviceCommandTypeEnum} - */ - public static DeviceCommandTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DeviceCommandTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link DeviceCommandTypeEnum} + */ + public static DeviceCommandTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DeviceCommandTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link DeviceCommandTypeEnum} - */ - public static DeviceCommandTypeEnum ofCode(String code) { - Optional any = Arrays.stream(DeviceCommandTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link DeviceCommandTypeEnum} + */ + public static DeviceCommandTypeEnum ofCode(String code) { + Optional any = Arrays.stream(DeviceCommandTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link DeviceCommandTypeEnum} - */ - public static DeviceCommandTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link DeviceCommandTypeEnum} + */ + public static DeviceCommandTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceEventTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceEventTypeEnum.java index c93dac7a0..f226acd5d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceEventTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceEventTypeEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum DeviceEventTypeEnum { - /** - * Heartbeat event. - */ - HEARTBEAT((byte) 0, "heartbeat", "heartbeat event"), + /** + * Heartbeat event. + */ + HEARTBEAT((byte) 0, "heartbeat", "heartbeat event"), - /** - * Alarm event. - */ - ALARM((byte) 1, "alarm", "alarm event"),; + /** + * Alarm event. + */ + ALARM((byte) 1, "alarm", "alarm event"), + ; - /** - * Index value stored in database. - */ - @EnumValue - private final Byte index; + /** + * Index value stored in database. + */ + @EnumValue + private final Byte index; - /** - * Code string. - */ - private final String code; + /** + * Code string. + */ + private final String code; - /** - * Human-readable description. - */ - private final String remark; + /** + * Human-readable description. + */ + private final String remark; - /** - * Get enum by index value. - * @param index index value - * @return {@link DeviceEventTypeEnum} or {@code null} if not found - */ - public static DeviceEventTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DeviceEventTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index value. + * + * @param index index value + * @return {@link DeviceEventTypeEnum} or {@code null} if not found + */ + public static DeviceEventTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DeviceEventTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code string. - * @param code code string - * @return {@link DeviceEventTypeEnum} or {@code null} if not found - */ - public static DeviceEventTypeEnum ofCode(String code) { - Optional any = Arrays.stream(DeviceEventTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code string. + * + * @param code code string + * @return {@link DeviceEventTypeEnum} or {@code null} if not found + */ + public static DeviceEventTypeEnum ofCode(String code) { + Optional any = Arrays.stream(DeviceEventTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by enum name. - * @param name enum name - * @return {@link DeviceEventTypeEnum} or {@code null} if parsing fails - */ - public static DeviceEventTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by enum name. + * + * @param name enum name + * @return {@link DeviceEventTypeEnum} or {@code null} if parsing fails + */ + public static DeviceEventTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceStatusEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceStatusEnum.java index 00d24a6e5..5a2b1a6c9 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceStatusEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DeviceStatusEnum.java @@ -35,61 +35,64 @@ import java.util.Optional; @AllArgsConstructor public enum DeviceStatusEnum { - ONLINE((byte) 0, "ONLINE", "online"), OFFLINE((byte) 1, "OFFLINE", "offline"), - MAINTAIN((byte) 2, "MAINTAIN", "maintenance"), FAULT((byte) 3, "FAULT", "fault"),; + ONLINE((byte) 0, "ONLINE", "online"), OFFLINE((byte) 1, "OFFLINE", "offline"), + MAINTAIN((byte) 2, "MAINTAIN", "maintenance"), FAULT((byte) 3, "FAULT", "fault"), + ; - /** - * Index value stored in database. - */ - @EnumValue - private final Byte index; + /** + * Index value stored in database. + */ + @EnumValue + private final Byte index; - /** - * Status code string. - */ - private final String code; + /** + * Status code string. + */ + private final String code; - /** - * Human-readable description. - */ - private final String remark; + /** + * Human-readable description. + */ + private final String remark; - /** - * Get enum by index value. - * @param index index value - * @return {@link DeviceStatusEnum} or {@code null} if not found - */ - public static DeviceStatusEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DeviceStatusEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index value. + * + * @param index index value + * @return {@link DeviceStatusEnum} or {@code null} if not found + */ + public static DeviceStatusEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DeviceStatusEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code string. - * @param code code string - * @return {@link DeviceStatusEnum} or {@code null} if not found - */ - public static DeviceStatusEnum ofCode(String code) { - Optional any = Arrays.stream(DeviceStatusEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code string. + * + * @param code code string + * @return {@link DeviceStatusEnum} or {@code null} if not found + */ + public static DeviceStatusEnum ofCode(String code) { + Optional any = Arrays.stream(DeviceStatusEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by enum name. - * @param name enum name - * @return {@link DeviceStatusEnum} or {@code null} if parsing fails - */ - public static DeviceStatusEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by enum name. + * + * @param name enum name + * @return {@link DeviceStatusEnum} or {@code null} if parsing fails + */ + public static DeviceStatusEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverCommandTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverCommandTypeEnum.java index e1419dffa..6f68c0e8d 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverCommandTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverCommandTypeEnum.java @@ -35,63 +35,66 @@ import java.util.Optional; @AllArgsConstructor public enum DriverCommandTypeEnum { - /** - * Driver config command - */ - CONFIG((byte) 0, "config", "Driver config command"),; + /** + * Driver config command + */ + CONFIG((byte) 0, "config", "Driver config command"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link DriverCommandTypeEnum} - */ - public static DriverCommandTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DriverCommandTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link DriverCommandTypeEnum} + */ + public static DriverCommandTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DriverCommandTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link DriverCommandTypeEnum} - */ - public static DriverCommandTypeEnum ofCode(String code) { - Optional any = Arrays.stream(DriverCommandTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link DriverCommandTypeEnum} + */ + public static DriverCommandTypeEnum ofCode(String code) { + Optional any = Arrays.stream(DriverCommandTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link DriverCommandTypeEnum} - */ - public static DriverCommandTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link DriverCommandTypeEnum} + */ + public static DriverCommandTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverEventTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverEventTypeEnum.java index 594774f32..6b51a715f 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverEventTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverEventTypeEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum DriverEventTypeEnum { - /** - * Heartbeat event - */ - HEARTBEAT((byte) 0, "heartbeat", "Heartbeat event"), + /** + * Heartbeat event + */ + HEARTBEAT((byte) 0, "heartbeat", "Heartbeat event"), - /** - * Alarm event - */ - ALARM((byte) 1, "alarm", "Alarm event"),; + /** + * Alarm event + */ + ALARM((byte) 1, "alarm", "Alarm event"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link DriverEventTypeEnum} - */ - public static DriverEventTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DriverEventTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link DriverEventTypeEnum} + */ + public static DriverEventTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DriverEventTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link DriverEventTypeEnum} - */ - public static DriverEventTypeEnum ofCode(String code) { - Optional any = Arrays.stream(DriverEventTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link DriverEventTypeEnum} + */ + public static DriverEventTypeEnum ofCode(String code) { + Optional any = Arrays.stream(DriverEventTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link DriverEventTypeEnum} - */ - public static DriverEventTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link DriverEventTypeEnum} + */ + public static DriverEventTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverStatusEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverStatusEnum.java index 1b5082bda..1b9c9f2ba 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverStatusEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverStatusEnum.java @@ -35,61 +35,64 @@ import java.util.Optional; @AllArgsConstructor public enum DriverStatusEnum { - ONLINE((byte) 0, "ONLINE", "Online"), OFFLINE((byte) 1, "OFFLINE", "Offline"), - MAINTAIN((byte) 2, "MAINTAIN", "Maintain"), FAULT((byte) 3, "FAULT", "Fault"),; + ONLINE((byte) 0, "ONLINE", "Online"), OFFLINE((byte) 1, "OFFLINE", "Offline"), + MAINTAIN((byte) 2, "MAINTAIN", "Maintain"), FAULT((byte) 3, "FAULT", "Fault"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link DriverStatusEnum} - */ - public static DriverStatusEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DriverStatusEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link DriverStatusEnum} + */ + public static DriverStatusEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DriverStatusEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link DriverStatusEnum} - */ - public static DriverStatusEnum ofCode(String code) { - Optional any = Arrays.stream(DriverStatusEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link DriverStatusEnum} + */ + public static DriverStatusEnum ofCode(String code) { + Optional any = Arrays.stream(DriverStatusEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link DriverStatusEnum} - */ - public static DriverStatusEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link DriverStatusEnum} + */ + public static DriverStatusEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverTypeFlagEnum.java index 08abbedf9..1b6d4279f 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/DriverTypeFlagEnum.java @@ -35,78 +35,81 @@ import java.util.Optional; @AllArgsConstructor public enum DriverTypeFlagEnum { - /** - * Protocol driver, client mode - */ - DRIVER_CLIENT((byte) 0, "driver_client", "Protocol driver, client mode"), + /** + * Protocol driver, client mode + */ + DRIVER_CLIENT((byte) 0, "driver_client", "Protocol driver, client mode"), - /** - * Protocol driver, server mode - */ - DRIVER_SERVER((byte) 1, "driver_server", "Protocol driver, server mode"), + /** + * Protocol driver, server mode + */ + DRIVER_SERVER((byte) 1, "driver_server", "Protocol driver, server mode"), - /** - * Gateway driver - */ - GATEWAY((byte) 2, "gateway", "Gateway driver"), + /** + * Gateway driver + */ + GATEWAY((byte) 2, "gateway", "Gateway driver"), - /** - * Connection driver - */ - CONNECT((byte) 3, "connect", "Connection driver"),; + /** + * Connection driver + */ + CONNECT((byte) 3, "connect", "Connection driver"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link DriverTypeFlagEnum} - */ - public static DriverTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(DriverTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link DriverTypeFlagEnum} + */ + public static DriverTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(DriverTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link DriverTypeFlagEnum} - */ - public static DriverTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(DriverTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link DriverTypeFlagEnum} + */ + public static DriverTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(DriverTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link DriverTypeFlagEnum} - */ - public static DriverTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link DriverTypeFlagEnum} + */ + public static DriverTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EnableFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EnableFlagEnum.java index fea08fb06..523d23569 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EnableFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EnableFlagEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum EnableFlagEnum { - /** - * Enabled. - */ - ENABLE((byte) 0, "enable", "enable"), + /** + * Enabled. + */ + ENABLE((byte) 0, "enable", "enable"), - /** - * Disabled. - */ - DISABLE((byte) 1, "disable", "disable"),; + /** + * Disabled. + */ + DISABLE((byte) 1, "disable", "disable"), + ; - /** - * Index value stored in database. - */ - @EnumValue - private final Byte index; + /** + * Index value stored in database. + */ + @EnumValue + private final Byte index; - /** - * Code string. - */ - private final String code; + /** + * Code string. + */ + private final String code; - /** - * Human-readable description. - */ - private final String remark; + /** + * Human-readable description. + */ + private final String remark; - /** - * Get enum by index value. - * @param index index value - * @return {@link EnableFlagEnum} or {@code null} if not found - */ - public static EnableFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(EnableFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index value. + * + * @param index index value + * @return {@link EnableFlagEnum} or {@code null} if not found + */ + public static EnableFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(EnableFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code string. - * @param code code string - * @return {@link EnableFlagEnum} or {@code null} if not found - */ - public static EnableFlagEnum ofCode(String code) { - Optional any = Arrays.stream(EnableFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code string. + * + * @param code code string + * @return {@link EnableFlagEnum} or {@code null} if not found + */ + public static EnableFlagEnum ofCode(String code) { + Optional any = Arrays.stream(EnableFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by enum name. - * @param name enum name - * @return {@link EnableFlagEnum} or {@code null} if parsing fails - */ - public static EnableFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by enum name. + * + * @param name enum name + * @return {@link EnableFlagEnum} or {@code null} if parsing fails + */ + public static EnableFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EntityTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EntityTypeFlagEnum.java index 0798ddecc..943e2c52a 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EntityTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/EntityTypeFlagEnum.java @@ -35,93 +35,96 @@ import java.util.Optional; @AllArgsConstructor public enum EntityTypeFlagEnum { - /** - * System - */ - SYSTEM((byte) 0, "system", "System"), + /** + * System + */ + SYSTEM((byte) 0, "system", "System"), - /** - * User - */ - USER((byte) 1, "user", "User"), + /** + * User + */ + USER((byte) 1, "user", "User"), - /** - * Group - */ - GROUP((byte) 2, "group", "Group"), + /** + * Group + */ + GROUP((byte) 2, "group", "Group"), - /** - * Driver - */ - DRIVER((byte) 3, "driver", "Driver"), + /** + * Driver + */ + DRIVER((byte) 3, "driver", "Driver"), - /** - * Profile - */ - PROFILE((byte) 4, "profile", "Profile"), + /** + * Profile + */ + PROFILE((byte) 4, "profile", "Profile"), - /** - * Point - */ - POINT((byte) 5, "point", "Point"), + /** + * Point + */ + POINT((byte) 5, "point", "Point"), - /** - * Device - */ - DEVICE((byte) 6, "device", "Device"),; + /** + * Device + */ + DEVICE((byte) 6, "device", "Device"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link EntityTypeFlagEnum} - */ - public static EntityTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(EntityTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link EntityTypeFlagEnum} + */ + public static EntityTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(EntityTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link EntityTypeFlagEnum} - */ - public static EntityTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(EntityTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link EntityTypeFlagEnum} + */ + public static EntityTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(EntityTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Enum name - * @return {@link EntityTypeFlagEnum} - */ - public static EntityTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Enum name + * @return {@link EntityTypeFlagEnum} + */ + public static EntityTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ExpireFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ExpireFlagEnum.java index 244215b16..9089a96dc 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ExpireFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ExpireFlagEnum.java @@ -35,98 +35,101 @@ import java.util.Optional; @AllArgsConstructor public enum ExpireFlagEnum { - /** - * Permanent - */ - PERMANENT((byte) 0, "permanent", "Permanent"), + /** + * Permanent + */ + PERMANENT((byte) 0, "permanent", "Permanent"), - /** - * One day - */ - ONE_DAY((byte) 1, "one_day", "One day"), + /** + * One day + */ + ONE_DAY((byte) 1, "one_day", "One day"), - /** - * One week - */ - ONE_WEEK((byte) 2, "one_week", "One week"), + /** + * One week + */ + ONE_WEEK((byte) 2, "one_week", "One week"), - /** - * One month - */ - ONE_MONTH((byte) 3, "one_month", "One month"), + /** + * One month + */ + ONE_MONTH((byte) 3, "one_month", "One month"), - /** - * Three months - */ - THREE_MONTHS((byte) 4, "three_months", "Three months"), + /** + * Three months + */ + THREE_MONTHS((byte) 4, "three_months", "Three months"), - /** - * Half year - */ - HALF_YEAR((byte) 5, "half_year", "Half year"), + /** + * Half year + */ + HALF_YEAR((byte) 5, "half_year", "Half year"), - /** - * One year - */ - ONE_YEAR((byte) 6, "one_year", "One year"), + /** + * One year + */ + ONE_YEAR((byte) 6, "one_year", "One year"), - /** - * Custom - */ - CUSTOM((byte) 7, "custom", "Custom"),; + /** + * Custom + */ + CUSTOM((byte) 7, "custom", "Custom"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link ExpireFlagEnum} - */ - public static ExpireFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ExpireFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ExpireFlagEnum} + */ + public static ExpireFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ExpireFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ExpireFlagEnum} - */ - public static ExpireFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ExpireFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ExpireFlagEnum} + */ + public static ExpireFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ExpireFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Enum name - * @return {@link ExpireFlagEnum} - */ - public static ExpireFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Enum name + * @return {@link ExpireFlagEnum} + */ + public static ExpireFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/GroupTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/GroupTypeFlagEnum.java index 4d4f13e4b..d4c04b821 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/GroupTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/GroupTypeFlagEnum.java @@ -35,60 +35,62 @@ import java.util.Optional; @AllArgsConstructor public enum GroupTypeFlagEnum { - ; + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index index - * @return {@link GroupTypeFlagEnum} - */ - public static GroupTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(GroupTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index index + * @return {@link GroupTypeFlagEnum} + */ + public static GroupTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(GroupTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code code - * @return {@link GroupTypeFlagEnum} - */ - public static GroupTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(GroupTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code code + * @return {@link GroupTypeFlagEnum} + */ + public static GroupTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(GroupTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name enum name - * @return {@link GroupTypeFlagEnum} - */ - public static GroupTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name enum name + * @return {@link GroupTypeFlagEnum} + */ + public static GroupTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuLevelFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuLevelFlagEnum.java index 73904b420..7bcafa7a1 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuLevelFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuLevelFlagEnum.java @@ -35,83 +35,86 @@ import java.util.Optional; @AllArgsConstructor public enum MenuLevelFlagEnum { - /** - * Root menu - */ - ROOT((byte) 0, "root", "Root menu"), + /** + * Root menu + */ + ROOT((byte) 0, "root", "Root menu"), - /** - * First-level submenu - */ - C1((byte) 1, "c1", "First-level submenu"), + /** + * First-level submenu + */ + C1((byte) 1, "c1", "First-level submenu"), - /** - * Second-level submenu - */ - C2((byte) 2, "c2", "Second-level submenu"), + /** + * Second-level submenu + */ + C2((byte) 2, "c2", "Second-level submenu"), - /** - * Third-level submenu - */ - C3((byte) 3, "c3", "Third-level submenu"), + /** + * Third-level submenu + */ + C3((byte) 3, "c3", "Third-level submenu"), - /** - * Fourth-level submenu - */ - C4((byte) 4, "c4", "Fourth-level submenu"),; + /** + * Fourth-level submenu + */ + C4((byte) 4, "c4", "Fourth-level submenu"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link MenuLevelFlagEnum} - */ - public static MenuLevelFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(MenuLevelFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link MenuLevelFlagEnum} + */ + public static MenuLevelFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(MenuLevelFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link MenuLevelFlagEnum} - */ - public static MenuLevelFlagEnum ofCode(String code) { - Optional any = Arrays.stream(MenuLevelFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link MenuLevelFlagEnum} + */ + public static MenuLevelFlagEnum ofCode(String code) { + Optional any = Arrays.stream(MenuLevelFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Enum name - * @return {@link MenuLevelFlagEnum} - */ - public static MenuLevelFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Enum name + * @return {@link MenuLevelFlagEnum} + */ + public static MenuLevelFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuTypeFlagEnum.java index 75b4de7c2..6af063ea7 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MenuTypeFlagEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum MenuTypeFlagEnum { - /** - * Title menu - */ - TITLE((byte) 0, "title", "Title menu"), + /** + * Title menu + */ + TITLE((byte) 0, "title", "Title menu"), - /** - * Common menu - */ - COMMON((byte) 1, "common", "Common menu"),; + /** + * Common menu + */ + COMMON((byte) 1, "common", "Common menu"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link MenuTypeFlagEnum} - */ - public static MenuTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(MenuTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link MenuTypeFlagEnum} + */ + public static MenuTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(MenuTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link MenuTypeFlagEnum} - */ - public static MenuTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(MenuTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link MenuTypeFlagEnum} + */ + public static MenuTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(MenuTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link MenuTypeFlagEnum} - */ - public static MenuTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link MenuTypeFlagEnum} + */ + public static MenuTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataOperateTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataOperateTypeEnum.java index 8549bf339..a338acf77 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataOperateTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataOperateTypeEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum MetadataOperateTypeEnum { - /** - * Add - */ - ADD((byte) 0, "add", "Add"), + /** + * Add + */ + ADD((byte) 0, "add", "Add"), - /** - * Delete - */ - DELETE((byte) 1, "delete", "Delete"), + /** + * Delete + */ + DELETE((byte) 1, "delete", "Delete"), - /** - * Update - */ - UPDATE((byte) 2, "update", "Update"),; + /** + * Update + */ + UPDATE((byte) 2, "update", "Update"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link MetadataOperateTypeEnum} - */ - public static MetadataOperateTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(MetadataOperateTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link MetadataOperateTypeEnum} + */ + public static MetadataOperateTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(MetadataOperateTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link MetadataOperateTypeEnum} - */ - public static MetadataOperateTypeEnum ofCode(String code) { - Optional any = Arrays.stream(MetadataOperateTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link MetadataOperateTypeEnum} + */ + public static MetadataOperateTypeEnum ofCode(String code) { + Optional any = Arrays.stream(MetadataOperateTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link MetadataOperateTypeEnum} - */ - public static MetadataOperateTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link MetadataOperateTypeEnum} + */ + public static MetadataOperateTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataTypeEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataTypeEnum.java index 9fe971fc7..5540bcf33 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataTypeEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/MetadataTypeEnum.java @@ -35,68 +35,71 @@ import java.util.Optional; @AllArgsConstructor public enum MetadataTypeEnum { - /** - * Device metadata - */ - DEVICE((byte) 0, "device", "Device metadata"), + /** + * Device metadata + */ + DEVICE((byte) 0, "device", "Device metadata"), - /** - * Point metadata - */ - POINT((byte) 1, "point", "Point metadata"),; + /** + * Point metadata + */ + POINT((byte) 1, "point", "Point metadata"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link MetadataTypeEnum} - */ - public static MetadataTypeEnum ofIndex(Byte index) { - Optional any = Arrays.stream(MetadataTypeEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link MetadataTypeEnum} + */ + public static MetadataTypeEnum ofIndex(Byte index) { + Optional any = Arrays.stream(MetadataTypeEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link MetadataTypeEnum} - */ - public static MetadataTypeEnum ofCode(String code) { - Optional any = Arrays.stream(MetadataTypeEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link MetadataTypeEnum} + */ + public static MetadataTypeEnum ofCode(String code) { + Optional any = Arrays.stream(MetadataTypeEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link MetadataTypeEnum} - */ - public static MetadataTypeEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link MetadataTypeEnum} + */ + public static MetadataTypeEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/PointTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/PointTypeFlagEnum.java index 455d1b08c..fe73502bf 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/PointTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/PointTypeFlagEnum.java @@ -35,98 +35,101 @@ import java.util.Optional; @AllArgsConstructor public enum PointTypeFlagEnum { - /** - * String - */ - STRING((byte) 0, "string", "String"), + /** + * String + */ + STRING((byte) 0, "string", "String"), - /** - * Byte - */ - BYTE((byte) 1, "byte", "Byte"), + /** + * Byte + */ + BYTE((byte) 1, "byte", "Byte"), - /** - * Short - */ - SHORT((byte) 2, "short", "Short"), + /** + * Short + */ + SHORT((byte) 2, "short", "Short"), - /** - * Int - */ - INT((byte) 3, "int", "Int"), + /** + * Int + */ + INT((byte) 3, "int", "Int"), - /** - * Long - */ - LONG((byte) 4, "long", "Long"), + /** + * Long + */ + LONG((byte) 4, "long", "Long"), - /** - * Float - */ - FLOAT((byte) 5, "float", "Float"), + /** + * Float + */ + FLOAT((byte) 5, "float", "Float"), - /** - * Double - */ - DOUBLE((byte) 6, "double", "Double"), + /** + * Double + */ + DOUBLE((byte) 6, "double", "Double"), - /** - * Boolean - */ - BOOLEAN((byte) 7, "boolean", "Boolean"),; + /** + * Boolean + */ + BOOLEAN((byte) 7, "boolean", "Boolean"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link PointTypeFlagEnum} - */ - public static PointTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(PointTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link PointTypeFlagEnum} + */ + public static PointTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(PointTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link PointTypeFlagEnum} - */ - public static PointTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(PointTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link PointTypeFlagEnum} + */ + public static PointTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(PointTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link PointTypeFlagEnum} - */ - public static PointTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link PointTypeFlagEnum} + */ + public static PointTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileShareFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileShareFlagEnum.java index 8c3680adc..c611bfdba 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileShareFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileShareFlagEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum ProfileShareFlagEnum { - /** - * Shared profile under tenant - */ - TENANT((byte) 0, "tenant", "Shared profile under tenant"), + /** + * Shared profile under tenant + */ + TENANT((byte) 0, "tenant", "Shared profile under tenant"), - /** - * Shared profile under driver - */ - DRIVER((byte) 1, "driver", "Shared profile under driver"), + /** + * Shared profile under driver + */ + DRIVER((byte) 1, "driver", "Shared profile under driver"), - /** - * Shared profile under user - */ - USER((byte) 2, "user", "Shared profile under user"),; + /** + * Shared profile under user + */ + USER((byte) 2, "user", "Shared profile under user"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link ProfileShareFlagEnum} - */ - public static ProfileShareFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ProfileShareFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ProfileShareFlagEnum} + */ + public static ProfileShareFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ProfileShareFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ProfileShareFlagEnum} - */ - public static ProfileShareFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ProfileShareFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ProfileShareFlagEnum} + */ + public static ProfileShareFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ProfileShareFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ProfileShareFlagEnum} - */ - public static ProfileShareFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ProfileShareFlagEnum} + */ + public static ProfileShareFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileTypeFlagEnum.java index 164ea016d..ff5b1e770 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ProfileTypeFlagEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum ProfileTypeFlagEnum { - /** - * System create - */ - SYSTEM((byte) 0, "system", "System create"), + /** + * System create + */ + SYSTEM((byte) 0, "system", "System create"), - /** - * Driver create - */ - DRIVER((byte) 1, "driver", "Driver create"), + /** + * Driver create + */ + DRIVER((byte) 1, "driver", "Driver create"), - /** - * User create - */ - USER((byte) 2, "user", "User create"),; + /** + * User create + */ + USER((byte) 2, "user", "User create"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link ProfileTypeFlagEnum} - */ - public static ProfileTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ProfileTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ProfileTypeFlagEnum} + */ + public static ProfileTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ProfileTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ProfileTypeFlagEnum} - */ - public static ProfileTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ProfileTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ProfileTypeFlagEnum} + */ + public static ProfileTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ProfileTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ProfileTypeFlagEnum} - */ - public static ProfileTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ProfileTypeFlagEnum} + */ + public static ProfileTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceScopeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceScopeFlagEnum.java index 49c0d0614..b40ccddc2 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceScopeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceScopeFlagEnum.java @@ -35,78 +35,81 @@ import java.util.Optional; @AllArgsConstructor public enum ResourceScopeFlagEnum { - /** - * Add - */ - ADD((byte) 0, "add", "Add"), + /** + * Add + */ + ADD((byte) 0, "add", "Add"), - /** - * Delete - */ - DELETE((byte) 1, "delete", "Delete"), + /** + * Delete + */ + DELETE((byte) 1, "delete", "Delete"), - /** - * Update - */ - UPDATE((byte) 2, "update", "Update"), + /** + * Update + */ + UPDATE((byte) 2, "update", "Update"), - /** - * List - */ - LIST((byte) 3, "list", "List"),; + /** + * List + */ + LIST((byte) 3, "list", "List"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link ResourceScopeFlagEnum} - */ - public static ResourceScopeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ResourceScopeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ResourceScopeFlagEnum} + */ + public static ResourceScopeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ResourceScopeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ResourceScopeFlagEnum} - */ - public static ResourceScopeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ResourceScopeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ResourceScopeFlagEnum} + */ + public static ResourceScopeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ResourceScopeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ResourceScopeFlagEnum} - */ - public static ResourceScopeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ResourceScopeFlagEnum} + */ + public static ResourceScopeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceTypeFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceTypeFlagEnum.java index da39cd1f2..77286c0df 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceTypeFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResourceTypeFlagEnum.java @@ -35,93 +35,96 @@ import java.util.Optional; @AllArgsConstructor public enum ResourceTypeFlagEnum { - /** - * Driver - */ - DRIVER((byte) 0, "driver", "Driver"), + /** + * Driver + */ + DRIVER((byte) 0, "driver", "Driver"), - /** - * Profile - */ - PROFILE((byte) 1, "profile", "Profile"), + /** + * Profile + */ + PROFILE((byte) 1, "profile", "Profile"), - /** - * Point - */ - POINT((byte) 2, "point", "Point"), + /** + * Point + */ + POINT((byte) 2, "point", "Point"), - /** - * Device - */ - DEVICE((byte) 3, "device", "Device"), + /** + * Device + */ + DEVICE((byte) 3, "device", "Device"), - /** - * Data - */ - DATA((byte) 4, "data", "Data"), + /** + * Data + */ + DATA((byte) 4, "data", "Data"), - /** - * Menu - */ - MENU((byte) 5, "menu", "Menu"), + /** + * Menu + */ + MENU((byte) 5, "menu", "Menu"), - /** - * Api - */ - API((byte) 6, "api", "Api"),; + /** + * Api + */ + API((byte) 6, "api", "Api"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Text - */ - private final String text; + /** + * Text + */ + private final String text; - /** - * Get enum by index - * @param index Index - * @return {@link ResourceTypeFlagEnum} - */ - public static ResourceTypeFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ResourceTypeFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ResourceTypeFlagEnum} + */ + public static ResourceTypeFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ResourceTypeFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ResourceTypeFlagEnum} - */ - public static ResourceTypeFlagEnum ofCode(String code) { - Optional any = Arrays.stream(ResourceTypeFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ResourceTypeFlagEnum} + */ + public static ResourceTypeFlagEnum ofCode(String code) { + Optional any = Arrays.stream(ResourceTypeFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ResourceTypeFlagEnum} - */ - public static ResourceTypeFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ResourceTypeFlagEnum} + */ + public static ResourceTypeFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResponseEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResponseEnum.java index d746e0f54..49b95b0f9 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResponseEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/ResponseEnum.java @@ -35,66 +35,69 @@ import java.util.Optional; @AllArgsConstructor public enum ResponseEnum { - OK((byte) 200, "R200", "Success"), TOKEN_INVALID((byte) 20301, "R20301", "Token is invalid"), - IP_INVALID((byte) 20302, "R20302", "Invalid IP"), FAILURE((byte) 500, "R500", "Service exception"), - NO_RESOURCE((byte) 404, "R404", "Resource does not exist"), OUT_RANGE((byte) 900, "R900", "Number out of range"), + OK((byte) 200, "R200", "Success"), TOKEN_INVALID((byte) 20301, "R20301", "Token is invalid"), + IP_INVALID((byte) 20302, "R20302", "Invalid IP"), FAILURE((byte) 500, "R500", "Service exception"), + NO_RESOURCE((byte) 404, "R404", "Resource does not exist"), OUT_RANGE((byte) 900, "R900", "Number out of range"), - ADD_SUCCESS((byte) 20001, "R20001", "Added successfully"), - DELETE_SUCCESS((byte) 20002, "R20002", "Deleted successfully"), - UPDATE_SUCCESS((byte) 20003, "R20003", "Updated successfully"),; + ADD_SUCCESS((byte) 20001, "R20001", "Added successfully"), + DELETE_SUCCESS((byte) 20002, "R20002", "Deleted successfully"), + UPDATE_SUCCESS((byte) 20003, "R20003", "Updated successfully"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Text - */ - private final String text; + /** + * Text + */ + private final String text; - /** - * Get enum by index - * @param index Index - * @return {@link ResponseEnum} - */ - public static ResponseEnum ofIndex(Byte index) { - Optional any = Arrays.stream(ResponseEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link ResponseEnum} + */ + public static ResponseEnum ofIndex(Byte index) { + Optional any = Arrays.stream(ResponseEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link ResponseEnum} - */ - public static ResponseEnum ofCode(String code) { - Optional any = Arrays.stream(ResponseEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link ResponseEnum} + */ + public static ResponseEnum ofCode(String code) { + Optional any = Arrays.stream(ResponseEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link ResponseEnum} - */ - public static ResponseEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link ResponseEnum} + */ + public static ResponseEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/RwFlagEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/RwFlagEnum.java index 8e3fc9ab4..3f74b9340 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/RwFlagEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/RwFlagEnum.java @@ -35,73 +35,76 @@ import java.util.Optional; @AllArgsConstructor public enum RwFlagEnum { - /** - * Read only - */ - R((byte) 0, "r", "Read only"), + /** + * Read only + */ + R((byte) 0, "r", "Read only"), - /** - * Write only - */ - W((byte) 1, "w", "Write only"), + /** + * Write only + */ + W((byte) 1, "w", "Write only"), - /** - * Read and Write - */ - RW((byte) 2, "rw", "Read and Write"),; + /** + * Read and Write + */ + RW((byte) 2, "rw", "Read and Write"), + ; - /** - * Index - */ - @EnumValue - private final Byte index; + /** + * Index + */ + @EnumValue + private final Byte index; - /** - * Code - */ - private final String code; + /** + * Code + */ + private final String code; - /** - * Remark - */ - private final String remark; + /** + * Remark + */ + private final String remark; - /** - * Get enum by index - * @param index Index - * @return {@link RwFlagEnum} - */ - public static RwFlagEnum ofIndex(Byte index) { - Optional any = Arrays.stream(RwFlagEnum.values()) - .filter(type -> type.getIndex().equals(index)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by index + * + * @param index Index + * @return {@link RwFlagEnum} + */ + public static RwFlagEnum ofIndex(Byte index) { + Optional any = Arrays.stream(RwFlagEnum.values()) + .filter(type -> type.getIndex().equals(index)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by code - * @param code Code - * @return {@link RwFlagEnum} - */ - public static RwFlagEnum ofCode(String code) { - Optional any = Arrays.stream(RwFlagEnum.values()) - .filter(type -> type.getCode().equals(code)) - .findFirst(); - return any.orElse(null); - } + /** + * Get enum by code + * + * @param code Code + * @return {@link RwFlagEnum} + */ + public static RwFlagEnum ofCode(String code) { + Optional any = Arrays.stream(RwFlagEnum.values()) + .filter(type -> type.getCode().equals(code)) + .findFirst(); + return any.orElse(null); + } - /** - * Get enum by name - * @param name Name - * @return {@link RwFlagEnum} - */ - public static RwFlagEnum ofName(String name) { - try { - return valueOf(name); - } - catch (IllegalArgumentException e) { - return null; - } - } + /** + * Get enum by name + * + * @param name Name + * @return {@link RwFlagEnum} + */ + public static RwFlagEnum ofName(String name) { + try { + return valueOf(name); + } catch (IllegalArgumentException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/TimeRangeKeyEnum.java b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/TimeRangeKeyEnum.java index 2e0104bf4..76d3bad66 100644 --- a/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/TimeRangeKeyEnum.java +++ b/dc3-common/dc3-common-constant/src/main/java/io/github/pnoker/common/enums/TimeRangeKeyEnum.java @@ -37,43 +37,44 @@ import java.util.Optional; @AllArgsConstructor public enum TimeRangeKeyEnum { - /** - * From local midnight of today to now. - */ - TODAY("today", "today"), + /** + * From local midnight of today to now. + */ + TODAY("today", "today"), - /** - * Rolling 24 hours ending now. - */ - H24("24h", "last 24 hours"), + /** + * Rolling 24 hours ending now. + */ + H24("24h", "last 24 hours"), - /** - * Rolling 7 days ending now. - */ - D7("7d", "last 7 days"), + /** + * Rolling 7 days ending now. + */ + D7("7d", "last 7 days"), - /** - * Rolling 30 days ending now. - */ - D30("30d", "last 30 days"),; + /** + * Rolling 30 days ending now. + */ + D30("30d", "last 30 days"), + ; - private final String code; + private final String code; - private final String remark; + private final String remark; - /** - * Resolve an enum instance by its wire-format code (e.g. {@code "today"}). Matching - * is case-insensitive; {@code null} / blank input returns {@code null}. - */ - public static TimeRangeKeyEnum ofCode(String code) { - if (code == null || code.isBlank()) { - return null; - } - String normalized = code.trim(); - Optional any = Arrays.stream(values()) - .filter(e -> e.getCode().equalsIgnoreCase(normalized)) - .findFirst(); - return any.orElse(null); - } + /** + * Resolve an enum instance by its wire-format code (e.g. {@code "today"}). Matching + * is case-insensitive; {@code null} / blank input returns {@code null}. + */ + public static TimeRangeKeyEnum ofCode(String code) { + if (code == null || code.isBlank()) { + return null; + } + String normalized = code.trim(); + Optional any = Arrays.stream(values()) + .filter(e -> e.getCode().equalsIgnoreCase(normalized)) + .findFirst(); + return any.orElse(null); + } } diff --git a/dc3-common/dc3-common-dal/README.md b/dc3-common/dc3-common-dal/README.md index efba7fc6b..74e521a45 100644 --- a/dc3-common/dc3-common-dal/README.md +++ b/dc3-common/dc3-common-dal/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-dal` is the shared Data Access Layer module of the IoT DC3 platform. It provides common VO/BO entities, DAL manager implementations, and shared data structures used +`dc3-common-dal` is the shared Data Access Layer module of the IoT DC3 platform. It provides common VO/BO entities, DAL +manager implementations, and shared data structures used across multiple service modules. ## Module Information diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/config/DalConfig.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/config/DalConfig.java index 5fec523f6..524ad299c 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/config/DalConfig.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/config/DalConfig.java @@ -35,8 +35,8 @@ import org.springframework.context.annotation.Configuration; */ @Slf4j @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.dal" }) -@MapperScan(basePackages = { "io.github.pnoker.common.dal.mapper" }) +@ComponentScan(basePackages = {"io.github.pnoker.common.dal"}) +@MapperScan(basePackages = {"io.github.pnoker.common.dal.mapper"}) public class DalConfig { } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/DictionaryBO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/DictionaryBO.java index 871f26ac4..c9f6d9178 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/DictionaryBO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/DictionaryBO.java @@ -38,37 +38,37 @@ import java.util.List; @AllArgsConstructor public class DictionaryBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Dictionary type. - */ - private String type; + /** + * Dictionary type. + */ + private String type; - /** - * Dictionary label name. - */ - private String label; + /** + * Dictionary label name. + */ + private String label; - /** - * Dictionary label value. - */ - private String value; + /** + * Dictionary label value. + */ + private String value; - /** - * Whether the dictionary item is disabled. - */ - private boolean disabled; + /** + * Whether the dictionary item is disabled. + */ + private boolean disabled; - /** - * Whether the dictionary node is expanded. - */ - private boolean expand; + /** + * Whether the dictionary node is expanded. + */ + private boolean expand; - /** - * Child dictionary nodes. - */ - private List children; + /** + * Child dictionary nodes. + */ + private List children; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/GroupBO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/GroupBO.java index 384351ac3..62fcd1548 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/GroupBO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/GroupBO.java @@ -36,44 +36,44 @@ import lombok.*; @ToString(callSuper = true) public class GroupBO extends BaseBO { - /** - * Parent group ID. - */ - private String parentGroupId; + /** + * Parent group ID. + */ + private String parentGroupId; - /** - * Group type flag. - */ - private GroupTypeFlagEnum groupTypeFlag; + /** + * Group type flag. + */ + private GroupTypeFlagEnum groupTypeFlag; - /** - * Group name. - */ - private String groupName; + /** + * Group name. + */ + private String groupName; - /** - * Group code. - */ - private String groupCode; + /** + * Group code. + */ + private String groupCode; - /** - * Group level. - */ - private Byte groupLevel; + /** + * Group level. + */ + private Byte groupLevel; - /** - * Group index/order. - */ - private Byte groupIndex; + /** + * Group index/order. + */ + private Byte groupIndex; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBO.java index 67a493e6f..68f875c4e 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBO.java @@ -36,34 +36,34 @@ import lombok.*; @ToString(callSuper = true) public class LabelBO extends BaseBO { - /** - * Label name. - */ - private String labelName; + /** + * Label name. + */ + private String labelName; - /** - * Label code. - */ - private String labelCode; + /** + * Label code. + */ + private String labelCode; - /** - * Label color. - */ - private String labelColor; + /** + * Label color. + */ + private String labelColor; - /** - * Entity type flag. - */ - private EntityTypeFlagEnum entityTypeFlag; + /** + * Entity type flag. + */ + private EntityTypeFlagEnum entityTypeFlag; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBindBO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBindBO.java index 39e4b1da7..0da2227bd 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBindBO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/bo/LabelBindBO.java @@ -36,24 +36,24 @@ import lombok.*; @ToString(callSuper = true) public class LabelBindBO extends BaseBO { - /** - * Entity type flag. - */ - private EntityTypeFlagEnum entityTypeFlag; + /** + * Entity type flag. + */ + private EntityTypeFlagEnum entityTypeFlag; - /** - * Label ID. - */ - private Long labelId; + /** + * Label ID. + */ + private Long labelId; - /** - * Entity ID. - */ - private Long entityId; + /** + * Entity ID. + */ + private Long entityId; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/DictionaryBuilder.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/DictionaryBuilder.java index 6bcbd8f4b..70908cdb6 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/DictionaryBuilder.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/DictionaryBuilder.java @@ -33,48 +33,53 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DictionaryBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - DictionaryBO buildBOByVO(DictionaryVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + DictionaryBO buildBOByVO(DictionaryVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - DictionaryVO buildVOByBO(DictionaryBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + DictionaryVO buildVOByBO(DictionaryBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO collection - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO collection + */ + List buildVOListByBOList(List entityBOList); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/GroupBuilder.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/GroupBuilder.java index 5a6797ebb..11fd62e4f 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/GroupBuilder.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/GroupBuilder.java @@ -41,122 +41,132 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GroupBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - GroupBO buildBOByVO(GroupVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + GroupBO buildBOByVO(GroupVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - GroupVO buildVOByBO(GroupBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + GroupVO buildVOByBO(GroupBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO collection - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO collection + */ + List buildVOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "groupTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - GroupBO buildBOByDO(GroupDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "groupTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + GroupBO buildBOByDO(GroupDO entityDO); - @AfterMapping - default void afterProcess(GroupDO entityDO, @MappingTarget GroupBO entityBO) { - // GroupType Flag - Byte groupTypeFlag = entityDO.getGroupTypeFlag(); - entityBO.setGroupTypeFlag(GroupTypeFlagEnum.ofIndex(groupTypeFlag)); + @AfterMapping + default void afterProcess(GroupDO entityDO, @MappingTarget GroupBO entityBO) { + // GroupType Flag + Byte groupTypeFlag = entityDO.getGroupTypeFlag(); + entityBO.setGroupTypeFlag(GroupTypeFlagEnum.ofIndex(groupTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "groupTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - GroupDO buildDOByBO(GroupBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "groupTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + GroupDO buildDOByBO(GroupBO entityBO); - @AfterMapping - default void afterProcess(GroupBO entityBO, @MappingTarget GroupDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getGroupCode())) { - entityDO.setGroupCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(GroupBO entityBO, @MappingTarget GroupDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getGroupCode())) { + entityDO.setGroupCode(CodeUtil.getCode()); + } - // GroupType Flag - GroupTypeFlagEnum groupTypeFlag = entityBO.getGroupTypeFlag(); - Optional.ofNullable(groupTypeFlag).ifPresent(value -> entityDO.setGroupTypeFlag(value.getIndex())); + // GroupType Flag + GroupTypeFlagEnum groupTypeFlag = entityBO.getGroupTypeFlag(); + Optional.ofNullable(groupTypeFlag).ifPresent(value -> entityDO.setGroupTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBindBuilder.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBindBuilder.java index 158914b8c..147903a24 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBindBuilder.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBindBuilder.java @@ -38,107 +38,117 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface LabelBindBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - LabelBindBO buildBOByVO(LabelBindVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + LabelBindBO buildBOByVO(LabelBindVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - LabelBindVO buildVOByBO(LabelBindBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + LabelBindVO buildVOByBO(LabelBindBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO collection - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO collection + */ + List buildVOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "entityTypeFlag", ignore = true) - LabelBindBO buildBOByDO(LabelBindDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "entityTypeFlag", ignore = true) + LabelBindBO buildBOByDO(LabelBindDO entityDO); - @AfterMapping - default void afterProcess(LabelBindDO entityDO, @MappingTarget LabelBindBO entityBO) { - // EntityType Flag - Byte groupTypeFlag = entityDO.getEntityTypeFlag(); - entityBO.setEntityTypeFlag(EntityTypeFlagEnum.ofIndex(groupTypeFlag)); - } + @AfterMapping + default void afterProcess(LabelBindDO entityDO, @MappingTarget LabelBindBO entityBO) { + // EntityType Flag + Byte groupTypeFlag = entityDO.getEntityTypeFlag(); + entityBO.setEntityTypeFlag(EntityTypeFlagEnum.ofIndex(groupTypeFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "entityTypeFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - LabelBindDO buildDOByBO(LabelBindBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "entityTypeFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + LabelBindDO buildDOByBO(LabelBindBO entityBO); - @AfterMapping - default void afterProcess(LabelBindBO entityBO, @MappingTarget LabelBindDO entityDO) { - // EntityType Flag - EntityTypeFlagEnum entityTypeFlag = entityBO.getEntityTypeFlag(); - Optional.ofNullable(entityTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); - } + @AfterMapping + default void afterProcess(LabelBindBO entityBO, @MappingTarget LabelBindDO entityDO) { + // EntityType Flag + EntityTypeFlagEnum entityTypeFlag = entityBO.getEntityTypeFlag(); + Optional.ofNullable(entityTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBuilder.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBuilder.java index 0166e4d57..d64163eca 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBuilder.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/builder/LabelBuilder.java @@ -41,122 +41,132 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface LabelBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - LabelBO buildBOByVO(LabelVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + LabelBO buildBOByVO(LabelVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - LabelVO buildVOByBO(LabelBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + LabelVO buildVOByBO(LabelBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO collection - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO collection + */ + List buildVOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "entityTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - LabelBO buildBOByDO(LabelDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "entityTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + LabelBO buildBOByDO(LabelDO entityDO); - @AfterMapping - default void afterProcess(LabelDO entityDO, @MappingTarget LabelBO entityBO) { - // EntityType Flag - Byte entityTypeFlag = entityDO.getEntityTypeFlag(); - entityBO.setEntityTypeFlag(EntityTypeFlagEnum.ofIndex(entityTypeFlag)); + @AfterMapping + default void afterProcess(LabelDO entityDO, @MappingTarget LabelBO entityBO) { + // EntityType Flag + Byte entityTypeFlag = entityDO.getEntityTypeFlag(); + entityBO.setEntityTypeFlag(EntityTypeFlagEnum.ofIndex(entityTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "entityTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - LabelDO buildDOByBO(LabelBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "entityTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + LabelDO buildDOByBO(LabelBO entityBO); - @AfterMapping - default void afterProcess(LabelBO entityBO, @MappingTarget LabelDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getLabelCode())) { - entityDO.setLabelCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(LabelBO entityBO, @MappingTarget LabelDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getLabelCode())) { + entityDO.setLabelCode(CodeUtil.getCode()); + } - // EntityType Flag - EntityTypeFlagEnum entityTypeFlag = entityBO.getEntityTypeFlag(); - Optional.ofNullable(entityTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); + // EntityType Flag + EntityTypeFlagEnum entityTypeFlag = entityBO.getEntityTypeFlag(); + Optional.ofNullable(entityTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupBindDO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupBindDO.java index ea854ac51..44c0c5e9c 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupBindDO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupBindDO.java @@ -41,86 +41,86 @@ import java.time.LocalDateTime; @TableName("dc3_group_bind") public class GroupBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID. - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID. + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Entity type flag. - */ - @TableField("entity_type_flag") - private Byte entityTypeFlag; + /** + * Entity type flag. + */ + @TableField("entity_type_flag") + private Byte entityTypeFlag; - /** - * Group ID. - */ - @TableField("group_id") - private Long groupId; + /** + * Group ID. + */ + @TableField("group_id") + private Long groupId; - /** - * Entity ID. - */ - @TableField("entity_id") - private Long entityId; + /** + * Entity ID. + */ + @TableField("entity_id") + private Long entityId; - /** - * Tenant ID. - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID. + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Remark or description. - */ - @TableField("remark") - private String remark; + /** + * Remark or description. + */ + @TableField("remark") + private String remark; - /** - * Creator ID. - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID. + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator name. - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator name. + */ + @TableField("creator_name") + private String creatorName; - /** - * Creation time. - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Creation time. + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID. - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID. + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator name. - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator name. + */ + @TableField("operator_name") + private String operatorName; - /** - * Operation time. - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operation time. + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupDO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupDO.java index e106a4ad1..8adcdefdd 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupDO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/GroupDO.java @@ -41,110 +41,110 @@ import java.time.LocalDateTime; @TableName("dc3_group") public class GroupDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID. - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID. + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Parent group ID. - */ - @TableField("parent_group_id") - private Long parentGroupId; + /** + * Parent group ID. + */ + @TableField("parent_group_id") + private Long parentGroupId; - /** - * Group type flag. - */ - @TableField("group_type_flag") - private Byte groupTypeFlag; + /** + * Group type flag. + */ + @TableField("group_type_flag") + private Byte groupTypeFlag; - /** - * Group name. - */ - @TableField("group_name") - private String groupName; + /** + * Group name. + */ + @TableField("group_name") + private String groupName; - /** - * Group code. - */ - @TableField("group_code") - private String groupCode; + /** + * Group code. + */ + @TableField("group_code") + private String groupCode; - /** - * Group level. - */ - @TableField("group_level") - private Byte groupLevel; + /** + * Group level. + */ + @TableField("group_level") + private Byte groupLevel; - /** - * Group index/order. - */ - @TableField("group_index") - private Byte groupIndex; + /** + * Group index/order. + */ + @TableField("group_index") + private Byte groupIndex; - /** - * Enable flag, {@code 0} for enabled, {@code 1} for disabled. - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, {@code 0} for enabled, {@code 1} for disabled. + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID. - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID. + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Remark or description. - */ - @TableField("remark") - private String remark; + /** + * Remark or description. + */ + @TableField("remark") + private String remark; - /** - * Creator ID. - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID. + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator name. - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator name. + */ + @TableField("creator_name") + private String creatorName; - /** - * Creation time. - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Creation time. + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID. - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID. + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator name. - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator name. + */ + @TableField("operator_name") + private String operatorName; - /** - * Operation time. - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operation time. + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelBindDO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelBindDO.java index bf072c1c7..1d2004213 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelBindDO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelBindDO.java @@ -41,86 +41,86 @@ import java.time.LocalDateTime; @TableName("dc3_label_bind") public class LabelBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID. - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID. + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Entity type flag. - */ - @TableField("entity_type_flag") - private Byte entityTypeFlag; + /** + * Entity type flag. + */ + @TableField("entity_type_flag") + private Byte entityTypeFlag; - /** - * Label ID. - */ - @TableField("label_id") - private Long labelId; + /** + * Label ID. + */ + @TableField("label_id") + private Long labelId; - /** - * Entity ID. - */ - @TableField("entity_id") - private Long entityId; + /** + * Entity ID. + */ + @TableField("entity_id") + private Long entityId; - /** - * Tenant ID. - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID. + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Remark or description. - */ - @TableField("remark") - private String remark; + /** + * Remark or description. + */ + @TableField("remark") + private String remark; - /** - * Creator ID. - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID. + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator name. - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator name. + */ + @TableField("creator_name") + private String creatorName; - /** - * Creation time. - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Creation time. + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID. - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID. + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator name. - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator name. + */ + @TableField("operator_name") + private String operatorName; - /** - * Operation time. - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operation time. + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelDO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelDO.java index 326c08602..8d385ea5f 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelDO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/model/LabelDO.java @@ -41,98 +41,98 @@ import java.time.LocalDateTime; @TableName("dc3_label") public class LabelDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID. - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID. + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Label name. - */ - @TableField("label_name") - private String labelName; + /** + * Label name. + */ + @TableField("label_name") + private String labelName; - /** - * Label code. - */ - @TableField("label_code") - private String labelCode; + /** + * Label code. + */ + @TableField("label_code") + private String labelCode; - /** - * Label color. - */ - @TableField("label_color") - private String labelColor; + /** + * Label color. + */ + @TableField("label_color") + private String labelColor; - /** - * Entity type flag. - */ - @TableField("entity_type_flag") - private Byte entityTypeFlag; + /** + * Entity type flag. + */ + @TableField("entity_type_flag") + private Byte entityTypeFlag; - /** - * Enable flag, {@code 0} for enabled, {@code 1} for disabled. - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, {@code 0} for enabled, {@code 1} for disabled. + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID. - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID. + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Remark or description. - */ - @TableField("remark") - private String remark; + /** + * Remark or description. + */ + @TableField("remark") + private String remark; - /** - * Creator ID. - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID. + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator name. - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator name. + */ + @TableField("creator_name") + private String creatorName; - /** - * Creation time. - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Creation time. + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID. - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID. + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator name. - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator name. + */ + @TableField("operator_name") + private String operatorName; - /** - * Operation time. - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operation time. + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, {@code 0} for not deleted, {@code 1} for deleted. + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/GroupQuery.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/GroupQuery.java index 5fbeecbf9..65622de03 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/GroupQuery.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/GroupQuery.java @@ -40,41 +40,41 @@ import java.io.Serializable; @AllArgsConstructor public class GroupQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; - // Query fields + // Query fields - /** - * Group name. - */ - private String groupName; + /** + * Group name. + */ + private String groupName; - /** - * Parent group ID. - */ - private String parentGroupId; + /** + * Parent group ID. + */ + private String parentGroupId; - /** - * Group sort position. - */ - private Integer position; + /** + * Group sort position. + */ + private Integer position; - /** - * Group type flag. - */ - private GroupTypeFlagEnum groupTypeFlag; + /** + * Group type flag. + */ + private GroupTypeFlagEnum groupTypeFlag; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelBindQuery.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelBindQuery.java index 12d514252..ce4ffa3e2 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelBindQuery.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelBindQuery.java @@ -38,26 +38,26 @@ import java.io.Serializable; @AllArgsConstructor public class LabelBindQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; - // Query fields + // Query fields - /** - * Label ID. - */ - private Long labelId; + /** + * Label ID. + */ + private Long labelId; - /** - * Entity ID. - */ - private Long entityId; + /** + * Entity ID. + */ + private Long entityId; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelQuery.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelQuery.java index d3fd54cc4..352e8ab5f 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelQuery.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/query/LabelQuery.java @@ -40,36 +40,36 @@ import java.io.Serializable; @AllArgsConstructor public class LabelQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID. - */ - private Long tenantId; + /** + * Tenant ID. + */ + private Long tenantId; - // Query fields + // Query fields - /** - * Label name. - */ - private String labelName; + /** + * Label name. + */ + private String labelName; - /** - * Label color. - */ - private String color; + /** + * Label color. + */ + private String color; - /** - * Entity type flag. - */ - private EntityTypeFlagEnum entityTypeFlag; + /** + * Entity type flag. + */ + private EntityTypeFlagEnum entityTypeFlag; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/DictionaryVO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/DictionaryVO.java index 15e560282..529fe8597 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/DictionaryVO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/DictionaryVO.java @@ -39,37 +39,37 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DictionaryVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Dictionary type. - */ - private String type; + /** + * Dictionary type. + */ + private String type; - /** - * Dictionary label name. - */ - private String label; + /** + * Dictionary label name. + */ + private String label; - /** - * Dictionary label value. - */ - private String value; + /** + * Dictionary label value. + */ + private String value; - /** - * Whether the dictionary item is disabled. - */ - private boolean disabled; + /** + * Whether the dictionary item is disabled. + */ + private boolean disabled; - /** - * Whether the dictionary node is expanded. - */ - private boolean expand; + /** + * Whether the dictionary node is expanded. + */ + private boolean expand; - /** - * Child dictionary nodes. - */ - private List children; + /** + * Child dictionary nodes. + */ + private List children; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/GroupVO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/GroupVO.java index ce97b1765..3e409b41e 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/GroupVO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/GroupVO.java @@ -42,42 +42,42 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class GroupVO extends BaseVO { - /** - * Parent group ID. - */ - private String parentGroupId; + /** + * Parent group ID. + */ + private String parentGroupId; - /** - * Group type flag. - */ - private GroupTypeFlagEnum groupTypeFlag; + /** + * Group type flag. + */ + private GroupTypeFlagEnum groupTypeFlag; - /** - * Group name. - */ - @NotBlank(message = "分组名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "分组名称格式无效", - groups = { Add.class, Update.class }) - private String groupName; + /** + * Group name. + */ + @NotBlank(message = "分组名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "分组名称格式无效", + groups = {Add.class, Update.class}) + private String groupName; - /** - * Group code. - */ - private String groupCode; + /** + * Group code. + */ + private String groupCode; - /** - * Group level. - */ - private Byte groupLevel; + /** + * Group level. + */ + private Byte groupLevel; - /** - * Group index/order. - */ - private Integer groupIndex; + /** + * Group index/order. + */ + private Integer groupIndex; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelBindVO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelBindVO.java index 499b78039..c737ceba3 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelBindVO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelBindVO.java @@ -41,22 +41,22 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class LabelBindVO extends BaseVO { - /** - * Entity type flag. - */ - @NotNull(message = "实体类型标识不能为空", groups = { Add.class, Update.class }) - private EntityTypeFlagEnum entityTypeFlag; + /** + * Entity type flag. + */ + @NotNull(message = "实体类型标识不能为空", groups = {Add.class, Update.class}) + private EntityTypeFlagEnum entityTypeFlag; - /** - * Label ID. - */ - @NotNull(message = "标签ID不能为空", groups = { Add.class, Update.class }) - private Long labelId; + /** + * Label ID. + */ + @NotNull(message = "标签ID不能为空", groups = {Add.class, Update.class}) + private Long labelId; - /** - * Entity ID. - */ - @NotNull(message = "实体ID不能为空", groups = { Add.class, Update.class }) - private Long entityId; + /** + * Entity ID. + */ + @NotNull(message = "实体ID不能为空", groups = {Add.class, Update.class}) + private Long entityId; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelVO.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelVO.java index c782fe6b1..811e9512c 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelVO.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/entity/vo/LabelVO.java @@ -42,32 +42,32 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class LabelVO extends BaseVO { - /** - * Label name. - */ - @NotBlank(message = "标签名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "标签名称格式无效", - groups = { Add.class, Update.class }) - private String labelName; + /** + * Label name. + */ + @NotBlank(message = "标签名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "标签名称格式无效", + groups = {Add.class, Update.class}) + private String labelName; - /** - * Label code. - */ - private String labelCode; + /** + * Label code. + */ + private String labelCode; - /** - * Label color. - */ - private String labelColor; + /** + * Label color. + */ + private String labelColor; - /** - * Entity type flag. - */ - private EntityTypeFlagEnum entityTypeFlag; + /** + * Entity type flag. + */ + private EntityTypeFlagEnum entityTypeFlag; - /** - * Enable status flag. - */ - private EnableFlagEnum enableFlag; + /** + * Enable status flag. + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/generator/MybatisGenerator.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/generator/MybatisGenerator.java index 64346b5b2..84ab829b8 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/generator/MybatisGenerator.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/generator/MybatisGenerator.java @@ -36,27 +36,27 @@ import java.util.Map; */ public class MybatisGenerator { - public static void main(String[] args) { - generator(); - } + public static void main(String[] args) { + generator(); + } - public static void generator() { - String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-dal/src/main"; - MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_auth", "dc3", "dc3dc3dc3") - .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) - .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) - .packageConfig(builder -> builder.parent("io.github.pnoker.common.dal") - .entity("entity.model") - .service("dal") - .serviceImpl("dal.impl") - .mapper("mapper") - .pathInfo(Map.of(OutputFile.service, path + "/java/io/github/pnoker/common/dal/dal", - OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/dal/dal/impl", OutputFile.xml, - path + "/resources/mapping"))) - .templateEngine(new FreemarkerTemplateEngine()) - .strategyConfig(MybatisUtil::defaultStrategyConfig) - .strategyConfig(builder -> builder.addInclude("dc3_group", "dc3_group_bind", "dc3_label", "dc3_label_bind")) - .execute(); - } + public static void generator() { + String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-dal/src/main"; + MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_auth", "dc3", "dc3dc3dc3") + .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) + .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) + .packageConfig(builder -> builder.parent("io.github.pnoker.common.dal") + .entity("entity.model") + .service("dal") + .serviceImpl("dal.impl") + .mapper("mapper") + .pathInfo(Map.of(OutputFile.service, path + "/java/io/github/pnoker/common/dal/dal", + OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/dal/dal/impl", OutputFile.xml, + path + "/resources/mapping"))) + .templateEngine(new FreemarkerTemplateEngine()) + .strategyConfig(MybatisUtil::defaultStrategyConfig) + .strategyConfig(builder -> builder.addInclude("dc3_group", "dc3_group_bind", "dc3_label", "dc3_label_bind")) + .execute(); + } } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/GroupServiceImpl.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/GroupServiceImpl.java index 0b5053e01..ce06f8ce6 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/GroupServiceImpl.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/GroupServiceImpl.java @@ -51,117 +51,120 @@ import java.util.Objects; @Service public class GroupServiceImpl implements GroupService { - @Resource - private GroupBuilder groupBuilder; + @Resource + private GroupBuilder groupBuilder; - @Resource - private GroupManager groupManager; + @Resource + private GroupManager groupManager; - @Override - public void save(GroupBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(GroupBO entityBO) { + checkDuplicate(entityBO, false, true); - GroupDO entityDO = groupBuilder.buildDOByBO(entityBO); - if (!groupManager.save(entityDO)) { - throw new AddException("Failed to create group"); - } - } + GroupDO entityDO = groupBuilder.buildDOByBO(entityBO); + if (!groupManager.save(entityDO)) { + throw new AddException("Failed to create group"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // Before deleting a group, check whether it has any child groups associated. - LambdaQueryChainWrapper wrapper = groupManager.lambdaQuery().eq(GroupDO::getParentGroupId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove group: there are subgroups under the group"); - } + // Before deleting a group, check whether it has any child groups associated. + LambdaQueryChainWrapper wrapper = groupManager.lambdaQuery().eq(GroupDO::getParentGroupId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove group: there are subgroups under the group"); + } - if (!groupManager.removeById(id)) { - throw new DeleteException("Failed to remove group"); - } - } + if (!groupManager.removeById(id)) { + throw new DeleteException("Failed to remove group"); + } + } - @Override - public void update(GroupBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(GroupBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - GroupDO entityDO = groupBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!groupManager.updateById(entityDO)) { - throw new UpdateException("Failed to update group"); - } - } + GroupDO entityDO = groupBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!groupManager.updateById(entityDO)) { + throw new UpdateException("Failed to update group"); + } + } - @Override - public GroupBO selectById(Long id) { - GroupDO entityDO = getDOById(id, true); - return groupBuilder.buildBOByDO(entityDO); - } + @Override + public GroupBO selectById(Long id) { + GroupDO entityDO = getDOById(id, true); + return groupBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(GroupQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = groupManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return groupBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(GroupQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = groupManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return groupBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * Build fuzzy query wrapper for group search. - * @param entityQuery {@link GroupQuery} query parameters - * @return {@link LambdaQueryWrapper} for {@link GroupDO} - */ - private LambdaQueryWrapper fuzzyQuery(GroupQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getGroupName()), GroupDO::getGroupName, - entityQuery.getGroupName()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), GroupDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * Build fuzzy query wrapper for group search. + * + * @param entityQuery {@link GroupQuery} query parameters + * @return {@link LambdaQueryWrapper} for {@link GroupDO} + */ + private LambdaQueryWrapper fuzzyQuery(GroupQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getGroupName()), GroupDO::getGroupName, + entityQuery.getGroupName()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), GroupDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * Check whether a group is duplicated under the same tenant and parent group. - * @param entityBO {@link GroupBO} to be validated - * @param isUpdate whether the operation is an update (true) or create (false) - * @param throwException whether to throw {@link DuplicateException} when duplicated - * @return {@code true} if duplicated, otherwise {@code false} - */ - private boolean checkDuplicate(GroupBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(GroupDO::getGroupName, entityBO.getGroupName()); - wrapper.eq(GroupDO::getGroupTypeFlag, entityBO.getGroupTypeFlag()); - wrapper.eq(GroupDO::getParentGroupId, entityBO.getParentGroupId()); - wrapper.eq(GroupDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - GroupDO one = groupManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Group has been duplicated"); - } - return duplicate; - } + /** + * Check whether a group is duplicated under the same tenant and parent group. + * + * @param entityBO {@link GroupBO} to be validated + * @param isUpdate whether the operation is an update (true) or create (false) + * @param throwException whether to throw {@link DuplicateException} when duplicated + * @return {@code true} if duplicated, otherwise {@code false} + */ + private boolean checkDuplicate(GroupBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(GroupDO::getGroupName, entityBO.getGroupName()); + wrapper.eq(GroupDO::getGroupTypeFlag, entityBO.getGroupTypeFlag()); + wrapper.eq(GroupDO::getParentGroupId, entityBO.getParentGroupId()); + wrapper.eq(GroupDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + GroupDO one = groupManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Group has been duplicated"); + } + return duplicate; + } - /** - * Get group data object by primary key ID. - * @param id primary key ID - * @param throwException whether to throw {@link NotFoundException} when not found - * @return {@link GroupDO} if found, otherwise {@code null} when - * {@code throwException} is false - */ - private GroupDO getDOById(Long id, boolean throwException) { - GroupDO entityDO = groupManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Group does not exist"); - } - return entityDO; - } + /** + * Get group data object by primary key ID. + * + * @param id primary key ID + * @param throwException whether to throw {@link NotFoundException} when not found + * @return {@link GroupDO} if found, otherwise {@code null} when + * {@code throwException} is false + */ + private GroupDO getDOById(Long id, boolean throwException) { + GroupDO entityDO = groupManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Group does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelBindServiceImpl.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelBindServiceImpl.java index 05c3eec15..0ed375432 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelBindServiceImpl.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelBindServiceImpl.java @@ -48,112 +48,115 @@ import java.util.Objects; @Service public class LabelBindServiceImpl implements LabelBindService { - @Resource - private LabelBindBuilder labelBindBuilder; + @Resource + private LabelBindBuilder labelBindBuilder; - @Resource - private LabelBindManager labelBindManager; + @Resource + private LabelBindManager labelBindManager; - @Override - public void save(LabelBindBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(LabelBindBO entityBO) { + checkDuplicate(entityBO, false, true); - LabelBindDO entityDO = labelBindBuilder.buildDOByBO(entityBO); - if (!labelBindManager.save(entityDO)) { - throw new AddException("Failed to create label bind"); - } - } + LabelBindDO entityDO = labelBindBuilder.buildDOByBO(entityBO); + if (!labelBindManager.save(entityDO)) { + throw new AddException("Failed to create label bind"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!labelBindManager.removeById(id)) { - throw new DeleteException("Failed to remove label bind"); - } - } + if (!labelBindManager.removeById(id)) { + throw new DeleteException("Failed to remove label bind"); + } + } - @Override - public void update(LabelBindBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(LabelBindBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - LabelBindDO entityDO = labelBindBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!labelBindManager.updateById(entityDO)) { - throw new UpdateException("The label bind update failed"); - } - } + LabelBindDO entityDO = labelBindBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!labelBindManager.updateById(entityDO)) { + throw new UpdateException("The label bind update failed"); + } + } - @Override - public LabelBindBO selectById(Long id) { - LabelBindDO entityDO = getDOById(id, false); - return labelBindBuilder.buildBOByDO(entityDO); - } + @Override + public LabelBindBO selectById(Long id) { + LabelBindDO entityDO = getDOById(id, false); + return labelBindBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(LabelBindQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = labelBindManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return labelBindBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(LabelBindQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = labelBindManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return labelBindBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * Build fuzzy query wrapper for label binding search. - * @param entityQuery {@link LabelBindQuery} query parameters - * @return {@link LambdaQueryWrapper} for {@link LabelBindDO} - */ - private LambdaQueryWrapper fuzzyQuery(LabelBindQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getLabelId()), LabelBindDO::getLabelId, - entityQuery.getLabelId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getEntityId()), LabelBindDO::getEntityId, - entityQuery.getEntityId()); - return wrapper; - } + /** + * Build fuzzy query wrapper for label binding search. + * + * @param entityQuery {@link LabelBindQuery} query parameters + * @return {@link LambdaQueryWrapper} for {@link LabelBindDO} + */ + private LambdaQueryWrapper fuzzyQuery(LabelBindQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getLabelId()), LabelBindDO::getLabelId, + entityQuery.getLabelId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getEntityId()), LabelBindDO::getEntityId, + entityQuery.getEntityId()); + return wrapper; + } - /** - * Check whether a label binding is duplicated under the same tenant. - * @param entityBO {@link LabelBindBO} to be validated - * @param isUpdate whether the operation is an update (true) or create (false) - * @param throwException whether to throw {@link DuplicateException} when duplicated - * @return {@code true} if duplicated, otherwise {@code false} - */ - private boolean checkDuplicate(LabelBindBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(LabelBindDO::getEntityTypeFlag, entityBO.getEntityTypeFlag()); - wrapper.eq(LabelBindDO::getLabelId, entityBO.getLabelId()); - wrapper.eq(LabelBindDO::getEntityId, entityBO.getEntityId()); - wrapper.eq(LabelBindDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - LabelBindDO one = labelBindManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Label bind has been duplicated"); - } - return duplicate; - } + /** + * Check whether a label binding is duplicated under the same tenant. + * + * @param entityBO {@link LabelBindBO} to be validated + * @param isUpdate whether the operation is an update (true) or create (false) + * @param throwException whether to throw {@link DuplicateException} when duplicated + * @return {@code true} if duplicated, otherwise {@code false} + */ + private boolean checkDuplicate(LabelBindBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(LabelBindDO::getEntityTypeFlag, entityBO.getEntityTypeFlag()); + wrapper.eq(LabelBindDO::getLabelId, entityBO.getLabelId()); + wrapper.eq(LabelBindDO::getEntityId, entityBO.getEntityId()); + wrapper.eq(LabelBindDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + LabelBindDO one = labelBindManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Label bind has been duplicated"); + } + return duplicate; + } - /** - * Get label binding data object by primary key ID. - * @param id primary key ID - * @param throwException whether to throw {@link NotFoundException} when not found - * @return {@link LabelBindDO} if found, otherwise {@code null} when - * {@code throwException} is false - */ - private LabelBindDO getDOById(Long id, boolean throwException) { - LabelBindDO entityDO = labelBindManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Label bind does not exist"); - } - return entityDO; - } + /** + * Get label binding data object by primary key ID. + * + * @param id primary key ID + * @param throwException whether to throw {@link NotFoundException} when not found + * @return {@link LabelBindDO} if found, otherwise {@code null} when + * {@code throwException} is false + */ + private LabelBindDO getDOById(Long id, boolean throwException) { + LabelBindDO entityDO = labelBindManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Label bind does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelServiceImpl.java b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelServiceImpl.java index 10544a936..17270cbef 100644 --- a/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelServiceImpl.java +++ b/dc3-common/dc3-common-dal/src/main/java/io/github/pnoker/common/dal/service/impl/LabelServiceImpl.java @@ -50,123 +50,126 @@ import java.util.Objects; @Service public class LabelServiceImpl implements LabelService { - @Resource - private LabelBuilder labelBuilder; + @Resource + private LabelBuilder labelBuilder; - @Resource - private LabelManager labelManager; + @Resource + private LabelManager labelManager; - @Resource - private LabelBindManager labelBindManager; + @Resource + private LabelBindManager labelBindManager; - @Override - public void save(LabelBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(LabelBO entityBO) { + checkDuplicate(entityBO, false, true); - LabelDO entityDO = labelBuilder.buildDOByBO(entityBO); - if (!labelManager.save(entityDO)) { - throw new AddException("Failed to create label"); - } - } + LabelDO entityDO = labelBuilder.buildDOByBO(entityBO); + if (!labelManager.save(entityDO)) { + throw new AddException("Failed to create label"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // Before deleting a label, check whether it is already bound to any entity. - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(LabelBindDO::getLabelId, id); - long count = labelBindManager.count(wrapper); - if (count > 0) { - throw new AssociatedException("The label has been bound by another entity"); - } + // Before deleting a label, check whether it is already bound to any entity. + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(LabelBindDO::getLabelId, id); + long count = labelBindManager.count(wrapper); + if (count > 0) { + throw new AssociatedException("The label has been bound by another entity"); + } - if (!labelManager.removeById(id)) { - throw new DeleteException("Failed to remove label"); - } - } + if (!labelManager.removeById(id)) { + throw new DeleteException("Failed to remove label"); + } + } - @Override - public void update(LabelBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(LabelBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - LabelDO entityDO = labelBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!labelManager.updateById(entityDO)) { - throw new UpdateException("The label update failed"); - } - } + LabelDO entityDO = labelBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!labelManager.updateById(entityDO)) { + throw new UpdateException("The label update failed"); + } + } - @Override - public LabelBO selectById(Long id) { - LabelDO entityDO = getDOById(id, false); - return labelBuilder.buildBOByDO(entityDO); - } + @Override + public LabelBO selectById(Long id) { + LabelDO entityDO = getDOById(id, false); + return labelBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(LabelQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = labelManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return labelBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(LabelQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = labelManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return labelBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * Build fuzzy query wrapper for label search. - * @param entityQuery {@link LabelQuery} query parameters - * @return {@link LambdaQueryWrapper} for {@link LabelDO} - */ - private LambdaQueryWrapper fuzzyQuery(LabelQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getLabelName()), LabelDO::getLabelName, - entityQuery.getLabelName()); - wrapper.eq(Objects.nonNull(entityQuery.getEntityTypeFlag()), LabelDO::getEntityTypeFlag, - entityQuery.getEntityTypeFlag()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getColor()), LabelDO::getLabelColor, entityQuery.getColor()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), LabelDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * Build fuzzy query wrapper for label search. + * + * @param entityQuery {@link LabelQuery} query parameters + * @return {@link LambdaQueryWrapper} for {@link LabelDO} + */ + private LambdaQueryWrapper fuzzyQuery(LabelQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getLabelName()), LabelDO::getLabelName, + entityQuery.getLabelName()); + wrapper.eq(Objects.nonNull(entityQuery.getEntityTypeFlag()), LabelDO::getEntityTypeFlag, + entityQuery.getEntityTypeFlag()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getColor()), LabelDO::getLabelColor, entityQuery.getColor()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), LabelDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * Check whether a label is duplicated under the same tenant and entity type. - * @param entityBO {@link LabelBO} to be validated - * @param isUpdate whether the operation is an update (true) or create (false) - * @param throwException whether to throw {@link DuplicateException} when duplicated - * @return {@code true} if duplicated, otherwise {@code false} - */ - private boolean checkDuplicate(LabelBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(LabelDO::getLabelName, entityBO.getLabelName()); - wrapper.eq(LabelDO::getEntityTypeFlag, entityBO.getEntityTypeFlag()); - wrapper.eq(LabelDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - LabelDO one = labelManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Label has been duplicated"); - } - return duplicate; - } + /** + * Check whether a label is duplicated under the same tenant and entity type. + * + * @param entityBO {@link LabelBO} to be validated + * @param isUpdate whether the operation is an update (true) or create (false) + * @param throwException whether to throw {@link DuplicateException} when duplicated + * @return {@code true} if duplicated, otherwise {@code false} + */ + private boolean checkDuplicate(LabelBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(LabelDO::getLabelName, entityBO.getLabelName()); + wrapper.eq(LabelDO::getEntityTypeFlag, entityBO.getEntityTypeFlag()); + wrapper.eq(LabelDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + LabelDO one = labelManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Label has been duplicated"); + } + return duplicate; + } - /** - * Get label data object by primary key ID. - * @param id primary key ID - * @param throwException whether to throw {@link NotFoundException} when not found - * @return {@link LabelDO} if found, otherwise {@code null} when - * {@code throwException} is false - */ - private LabelDO getDOById(Long id, boolean throwException) { - LabelDO entityDO = labelManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Label does not exist"); - } - return entityDO; - } + /** + * Get label data object by primary key ID. + * + * @param id primary key ID + * @param throwException whether to throw {@link NotFoundException} when not found + * @return {@link LabelDO} if found, otherwise {@code null} when + * {@code throwException} is false + */ + private LabelDO getDOById(Long id, boolean throwException) { + LabelDO entityDO = labelManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Label does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-data/README.md b/dc3-common/dc3-common-data/README.md index 57f5efa87..25acfa8d4 100644 --- a/dc3-common/dc3-common-data/README.md +++ b/dc3-common/dc3-common-data/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-data` is the shared Data Center business module of the IoT DC3 platform. It provides all service implementations for point value ingestion, command dispatch, +`dc3-common-data` is the shared Data Center business module of the IoT DC3 platform. It provides all service +implementations for point value ingestion, command dispatch, driver/device status tracking, and data query. It is wired into `dc3-center-data`. ## Module Information diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/ActiveDataProfileConfig.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/ActiveDataProfileConfig.java index ce98a3a26..23d05ad1f 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/ActiveDataProfileConfig.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/ActiveDataProfileConfig.java @@ -37,9 +37,9 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveDataProfileConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("data"); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("data"); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/DataTopicConfig.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/DataTopicConfig.java index 1a86ae943..d8200a4f9 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/DataTopicConfig.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/config/DataTopicConfig.java @@ -43,64 +43,64 @@ import java.util.Map; @ConditionalOnClass(ExchangeConfig.class) public class DataTopicConfig { - private final TopicExchange eventExchange; + private final TopicExchange eventExchange; - private final TopicExchange valueExchange; + private final TopicExchange valueExchange; - public DataTopicConfig(TopicExchange eventExchange, TopicExchange valueExchange) { - this.eventExchange = eventExchange; - this.valueExchange = valueExchange; - } + public DataTopicConfig(TopicExchange eventExchange, TopicExchange valueExchange) { + this.eventExchange = eventExchange; + this.valueExchange = valueExchange; + } - @Bean - Queue driverEventQueue() { - Map arguments = new HashMap<>(); - // 30 seconds: 30 * 1000 = 30000L - arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); - return new Queue(RabbitConstant.QUEUE_DRIVER_EVENT, true, false, false, arguments); - } + @Bean + Queue driverEventQueue() { + Map arguments = new HashMap<>(); + // 30 seconds: 30 * 1000 = 30000L + arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); + return new Queue(RabbitConstant.QUEUE_DRIVER_EVENT, true, false, false, arguments); + } - @Bean - Binding driverEventBinding(Queue driverEventQueue) { - Binding binding = BindingBuilder.bind(driverEventQueue) - .to(eventExchange) - .with(RabbitConstant.ROUTING_DRIVER_EVENT_PREFIX + SymbolConstant.ASTERISK); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + @Bean + Binding driverEventBinding(Queue driverEventQueue) { + Binding binding = BindingBuilder.bind(driverEventQueue) + .to(eventExchange) + .with(RabbitConstant.ROUTING_DRIVER_EVENT_PREFIX + SymbolConstant.ASTERISK); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } - @Bean - Queue deviceEventQueue() { - Map arguments = new HashMap<>(); - // 30 seconds: 30 * 1000 = 30000L - arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); - return new Queue(RabbitConstant.QUEUE_DEVICE_EVENT, true, false, false, arguments); - } + @Bean + Queue deviceEventQueue() { + Map arguments = new HashMap<>(); + // 30 seconds: 30 * 1000 = 30000L + arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); + return new Queue(RabbitConstant.QUEUE_DEVICE_EVENT, true, false, false, arguments); + } - @Bean - Binding deviceEventBinding(Queue deviceEventQueue) { - Binding binding = BindingBuilder.bind(deviceEventQueue) - .to(eventExchange) - .with(RabbitConstant.ROUTING_DEVICE_EVENT_PREFIX + SymbolConstant.ASTERISK); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + @Bean + Binding deviceEventBinding(Queue deviceEventQueue) { + Binding binding = BindingBuilder.bind(deviceEventQueue) + .to(eventExchange) + .with(RabbitConstant.ROUTING_DEVICE_EVENT_PREFIX + SymbolConstant.ASTERISK); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } - @Bean - Queue pointValueQueue() { - Map arguments = new HashMap<>(); - // 7 days: 7 * 24 * 60 * 60 * 1000 = 604800000L - arguments.put(RabbitConstant.MESSAGE_TTL, 604800000L); - return new Queue(RabbitConstant.QUEUE_POINT_VALUE, true, false, false, arguments); - } + @Bean + Queue pointValueQueue() { + Map arguments = new HashMap<>(); + // 7 days: 7 * 24 * 60 * 60 * 1000 = 604800000L + arguments.put(RabbitConstant.MESSAGE_TTL, 604800000L); + return new Queue(RabbitConstant.QUEUE_POINT_VALUE, true, false, false, arguments); + } - @Bean - Binding pointValueBinding(Queue pointValueQueue) { - Binding binding = BindingBuilder.bind(pointValueQueue) - .to(valueExchange) - .with(RabbitConstant.ROUTING_POINT_VALUE_PREFIX + SymbolConstant.ASTERISK); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + @Bean + Binding pointValueBinding(Queue pointValueQueue) { + Binding binding = BindingBuilder.bind(pointValueQueue) + .to(valueExchange) + .with(RabbitConstant.ROUTING_POINT_VALUE_PREFIX + SymbolConstant.ASTERISK); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DashboardService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DashboardService.java index 27f6c9192..8f127528d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DashboardService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DashboardService.java @@ -35,174 +35,175 @@ import java.util.List; */ public interface DashboardService { - /** - * Total point-value rows written today (00:00 local → now) for the tenant. - */ - long countToday(Long tenantId); + /** + * Total point-value rows written today (00:00 local → now) for the tenant. + */ + long countToday(Long tenantId); - /** - * Total point-value rows written yesterday (for the "vs yesterday" delta on the - * today-total indicator card). - */ - long countYesterday(Long tenantId); + /** + * Total point-value rows written yesterday (for the "vs yesterday" delta on the + * today-total indicator card). + */ + long countYesterday(Long tenantId); - /** - * Total point-value rows across all time for the tenant. - */ - long countTotal(Long tenantId); + /** + * Total point-value rows across all time for the tenant. + */ + long countTotal(Long tenantId); - /** - * Time-bucketed series of point-value row counts. {@code granularity} is either - * {@code "hour"} (24-hour default) or {@code "day"} (7/30-day). {@code rangeHours} - * controls how far back to look. - */ - List timeseries(Long tenantId, String granularity, int rangeHours); + /** + * Time-bucketed series of point-value row counts. {@code granularity} is either + * {@code "hour"} (24-hour default) or {@code "day"} (7/30-day). {@code rangeHours} + * controls how far back to look. + */ + List timeseries(Long tenantId, String granularity, int rangeHours); - /** - * Top-N devices / points / drivers by point-value count. - * @param dimension one of {@code device}, {@code point}, {@code driver} - * @param rangeHours lookback window in hours (e.g. 24, 168, 720) - * @param limit max rows returned (clamped 1..50) - */ - List top(Long tenantId, String dimension, int rangeHours, int limit); + /** + * Top-N devices / points / drivers by point-value count. + * + * @param dimension one of {@code device}, {@code point}, {@code driver} + * @param rangeHours lookback window in hours (e.g. 24, 168, 720) + * @param limit max rows returned (clamped 1..50) + */ + List top(Long tenantId, String dimension, int rangeHours, int limit); - /** - * Most recent N point-value rows across every typed hypertable — drives the - * dashboard's live feed panel. {@code size} clamped 1..100. - */ - List latestStream(Long tenantId, int size); + /** + * Most recent N point-value rows across every typed hypertable — drives the + * dashboard's live feed panel. {@code size} clamped 1..100. + */ + List latestStream(Long tenantId, int size); - /** - * Aggregate counters for the alert indicator card (total, unconfirmed, by - * event-type), scoped to one tenant. - */ - AlertStatsVO alertStats(Long tenantId); + /** + * Aggregate counters for the alert indicator card (total, unconfirmed, by + * event-type), scoped to one tenant. + */ + AlertStatsVO alertStats(Long tenantId); - /** - * Most recent N alert rows across device + driver event tables for the given tenant. - * Used by the alert list panel on the home page. {@code size} clamped 1..50. - */ - List alertLatest(Long tenantId, int size); + /** + * Most recent N alert rows across device + driver event tables for the given tenant. + * Used by the alert list panel on the home page. {@code size} clamped 1..50. + */ + List alertLatest(Long tenantId, int size); - /** - * Acquisition-to-storage latency histogram across all point-value rows in the given - * lookback window. Returns exactly 6 rows (bins 0..5) even if a bin is empty — the - * service pads missing buckets with zero counts. - */ - List latencyHistogram(Long tenantId, int rangeHours); + /** + * Acquisition-to-storage latency histogram across all point-value rows in the given + * lookback window. Returns exactly 6 rows (bins 0..5) even if a bin is empty — the + * service pads missing buckets with zero counts. + */ + List latencyHistogram(Long tenantId, int rangeHours); - /** - * Day-of-week × hour-of-day activity heatmap (7 × 24 = 168 cells). Missing (dow, - * hour) pairs are padded with zero so the frontend always gets a fully-filled grid. - */ - List hourlyActivity(Long tenantId, int rangeHours); + /** + * Day-of-week × hour-of-day activity heatmap (7 × 24 = 168 cells). Missing (dow, + * hour) pairs are padded with zero so the frontend always gets a fully-filled grid. + */ + List hourlyActivity(Long tenantId, int rangeHours); - /** - * Paged event/alarm list. {@code source} is null (both tables), "device", or "driver" - * (service whitelists). Returns a MyBatis-Plus - * {@link com.baomidou.mybatisplus.extension.plugins.pagination.Page Page} so the JSON - * shape matches every other list endpoint in the project - * ({@code current / size / total / pages / records}). - */ - com.baomidou.mybatisplus.extension.plugins.pagination.Page alertPage(Long tenantId, String source, - Integer eventTypeFlag, Integer confirmFlag, java.time.LocalDateTime from, long current, long size); + /** + * Paged event/alarm list. {@code source} is null (both tables), "device", or "driver" + * (service whitelists). Returns a MyBatis-Plus + * {@link com.baomidou.mybatisplus.extension.plugins.pagination.Page Page} so the JSON + * shape matches every other list endpoint in the project + * ({@code current / size / total / pages / records}). + */ + com.baomidou.mybatisplus.extension.plugins.pagination.Page alertPage(Long tenantId, String source, + Integer eventTypeFlag, Integer confirmFlag, java.time.LocalDateTime from, long current, long size); - /** - * Flip confirm_flag = 1 on a single event row. Returns true when the row was actually - * updated (id + tenant match), false otherwise. - */ - boolean confirmAlert(Long tenantId, String source, Long id); + /** + * Flip confirm_flag = 1 on a single event row. Returns true when the row was actually + * updated (id + tenant match), false otherwise. + */ + boolean confirmAlert(Long tenantId, String source, Long id); - /** - * Flip confirm_flag back to 0 — undo a previous confirm. - */ - boolean unconfirmAlert(Long tenantId, String source, Long id); + /** + * Flip confirm_flag back to 0 — undo a previous confirm. + */ + boolean unconfirmAlert(Long tenantId, String source, Long id); - /** - * Bulk confirm / unconfirm. {@code confirm} chooses the direction (true = set to 1, - * false = set to 0). Returns the number of rows actually changed across all entries. - */ - int bulkConfirmAlert(Long tenantId, java.util.List> items, boolean confirm); + /** + * Bulk confirm / unconfirm. {@code confirm} chooses the direction (true = set to 1, + * false = set to 0). Returns the number of rows actually changed across all entries. + */ + int bulkConfirmAlert(Long tenantId, java.util.List> items, boolean confirm); - /** - * Daily event trend for the last {@code days} days, split by device/driver source. - */ - List alertTrend(Long tenantId, int days); + /** + * Daily event trend for the last {@code days} days, split by device/driver source. + */ + List alertTrend(Long tenantId, int days); - /** - * Top N event sources by alarm count in the last {@code days} days. - */ - List alertTopSources(Long tenantId, int days, int limit); + /** + * Top N event sources by alarm count in the last {@code days} days. + */ + List alertTopSources(Long tenantId, int days, int limit); - /** - * ALARM counts in a day-of-week × hour-of-day heatmap over the last {@code days} - * days. Always returns 7 × 24 = 168 cells (zero-padded). - */ - List alertActivity(Long tenantId, int days); + /** + * ALARM counts in a day-of-week × hour-of-day heatmap over the last {@code days} + * days. Always returns 7 × 24 = 168 cells (zero-padded). + */ + List alertActivity(Long tenantId, int days); - /** - * ALARM count per {@code event_ext.type} bucket over the last {@code days} days, - * ordered by count DESC. - */ - List alertTypeDistribution(Long tenantId, int days); + /** + * ALARM count per {@code event_ext.type} bucket over the last {@code days} days, + * ordered by count DESC. + */ + List alertTypeDistribution(Long tenantId, int days); - /** - * Sources whose ALARM count in the last {@code hours} hours reaches {@code minCount} - * — "alarm-storm" sources worth immediate attention. Returns at most {@code limit} - * rows, ordered by count DESC. - */ - List alertStormSources(Long tenantId, int hours, int minCount, int limit); + /** + * Sources whose ALARM count in the last {@code hours} hours reaches {@code minCount} + * — "alarm-storm" sources worth immediate attention. Returns at most {@code limit} + * rows, ordered by count DESC. + */ + List alertStormSources(Long tenantId, int hours, int minCount, int limit); - // ===== Phase-2 insights ==================================================== + // ===== Phase-2 insights ==================================================== - /** - * (source, eventType) pairs that fired repeatedly in the last {@code hours} hours. - * Returns rows with count >= {@code minCount}. - */ - List alertFlapping(Long tenantId, int hours, int minCount, int limit); + /** + * (source, eventType) pairs that fired repeatedly in the last {@code hours} hours. + * Returns rows with count >= {@code minCount}. + */ + List alertFlapping(Long tenantId, int hours, int minCount, int limit); - /** - * Co-occurring event pairs within a time proximity window. Heavy query — callers - * should expect ~100ms+ on busy tenants. - */ - List alertCorrelation(Long tenantId, int hours, int windowSec, int limit); + /** + * Co-occurring event pairs within a time proximity window. Heavy query — callers + * should expect ~100ms+ on busy tenants. + */ + List alertCorrelation(Long tenantId, int hours, int windowSec, int limit); - /** - * Devices whose alarm count is at least 3× their profile-peer median over the - * lookback window. Service computes medians per profile. - */ - List alertPeerDeviation(Long tenantId, int days); + /** + * Devices whose alarm count is at least 3× their profile-peer median over the + * lookback window. Service computes medians per profile. + */ + List alertPeerDeviation(Long tenantId, int days); - /** - * Current unconfirmed-alarm backlog bucketed by age. - */ - AgingBacklogVO alertAgingBacklog(Long tenantId); + /** + * Current unconfirmed-alarm backlog bucketed by age. + */ + AgingBacklogVO alertAgingBacklog(Long tenantId); - /** - * Per-day p50/p95 MTTA trend for the last {@code days} days. - */ - List alertMtta(Long tenantId, int days); + /** + * Per-day p50/p95 MTTA trend for the last {@code days} days. + */ + List alertMtta(Long tenantId, int days); - /** - * Driver service_name rollup. - */ - List protocolHealth(Long tenantId); + /** + * Driver service_name rollup. + */ + List protocolHealth(Long tenantId); - /** - * Recent config edits for the trend-chart overlay. - */ - List changeImpact(Long tenantId, int days, int limit); + /** + * Recent config edits for the trend-chart overlay. + */ + List changeImpact(Long tenantId, int days, int limit); - /** - * Devices/points that have data in the baseline window but have gone silent. - * {@code baselineDays} = lookback for "was active"; {@code - * silentMinutes} = silence threshold. - */ - List silentSources(Long tenantId, int baselineDays, int silentMinutes, int limit); + /** + * Devices/points that have data in the baseline window but have gone silent. + * {@code baselineDays} = lookback for "was active"; {@code + * silentMinutes} = silence threshold. + */ + List silentSources(Long tenantId, int baselineDays, int silentMinutes, int limit); - /** - * Points declared but never reported — config-vs-reality gap. - */ - CoverageGapVO coverageGap(Long tenantId, int limit); + /** + * Points declared but never reported — config-vs-reality gap. + */ + CoverageGapVO coverageGap(Long tenantId, int limit); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceEventService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceEventService.java index 789533ea1..930f1d6d9 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceEventService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceEventService.java @@ -28,18 +28,20 @@ import io.github.pnoker.common.entity.dto.DeviceEventDTO; */ public interface DeviceEventService { - /** - * Handle a device heartbeat event: refresh the in-memory online-status key and - * persist one row to {@code dc3_device_event}. Derives an ALARM event if the status - * flipped between ONLINE/MAINTAIN and OFFLINE. - * @param entityDTO DeviceEventDTO - */ - void heartbeatEvent(DeviceEventDTO entityDTO); + /** + * Handle a device heartbeat event: refresh the in-memory online-status key and + * persist one row to {@code dc3_device_event}. Derives an ALARM event if the status + * flipped between ONLINE/MAINTAIN and OFFLINE. + * + * @param entityDTO DeviceEventDTO + */ + void heartbeatEvent(DeviceEventDTO entityDTO); - /** - * Persist a device ALARM event to {@code dc3_device_event}. - * @param entityDTO DeviceEventDTO with type=ALARM - */ - void alarmEvent(DeviceEventDTO entityDTO); + /** + * Persist a device ALARM event to {@code dc3_device_event}. + * + * @param entityDTO DeviceEventDTO with type=ALARM + */ + void alarmEvent(DeviceEventDTO entityDTO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceStatusService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceStatusService.java index 1a0a79a50..dd0eae8e4 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceStatusService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DeviceStatusService.java @@ -30,20 +30,22 @@ import java.util.Map; */ public interface DeviceStatusService { - /** - * Paged query of device status, used in conjunction with paged query of devices - * @param deviceQuery DeviceQuery, including pagination parameters - * @return Map Long:String, where Long is the device ID and String is the device - * status - */ - Map selectByPage(DeviceQuery deviceQuery); + /** + * Paged query of device status, used in conjunction with paged query of devices + * + * @param deviceQuery DeviceQuery, including pagination parameters + * @return Map Long:String, where Long is the device ID and String is the device + * status + */ + Map selectByPage(DeviceQuery deviceQuery); - /** - * Query device status by profile ID - * @param profileId Profile ID - * @return Map Long:String, where Long is the device ID and String is the device - * status - */ - Map selectByProfileId(Long profileId); + /** + * Query device status by profile ID + * + * @param profileId Profile ID + * @return Map Long:String, where Long is the device ID and String is the device + * status + */ + Map selectByProfileId(Long profileId); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverEventService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverEventService.java index 96ee748b0..fab182d05 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverEventService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverEventService.java @@ -28,18 +28,20 @@ import io.github.pnoker.common.entity.dto.DriverEventDTO; */ public interface DriverEventService { - /** - * Handle a driver heartbeat event: refresh the in-memory online-status key and - * persist one row to {@code dc3_driver_event}. Derives an ALARM event if the status - * flipped between ONLINE/MAINTAIN and OFFLINE. - * @param entityDTO DriverEventDTO - */ - void heartbeatEvent(DriverEventDTO entityDTO); + /** + * Handle a driver heartbeat event: refresh the in-memory online-status key and + * persist one row to {@code dc3_driver_event}. Derives an ALARM event if the status + * flipped between ONLINE/MAINTAIN and OFFLINE. + * + * @param entityDTO DriverEventDTO + */ + void heartbeatEvent(DriverEventDTO entityDTO); - /** - * Persist a driver ALARM event to {@code dc3_driver_event}. - * @param entityDTO DriverEventDTO with type=ALARM - */ - void alarmEvent(DriverEventDTO entityDTO); + /** + * Persist a driver ALARM event to {@code dc3_driver_event}. + * + * @param entityDTO DriverEventDTO with type=ALARM + */ + void alarmEvent(DriverEventDTO entityDTO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverStatusService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverStatusService.java index 9d7bc0a13..0846d6ae9 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverStatusService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/DriverStatusService.java @@ -30,26 +30,29 @@ import java.util.Map; */ public interface DriverStatusService { - /** - * Paged query of driver status, used in conjunction with paged query of drivers - * @param driverQuery DriverQuery, including pagination parameters - * @return Map Long:String, where Long is the driver ID and String is the driver - * status - */ - Map selectByPage(DriverQuery driverQuery); + /** + * Paged query of driver status, used in conjunction with paged query of drivers + * + * @param driverQuery DriverQuery, including pagination parameters + * @return Map Long:String, where Long is the driver ID and String is the driver + * status + */ + Map selectByPage(DriverQuery driverQuery); - /** - * Count of currently online devices under the driver. - * @param driverId Driver ID - * @return Number of online devices, as a string - */ - String getDeviceOnlineByDriverId(Long driverId); + /** + * Count of currently online devices under the driver. + * + * @param driverId Driver ID + * @return Number of online devices, as a string + */ + String getDeviceOnlineByDriverId(Long driverId); - /** - * Count of currently offline devices under the driver. - * @param driverId Driver ID - * @return Number of offline devices, as a string - */ - String getDeviceOfflineByDriverId(Long driverId); + /** + * Count of currently offline devices under the driver. + * + * @param driverId Driver ID + * @return Number of offline devices, as a string + */ + String getDeviceOfflineByDriverId(Long driverId); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueCommandService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueCommandService.java index 94df190cc..2fd07fc7d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueCommandService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueCommandService.java @@ -29,16 +29,18 @@ import io.github.pnoker.common.data.entity.vo.PointValueWriteVO; */ public interface PointValueCommandService { - /** - * Read command - * @param entityVO PointValueReadVO - */ - void read(PointValueReadVO entityVO); + /** + * Read command + * + * @param entityVO PointValueReadVO + */ + void read(PointValueReadVO entityVO); - /** - * Write command - * @param entityVO PointValueWriteVO - */ - void write(PointValueWriteVO entityVO); + /** + * Write command + * + * @param entityVO PointValueWriteVO + */ + void write(PointValueWriteVO entityVO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueService.java index 1c87eba70..7d757ab81 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/PointValueService.java @@ -32,40 +32,45 @@ import java.util.List; */ public interface PointValueService { - /** - * Save point value - * @param pointValueBO PointValue - */ - void save(PointValueBO pointValueBO); + /** + * Save point value + * + * @param pointValueBO PointValue + */ + void save(PointValueBO pointValueBO); - /** - * Batch save point values - * @param pointValueBOList Array - */ - void save(List pointValueBOList); + /** + * Batch save point values + * + * @param pointValueBOList Array + */ + void save(List pointValueBOList); - /** - * Get historical point values within the tenant scope. - * @param tenantId Tenant ID (required for tenant isolation) - * @param deviceId Device ID - * @param pointId Point ID - * @param count Number of values to retrieve - * @return History Value Array - */ - List history(Long tenantId, Long deviceId, Long pointId, int count); + /** + * Get historical point values within the tenant scope. + * + * @param tenantId Tenant ID (required for tenant isolation) + * @param deviceId Device ID + * @param pointId Point ID + * @param count Number of values to retrieve + * @return History Value Array + */ + List history(Long tenantId, Long deviceId, Long pointId, int count); - /** - * Get latest point values with pagination and sorting - * @param pointValueQuery Entry of Query - * @return Entity of BO Page - */ - Page latest(PointValueQuery pointValueQuery); + /** + * Get latest point values with pagination and sorting + * + * @param pointValueQuery Entry of Query + * @return Entity of BO Page + */ + Page latest(PointValueQuery pointValueQuery); - /** - * Get point values with pagination and sorting - * @param pointValueQuery Entry of Query - * @return Entity of BO Page - */ - Page page(PointValueQuery pointValueQuery); + /** + * Get point values with pagination and sorting + * + * @param pointValueQuery Entry of Query + * @return Entity of BO Page + */ + Page page(PointValueQuery pointValueQuery); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/ScheduleForDataService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/ScheduleForDataService.java index 9ba5ce7fb..8083486dc 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/ScheduleForDataService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/ScheduleForDataService.java @@ -26,9 +26,9 @@ package io.github.pnoker.common.data.biz; */ public interface ScheduleForDataService { - /** - * Initialize schedule tasks for data processing - */ - void initial(); + /** + * Initialize schedule tasks for data processing + */ + void initial(); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/SystemHealthService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/SystemHealthService.java index 925a823bb..54bc5fdbe 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/SystemHealthService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/SystemHealthService.java @@ -29,15 +29,15 @@ import io.github.pnoker.common.data.entity.vo.dashboard.SystemHealthVO; */ public interface SystemHealthService { - /** - * Probe everything once and collect a snapshot. Probes must be short-circuited / - * bounded in time so a slow dependency doesn't stall the dashboard. - * - *

- * Takes tenantId because the driver / device fleet summaries query tenant-scoped - * facades; infra / center probes ignore it. - *

- */ - SystemHealthVO snapshot(Long tenantId); + /** + * Probe everything once and collect a snapshot. Probes must be short-circuited / + * bounded in time so a slow dependency doesn't stall the dashboard. + * + *

+ * Takes tenantId because the driver / device fleet summaries query tenant-scoped + * facades; infra / center probes ignore it. + *

+ */ + SystemHealthVO snapshot(Long tenantId); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DashboardServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DashboardServiceImpl.java index a7fa02aeb..5e99ee99f 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DashboardServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DashboardServiceImpl.java @@ -47,665 +47,662 @@ import static io.github.pnoker.common.data.constant.DashboardLimits.*; @Service public class DashboardServiceImpl implements DashboardService { - /** - * Dimensions whose column name we interpolate directly into the GROUP BY. Only these - * are accepted — never pass user input through unchecked. - */ - private static final Map DIMENSION_COLUMN = Map.of("device", "device_id", "point", "point_id", - "driver", "driver_id"); + /** + * Dimensions whose column name we interpolate directly into the GROUP BY. Only these + * are accepted — never pass user input through unchecked. + */ + private static final Map DIMENSION_COLUMN = Map.of("device", "device_id", "point", "point_id", + "driver", "driver_id"); - private static final Set GRANULARITY = Set.of("hour", "day"); + private static final Set GRANULARITY = Set.of("hour", "day"); - /** - * Whitelist for the alert source parameter. - */ - private static final Set ALERT_SOURCES = Set.of(SOURCE_DEVICE, SOURCE_DRIVER); + /** + * Whitelist for the alert source parameter. + */ + private static final Set ALERT_SOURCES = Set.of(SOURCE_DEVICE, SOURCE_DRIVER); - @Resource - private DashboardMapper dashboardMapper; + @Resource + private DashboardMapper dashboardMapper; - @Resource - private AlertMapper alertMapper; + @Resource + private AlertMapper alertMapper; - @Resource - private DeviceFacade deviceFacade; + @Resource + private DeviceFacade deviceFacade; - @Resource - private PointFacade pointFacade; + @Resource + private PointFacade pointFacade; - @Resource - private DriverFacade driverFacade; + @Resource + private DriverFacade driverFacade; - /** - * BucketRow.key is Object (shared across SMALLINT / VARCHAR / BIGINT group columns); - * stringify for the VO. - */ - private static String asString(Object v) { - return v == null ? null : v.toString(); - } + /** + * BucketRow.key is Object (shared across SMALLINT / VARCHAR / BIGINT group columns); + * stringify for the VO. + */ + private static String asString(Object v) { + return v == null ? null : v.toString(); + } - @Override - public List latencyHistogram(Long tenantId, int rangeHours) { - int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); - LocalDateTime to = LocalDateTime.now(); - LocalDateTime from = to.minusHours(hours); - var rows = dashboardMapper.latencyHistogram(tenantId, from, to); - // Pad missing bins with zero so the UI always gets six buckets. - long[] counts = new long[6]; - for (var row : rows) { - int bin = row.getBin(); - if (bin >= 0 && bin < counts.length) { - counts[bin] = row.getCount(); - } - } - List out = new ArrayList<>(counts.length); - for (int i = 0; i < counts.length; i++) { - LatencyBucketVO vo = new LatencyBucketVO(); - vo.setBin(i); - vo.setCount(counts[i]); - out.add(vo); - } - return out; - } + @Override + public List latencyHistogram(Long tenantId, int rangeHours) { + int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); + LocalDateTime to = LocalDateTime.now(); + LocalDateTime from = to.minusHours(hours); + var rows = dashboardMapper.latencyHistogram(tenantId, from, to); + // Pad missing bins with zero so the UI always gets six buckets. + long[] counts = new long[6]; + for (var row : rows) { + int bin = row.getBin(); + if (bin >= 0 && bin < counts.length) { + counts[bin] = row.getCount(); + } + } + List out = new ArrayList<>(counts.length); + for (int i = 0; i < counts.length; i++) { + LatencyBucketVO vo = new LatencyBucketVO(); + vo.setBin(i); + vo.setCount(counts[i]); + out.add(vo); + } + return out; + } - @Override - public List hourlyActivity(Long tenantId, int rangeHours) { - int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); - LocalDateTime to = LocalDateTime.now(); - LocalDateTime from = to.minusHours(hours); - var rows = dashboardMapper.hourlyActivity(tenantId, from, to); - long[][] grid = new long[7][24]; - for (var row : rows) { - int dow = row.getDow(); - int hour = row.getHour(); - if (dow >= 0 && dow < 7 && hour >= 0 && hour < 24) { - grid[dow][hour] = row.getCount(); - } - } - List out = new ArrayList<>(7 * 24); - for (int d = 0; d < 7; d++) { - for (int h = 0; h < 24; h++) { - ActivityCellVO vo = new ActivityCellVO(); - vo.setDow(d); - vo.setHour(h); - vo.setCount(grid[d][h]); - out.add(vo); - } - } - return out; - } + @Override + public List hourlyActivity(Long tenantId, int rangeHours) { + int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); + LocalDateTime to = LocalDateTime.now(); + LocalDateTime from = to.minusHours(hours); + var rows = dashboardMapper.hourlyActivity(tenantId, from, to); + long[][] grid = new long[7][24]; + for (var row : rows) { + int dow = row.getDow(); + int hour = row.getHour(); + if (dow >= 0 && dow < 7 && hour >= 0 && hour < 24) { + grid[dow][hour] = row.getCount(); + } + } + List out = new ArrayList<>(7 * 24); + for (int d = 0; d < 7; d++) { + for (int h = 0; h < 24; h++) { + ActivityCellVO vo = new ActivityCellVO(); + vo.setDow(d); + vo.setHour(h); + vo.setCount(grid[d][h]); + out.add(vo); + } + } + return out; + } - @Override - public Page alertPage(Long tenantId, String source, Integer eventTypeFlag, Integer confirmFlag, - LocalDateTime from, long current, long size) { - String src = source == null || source.isBlank() ? null : (ALERT_SOURCES.contains(source) ? source : null); - long clampedCurrent = Math.max(1L, current); - long clampedSize = Math.clamp(size, 1L, MAX_PAGE_SIZE); - long offset = (clampedCurrent - 1L) * clampedSize; + @Override + public Page alertPage(Long tenantId, String source, Integer eventTypeFlag, Integer confirmFlag, + LocalDateTime from, long current, long size) { + String src = source == null || source.isBlank() ? null : (ALERT_SOURCES.contains(source) ? source : null); + long clampedCurrent = Math.max(1L, current); + long clampedSize = Math.clamp(size, 1L, MAX_PAGE_SIZE); + long offset = (clampedCurrent - 1L) * clampedSize; - long total = alertMapper.countFiltered(tenantId, src, eventTypeFlag, confirmFlag, from); - var rows = alertMapper.listPaged(tenantId, src, eventTypeFlag, confirmFlag, from, offset, clampedSize); - List records = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertItemVO vo = new AlertItemVO(); - vo.setId(row.getId()); - vo.setSource(row.getSource()); - vo.setSourceId(row.getSourceId()); - vo.setPointId(row.getPointId()); - vo.setEventTypeFlag(row.getEventTypeFlag()); - vo.setConfirmFlag(row.getConfirmFlag()); - vo.setCreateTime(row.getCreateTime()); - vo.setMessage(row.getMessage()); - records.add(vo); - } - // Use MyBatis-Plus Page so the JSON shape matches every other list - // endpoint in the project (current / size / total / pages / records). - Page page = new Page<>(clampedCurrent, clampedSize, total); - page.setRecords(records); - return page; - } + long total = alertMapper.countFiltered(tenantId, src, eventTypeFlag, confirmFlag, from); + var rows = alertMapper.listPaged(tenantId, src, eventTypeFlag, confirmFlag, from, offset, clampedSize); + List records = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertItemVO vo = new AlertItemVO(); + vo.setId(row.getId()); + vo.setSource(row.getSource()); + vo.setSourceId(row.getSourceId()); + vo.setPointId(row.getPointId()); + vo.setEventTypeFlag(row.getEventTypeFlag()); + vo.setConfirmFlag(row.getConfirmFlag()); + vo.setCreateTime(row.getCreateTime()); + vo.setMessage(row.getMessage()); + records.add(vo); + } + // Use MyBatis-Plus Page so the JSON shape matches every other list + // endpoint in the project (current / size / total / pages / records). + Page page = new Page<>(clampedCurrent, clampedSize, total); + page.setRecords(records); + return page; + } - @Override - public boolean confirmAlert(Long tenantId, String source, Long id) { - if (source == null || !ALERT_SOURCES.contains(source) || id == null) { - return false; - } - return alertMapper.confirmOne(tenantId, source, id) > 0; - } + @Override + public boolean confirmAlert(Long tenantId, String source, Long id) { + if (source == null || !ALERT_SOURCES.contains(source) || id == null) { + return false; + } + return alertMapper.confirmOne(tenantId, source, id) > 0; + } - @Override - public boolean unconfirmAlert(Long tenantId, String source, Long id) { - if (source == null || !ALERT_SOURCES.contains(source) || id == null) { - return false; - } - return alertMapper.unconfirmOne(tenantId, source, id) > 0; - } + @Override + public boolean unconfirmAlert(Long tenantId, String source, Long id) { + if (source == null || !ALERT_SOURCES.contains(source) || id == null) { + return false; + } + return alertMapper.unconfirmOne(tenantId, source, id) > 0; + } - @Override - public int bulkConfirmAlert(Long tenantId, List> items, boolean confirm) { - if (items == null || items.isEmpty()) - return 0; - int changed = 0; - for (Map item : items) { - Object srcRaw = item.get("source"); - Object idRaw = item.get("id"); - if (srcRaw == null || idRaw == null) - continue; - String source = srcRaw.toString(); - if (!ALERT_SOURCES.contains(source)) - continue; - long id; - try { - id = Long.parseLong(idRaw.toString()); - } - catch (NumberFormatException ignore) { - continue; - } - changed += confirm ? alertMapper.confirmOne(tenantId, source, id) - : alertMapper.unconfirmOne(tenantId, source, id); - } - return changed; - } + @Override + public int bulkConfirmAlert(Long tenantId, List> items, boolean confirm) { + if (items == null || items.isEmpty()) + return 0; + int changed = 0; + for (Map item : items) { + Object srcRaw = item.get("source"); + Object idRaw = item.get("id"); + if (srcRaw == null || idRaw == null) + continue; + String source = srcRaw.toString(); + if (!ALERT_SOURCES.contains(source)) + continue; + long id; + try { + id = Long.parseLong(idRaw.toString()); + } catch (NumberFormatException ignore) { + continue; + } + changed += confirm ? alertMapper.confirmOne(tenantId, source, id) + : alertMapper.unconfirmOne(tenantId, source, id); + } + return changed; + } - @Override - public long countToday(Long tenantId) { - LocalDateTime from = LocalDate.now().atStartOfDay(); - LocalDateTime to = LocalDateTime.now(); - return dashboardMapper.countInRange(tenantId, from, to); - } + @Override + public long countToday(Long tenantId) { + LocalDateTime from = LocalDate.now().atStartOfDay(); + LocalDateTime to = LocalDateTime.now(); + return dashboardMapper.countInRange(tenantId, from, to); + } - @Override - public long countYesterday(Long tenantId) { - LocalDateTime from = LocalDate.now().minusDays(1).atStartOfDay(); - LocalDateTime to = LocalDate.now().atStartOfDay(); - return dashboardMapper.countInRange(tenantId, from, to); - } + @Override + public long countYesterday(Long tenantId) { + LocalDateTime from = LocalDate.now().minusDays(1).atStartOfDay(); + LocalDateTime to = LocalDate.now().atStartOfDay(); + return dashboardMapper.countInRange(tenantId, from, to); + } - @Override - public long countTotal(Long tenantId) { - return dashboardMapper.countTotal(tenantId); - } + @Override + public long countTotal(Long tenantId) { + return dashboardMapper.countTotal(tenantId); + } - @Override - public List timeseries(Long tenantId, String granularity, int rangeHours) { - String g = GRANULARITY.contains(granularity) ? granularity : "hour"; - int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); - LocalDateTime to = LocalDateTime.now(); - LocalDateTime from = to.minusHours(hours); - String bucket = "1 " + g; + @Override + public List timeseries(Long tenantId, String granularity, int rangeHours) { + String g = GRANULARITY.contains(granularity) ? granularity : "hour"; + int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); + LocalDateTime to = LocalDateTime.now(); + LocalDateTime from = to.minusHours(hours); + String bucket = "1 " + g; - var rows = dashboardMapper.timeseries(tenantId, from, to, bucket); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - TimeseriesPointVO vo = new TimeseriesPointVO(); - vo.setBucket(row.getBucket()); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + var rows = dashboardMapper.timeseries(tenantId, from, to, bucket); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + TimeseriesPointVO vo = new TimeseriesPointVO(); + vo.setBucket(row.getBucket()); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - @Override - public List top(Long tenantId, String dimension, int rangeHours, int limit) { - String column = DIMENSION_COLUMN.get(dimension); - if (column == null) { - throw new IllegalArgumentException("Unsupported dimension: " + dimension); - } - int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); - int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); - LocalDateTime to = LocalDateTime.now(); - LocalDateTime from = to.minusHours(hours); + @Override + public List top(Long tenantId, String dimension, int rangeHours, int limit) { + String column = DIMENSION_COLUMN.get(dimension); + if (column == null) { + throw new IllegalArgumentException("Unsupported dimension: " + dimension); + } + int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); + int hours = Math.clamp(rangeHours, 1, MAX_HOURS_90D); + LocalDateTime to = LocalDateTime.now(); + LocalDateTime from = to.minusHours(hours); - var rows = dashboardMapper.top(tenantId, column, from, to, clampedLimit); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - TopEntityVO vo = new TopEntityVO(); - vo.setEntityId(row.getEntityId()); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + var rows = dashboardMapper.top(tenantId, column, from, to, clampedLimit); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + TopEntityVO vo = new TopEntityVO(); + vo.setEntityId(row.getEntityId()); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - @Override - public List latestStream(Long tenantId, int size) { - int clamped = Math.clamp(size, 1, MAX_LIVE_SIZE); - var rows = dashboardMapper.latestStream(tenantId, clamped); - List out = new ArrayList<>(rows.size()); - Set deviceIds = new HashSet<>(); - Set pointIds = new HashSet<>(); - Set driverIds = new HashSet<>(); - for (var row : rows) { - LatestPointValueVO vo = new LatestPointValueVO(); - vo.setDeviceId(row.getDeviceId()); - vo.setPointId(row.getPointId()); - vo.setDriverId(row.getDriverId()); - vo.setRawValue(row.getRawValue()); - vo.setCalValue(row.getCalValue()); - vo.setValueType(row.getValueType()); - vo.setCreateTime(row.getCreateTime()); - out.add(vo); - if (vo.getDeviceId() != null && vo.getDeviceId() > 0) - deviceIds.add(vo.getDeviceId()); - if (vo.getPointId() != null && vo.getPointId() > 0) - pointIds.add(vo.getPointId()); - if (vo.getDriverId() != null && vo.getDriverId() > 0) - driverIds.add(vo.getDriverId()); - } + @Override + public List latestStream(Long tenantId, int size) { + int clamped = Math.clamp(size, 1, MAX_LIVE_SIZE); + var rows = dashboardMapper.latestStream(tenantId, clamped); + List out = new ArrayList<>(rows.size()); + Set deviceIds = new HashSet<>(); + Set pointIds = new HashSet<>(); + Set driverIds = new HashSet<>(); + for (var row : rows) { + LatestPointValueVO vo = new LatestPointValueVO(); + vo.setDeviceId(row.getDeviceId()); + vo.setPointId(row.getPointId()); + vo.setDriverId(row.getDriverId()); + vo.setRawValue(row.getRawValue()); + vo.setCalValue(row.getCalValue()); + vo.setValueType(row.getValueType()); + vo.setCreateTime(row.getCreateTime()); + out.add(vo); + if (vo.getDeviceId() != null && vo.getDeviceId() > 0) + deviceIds.add(vo.getDeviceId()); + if (vo.getPointId() != null && vo.getPointId() > 0) + pointIds.add(vo.getPointId()); + if (vo.getDriverId() != null && vo.getDriverId() > 0) + driverIds.add(vo.getDriverId()); + } - // Point-value tables live in the history data source; device / point / - // driver metadata lives in the master data source (and in remote - // Manager in distributed deployments), so we cannot JOIN them in SQL. - // Resolve names via the Facade once per distinct id — the live feed - // is a manual-refresh endpoint capped at 100 rows, so at most a few - // dozen facade calls per request. The Facade implementation (local - // or gRPC) already sits behind Manager's own caching. - Map deviceNames = new HashMap<>(deviceIds.size()); - for (Long id : deviceIds) { - FacadeDeviceBO bo = deviceFacade.selectById(id); - if (Objects.nonNull(bo)) - deviceNames.put(id, bo.getDeviceName()); - } - Map pointNames = new HashMap<>(pointIds.size()); - for (Long id : pointIds) { - FacadePointBO bo = pointFacade.selectById(id); - if (Objects.nonNull(bo)) - pointNames.put(id, bo.getPointName()); - } - Map driverNames = new HashMap<>(driverIds.size()); - for (Long id : driverIds) { - FacadeDriverBO bo = driverFacade.selectById(id); - if (Objects.nonNull(bo)) - driverNames.put(id, bo.getDriverName()); - } + // Point-value tables live in the history data source; device / point / + // driver metadata lives in the master data source (and in remote + // Manager in distributed deployments), so we cannot JOIN them in SQL. + // Resolve names via the Facade once per distinct id — the live feed + // is a manual-refresh endpoint capped at 100 rows, so at most a few + // dozen facade calls per request. The Facade implementation (local + // or gRPC) already sits behind Manager's own caching. + Map deviceNames = new HashMap<>(deviceIds.size()); + for (Long id : deviceIds) { + FacadeDeviceBO bo = deviceFacade.selectById(id); + if (Objects.nonNull(bo)) + deviceNames.put(id, bo.getDeviceName()); + } + Map pointNames = new HashMap<>(pointIds.size()); + for (Long id : pointIds) { + FacadePointBO bo = pointFacade.selectById(id); + if (Objects.nonNull(bo)) + pointNames.put(id, bo.getPointName()); + } + Map driverNames = new HashMap<>(driverIds.size()); + for (Long id : driverIds) { + FacadeDriverBO bo = driverFacade.selectById(id); + if (Objects.nonNull(bo)) + driverNames.put(id, bo.getDriverName()); + } - for (LatestPointValueVO vo : out) { - if (vo.getDeviceId() != null) - vo.setDeviceName(deviceNames.get(vo.getDeviceId())); - if (vo.getPointId() != null) - vo.setPointName(pointNames.get(vo.getPointId())); - if (vo.getDriverId() != null) - vo.setDriverName(driverNames.get(vo.getDriverId())); - } + for (LatestPointValueVO vo : out) { + if (vo.getDeviceId() != null) + vo.setDeviceName(deviceNames.get(vo.getDeviceId())); + if (vo.getPointId() != null) + vo.setPointName(pointNames.get(vo.getPointId())); + if (vo.getDriverId() != null) + vo.setDriverName(driverNames.get(vo.getDriverId())); + } - return out; - } + return out; + } - @Override - public AlertStatsVO alertStats(Long tenantId) { - AlertStatsVO vo = new AlertStatsVO(); - var totals = alertMapper.countAll(tenantId); - if (totals != null) { - vo.setTotal(totals.getTotal()); - vo.setUnconfirmed(totals.getUnconfirmed()); - } - var rows = alertMapper.countByType(tenantId); - List buckets = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertStatsVO.BucketVO b = new AlertStatsVO.BucketVO(); - b.setKey(asString(row.getKey())); - b.setCount(row.getCount()); - buckets.add(b); - } - vo.setByType(buckets); + @Override + public AlertStatsVO alertStats(Long tenantId) { + AlertStatsVO vo = new AlertStatsVO(); + var totals = alertMapper.countAll(tenantId); + if (totals != null) { + vo.setTotal(totals.getTotal()); + vo.setUnconfirmed(totals.getUnconfirmed()); + } + var rows = alertMapper.countByType(tenantId); + List buckets = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertStatsVO.BucketVO b = new AlertStatsVO.BucketVO(); + b.setKey(asString(row.getKey())); + b.setCount(row.getCount()); + buckets.add(b); + } + vo.setByType(buckets); - for (var row : alertMapper.countBySource(tenantId)) { - String src = row.getSource(); - long srcTotal = row.getTotal(); - long srcUnconfirmed = row.getUnconfirmed(); - if ("device".equals(src)) { - vo.setDeviceAlerts(srcTotal); - vo.setDeviceUnconfirmed(srcUnconfirmed); - } - else if ("driver".equals(src)) { - vo.setDriverAlerts(srcTotal); - vo.setDriverUnconfirmed(srcUnconfirmed); - } - } + for (var row : alertMapper.countBySource(tenantId)) { + String src = row.getSource(); + long srcTotal = row.getTotal(); + long srcUnconfirmed = row.getUnconfirmed(); + if ("device".equals(src)) { + vo.setDeviceAlerts(srcTotal); + vo.setDeviceUnconfirmed(srcUnconfirmed); + } else if ("driver".equals(src)) { + vo.setDriverAlerts(srcTotal); + vo.setDriverUnconfirmed(srcUnconfirmed); + } + } - // Today's ALARM counts per source - LocalDateTime todayStart = LocalDate.now().atStartOfDay(); - for (var row : alertMapper.todayBySource(tenantId, todayStart)) { - String src = row.getSource(); - long srcTotal = row.getTotal(); - long srcUnconfirmed = row.getUnconfirmed(); - if ("device".equals(src)) { - vo.setTodayDeviceAlarms(srcTotal); - vo.setTodayDeviceUnconfirmed(srcUnconfirmed); - } - else if ("driver".equals(src)) { - vo.setTodayDriverAlarms(srcTotal); - vo.setTodayDriverUnconfirmed(srcUnconfirmed); - } - } + // Today's ALARM counts per source + LocalDateTime todayStart = LocalDate.now().atStartOfDay(); + for (var row : alertMapper.todayBySource(tenantId, todayStart)) { + String src = row.getSource(); + long srcTotal = row.getTotal(); + long srcUnconfirmed = row.getUnconfirmed(); + if ("device".equals(src)) { + vo.setTodayDeviceAlarms(srcTotal); + vo.setTodayDeviceUnconfirmed(srcUnconfirmed); + } else if ("driver".equals(src)) { + vo.setTodayDriverAlarms(srcTotal); + vo.setTodayDriverUnconfirmed(srcUnconfirmed); + } + } - // 24-hour hourly sparkline, anchored to top-of-hour now-23. - LocalDateTime anchor = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0).minusHours(23); - long[] series = new long[24]; - for (var row : alertMapper.hourlyCounts(tenantId, anchor)) { - LocalDateTime bucket = row.getBucket(); - if (bucket == null) - continue; - long diffHours = java.time.Duration.between(anchor, bucket).toHours(); - int idx = (int) diffHours; - if (idx >= 0 && idx < series.length) { - series[idx] = row.getCount(); - } - } - List sparkline = new ArrayList<>(series.length); - for (long v : series) - sparkline.add(v); - vo.setSparkline24h(sparkline); - return vo; - } + // 24-hour hourly sparkline, anchored to top-of-hour now-23. + LocalDateTime anchor = LocalDateTime.now().withMinute(0).withSecond(0).withNano(0).minusHours(23); + long[] series = new long[24]; + for (var row : alertMapper.hourlyCounts(tenantId, anchor)) { + LocalDateTime bucket = row.getBucket(); + if (bucket == null) + continue; + long diffHours = java.time.Duration.between(anchor, bucket).toHours(); + int idx = (int) diffHours; + if (idx >= 0 && idx < series.length) { + series[idx] = row.getCount(); + } + } + List sparkline = new ArrayList<>(series.length); + for (long v : series) + sparkline.add(v); + vo.setSparkline24h(sparkline); + return vo; + } - @Override - public List alertLatest(Long tenantId, int size) { - int clamped = Math.clamp(size, 1, MAX_LIMIT); - var rows = alertMapper.latest(tenantId, clamped); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertItemVO vo = new AlertItemVO(); - vo.setId(row.getId()); - vo.setSource(row.getSource()); - vo.setSourceId(row.getSourceId()); - vo.setPointId(row.getPointId()); - vo.setEventTypeFlag(row.getEventTypeFlag()); - vo.setConfirmFlag(row.getConfirmFlag()); - vo.setCreateTime(row.getCreateTime()); - vo.setMessage(row.getMessage()); - out.add(vo); - } - return out; - } + @Override + public List alertLatest(Long tenantId, int size) { + int clamped = Math.clamp(size, 1, MAX_LIMIT); + var rows = alertMapper.latest(tenantId, clamped); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertItemVO vo = new AlertItemVO(); + vo.setId(row.getId()); + vo.setSource(row.getSource()); + vo.setSourceId(row.getSourceId()); + vo.setPointId(row.getPointId()); + vo.setEventTypeFlag(row.getEventTypeFlag()); + vo.setConfirmFlag(row.getConfirmFlag()); + vo.setCreateTime(row.getCreateTime()); + vo.setMessage(row.getMessage()); + out.add(vo); + } + return out; + } - @Override - public List alertTrend(Long tenantId, int days) { - int clamped = Math.clamp(days, 1, MAX_DAYS); - LocalDateTime from = LocalDate.now().minusDays(clamped).atTime(LocalTime.MIN); - var rows = alertMapper.dailyTrend(tenantId, from); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertTrendVO vo = new AlertTrendVO(); - vo.setDate(row.getDate()); - vo.setDeviceCount(row.getDeviceCount()); - vo.setDriverCount(row.getDriverCount()); - out.add(vo); - } - return out; - } + @Override + public List alertTrend(Long tenantId, int days) { + int clamped = Math.clamp(days, 1, MAX_DAYS); + LocalDateTime from = LocalDate.now().minusDays(clamped).atTime(LocalTime.MIN); + var rows = alertMapper.dailyTrend(tenantId, from); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertTrendVO vo = new AlertTrendVO(); + vo.setDate(row.getDate()); + vo.setDeviceCount(row.getDeviceCount()); + vo.setDriverCount(row.getDriverCount()); + out.add(vo); + } + return out; + } - @Override - public List alertTopSources(Long tenantId, int days, int limit) { - int clampedDays = Math.clamp(days, 1, MAX_DAYS); - int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); - LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); - var rows = alertMapper.topSources(tenantId, from, clampedLimit); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertTopSourceVO vo = new AlertTopSourceVO(); - vo.setSource(row.getSource()); - vo.setSourceId(row.getSourceId()); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + @Override + public List alertTopSources(Long tenantId, int days, int limit) { + int clampedDays = Math.clamp(days, 1, MAX_DAYS); + int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); + LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); + var rows = alertMapper.topSources(tenantId, from, clampedLimit); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertTopSourceVO vo = new AlertTopSourceVO(); + vo.setSource(row.getSource()); + vo.setSourceId(row.getSourceId()); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - @Override - public List alertActivity(Long tenantId, int days) { - int clampedDays = Math.clamp(days, 1, MAX_DAYS); - LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); - var rows = alertMapper.activityHeatmap(tenantId, from); - long[][] grid = new long[7][24]; - for (var row : rows) { - int dow = row.getDow(); - int hour = row.getHour(); - if (dow >= 0 && dow < 7 && hour >= 0 && hour < 24) { - grid[dow][hour] = row.getCount(); - } - } - // Zero-pad every cell so the UI always receives 7 × 24 = 168 rows. - List out = new ArrayList<>(7 * 24); - for (int d = 0; d < 7; d++) { - for (int h = 0; h < 24; h++) { - AlertActivityCellVO vo = new AlertActivityCellVO(); - vo.setDow(d); - vo.setHour(h); - vo.setCount(grid[d][h]); - out.add(vo); - } - } - return out; - } + @Override + public List alertActivity(Long tenantId, int days) { + int clampedDays = Math.clamp(days, 1, MAX_DAYS); + LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); + var rows = alertMapper.activityHeatmap(tenantId, from); + long[][] grid = new long[7][24]; + for (var row : rows) { + int dow = row.getDow(); + int hour = row.getHour(); + if (dow >= 0 && dow < 7 && hour >= 0 && hour < 24) { + grid[dow][hour] = row.getCount(); + } + } + // Zero-pad every cell so the UI always receives 7 × 24 = 168 rows. + List out = new ArrayList<>(7 * 24); + for (int d = 0; d < 7; d++) { + for (int h = 0; h < 24; h++) { + AlertActivityCellVO vo = new AlertActivityCellVO(); + vo.setDow(d); + vo.setHour(h); + vo.setCount(grid[d][h]); + out.add(vo); + } + } + return out; + } - @Override - public List alertTypeDistribution(Long tenantId, int days) { - int clampedDays = Math.clamp(days, 1, MAX_DAYS); - LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); - var rows = alertMapper.typeDistribution(tenantId, from); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertTypeBucketVO vo = new AlertTypeBucketVO(); - vo.setType(row.getKey() == null ? null : row.getKey().toString()); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + @Override + public List alertTypeDistribution(Long tenantId, int days) { + int clampedDays = Math.clamp(days, 1, MAX_DAYS); + LocalDateTime from = LocalDate.now().minusDays(clampedDays).atTime(LocalTime.MIN); + var rows = alertMapper.typeDistribution(tenantId, from); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertTypeBucketVO vo = new AlertTypeBucketVO(); + vo.setType(row.getKey() == null ? null : row.getKey().toString()); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - @Override - public List alertStormSources(Long tenantId, int hours, int minCount, int limit) { - int clampedHours = Math.clamp(hours, 1, MAX_HOURS_30D); - int clampedMin = Math.max(1, minCount); - int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); - LocalDateTime from = LocalDateTime.now().minusHours(clampedHours); - var rows = alertMapper.stormSources(tenantId, from, clampedMin, clampedLimit); - List out = new ArrayList<>(rows.size()); - for (var row : rows) { - AlertTopSourceVO vo = new AlertTopSourceVO(); - vo.setSource(row.getSource()); - vo.setSourceId(row.getSourceId()); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + @Override + public List alertStormSources(Long tenantId, int hours, int minCount, int limit) { + int clampedHours = Math.clamp(hours, 1, MAX_HOURS_30D); + int clampedMin = Math.max(1, minCount); + int clampedLimit = Math.clamp(limit, 1, MAX_LIMIT); + LocalDateTime from = LocalDateTime.now().minusHours(clampedHours); + var rows = alertMapper.stormSources(tenantId, from, clampedMin, clampedLimit); + List out = new ArrayList<>(rows.size()); + for (var row : rows) { + AlertTopSourceVO vo = new AlertTopSourceVO(); + vo.setSource(row.getSource()); + vo.setSourceId(row.getSourceId()); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - // ================================================================ - // Phase-2 insights - // ================================================================ + // ================================================================ + // Phase-2 insights + // ================================================================ - @Override - public List alertFlapping(Long tenantId, int hours, int minCount, int limit) { - int h = Math.clamp(hours, 1, MAX_HOURS_7D); - int min = Math.max(MIN_FLAPPING_COUNT, minCount); - int lim = Math.clamp(limit, 1, MAX_LIMIT); - LocalDateTime from = LocalDateTime.now().minusHours(h); - var rows = alertMapper.flappingSources(tenantId, from, min, lim); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - FlappingSourceVO vo = new FlappingSourceVO(); - vo.setSource(r.getSource()); - vo.setSourceId(r.getSourceId()); - vo.setEventTypeFlag(r.getEventTypeFlag()); - vo.setCount(r.getCount()); - out.add(vo); - } - return out; - } + @Override + public List alertFlapping(Long tenantId, int hours, int minCount, int limit) { + int h = Math.clamp(hours, 1, MAX_HOURS_7D); + int min = Math.max(MIN_FLAPPING_COUNT, minCount); + int lim = Math.clamp(limit, 1, MAX_LIMIT); + LocalDateTime from = LocalDateTime.now().minusHours(h); + var rows = alertMapper.flappingSources(tenantId, from, min, lim); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + FlappingSourceVO vo = new FlappingSourceVO(); + vo.setSource(r.getSource()); + vo.setSourceId(r.getSourceId()); + vo.setEventTypeFlag(r.getEventTypeFlag()); + vo.setCount(r.getCount()); + out.add(vo); + } + return out; + } - @Override - public List alertCorrelation(Long tenantId, int hours, int windowSec, int limit) { - int h = Math.clamp(hours, 1, MAX_HOURS_7D); - int w = Math.clamp(windowSec, MIN_CORRELATION_WINDOW_SEC, MAX_CORRELATION_WINDOW_SEC); - int lim = Math.clamp(limit, 1, MAX_CORRELATION_PAIRS); - LocalDateTime from = LocalDateTime.now().minusHours(h); - var rows = alertMapper.correlationPairs(tenantId, from, w, lim); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - CorrelationPairVO vo = new CorrelationPairVO(); - vo.setASource(r.getASource()); - vo.setASourceId(r.getASourceId()); - vo.setAEventType(r.getAEventType()); - vo.setBSource(r.getBSource()); - vo.setBSourceId(r.getBSourceId()); - vo.setBEventType(r.getBEventType()); - vo.setCoCount(r.getCoCount()); - out.add(vo); - } - return out; - } + @Override + public List alertCorrelation(Long tenantId, int hours, int windowSec, int limit) { + int h = Math.clamp(hours, 1, MAX_HOURS_7D); + int w = Math.clamp(windowSec, MIN_CORRELATION_WINDOW_SEC, MAX_CORRELATION_WINDOW_SEC); + int lim = Math.clamp(limit, 1, MAX_CORRELATION_PAIRS); + LocalDateTime from = LocalDateTime.now().minusHours(h); + var rows = alertMapper.correlationPairs(tenantId, from, w, lim); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + CorrelationPairVO vo = new CorrelationPairVO(); + vo.setASource(r.getASource()); + vo.setASourceId(r.getASourceId()); + vo.setAEventType(r.getAEventType()); + vo.setBSource(r.getBSource()); + vo.setBSourceId(r.getBSourceId()); + vo.setBEventType(r.getBEventType()); + vo.setCoCount(r.getCoCount()); + out.add(vo); + } + return out; + } - @Override - public List alertPeerDeviation(Long tenantId, int days) { - int d = Math.clamp(days, 1, MAX_PEER_DAYS); - LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); - var rows = alertMapper.peerAlarmCounts(tenantId, from); + @Override + public List alertPeerDeviation(Long tenantId, int days) { + int d = Math.clamp(days, 1, MAX_PEER_DAYS); + LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); + var rows = alertMapper.peerAlarmCounts(tenantId, from); - // Group by profile → list of (device, alarmCount); then pick median - // and flag devices with count >= 3x median (and a floor of 5 alarms - // so a profile with median=1 doesn't emit noise). - Map> byProfile = new HashMap<>(); - for (var r : rows) { - long prof = r.getProfileId(); - long dev = r.getDeviceId(); - long cnt = r.getAlarmCount(); - byProfile.computeIfAbsent(prof, k -> new ArrayList<>()).add(new long[] { dev, cnt }); - } - List out = new ArrayList<>(); - for (Map.Entry> e : byProfile.entrySet()) { - List devs = e.getValue(); - if (devs.size() < 3) - continue; // need enough peers for a peer test - long[] sorted = devs.stream().mapToLong(a -> a[1]).sorted().toArray(); - long median = sorted[sorted.length / 2]; - for (long[] a : devs) { - if (a[1] < 5) - continue; - if (median > 0 && a[1] < median * 3) - continue; - if (median == 0 && a[1] < 5) - continue; - PeerDeviationVO vo = new PeerDeviationVO(); - vo.setProfileId(e.getKey()); - vo.setDeviceId(a[0]); - vo.setAlarmCount(a[1]); - vo.setPeerMedian(median); - vo.setRatio(median == 0 ? 0.0 : Math.round((double) a[1] / median * 100.0) / 100.0); - out.add(vo); - } - } - out.sort((a, b) -> Long.compare(b.getAlarmCount(), a.getAlarmCount())); - // Cap to 50 to keep payload bounded - return out.size() > 50 ? out.subList(0, 50) : out; - } + // Group by profile → list of (device, alarmCount); then pick median + // and flag devices with count >= 3x median (and a floor of 5 alarms + // so a profile with median=1 doesn't emit noise). + Map> byProfile = new HashMap<>(); + for (var r : rows) { + long prof = r.getProfileId(); + long dev = r.getDeviceId(); + long cnt = r.getAlarmCount(); + byProfile.computeIfAbsent(prof, k -> new ArrayList<>()).add(new long[]{dev, cnt}); + } + List out = new ArrayList<>(); + for (Map.Entry> e : byProfile.entrySet()) { + List devs = e.getValue(); + if (devs.size() < 3) + continue; // need enough peers for a peer test + long[] sorted = devs.stream().mapToLong(a -> a[1]).sorted().toArray(); + long median = sorted[sorted.length / 2]; + for (long[] a : devs) { + if (a[1] < 5) + continue; + if (median > 0 && a[1] < median * 3) + continue; + if (median == 0 && a[1] < 5) + continue; + PeerDeviationVO vo = new PeerDeviationVO(); + vo.setProfileId(e.getKey()); + vo.setDeviceId(a[0]); + vo.setAlarmCount(a[1]); + vo.setPeerMedian(median); + vo.setRatio(median == 0 ? 0.0 : Math.round((double) a[1] / median * 100.0) / 100.0); + out.add(vo); + } + } + out.sort((a, b) -> Long.compare(b.getAlarmCount(), a.getAlarmCount())); + // Cap to 50 to keep payload bounded + return out.size() > 50 ? out.subList(0, 50) : out; + } - @Override - public AgingBacklogVO alertAgingBacklog(Long tenantId) { - var row = alertMapper.agingBuckets(tenantId); - AgingBacklogVO vo = new AgingBacklogVO(); - if (row != null) { - vo.setUnder1h(row.getUnder1h()); - vo.setH1to6(row.getH1to6()); - vo.setH6to24(row.getH6to24()); - vo.setOver24h(row.getOver24h()); - vo.setTotal(row.getTotal()); - } - return vo; - } + @Override + public AgingBacklogVO alertAgingBacklog(Long tenantId) { + var row = alertMapper.agingBuckets(tenantId); + AgingBacklogVO vo = new AgingBacklogVO(); + if (row != null) { + vo.setUnder1h(row.getUnder1h()); + vo.setH1to6(row.getH1to6()); + vo.setH6to24(row.getH6to24()); + vo.setOver24h(row.getOver24h()); + vo.setTotal(row.getTotal()); + } + return vo; + } - @Override - public List alertMtta(Long tenantId, int days) { - int d = Math.clamp(days, 1, MAX_DAYS); - LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); - var rows = alertMapper.mttaByDay(tenantId, from); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - MttaTrendVO vo = new MttaTrendVO(); - vo.setDate(r.getDate()); - vo.setP50Ms(r.getP50Ms()); - vo.setP95Ms(r.getP95Ms()); - vo.setConfirmedCount(r.getConfirmedCount()); - out.add(vo); - } - return out; - } + @Override + public List alertMtta(Long tenantId, int days) { + int d = Math.clamp(days, 1, MAX_DAYS); + LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); + var rows = alertMapper.mttaByDay(tenantId, from); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + MttaTrendVO vo = new MttaTrendVO(); + vo.setDate(r.getDate()); + vo.setP50Ms(r.getP50Ms()); + vo.setP95Ms(r.getP95Ms()); + vo.setConfirmedCount(r.getConfirmedCount()); + out.add(vo); + } + return out; + } - @Override - public List protocolHealth(Long tenantId) { - var rows = alertMapper.protocolHealth(tenantId); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - ProtocolHealthVO vo = new ProtocolHealthVO(); - vo.setServiceName(r.getServiceName()); - vo.setDriverCount(r.getDriverCount()); - vo.setEnabledCount(r.getEnabledCount()); - vo.setDeviceCount(r.getDeviceCount()); - out.add(vo); - } - return out; - } + @Override + public List protocolHealth(Long tenantId) { + var rows = alertMapper.protocolHealth(tenantId); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + ProtocolHealthVO vo = new ProtocolHealthVO(); + vo.setServiceName(r.getServiceName()); + vo.setDriverCount(r.getDriverCount()); + vo.setEnabledCount(r.getEnabledCount()); + vo.setDeviceCount(r.getDeviceCount()); + out.add(vo); + } + return out; + } - @Override - public List changeImpact(Long tenantId, int days, int limit) { - int d = Math.clamp(days, 1, MAX_DAYS); - int lim = Math.clamp(limit, 1, MAX_LIMIT); - LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); - var rows = alertMapper.recentChanges(tenantId, from, lim); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - ChangeImpactVO vo = new ChangeImpactVO(); - vo.setKind(r.getKind()); - vo.setEntityId(r.getEntityId()); - vo.setOperateTime(r.getOperateTime()); - out.add(vo); - } - return out; - } + @Override + public List changeImpact(Long tenantId, int days, int limit) { + int d = Math.clamp(days, 1, MAX_DAYS); + int lim = Math.clamp(limit, 1, MAX_LIMIT); + LocalDateTime from = LocalDate.now().minusDays(d).atTime(LocalTime.MIN); + var rows = alertMapper.recentChanges(tenantId, from, lim); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + ChangeImpactVO vo = new ChangeImpactVO(); + vo.setKind(r.getKind()); + vo.setEntityId(r.getEntityId()); + vo.setOperateTime(r.getOperateTime()); + out.add(vo); + } + return out; + } - @Override - public List silentSources(Long tenantId, int baselineDays, int silentMinutes, int limit) { - int baseline = Math.clamp(baselineDays, 1, MAX_BASELINE_DAYS); - int silent = Math.clamp(silentMinutes, 5, 60 * 24); - int lim = Math.clamp(limit, 1, MAX_COVERAGE_GAP_LIMIT); + @Override + public List silentSources(Long tenantId, int baselineDays, int silentMinutes, int limit) { + int baseline = Math.clamp(baselineDays, 1, MAX_BASELINE_DAYS); + int silent = Math.clamp(silentMinutes, 5, 60 * 24); + int lim = Math.clamp(limit, 1, MAX_COVERAGE_GAP_LIMIT); - LocalDateTime now = LocalDateTime.now(); - LocalDateTime from = now.minusDays(baseline); - LocalDateTime silentThreshold = now.minusMinutes(silent); + LocalDateTime now = LocalDateTime.now(); + LocalDateTime from = now.minusDays(baseline); + LocalDateTime silentThreshold = now.minusMinutes(silent); - var rows = dashboardMapper.silentSources(tenantId, from, silentThreshold, lim); - List out = new ArrayList<>(rows.size()); - for (var r : rows) { - SilentSourceVO vo = new SilentSourceVO(); - vo.setDeviceId(r.getDeviceId()); - vo.setPointId(r.getPointId()); - LocalDateTime last = r.getLastSeen(); - vo.setLastSeen(last); - if (last != null) { - vo.setSilentSeconds(java.time.Duration.between(last, now).getSeconds()); - } - out.add(vo); - } - return out; - } + var rows = dashboardMapper.silentSources(tenantId, from, silentThreshold, lim); + List out = new ArrayList<>(rows.size()); + for (var r : rows) { + SilentSourceVO vo = new SilentSourceVO(); + vo.setDeviceId(r.getDeviceId()); + vo.setPointId(r.getPointId()); + LocalDateTime last = r.getLastSeen(); + vo.setLastSeen(last); + if (last != null) { + vo.setSilentSeconds(java.time.Duration.between(last, now).getSeconds()); + } + out.add(vo); + } + return out; + } - @Override - public CoverageGapVO coverageGap(Long tenantId, int limit) { - int lim = Math.clamp(limit, 1, MAX_COVERAGE_GAP_LIMIT); - CoverageGapVO vo = new CoverageGapVO(); - vo.setTotalPoints(dashboardMapper.countPointsInTenant(tenantId)); - var rows = dashboardMapper.coverageGapItems(tenantId, lim); - for (var r : rows) { - CoverageGapVO.Item it = new CoverageGapVO.Item(); - it.setPointId(r.getPointId()); - it.setProfileId(r.getProfileId()); - vo.getItems().add(it); - } - // missingPoints = actual count; items may be capped. Use a second - // query only if we hit the cap — otherwise items.size() is authoritative. - vo.setMissingPoints(vo.getItems().size()); - return vo; - } + @Override + public CoverageGapVO coverageGap(Long tenantId, int limit) { + int lim = Math.clamp(limit, 1, MAX_COVERAGE_GAP_LIMIT); + CoverageGapVO vo = new CoverageGapVO(); + vo.setTotalPoints(dashboardMapper.countPointsInTenant(tenantId)); + var rows = dashboardMapper.coverageGapItems(tenantId, lim); + for (var r : rows) { + CoverageGapVO.Item it = new CoverageGapVO.Item(); + it.setPointId(r.getPointId()); + it.setProfileId(r.getProfileId()); + vo.getItems().add(it); + } + // missingPoints = actual count; items may be capped. Use a second + // query only if we hit the cap — otherwise items.size() is authoritative. + vo.setMissingPoints(vo.getItems().size()); + return vo; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceEventServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceEventServiceImpl.java index 9b4819260..1c9e807f3 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceEventServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceEventServiceImpl.java @@ -48,78 +48,78 @@ import java.util.Objects; @Service public class DeviceEventServiceImpl implements DeviceEventService { - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - @Resource - private DeviceEventManager deviceEventManager; + @Resource + private DeviceEventManager deviceEventManager; - /** - * Flip between the online family (ONLINE / MAINTAIN) and the unavailable family - * (OFFLINE / FAULT) is a user-visible transition worth a derived ALARM. Within-family - * flips (e.g. ONLINE -> MAINTAIN) are not. - */ - private static boolean isFlip(String prev, String current) { - return online(prev) != online(current); - } + /** + * Flip between the online family (ONLINE / MAINTAIN) and the unavailable family + * (OFFLINE / FAULT) is a user-visible transition worth a derived ALARM. Within-family + * flips (e.g. ONLINE -> MAINTAIN) are not. + */ + private static boolean isFlip(String prev, String current) { + return online(prev) != online(current); + } - private static boolean online(String code) { - return DeviceStatusEnum.ONLINE.getCode().equals(code) || DeviceStatusEnum.MAINTAIN.getCode().equals(code); - } + private static boolean online(String code) { + return DeviceStatusEnum.ONLINE.getCode().equals(code) || DeviceStatusEnum.MAINTAIN.getCode().equals(code); + } - @Override - public void heartbeatEvent(DeviceEventDTO entityDTO) { - DeviceEventDTO.DeviceStatus payload = JsonUtil.parseObject(entityDTO.getContent(), - DeviceEventDTO.DeviceStatus.class); - if (Objects.isNull(payload) || Objects.isNull(payload.getDeviceId()) || Objects.isNull(payload.getStatus())) { - return; - } + @Override + public void heartbeatEvent(DeviceEventDTO entityDTO) { + DeviceEventDTO.DeviceStatus payload = JsonUtil.parseObject(entityDTO.getContent(), + DeviceEventDTO.DeviceStatus.class); + if (Objects.isNull(payload) || Objects.isNull(payload.getDeviceId()) || Objects.isNull(payload.getStatus())) { + return; + } - String statusKey = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + payload.getDeviceId(); - String prev = localCacheService.getKey(statusKey); - String current = payload.getStatus().getCode(); + String statusKey = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + payload.getDeviceId(); + String prev = localCacheService.getKey(statusKey); + String current = payload.getStatus().getCode(); - // Refresh the online-status cache so the dashboard's "online" badge reacts - // immediately. - // Heartbeats do NOT write to dc3_device_event any more — they'd flood the table - // at - // the heartbeat rate (potentially per-second per device). The cache entry alone - // is - // enough to drive the online badge, and an ALARM row is still persisted on a real - // state flip below. - localCacheService.setKey(statusKey, current, payload.getTimeOut(), payload.getTimeUnit()); + // Refresh the online-status cache so the dashboard's "online" badge reacts + // immediately. + // Heartbeats do NOT write to dc3_device_event any more — they'd flood the table + // at + // the heartbeat rate (potentially per-second per device). The cache entry alone + // is + // enough to drive the online badge, and an ALARM row is still persisted on a real + // state flip below. + localCacheService.setKey(statusKey, current, payload.getTimeOut(), payload.getTimeUnit()); - // Derive an ALARM row on state flips so operators see transitions in the alert - // list. - if (prev != null && !Objects.equals(prev, current) && isFlip(prev, current)) { - String message = String.format("Device status changed: %s -> %s", prev, current); - persist(payload, DeviceEventTypeEnum.ALARM, "device-state-flip", message); - } - } + // Derive an ALARM row on state flips so operators see transitions in the alert + // list. + if (prev != null && !Objects.equals(prev, current) && isFlip(prev, current)) { + String message = String.format("Device status changed: %s -> %s", prev, current); + persist(payload, DeviceEventTypeEnum.ALARM, "device-state-flip", message); + } + } - @Override - public void alarmEvent(DeviceEventDTO entityDTO) { - DeviceEventDTO.DeviceStatus payload = JsonUtil.parseObject(entityDTO.getContent(), - DeviceEventDTO.DeviceStatus.class); - if (Objects.isNull(payload) || Objects.isNull(payload.getDeviceId())) { - log.warn("Drop device alarm without deviceId: {}", entityDTO.getContent()); - return; - } - String msg = payload.getMessage() != null ? payload.getMessage() : entityDTO.getContent(); - persist(payload, DeviceEventTypeEnum.ALARM, "device-alarm", msg); - } + @Override + public void alarmEvent(DeviceEventDTO entityDTO) { + DeviceEventDTO.DeviceStatus payload = JsonUtil.parseObject(entityDTO.getContent(), + DeviceEventDTO.DeviceStatus.class); + if (Objects.isNull(payload) || Objects.isNull(payload.getDeviceId())) { + log.warn("Drop device alarm without deviceId: {}", entityDTO.getContent()); + return; + } + String msg = payload.getMessage() != null ? payload.getMessage() : entityDTO.getContent(); + persist(payload, DeviceEventTypeEnum.ALARM, "device-alarm", msg); + } - private void persist(DeviceEventDTO.DeviceStatus payload, DeviceEventTypeEnum type, String extType, - String extContent) { - DeviceEventDO entity = new DeviceEventDO(); - entity.setDeviceId(payload.getDeviceId()); - entity.setPointId(0L); - entity.setEventTypeFlag(type.getIndex()); - entity.setEventExt(JsonExt.builder().type(extType).content(extContent).version(1).build()); - entity.setExpiredTime(0L); - entity.setConfirmFlag((byte) 0); - entity.setTenantId(payload.getTenantId() != null ? payload.getTenantId() : 0L); - deviceEventManager.save(entity); - } + private void persist(DeviceEventDTO.DeviceStatus payload, DeviceEventTypeEnum type, String extType, + String extContent) { + DeviceEventDO entity = new DeviceEventDO(); + entity.setDeviceId(payload.getDeviceId()); + entity.setPointId(0L); + entity.setEventTypeFlag(type.getIndex()); + entity.setEventExt(JsonExt.builder().type(extType).content(extContent).version(1).build()); + entity.setExpiredTime(0L); + entity.setConfirmFlag((byte) 0); + entity.setTenantId(payload.getTenantId() != null ? payload.getTenantId() : 0L); + deviceEventManager.save(entity); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceStatusServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceStatusServiceImpl.java index 17e96ad3c..8c0b9a592 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceStatusServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DeviceStatusServiceImpl.java @@ -44,54 +44,54 @@ import java.util.stream.Collectors; @Service public class DeviceStatusServiceImpl implements DeviceStatusService { - @Resource - private DeviceFacade deviceFacade; + @Resource + private DeviceFacade deviceFacade; - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - @Override - public Map selectByPage(DeviceQuery pageQuery) { - FacadeDeviceQuery facadeQuery = FacadeDeviceQuery.builder() - .page(pageQuery.getPage()) - .deviceName(pageQuery.getDeviceName()) - .deviceCode(pageQuery.getDeviceCode()) - .driverId(pageQuery.getDriverId()) - .profileId(pageQuery.getProfileId()) - .tenantId(pageQuery.getTenantId()) - .enableFlag(pageQuery.getEnableFlag()) - .build(); + @Override + public Map selectByPage(DeviceQuery pageQuery) { + FacadeDeviceQuery facadeQuery = FacadeDeviceQuery.builder() + .page(pageQuery.getPage()) + .deviceName(pageQuery.getDeviceName()) + .deviceCode(pageQuery.getDeviceCode()) + .driverId(pageQuery.getDriverId()) + .profileId(pageQuery.getProfileId()) + .tenantId(pageQuery.getTenantId()) + .enableFlag(pageQuery.getEnableFlag()) + .build(); - FacadePage page = deviceFacade.selectByPage(facadeQuery); - if (page.getRecords().isEmpty()) { - return Map.of(); - } + FacadePage page = deviceFacade.selectByPage(facadeQuery); + if (page.getRecords().isEmpty()) { + return Map.of(); + } - return getStatusMap(page.getRecords()); - } + return getStatusMap(page.getRecords()); + } - @Override - public Map selectByProfileId(Long profileId) { - List devices = deviceFacade.selectByProfileId(profileId); - if (devices.isEmpty()) { - return Map.of(); - } - return getStatusMap(devices); - } + @Override + public Map selectByProfileId(Long profileId) { + List devices = deviceFacade.selectByProfileId(profileId); + if (devices.isEmpty()) { + return Map.of(); + } + return getStatusMap(devices); + } - /** - * Get a map of device statuses keyed by device id. - */ - private Map getStatusMap(List devices) { - Map statusMap = new HashMap<>(16); - Set deviceIds = devices.stream().map(FacadeDeviceBO::getId).collect(Collectors.toSet()); - deviceIds.forEach(id -> { - String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + id; - String status = localCacheService.getKey(key); - status = Objects.nonNull(status) ? status : DeviceStatusEnum.OFFLINE.getCode(); - statusMap.put(id, status); - }); - return statusMap; - } + /** + * Get a map of device statuses keyed by device id. + */ + private Map getStatusMap(List devices) { + Map statusMap = new HashMap<>(16); + Set deviceIds = devices.stream().map(FacadeDeviceBO::getId).collect(Collectors.toSet()); + deviceIds.forEach(id -> { + String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + id; + String status = localCacheService.getKey(key); + status = Objects.nonNull(status) ? status : DeviceStatusEnum.OFFLINE.getCode(); + statusMap.put(id, status); + }); + return statusMap; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverEventServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverEventServiceImpl.java index 0a63164bb..a9be7190e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverEventServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverEventServiceImpl.java @@ -48,77 +48,77 @@ import java.util.concurrent.TimeUnit; @Service public class DriverEventServiceImpl implements DriverEventService { - // Driver status TTL must comfortably exceed the heartbeat cadence - // (ScheduleConstant.DRIVER_STATUS_SCHEDULE_CRON = 15s); otherwise the - // cache key expires before the next heartbeat lands, the offline-expiry - // listener fires on every healthy cycle, and each following heartbeat is - // interpreted as an OFFLINE→ONLINE flip — producing a 2-row/cycle alarm - // storm. 45s ≈ 3× the cron interval, which tolerates a couple of missed - // beats (network blip, GC pause) without flapping. - private static final int STATUS_TTL_SECONDS = 45; + // Driver status TTL must comfortably exceed the heartbeat cadence + // (ScheduleConstant.DRIVER_STATUS_SCHEDULE_CRON = 15s); otherwise the + // cache key expires before the next heartbeat lands, the offline-expiry + // listener fires on every healthy cycle, and each following heartbeat is + // interpreted as an OFFLINE→ONLINE flip — producing a 2-row/cycle alarm + // storm. 45s ≈ 3× the cron interval, which tolerates a couple of missed + // beats (network blip, GC pause) without flapping. + private static final int STATUS_TTL_SECONDS = 45; - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - @Resource - private DriverEventManager driverEventManager; + @Resource + private DriverEventManager driverEventManager; - private static boolean isFlip(String prev, String current) { - return online(prev) != online(current); - } + private static boolean isFlip(String prev, String current) { + return online(prev) != online(current); + } - private static boolean online(String code) { - return DriverStatusEnum.ONLINE.getCode().equals(code) || DriverStatusEnum.MAINTAIN.getCode().equals(code); - } + private static boolean online(String code) { + return DriverStatusEnum.ONLINE.getCode().equals(code) || DriverStatusEnum.MAINTAIN.getCode().equals(code); + } - @Override - public void heartbeatEvent(DriverEventDTO entityDTO) { - DriverEventDTO.DriverStatus payload = JsonUtil.parseObject(entityDTO.getContent(), - DriverEventDTO.DriverStatus.class); - if (Objects.isNull(payload) || Objects.isNull(payload.getDriverId()) || Objects.isNull(payload.getStatus())) { - return; - } + @Override + public void heartbeatEvent(DriverEventDTO entityDTO) { + DriverEventDTO.DriverStatus payload = JsonUtil.parseObject(entityDTO.getContent(), + DriverEventDTO.DriverStatus.class); + if (Objects.isNull(payload) || Objects.isNull(payload.getDriverId()) || Objects.isNull(payload.getStatus())) { + return; + } - String statusKey = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + payload.getDriverId(); - String prev = localCacheService.getKey(statusKey); - String current = payload.getStatus().getCode(); + String statusKey = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + payload.getDriverId(); + String prev = localCacheService.getKey(statusKey); + String current = payload.getStatus().getCode(); - localCacheService.setKey(statusKey, current, STATUS_TTL_SECONDS, TimeUnit.SECONDS); + localCacheService.setKey(statusKey, current, STATUS_TTL_SECONDS, TimeUnit.SECONDS); - // Heartbeats no longer write to dc3_driver_event every tick — the cache TTL is - // the - // source of truth for "is the driver alive". An ALARM row lands on actual state - // flips below, and the matching removal hook (see OfflineExpiryListener) lands - // one - // when the TTL elapses without a fresh heartbeat. - if (prev != null && !Objects.equals(prev, current) && isFlip(prev, current)) { - String message = String.format("Driver status changed: %s -> %s", prev, current); - persist(payload, DriverEventTypeEnum.ALARM, "driver-state-flip", message); - } - } + // Heartbeats no longer write to dc3_driver_event every tick — the cache TTL is + // the + // source of truth for "is the driver alive". An ALARM row lands on actual state + // flips below, and the matching removal hook (see OfflineExpiryListener) lands + // one + // when the TTL elapses without a fresh heartbeat. + if (prev != null && !Objects.equals(prev, current) && isFlip(prev, current)) { + String message = String.format("Driver status changed: %s -> %s", prev, current); + persist(payload, DriverEventTypeEnum.ALARM, "driver-state-flip", message); + } + } - @Override - public void alarmEvent(DriverEventDTO entityDTO) { - DriverEventDTO.DriverStatus payload = JsonUtil.parseObject(entityDTO.getContent(), - DriverEventDTO.DriverStatus.class); - if (Objects.isNull(payload) || Objects.isNull(payload.getDriverId())) { - log.warn("Drop driver alarm without driverId: {}", entityDTO.getContent()); - return; - } - String msg = payload.getMessage() != null ? payload.getMessage() : entityDTO.getContent(); - persist(payload, DriverEventTypeEnum.ALARM, "driver-alarm", msg); - } + @Override + public void alarmEvent(DriverEventDTO entityDTO) { + DriverEventDTO.DriverStatus payload = JsonUtil.parseObject(entityDTO.getContent(), + DriverEventDTO.DriverStatus.class); + if (Objects.isNull(payload) || Objects.isNull(payload.getDriverId())) { + log.warn("Drop driver alarm without driverId: {}", entityDTO.getContent()); + return; + } + String msg = payload.getMessage() != null ? payload.getMessage() : entityDTO.getContent(); + persist(payload, DriverEventTypeEnum.ALARM, "driver-alarm", msg); + } - private void persist(DriverEventDTO.DriverStatus payload, DriverEventTypeEnum type, String extType, - String extContent) { - DriverEventDO entity = new DriverEventDO(); - entity.setDriverId(payload.getDriverId()); - entity.setEventTypeFlag(type.getIndex()); - entity.setEventExt(JsonExt.builder().type(extType).content(extContent).version(1).build()); - entity.setExpiredTime(0L); - entity.setConfirmFlag((byte) 0); - entity.setTenantId(payload.getTenantId() != null ? payload.getTenantId() : 0L); - driverEventManager.save(entity); - } + private void persist(DriverEventDTO.DriverStatus payload, DriverEventTypeEnum type, String extType, + String extContent) { + DriverEventDO entity = new DriverEventDO(); + entity.setDriverId(payload.getDriverId()); + entity.setEventTypeFlag(type.getIndex()); + entity.setEventExt(JsonExt.builder().type(extType).content(extContent).version(1).build()); + entity.setExpiredTime(0L); + entity.setConfirmFlag((byte) 0); + entity.setTenantId(payload.getTenantId() != null ? payload.getTenantId() : 0L); + driverEventManager.save(entity); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverStatusServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverStatusServiceImpl.java index 4d430724f..bc906a311 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverStatusServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/DriverStatusServiceImpl.java @@ -47,86 +47,86 @@ import java.util.stream.Collectors; @Service public class DriverStatusServiceImpl implements DriverStatusService { - @Resource - private DriverFacade driverFacade; + @Resource + private DriverFacade driverFacade; - @Resource - private DeviceFacade deviceFacade; + @Resource + private DeviceFacade deviceFacade; - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - @Override - public Map selectByPage(DriverQuery pageQuery) { - FacadeDriverQuery facadeQuery = FacadeDriverQuery.builder() - .page(pageQuery.getPage()) - .driverName(pageQuery.getDriverName()) - .driverCode(pageQuery.getDriverCode()) - .serviceName(pageQuery.getServiceName()) - .serviceHost(pageQuery.getServiceHost()) - .tenantId(pageQuery.getTenantId()) - .driverTypeFlag(pageQuery.getDriverTypeFlag()) - .enableFlag(pageQuery.getEnableFlag()) - .build(); + @Override + public Map selectByPage(DriverQuery pageQuery) { + FacadeDriverQuery facadeQuery = FacadeDriverQuery.builder() + .page(pageQuery.getPage()) + .driverName(pageQuery.getDriverName()) + .driverCode(pageQuery.getDriverCode()) + .serviceName(pageQuery.getServiceName()) + .serviceHost(pageQuery.getServiceHost()) + .tenantId(pageQuery.getTenantId()) + .driverTypeFlag(pageQuery.getDriverTypeFlag()) + .enableFlag(pageQuery.getEnableFlag()) + .build(); - FacadePage page = driverFacade.selectByPage(facadeQuery); - if (page.getRecords().isEmpty()) { - return Map.of(); - } - return getStatusMap(page.getRecords()); - } + FacadePage page = driverFacade.selectByPage(facadeQuery); + if (page.getRecords().isEmpty()) { + return Map.of(); + } + return getStatusMap(page.getRecords()); + } - @Override - public String getDeviceOnlineByDriverId(Long driverId) { - List list = getDeviceStatuses(driverId); - if (list == null) { - return String.valueOf(0L); - } - long count = list.stream().filter(e -> e.equals(DeviceStatusEnum.ONLINE.getCode())).count(); - return String.valueOf(count); - } + @Override + public String getDeviceOnlineByDriverId(Long driverId) { + List list = getDeviceStatuses(driverId); + if (list == null) { + return String.valueOf(0L); + } + long count = list.stream().filter(e -> e.equals(DeviceStatusEnum.ONLINE.getCode())).count(); + return String.valueOf(count); + } - @Override - public String getDeviceOfflineByDriverId(Long driverId) { - List list = getDeviceStatuses(driverId); - if (list == null) { - return String.valueOf(0L); - } - long count = list.stream().filter(e -> e.equals(DeviceStatusEnum.OFFLINE.getCode())).count(); - return String.valueOf(count); - } + @Override + public String getDeviceOfflineByDriverId(Long driverId) { + List list = getDeviceStatuses(driverId); + if (list == null) { + return String.valueOf(0L); + } + long count = list.stream().filter(e -> e.equals(DeviceStatusEnum.OFFLINE.getCode())).count(); + return String.valueOf(count); + } - /** - * Load the status of every device attached to the given driver. Returns {@code null} - * when the driver has no devices (preserves legacy "0" signal). - */ - private List getDeviceStatuses(Long driverId) { - List devices = deviceFacade.selectByDriverId(driverId); - if (devices.isEmpty()) { - return null; - } + /** + * Load the status of every device attached to the given driver. Returns {@code null} + * when the driver has no devices (preserves legacy "0" signal). + */ + private List getDeviceStatuses(Long driverId) { + List devices = deviceFacade.selectByDriverId(driverId); + if (devices.isEmpty()) { + return null; + } - Set deviceIds = devices.stream().map(FacadeDeviceBO::getId).collect(Collectors.toSet()); - List list = new ArrayList<>(deviceIds.size()); - deviceIds.forEach(id -> { - String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + id; - String status = localCacheService.getKey(key); - status = Objects.nonNull(status) ? status : DeviceStatusEnum.OFFLINE.getCode(); - list.add(status); - }); - return list; - } + Set deviceIds = devices.stream().map(FacadeDeviceBO::getId).collect(Collectors.toSet()); + List list = new ArrayList<>(deviceIds.size()); + deviceIds.forEach(id -> { + String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + id; + String status = localCacheService.getKey(key); + status = Objects.nonNull(status) ? status : DeviceStatusEnum.OFFLINE.getCode(); + list.add(status); + }); + return list; + } - private Map getStatusMap(List drivers) { - Map statusMap = new HashMap<>(16); - Set driverIds = drivers.stream().map(FacadeDriverBO::getId).collect(Collectors.toSet()); - driverIds.forEach(id -> { - String key = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + id; - String status = localCacheService.getKey(key); - status = Objects.nonNull(status) ? status : DriverStatusEnum.OFFLINE.getCode(); - statusMap.put(id, status); - }); - return statusMap; - } + private Map getStatusMap(List drivers) { + Map statusMap = new HashMap<>(16); + Set driverIds = drivers.stream().map(FacadeDriverBO::getId).collect(Collectors.toSet()); + driverIds.forEach(id -> { + String key = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + id; + String status = localCacheService.getKey(key); + status = Objects.nonNull(status) ? status : DriverStatusEnum.OFFLINE.getCode(); + statusMap.put(id, status); + }); + return statusMap; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/OfflineExpiryListener.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/OfflineExpiryListener.java index 67d8f418c..fa6491c6d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/OfflineExpiryListener.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/OfflineExpiryListener.java @@ -60,123 +60,120 @@ import java.util.concurrent.CompletableFuture; @Component public class OfflineExpiryListener { - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - @Resource - private DriverFacade driverFacade; + @Resource + private DriverFacade driverFacade; - @Resource - private DeviceFacade deviceFacade; + @Resource + private DeviceFacade deviceFacade; - @Resource - private DriverEventManager driverEventManager; + @Resource + private DriverEventManager driverEventManager; - @Resource - private DeviceEventManager deviceEventManager; + @Resource + private DeviceEventManager deviceEventManager; - private static Long parseIdSuffix(String key, String prefix) { - try { - return Long.parseLong(key.substring(prefix.length())); - } - catch (Exception e) { - log.debug("Unexpected status key '{}': {}", key, e.getMessage()); - return null; - } - } + private static Long parseIdSuffix(String key, String prefix) { + try { + return Long.parseLong(key.substring(prefix.length())); + } catch (Exception e) { + log.debug("Unexpected status key '{}': {}", key, e.getMessage()); + return null; + } + } - @PostConstruct - void register() { - localCacheService.onExpire(this::onExpire); - } + @PostConstruct + void register() { + localCacheService.onExpire(this::onExpire); + } - private void onExpire(String key, Object lastValue) { - if (key == null) - return; - final String lastStatus = lastValue instanceof String s ? s : null; - // Skip if the key was already offline — avoids a duplicate alarm on - // the same outage when the cache is manually re-seeded below. - CompletableFuture.runAsync(() -> { - try { - if (key.startsWith(PrefixConstant.DRIVER_STATUS_KEY_PREFIX)) { - handleDriverExpiry(key, lastStatus); - } - else if (key.startsWith(PrefixConstant.DEVICE_STATUS_KEY_PREFIX)) { - handleDeviceExpiry(key, lastStatus); - } - } - catch (Exception e) { - log.warn("Offline expiry handling failed for key {}: {}", key, e.getMessage(), e); - } - }); - } + private void onExpire(String key, Object lastValue) { + if (key == null) + return; + final String lastStatus = lastValue instanceof String s ? s : null; + // Skip if the key was already offline — avoids a duplicate alarm on + // the same outage when the cache is manually re-seeded below. + CompletableFuture.runAsync(() -> { + try { + if (key.startsWith(PrefixConstant.DRIVER_STATUS_KEY_PREFIX)) { + handleDriverExpiry(key, lastStatus); + } else if (key.startsWith(PrefixConstant.DEVICE_STATUS_KEY_PREFIX)) { + handleDeviceExpiry(key, lastStatus); + } + } catch (Exception e) { + log.warn("Offline expiry handling failed for key {}: {}", key, e.getMessage(), e); + } + }); + } - private void handleDriverExpiry(String key, String lastStatus) { - if (Objects.equals(lastStatus, DriverStatusEnum.OFFLINE.getCode())) - return; - Long id = parseIdSuffix(key, PrefixConstant.DRIVER_STATUS_KEY_PREFIX); - if (id == null) - return; + private void handleDriverExpiry(String key, String lastStatus) { + if (Objects.equals(lastStatus, DriverStatusEnum.OFFLINE.getCode())) + return; + Long id = parseIdSuffix(key, PrefixConstant.DRIVER_STATUS_KEY_PREFIX); + if (id == null) + return; - FacadeDriverBO driver = driverFacade.selectById(id); - if (driver == null) { - log.debug("Driver {} not found when handling offline expiry", id); - return; - } + FacadeDriverBO driver = driverFacade.selectById(id); + if (driver == null) { + log.debug("Driver {} not found when handling offline expiry", id); + return; + } - DriverEventDO entity = new DriverEventDO(); - entity.setDriverId(id); - entity.setEventTypeFlag(DriverEventTypeEnum.ALARM.getIndex()); - entity.setEventExt(JsonExt.builder() - .type("driver-offline") - .content(String.format("Driver heartbeat timed out (last=%s); marked OFFLINE", lastStatus)) - .version(1) - .build()); - entity.setExpiredTime(0L); - entity.setConfirmFlag((byte) 0); - entity.setTenantId(driver.getTenantId() != null ? driver.getTenantId() : 0L); - driverEventManager.save(entity); + DriverEventDO entity = new DriverEventDO(); + entity.setDriverId(id); + entity.setEventTypeFlag(DriverEventTypeEnum.ALARM.getIndex()); + entity.setEventExt(JsonExt.builder() + .type("driver-offline") + .content(String.format("Driver heartbeat timed out (last=%s); marked OFFLINE", lastStatus)) + .version(1) + .build()); + entity.setExpiredTime(0L); + entity.setConfirmFlag((byte) 0); + entity.setTenantId(driver.getTenantId() != null ? driver.getTenantId() : 0L); + driverEventManager.save(entity); - // Deliberately do NOT re-seed the cache. The previous version wrote - // OFFLINE back with a 1-day TTL so the dashboard "saw" the state, - // but that made every subsequent heartbeat look like an - // OFFLINE→ONLINE flip and fire a state-flip ALARM, producing an - // alarm storm every cron cycle. Consumers (DriverStatusServiceImpl, - // SystemHealthServiceImpl) already treat a missing key as OFFLINE, - // so leaving the key evicted gives the right UI behaviour without - // any spurious flip alarms. - } + // Deliberately do NOT re-seed the cache. The previous version wrote + // OFFLINE back with a 1-day TTL so the dashboard "saw" the state, + // but that made every subsequent heartbeat look like an + // OFFLINE→ONLINE flip and fire a state-flip ALARM, producing an + // alarm storm every cron cycle. Consumers (DriverStatusServiceImpl, + // SystemHealthServiceImpl) already treat a missing key as OFFLINE, + // so leaving the key evicted gives the right UI behaviour without + // any spurious flip alarms. + } - private void handleDeviceExpiry(String key, String lastStatus) { - if (Objects.equals(lastStatus, DeviceStatusEnum.OFFLINE.getCode())) - return; - Long id = parseIdSuffix(key, PrefixConstant.DEVICE_STATUS_KEY_PREFIX); - if (id == null) - return; + private void handleDeviceExpiry(String key, String lastStatus) { + if (Objects.equals(lastStatus, DeviceStatusEnum.OFFLINE.getCode())) + return; + Long id = parseIdSuffix(key, PrefixConstant.DEVICE_STATUS_KEY_PREFIX); + if (id == null) + return; - FacadeDeviceBO device = deviceFacade.selectById(id); - if (device == null) { - log.debug("Device {} not found when handling offline expiry", id); - return; - } + FacadeDeviceBO device = deviceFacade.selectById(id); + if (device == null) { + log.debug("Device {} not found when handling offline expiry", id); + return; + } - DeviceEventDO entity = new DeviceEventDO(); - entity.setDeviceId(id); - entity.setPointId(0L); - entity.setEventTypeFlag(DeviceEventTypeEnum.ALARM.getIndex()); - entity.setEventExt(JsonExt.builder() - .type("device-offline") - .content(String.format("Device heartbeat timed out (last=%s); marked OFFLINE", lastStatus)) - .version(1) - .build()); - entity.setExpiredTime(0L); - entity.setConfirmFlag((byte) 0); - entity.setTenantId(device.getTenantId() != null ? device.getTenantId() : 0L); - deviceEventManager.save(entity); + DeviceEventDO entity = new DeviceEventDO(); + entity.setDeviceId(id); + entity.setPointId(0L); + entity.setEventTypeFlag(DeviceEventTypeEnum.ALARM.getIndex()); + entity.setEventExt(JsonExt.builder() + .type("device-offline") + .content(String.format("Device heartbeat timed out (last=%s); marked OFFLINE", lastStatus)) + .version(1) + .build()); + entity.setExpiredTime(0L); + entity.setConfirmFlag((byte) 0); + entity.setTenantId(device.getTenantId() != null ? device.getTenantId() : 0L); + deviceEventManager.save(entity); - // See handleDriverExpiry — don't re-seed: the previous OFFLINE - // re-seed with a 1-day TTL turned every subsequent heartbeat into - // a state-flip ALARM. Consumers read a missing key as OFFLINE. - } + // See handleDriverExpiry — don't re-seed: the previous OFFLINE + // re-seed with a 1-day TTL turned every subsequent heartbeat into + // a state-flip ALARM. Consumers read a missing key as OFFLINE. + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueCommandServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueCommandServiceImpl.java index ff18f20f0..da1d0722c 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueCommandServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueCommandServiceImpl.java @@ -42,40 +42,40 @@ import java.util.Objects; @Service public class PointValueCommandServiceImpl implements PointValueCommandService { - @Resource - private DriverFacade driverFacade; + @Resource + private DriverFacade driverFacade; - @Resource - private RabbitTemplate rabbitTemplate; + @Resource + private RabbitTemplate rabbitTemplate; - @Override - public void read(PointValueReadVO entityVO) { - FacadeDriverBO driver = driverFacade.selectByDeviceId(entityVO.getDeviceId()); - if (Objects.isNull(driver)) { - return; - } + @Override + public void read(PointValueReadVO entityVO) { + FacadeDriverBO driver = driverFacade.selectByDeviceId(entityVO.getDeviceId()); + if (Objects.isNull(driver)) { + return; + } - DeviceCommandDTO.DeviceRead deviceRead = new DeviceCommandDTO.DeviceRead(entityVO.getDeviceId(), - entityVO.getPointId()); - DeviceCommandDTO deviceCommandDTO = new DeviceCommandDTO(DeviceCommandTypeEnum.READ, - JsonUtil.toJsonString(deviceRead)); - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_COMMAND, - RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driver.getServiceName(), deviceCommandDTO); - } + DeviceCommandDTO.DeviceRead deviceRead = new DeviceCommandDTO.DeviceRead(entityVO.getDeviceId(), + entityVO.getPointId()); + DeviceCommandDTO deviceCommandDTO = new DeviceCommandDTO(DeviceCommandTypeEnum.READ, + JsonUtil.toJsonString(deviceRead)); + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_COMMAND, + RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driver.getServiceName(), deviceCommandDTO); + } - @Override - public void write(PointValueWriteVO entityVO) { - FacadeDriverBO driver = driverFacade.selectByDeviceId(entityVO.getDeviceId()); - if (Objects.isNull(driver)) { - return; - } + @Override + public void write(PointValueWriteVO entityVO) { + FacadeDriverBO driver = driverFacade.selectByDeviceId(entityVO.getDeviceId()); + if (Objects.isNull(driver)) { + return; + } - DeviceCommandDTO.DeviceWrite deviceWrite = new DeviceCommandDTO.DeviceWrite(entityVO.getDeviceId(), - entityVO.getPointId(), entityVO.getValue()); - DeviceCommandDTO deviceCommandDTO = new DeviceCommandDTO(DeviceCommandTypeEnum.WRITE, - JsonUtil.toJsonString(deviceWrite)); - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_COMMAND, - RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driver.getServiceName(), deviceCommandDTO); - } + DeviceCommandDTO.DeviceWrite deviceWrite = new DeviceCommandDTO.DeviceWrite(entityVO.getDeviceId(), + entityVO.getPointId(), entityVO.getValue()); + DeviceCommandDTO deviceCommandDTO = new DeviceCommandDTO(DeviceCommandTypeEnum.WRITE, + JsonUtil.toJsonString(deviceWrite)); + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_COMMAND, + RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driver.getServiceName(), deviceCommandDTO); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueServiceImpl.java index fd1b1deed..086fb605e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/PointValueServiceImpl.java @@ -50,181 +50,182 @@ import java.util.stream.Collectors; @Service public class PointValueServiceImpl implements PointValueService { - @Resource - private PointFacade pointFacade; + @Resource + private PointFacade pointFacade; - @Resource - private PointValueLocalCacheService pointValueLocalCacheService; + @Resource + private PointValueLocalCacheService pointValueLocalCacheService; - @Override - public void save(PointValueBO pointValueBO) { - if (Objects.isNull(pointValueBO)) { - return; - } + @Override + public void save(PointValueBO pointValueBO) { + if (Objects.isNull(pointValueBO)) { + return; + } - // create_time carries the driver's acquisition timestamp; operate_time - // is stamped at persistence. Keeping them distinct lets the dashboard - // measure the collect→store pipeline latency. - if (Objects.isNull(pointValueBO.getCreateTime())) { - pointValueBO.setCreateTime(LocalDateTimeUtil.now()); - } - pointValueBO.setOperateTime(LocalDateTimeUtil.now()); - savePointValueToRepository(pointValueBO); - } + // create_time carries the driver's acquisition timestamp; operate_time + // is stamped at persistence. Keeping them distinct lets the dashboard + // measure the collect→store pipeline latency. + if (Objects.isNull(pointValueBO.getCreateTime())) { + pointValueBO.setCreateTime(LocalDateTimeUtil.now()); + } + pointValueBO.setOperateTime(LocalDateTimeUtil.now()); + savePointValueToRepository(pointValueBO); + } - @Override - public void save(List pointValueBOList) { - if (CollectionUtils.isEmpty(pointValueBOList)) { - return; - } + @Override + public void save(List pointValueBOList) { + if (CollectionUtils.isEmpty(pointValueBOList)) { + return; + } - final Map> group = pointValueBOList.stream().map(pointValue -> { - if (Objects.isNull(pointValue.getCreateTime())) { - pointValue.setCreateTime(LocalDateTimeUtil.now()); - } - // See single-row save() — operate_time is the persistence - // timestamp, not a mirror of create_time. - pointValue.setOperateTime(LocalDateTimeUtil.now()); - return pointValue; - }).collect(Collectors.groupingBy(PointValueBO::getDeviceId)); + final Map> group = pointValueBOList.stream().map(pointValue -> { + if (Objects.isNull(pointValue.getCreateTime())) { + pointValue.setCreateTime(LocalDateTimeUtil.now()); + } + // See single-row save() — operate_time is the persistence + // timestamp, not a mirror of create_time. + pointValue.setOperateTime(LocalDateTimeUtil.now()); + return pointValue; + }).collect(Collectors.groupingBy(PointValueBO::getDeviceId)); - group.forEach(this::savePointValuesToRepository); - } + group.forEach(this::savePointValuesToRepository); + } - @Override - public List history(Long tenantId, Long deviceId, Long pointId, int count) { - if (Objects.isNull(tenantId) || Objects.isNull(deviceId) || Objects.isNull(pointId)) { - return Collections.emptyList(); - } - if (count < 1) { - count = 100; - } - if (count > 500) { - count = 500; - } + @Override + public List history(Long tenantId, Long deviceId, Long pointId, int count) { + if (Objects.isNull(tenantId) || Objects.isNull(deviceId) || Objects.isNull(pointId)) { + return Collections.emptyList(); + } + if (count < 1) { + count = 100; + } + if (count > 500) { + count = 500; + } - RepositoryService repositoryService = getFirstRepositoryService(); - return repositoryService.selectHistoryPointValue(tenantId, deviceId, pointId, count); - } + RepositoryService repositoryService = getFirstRepositoryService(); + return repositoryService.selectHistoryPointValue(tenantId, deviceId, pointId, count); + } - @Override - public Page latest(PointValueQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page latest(PointValueQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - Page entityPageBO = new Page<>(); - entityPageBO.setCurrent(entityQuery.getPage().getCurrent()).setSize(entityQuery.getPage().getSize()); + Page entityPageBO = new Page<>(); + entityPageBO.setCurrent(entityQuery.getPage().getCurrent()).setSize(entityQuery.getPage().getSize()); - FacadePointQuery facadeQuery = FacadePointQuery.builder() - .page(entityQuery.getPage()) - .pointName(entityQuery.getPointName()) - .tenantId(entityQuery.getTenantId()) - .deviceId(entityQuery.getDeviceId()) - .enableFlag(entityQuery.getEnableFlag()) - .build(); + FacadePointQuery facadeQuery = FacadePointQuery.builder() + .page(entityQuery.getPage()) + .pointName(entityQuery.getPointName()) + .tenantId(entityQuery.getTenantId()) + .deviceId(entityQuery.getDeviceId()) + .enableFlag(entityQuery.getEnableFlag()) + .build(); - FacadePage page = pointFacade.selectByPage(facadeQuery); - List pointIds = page.getRecords().stream().map(FacadePointBO::getId).toList(); + FacadePage page = pointFacade.selectByPage(facadeQuery); + List pointIds = page.getRecords().stream().map(FacadePointBO::getId).toList(); - if (pointIds.isEmpty()) { - return entityPageBO; - } + if (pointIds.isEmpty()) { + return entityPageBO; + } - Long tenantId = entityQuery.getTenantId(); - Map pointValueBOMap = pointValueLocalCacheService.selectLatestPointValue(tenantId, - entityQuery.getDeviceId(), pointIds); - RepositoryService repositoryService = getFirstRepositoryService(); - List pointValueBOList = pointIds.stream().map(id -> { - PointValueBO value = pointValueBOMap.get(id); - return Objects.isNull(value) - ? repositoryService.selectLatestPointValue(tenantId, entityQuery.getDeviceId(), id) : value; - }).filter(Objects::nonNull).toList(); + Long tenantId = entityQuery.getTenantId(); + Map pointValueBOMap = pointValueLocalCacheService.selectLatestPointValue(tenantId, + entityQuery.getDeviceId(), pointIds); + RepositoryService repositoryService = getFirstRepositoryService(); + List pointValueBOList = pointIds.stream().map(id -> { + PointValueBO value = pointValueBOMap.get(id); + return Objects.isNull(value) + ? repositoryService.selectLatestPointValue(tenantId, entityQuery.getDeviceId(), id) : value; + }).filter(Objects::nonNull).toList(); - entityPageBO.setCurrent(page.getCurrent()) - .setSize(page.getSize()) - .setTotal(page.getTotal()) - .setRecords(pointValueBOList); + entityPageBO.setCurrent(page.getCurrent()) + .setSize(page.getSize()) + .setTotal(page.getTotal()) + .setRecords(pointValueBOList); - return entityPageBO; - } + return entityPageBO; + } - @Override - @SneakyThrows - public Page page(PointValueQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - if (entityQuery.getCreateTimeFrom() == null) { - java.time.LocalDateTime from = io.github.pnoker.common.utils.TimeRangeUtil - .resolveFrom(entityQuery.getRangeKey(), entityQuery.getRangeHours()); - if (from != null) { - entityQuery.setCreateTimeFrom(from); - } - } + @Override + @SneakyThrows + public Page page(PointValueQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + if (entityQuery.getCreateTimeFrom() == null) { + java.time.LocalDateTime from = io.github.pnoker.common.utils.TimeRangeUtil + .resolveFrom(entityQuery.getRangeKey(), entityQuery.getRangeHours()); + if (from != null) { + entityQuery.setCreateTimeFrom(from); + } + } - RepositoryService repositoryService = getFirstRepositoryService(); - return repositoryService.selectPagePointValue(entityQuery); - } + RepositoryService repositoryService = getFirstRepositoryService(); + return repositoryService.selectPagePointValue(entityQuery); + } - /** - * Save PointValue to the specified storage service - * @param pointValueBO PointValue - */ - private void savePointValueToRepository(PointValueBO pointValueBO) { - try { - // local hot cache - pointValueLocalCacheService.savePointValue(pointValueBO); + /** + * Save PointValue to the specified storage service + * + * @param pointValueBO PointValue + */ + private void savePointValueToRepository(PointValueBO pointValueBO) { + try { + // local hot cache + pointValueLocalCacheService.savePointValue(pointValueBO); - // other repository - RepositoryService repositoryService = getFirstRepositoryService(); - repositoryService.savePointValue(pointValueBO); - } - catch (Exception e) { - log.error("Save point value to error {}", e.getMessage()); - } - } + // other repository + RepositoryService repositoryService = getFirstRepositoryService(); + repositoryService.savePointValue(pointValueBO); + } catch (Exception e) { + log.error("Save point value to error {}", e.getMessage()); + } + } - /** - * Save PointValues to the specified storage service - * @param deviceId Device ID - * @param pointValueBOList Array - */ - private void savePointValuesToRepository(Long deviceId, List pointValueBOList) { - try { - // local hot cache - pointValueLocalCacheService.savePointValue(deviceId, pointValueBOList); + /** + * Save PointValues to the specified storage service + * + * @param deviceId Device ID + * @param pointValueBOList Array + */ + private void savePointValuesToRepository(Long deviceId, List pointValueBOList) { + try { + // local hot cache + pointValueLocalCacheService.savePointValue(deviceId, pointValueBOList); - // other repository - RepositoryService repositoryService = getFirstRepositoryService(); - List> splitPointValueBOList = ListUtils.partition(pointValueBOList, 100); - for (List splitPointValueBO : splitPointValueBOList) { - repositoryService.savePointValues(splitPointValueBO); - } - } - catch (Exception e) { - log.error("Save point values to error {}", e.getMessage()); - } - } + // other repository + RepositoryService repositoryService = getFirstRepositoryService(); + List> splitPointValueBOList = ListUtils.partition(pointValueBOList, 100); + for (List splitPointValueBO : splitPointValueBOList) { + repositoryService.savePointValues(splitPointValueBO); + } + } catch (Exception e) { + log.error("Save point values to error {}", e.getMessage()); + } + } - /** - * Get data storage service - * @return RepositoryService - */ - private RepositoryService getFirstRepositoryService() { - List repositoryServices = RepositoryStrategyFactory.get(); - if (!repositoryServices.isEmpty() && repositoryServices.size() > 1) { - throw new RepositoryException( - "Save point values to repository error: There are multiple repository, only one is supported."); - } + /** + * Get data storage service + * + * @return RepositoryService + */ + private RepositoryService getFirstRepositoryService() { + List repositoryServices = RepositoryStrategyFactory.get(); + if (!repositoryServices.isEmpty() && repositoryServices.size() > 1) { + throw new RepositoryException( + "Save point values to repository error: There are multiple repository, only one is supported."); + } - Optional first = repositoryServices.stream().findFirst(); - if (first.isEmpty()) { - throw new RepositoryException( - "Save point values to repository error: Please configure at least one repository."); - } + Optional first = repositoryServices.stream().findFirst(); + if (first.isEmpty()) { + throw new RepositoryException( + "Save point values to repository error: Please configure at least one repository."); + } - return first.get(); - } + return first.get(); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/ScheduleForDataServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/ScheduleForDataServiceImpl.java index 405082723..fd3db9c14 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/ScheduleForDataServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/ScheduleForDataServiceImpl.java @@ -40,30 +40,29 @@ import org.springframework.stereotype.Service; @Service public class ScheduleForDataServiceImpl implements ScheduleForDataService { - @Value("${data.point.batch.interval}") - private Integer interval; + @Value("${data.point.batch.interval}") + private Integer interval; - @Resource - private QuartzService quartzService; + @Resource + private QuartzService quartzService; - /** - * Initialize data scheduling - */ - @Override - public void initial() { - try { - quartzService.createJobWithInterval(ScheduleConstant.DATA_SCHEDULE_GROUP, "data-point-value-schedule-job", - interval, DateBuilder.IntervalUnit.SECOND, PointValueJob.class); + /** + * Initialize data scheduling + */ + @Override + public void initial() { + try { + quartzService.createJobWithInterval(ScheduleConstant.DATA_SCHEDULE_GROUP, "data-point-value-schedule-job", + interval, DateBuilder.IntervalUnit.SECOND, PointValueJob.class); - // Custom scheduling - quartzService.createJobWithCron(ScheduleConstant.DATA_SCHEDULE_GROUP, "hourly-job", "0 0 0/1 * * ?", - HourlyJobForData.class); + // Custom scheduling + quartzService.createJobWithCron(ScheduleConstant.DATA_SCHEDULE_GROUP, "hourly-job", "0 0 0/1 * * ?", + HourlyJobForData.class); - quartzService.startScheduler(); - } - catch (SchedulerException e) { - log.error(e.getMessage(), e); - } - } + quartzService.startScheduler(); + } catch (SchedulerException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/SystemHealthServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/SystemHealthServiceImpl.java index 46b132375..8037550ad 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/SystemHealthServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/impl/SystemHealthServiceImpl.java @@ -67,175 +67,169 @@ import java.util.concurrent.TimeoutException; @Service public class SystemHealthServiceImpl implements SystemHealthService { - private static final String UP = "up"; + private static final String UP = "up"; - private static final String DOWN = "down"; + private static final String DOWN = "down"; - /** - * Per-probe hard deadline. gRPC facades don't set a client-side timeout by default, - * so a dead sibling would otherwise stall the whole banner. - */ - private static final long PROBE_TIMEOUT_MS = 2000L; + /** + * Per-probe hard deadline. gRPC facades don't set a client-side timeout by default, + * so a dead sibling would otherwise stall the whole banner. + */ + private static final long PROBE_TIMEOUT_MS = 2000L; - @Resource - private DataSource dataSource; + @Resource + private DataSource dataSource; - @Resource - private ConnectionFactory rabbitConnectionFactory; + @Resource + private ConnectionFactory rabbitConnectionFactory; - @Resource - private TenantFacade tenantFacade; + @Resource + private TenantFacade tenantFacade; - @Resource - private DriverFacade driverFacade; + @Resource + private DriverFacade driverFacade; - @Resource - private DeviceFacade deviceFacade; + @Resource + private DeviceFacade deviceFacade; - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - private static Pages firstPage(int size) { - Pages p = new Pages(); - p.setCurrent(1L); - p.setSize((long) size); - return p; - } + private static Pages firstPage(int size) { + Pages p = new Pages(); + p.setCurrent(1L); + p.setSize((long) size); + return p; + } - /** - * Runs a truthy probe on the common ForkJoinPool with a hard timeout. Any exception, - * false return, or timeout maps to "down". - */ - private static String probe(Probe probe) { - CompletableFuture future = CompletableFuture.supplyAsync(() -> { - try { - return probe.check(); - } - catch (Exception e) { - log.debug("Probe failed: {}", e.getMessage()); - return false; - } - }); - try { - return future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS) ? UP : DOWN; - } - catch (TimeoutException e) { - future.cancel(true); - log.debug("Probe timed out after {}ms", PROBE_TIMEOUT_MS); - return DOWN; - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return DOWN; - } - catch (ExecutionException e) { - log.debug("Probe execution failed: {}", e.getMessage()); - return DOWN; - } - } + /** + * Runs a truthy probe on the common ForkJoinPool with a hard timeout. Any exception, + * false return, or timeout maps to "down". + */ + private static String probe(Probe probe) { + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + try { + return probe.check(); + } catch (Exception e) { + log.debug("Probe failed: {}", e.getMessage()); + return false; + } + }); + try { + return future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS) ? UP : DOWN; + } catch (TimeoutException e) { + future.cancel(true); + log.debug("Probe timed out after {}ms", PROBE_TIMEOUT_MS); + return DOWN; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return DOWN; + } catch (ExecutionException e) { + log.debug("Probe execution failed: {}", e.getMessage()); + return DOWN; + } + } - @Override - public SystemHealthVO snapshot(Long tenantId) { - SystemHealthVO vo = new SystemHealthVO(); - vo.setCenter(probeCenter()); - vo.setInfra(probeInfra()); - vo.setDrivers(summariseDrivers(tenantId)); - vo.setDevices(summariseDevices(tenantId)); - return vo; - } + @Override + public SystemHealthVO snapshot(Long tenantId) { + SystemHealthVO vo = new SystemHealthVO(); + vo.setCenter(probeCenter()); + vo.setInfra(probeInfra()); + vo.setDrivers(summariseDrivers(tenantId)); + vo.setDevices(summariseDevices(tenantId)); + return vo; + } - private Map probeCenter() { - Map out = new LinkedHashMap<>(); - out.put("auth", probe(() -> tenantFacade.selectByCode("default") != null)); - out.put("data", UP); // reaching this code == data is up - out.put("manager", probe(() -> { - FacadeDriverQuery q = FacadeDriverQuery.builder().page(firstPage(1)).build(); - return driverFacade.selectByPage(q) != null; - })); - return out; - } + private Map probeCenter() { + Map out = new LinkedHashMap<>(); + out.put("auth", probe(() -> tenantFacade.selectByCode("default") != null)); + out.put("data", UP); // reaching this code == data is up + out.put("manager", probe(() -> { + FacadeDriverQuery q = FacadeDriverQuery.builder().page(firstPage(1)).build(); + return driverFacade.selectByPage(q) != null; + })); + return out; + } - private Map probeInfra() { - Map out = new LinkedHashMap<>(); - out.put("database", probe(() -> { - try (Connection conn = dataSource.getConnection()) { - return conn.isValid(1); - } - })); - out.put("mq", probe(() -> { - try (var connection = rabbitConnectionFactory.createConnection()) { - return connection.isOpen(); - } - })); - out.put("gateway", UP); // the request reached this server via gateway - return out; - } + private Map probeInfra() { + Map out = new LinkedHashMap<>(); + out.put("database", probe(() -> { + try (Connection conn = dataSource.getConnection()) { + return conn.isValid(1); + } + })); + out.put("mq", probe(() -> { + try (var connection = rabbitConnectionFactory.createConnection()) { + return connection.isOpen(); + } + })); + out.put("gateway", UP); // the request reached this server via gateway + return out; + } - private SystemHealthVO.FleetSummary summariseDrivers(Long tenantId) { - SystemHealthVO.FleetSummary summary = new SystemHealthVO.FleetSummary(); - CompletableFuture> future = CompletableFuture.supplyAsync(() -> { - FacadeDriverQuery q = FacadeDriverQuery.builder().page(firstPage(1000)).tenantId(tenantId).build(); - FacadePage page = driverFacade.selectByPage(q); - return page != null ? page.getRecords() : List.of(); - }); - List drivers; - try { - drivers = future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } - catch (Exception e) { - future.cancel(true); - log.warn("Driver summary failed: {}", e.getMessage(), e); - return summary; - } - int online = 0; - String onlineCode = DriverStatusEnum.ONLINE.getCode(); - for (FacadeDriverBO d : drivers) { - String key = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + d.getId(); - String status = localCacheService.getKey(key); - if (Objects.equals(status, onlineCode)) { - online++; - } - } - summary.setTotal(drivers.size()); - summary.setOnline(online); - return summary; - } + private SystemHealthVO.FleetSummary summariseDrivers(Long tenantId) { + SystemHealthVO.FleetSummary summary = new SystemHealthVO.FleetSummary(); + CompletableFuture> future = CompletableFuture.supplyAsync(() -> { + FacadeDriverQuery q = FacadeDriverQuery.builder().page(firstPage(1000)).tenantId(tenantId).build(); + FacadePage page = driverFacade.selectByPage(q); + return page != null ? page.getRecords() : List.of(); + }); + List drivers; + try { + drivers = future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (Exception e) { + future.cancel(true); + log.warn("Driver summary failed: {}", e.getMessage(), e); + return summary; + } + int online = 0; + String onlineCode = DriverStatusEnum.ONLINE.getCode(); + for (FacadeDriverBO d : drivers) { + String key = PrefixConstant.DRIVER_STATUS_KEY_PREFIX + d.getId(); + String status = localCacheService.getKey(key); + if (Objects.equals(status, onlineCode)) { + online++; + } + } + summary.setTotal(drivers.size()); + summary.setOnline(online); + return summary; + } - private SystemHealthVO.FleetSummary summariseDevices(Long tenantId) { - SystemHealthVO.FleetSummary summary = new SystemHealthVO.FleetSummary(); - CompletableFuture> future = CompletableFuture.supplyAsync(() -> { - FacadeDeviceQuery q = FacadeDeviceQuery.builder().page(firstPage(5000)).tenantId(tenantId).build(); - FacadePage page = deviceFacade.selectByPage(q); - return page != null ? page.getRecords() : List.of(); - }); - List devices; - try { - devices = future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } - catch (Exception e) { - future.cancel(true); - log.warn("Device summary failed: {}", e.getMessage(), e); - return summary; - } - int online = 0; - String onlineCode = DeviceStatusEnum.ONLINE.getCode(); - for (FacadeDeviceBO d : devices) { - String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + d.getId(); - String status = localCacheService.getKey(key); - if (Objects.equals(status, onlineCode)) { - online++; - } - } - summary.setTotal(devices.size()); - summary.setOnline(online); - return summary; - } + private SystemHealthVO.FleetSummary summariseDevices(Long tenantId) { + SystemHealthVO.FleetSummary summary = new SystemHealthVO.FleetSummary(); + CompletableFuture> future = CompletableFuture.supplyAsync(() -> { + FacadeDeviceQuery q = FacadeDeviceQuery.builder().page(firstPage(5000)).tenantId(tenantId).build(); + FacadePage page = deviceFacade.selectByPage(q); + return page != null ? page.getRecords() : List.of(); + }); + List devices; + try { + devices = future.get(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS); + } catch (Exception e) { + future.cancel(true); + log.warn("Device summary failed: {}", e.getMessage(), e); + return summary; + } + int online = 0; + String onlineCode = DeviceStatusEnum.ONLINE.getCode(); + for (FacadeDeviceBO d : devices) { + String key = PrefixConstant.DEVICE_STATUS_KEY_PREFIX + d.getId(); + String status = localCacheService.getKey(key); + if (Objects.equals(status, onlineCode)) { + online++; + } + } + summary.setTotal(devices.size()); + summary.setOnline(online); + return summary; + } - @FunctionalInterface - private interface Probe { + @FunctionalInterface + private interface Probe { - boolean check() throws Exception; + boolean check() throws Exception; - } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/repository/PostgresRepositoryServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/repository/PostgresRepositoryServiceImpl.java index dd918bc5e..14046394e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/repository/PostgresRepositoryServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/biz/repository/PostgresRepositoryServiceImpl.java @@ -48,94 +48,95 @@ import java.util.Objects; @Service("postgresRepositoryService") public class PostgresRepositoryServiceImpl implements RepositoryService, InitializingBean { - @Resource - private PointValueBuilder pointValueBuilder; + @Resource + private PointValueBuilder pointValueBuilder; - @Resource - private PointValueManager pointValueManager; + @Resource + private PointValueManager pointValueManager; - @Override - public String getRepositoryName() { - return StrategyConstant.Storage.POSTGRES; - } + @Override + public String getRepositoryName() { + return StrategyConstant.Storage.POSTGRES; + } - @Override - public void savePointValue(PointValueBO entityBO) { - PointValueDO entityDO = pointValueBuilder.buildDOByBO(entityBO); - if (!pointValueManager.save(entityDO)) { - throw new AddException("Failed to create point value"); - } - } + @Override + public void savePointValue(PointValueBO entityBO) { + PointValueDO entityDO = pointValueBuilder.buildDOByBO(entityBO); + if (!pointValueManager.save(entityDO)) { + throw new AddException("Failed to create point value"); + } + } - @Override - public void savePointValues(List entityBOList) { - List entityDOList = pointValueBuilder.buildDOListByBOList(entityBOList); - if (!pointValueManager.saveBatch(entityDOList)) { - throw new AddException("Failed to create point value list"); - } - } + @Override + public void savePointValues(List entityBOList) { + List entityDOList = pointValueBuilder.buildDOListByBOList(entityBOList); + if (!pointValueManager.saveBatch(entityDOList)) { + throw new AddException("Failed to create point value list"); + } + } - @Override - public List selectHistoryPointValue(Long tenantId, Long deviceId, Long pointId, int count) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointValueDO::getTenantId, tenantId); - wrapper.eq(PointValueDO::getDeviceId, deviceId); - wrapper.eq(PointValueDO::getPointId, pointId); - wrapper.orderByDesc(PointValueDO::getCreateTime); - wrapper.last("limit %s".formatted(count)); + @Override + public List selectHistoryPointValue(Long tenantId, Long deviceId, Long pointId, int count) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointValueDO::getTenantId, tenantId); + wrapper.eq(PointValueDO::getDeviceId, deviceId); + wrapper.eq(PointValueDO::getPointId, pointId); + wrapper.orderByDesc(PointValueDO::getCreateTime); + wrapper.last("limit %s".formatted(count)); - List entityPageDO = pointValueManager.list(wrapper); - return entityPageDO.stream().map(PointValueDO::getCalValue).toList(); - } + List entityPageDO = pointValueManager.list(wrapper); + return entityPageDO.stream().map(PointValueDO::getCalValue).toList(); + } - @Override - public PointValueBO selectLatestPointValue(Long tenantId, Long deviceId, Long pointId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointValueDO::getTenantId, tenantId); - wrapper.eq(PointValueDO::getDeviceId, deviceId); - wrapper.eq(PointValueDO::getPointId, pointId); - wrapper.orderByDesc(PointValueDO::getCreateTime); - wrapper.last("limit 1"); + @Override + public PointValueBO selectLatestPointValue(Long tenantId, Long deviceId, Long pointId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointValueDO::getTenantId, tenantId); + wrapper.eq(PointValueDO::getDeviceId, deviceId); + wrapper.eq(PointValueDO::getPointId, pointId); + wrapper.orderByDesc(PointValueDO::getCreateTime); + wrapper.last("limit 1"); - PointValueDO entityDO = pointValueManager.getOne(wrapper); - return pointValueBuilder.buildBOByDO(entityDO); - } + PointValueDO entityDO = pointValueManager.getOne(wrapper); + return pointValueBuilder.buildBOByDO(entityDO); + } - @Override - public List selectLatestPointValues(Long tenantId, Long deviceId, List pointIds) { - throw new UnsupportedOperationException( - "selectLatestPointValues is not implemented; callers should use selectLatestPointValue in a loop " - + "or the PointValueLocalCacheService batch API until a real batch query is wired up."); - } + @Override + public List selectLatestPointValues(Long tenantId, Long deviceId, List pointIds) { + throw new UnsupportedOperationException( + "selectLatestPointValues is not implemented; callers should use selectLatestPointValue in a loop " + + "or the PointValueLocalCacheService batch API until a real batch query is wired up."); + } - @Override - public Page selectPagePointValue(PointValueQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = pointValueManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return pointValueBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectPagePointValue(PointValueQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = pointValueManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return pointValueBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * Construct a fuzzy query wrapper for point value retrieval - * @param entityQuery {@link PointValueQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(PointValueQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointValueDO::getTenantId, entityQuery.getTenantId()); - wrapper.eq(Objects.nonNull(entityQuery.getDeviceId()), PointValueDO::getDeviceId, entityQuery.getDeviceId()); - wrapper.eq(Objects.nonNull(entityQuery.getPointId()), PointValueDO::getPointId, entityQuery.getPointId()); - wrapper.ge(Objects.nonNull(entityQuery.getCreateTimeFrom()), PointValueDO::getCreateTime, - entityQuery.getCreateTimeFrom()); - return wrapper; - } + /** + * Construct a fuzzy query wrapper for point value retrieval + * + * @param entityQuery {@link PointValueQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(PointValueQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointValueDO::getTenantId, entityQuery.getTenantId()); + wrapper.eq(Objects.nonNull(entityQuery.getDeviceId()), PointValueDO::getDeviceId, entityQuery.getDeviceId()); + wrapper.eq(Objects.nonNull(entityQuery.getPointId()), PointValueDO::getPointId, entityQuery.getPointId()); + wrapper.ge(Objects.nonNull(entityQuery.getCreateTimeFrom()), PointValueDO::getCreateTime, + entityQuery.getCreateTimeFrom()); + return wrapper; + } - @Override - public void afterPropertiesSet() { - RepositoryStrategyFactory.put(StrategyConstant.Storage.POSTGRES, this); - } + @Override + public void afterPropertiesSet() { + RepositoryStrategyFactory.put(StrategyConstant.Storage.POSTGRES, this); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/LocalCacheService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/LocalCacheService.java index b0abf80aa..e7f7f3197 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/LocalCacheService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/LocalCacheService.java @@ -46,102 +46,101 @@ import java.util.concurrent.TimeUnit; @Component public class LocalCacheService { - /** - * Hooks fired exclusively on TTL-driven evictions. Copy-on-write list so registration - * from different modules (data biz, dashboards, …) is safe without locking. - */ - private final List expireListeners = new CopyOnWriteArrayList<>(); + /** + * Hooks fired exclusively on TTL-driven evictions. Copy-on-write list so registration + * from different modules (data biz, dashboards, …) is safe without locking. + */ + private final List expireListeners = new CopyOnWriteArrayList<>(); - private Cache cache; + private Cache cache; - @PostConstruct - public void init() { - this.cache = Caffeine.newBuilder().maximumSize(200_000L).expireAfter(new Expiry() { - @Override - @SuppressWarnings("NullableProblems") - public long expireAfterCreate(String key, Entry value, long currentTime) { - return value.ttlNanos; - } + @PostConstruct + public void init() { + this.cache = Caffeine.newBuilder().maximumSize(200_000L).expireAfter(new Expiry() { + @Override + @SuppressWarnings("NullableProblems") + public long expireAfterCreate(String key, Entry value, long currentTime) { + return value.ttlNanos; + } - @Override - @SuppressWarnings("NullableProblems") - public long expireAfterUpdate(String key, Entry value, long currentTime, long currentDuration) { - return value.ttlNanos; - } + @Override + @SuppressWarnings("NullableProblems") + public long expireAfterUpdate(String key, Entry value, long currentTime, long currentDuration) { + return value.ttlNanos; + } - @Override - @SuppressWarnings("NullableProblems") - public long expireAfterRead(String key, Entry value, long currentTime, long currentDuration) { - return currentDuration; - } - }).removalListener((String key, Entry value, RemovalCause cause) -> { - // Only fire listeners for natural TTL expiries. Explicit - // cache.invalidate() / size-based eviction aren't - // "the key went offline" semantically. - if (cause != RemovalCause.EXPIRED || key == null || value == null) - return; - for (ExpireListener listener : expireListeners) { - try { - listener.onExpire(key, value.value); - } - catch (Exception e) { - log.warn("Expire listener failed for key {}: {}", key, e.getMessage()); - } - } - }).build(); - } + @Override + @SuppressWarnings("NullableProblems") + public long expireAfterRead(String key, Entry value, long currentTime, long currentDuration) { + return currentDuration; + } + }).removalListener((String key, Entry value, RemovalCause cause) -> { + // Only fire listeners for natural TTL expiries. Explicit + // cache.invalidate() / size-based eviction aren't + // "the key went offline" semantically. + if (cause != RemovalCause.EXPIRED || key == null || value == null) + return; + for (ExpireListener listener : expireListeners) { + try { + listener.onExpire(key, value.value); + } catch (Exception e) { + log.warn("Expire listener failed for key {}: {}", key, e.getMessage()); + } + } + }).build(); + } - public void setKey(String key, T value) { - cache.put(key, new Entry(value, Long.MAX_VALUE)); - } + public void setKey(String key, T value) { + cache.put(key, new Entry(value, Long.MAX_VALUE)); + } - public void setKey(String key, T value, long time, TimeUnit unit) { - long ttl = time > 0 ? unit.toNanos(time) : Long.MAX_VALUE; - cache.put(key, new Entry(value, ttl)); - } + public void setKey(String key, T value, long time, TimeUnit unit) { + long ttl = time > 0 ? unit.toNanos(time) : Long.MAX_VALUE; + cache.put(key, new Entry(value, ttl)); + } - public void setKey(Map valuesMap) { - if (valuesMap == null || valuesMap.isEmpty()) { - return; - } - valuesMap.forEach(this::setKey); - } + public void setKey(Map valuesMap) { + if (valuesMap == null || valuesMap.isEmpty()) { + return; + } + valuesMap.forEach(this::setKey); + } - @SuppressWarnings("unchecked") - public T getKey(String key) { - Entry entry = cache.getIfPresent(key); - return entry == null ? null : (T) entry.value; - } + @SuppressWarnings("unchecked") + public T getKey(String key) { + Entry entry = cache.getIfPresent(key); + return entry == null ? null : (T) entry.value; + } - public List getKey(List keys) { - if (keys == null || keys.isEmpty()) { - return List.of(); - } - List result = new ArrayList<>(keys.size()); - for (String key : keys) { - result.add(getKey(key)); - } - return result; - } + public List getKey(List keys) { + if (keys == null || keys.isEmpty()) { + return List.of(); + } + List result = new ArrayList<>(keys.size()); + for (String key : keys) { + result.add(getKey(key)); + } + return result; + } - /** - * Register a callback that fires when an entry expires due to its TTL. The callback - * runs on Caffeine's removal executor (default: same thread that triggered the expiry - * read / write); keep the handler short. - */ - public void onExpire(ExpireListener listener) { - if (listener != null) - expireListeners.add(listener); - } + /** + * Register a callback that fires when an entry expires due to its TTL. The callback + * runs on Caffeine's removal executor (default: same thread that triggered the expiry + * read / write); keep the handler short. + */ + public void onExpire(ExpireListener listener) { + if (listener != null) + expireListeners.add(listener); + } - @FunctionalInterface - public interface ExpireListener { + @FunctionalInterface + public interface ExpireListener { - void onExpire(String key, Object lastValue); + void onExpire(String key, Object lastValue); - } + } - private record Entry(Object value, long ttlNanos) { - } + private record Entry(Object value, long ttlNanos) { + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/PointValueLocalCacheService.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/PointValueLocalCacheService.java index ac2f4397b..20da0efdc 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/PointValueLocalCacheService.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/cache/PointValueLocalCacheService.java @@ -42,43 +42,43 @@ import java.util.stream.Collectors; @Service public class PointValueLocalCacheService { - @Resource - private LocalCacheService localCacheService; + @Resource + private LocalCacheService localCacheService; - public void savePointValue(PointValueBO entityBO) { - if (Objects.isNull(entityBO.getTenantId()) || Objects.isNull(entityBO.getDeviceId()) - || Objects.isNull(entityBO.getPointId())) { - return; - } - String key = buildKey(entityBO.getTenantId(), entityBO.getDeviceId(), entityBO.getPointId()); - localCacheService.setKey(key, entityBO); - } + public void savePointValue(PointValueBO entityBO) { + if (Objects.isNull(entityBO.getTenantId()) || Objects.isNull(entityBO.getDeviceId()) + || Objects.isNull(entityBO.getPointId())) { + return; + } + String key = buildKey(entityBO.getTenantId(), entityBO.getDeviceId(), entityBO.getPointId()); + localCacheService.setKey(key, entityBO); + } - public void savePointValue(Long deviceId, List entityBOList) { - if (Objects.isNull(deviceId) || CollectionUtils.isEmpty(entityBOList)) { - return; - } - Map valuesMap = entityBOList.stream() - .filter(entityBO -> Objects.nonNull(entityBO.getTenantId()) && Objects.nonNull(entityBO.getPointId())) - .collect(Collectors.toMap(entityBO -> buildKey(entityBO.getTenantId(), deviceId, entityBO.getPointId()), - Function.identity())); - localCacheService.setKey(valuesMap); - } + public void savePointValue(Long deviceId, List entityBOList) { + if (Objects.isNull(deviceId) || CollectionUtils.isEmpty(entityBOList)) { + return; + } + Map valuesMap = entityBOList.stream() + .filter(entityBO -> Objects.nonNull(entityBO.getTenantId()) && Objects.nonNull(entityBO.getPointId())) + .collect(Collectors.toMap(entityBO -> buildKey(entityBO.getTenantId(), deviceId, entityBO.getPointId()), + Function.identity())); + localCacheService.setKey(valuesMap); + } - public Map selectLatestPointValue(Long tenantId, Long deviceId, List pointIds) { - if (Objects.isNull(tenantId) || Objects.isNull(deviceId) || CollectionUtils.isEmpty(pointIds)) { - return Collections.emptyMap(); - } - List keys = pointIds.stream().map(pointId -> buildKey(tenantId, deviceId, pointId)).toList(); - List hits = localCacheService.getKey(keys); - return hits.stream() - .filter(Objects::nonNull) - .collect(Collectors.toMap(PointValueBO::getPointId, Function.identity())); - } + public Map selectLatestPointValue(Long tenantId, Long deviceId, List pointIds) { + if (Objects.isNull(tenantId) || Objects.isNull(deviceId) || CollectionUtils.isEmpty(pointIds)) { + return Collections.emptyMap(); + } + List keys = pointIds.stream().map(pointId -> buildKey(tenantId, deviceId, pointId)).toList(); + List hits = localCacheService.getKey(keys); + return hits.stream() + .filter(Objects::nonNull) + .collect(Collectors.toMap(PointValueBO::getPointId, Function.identity())); + } - private String buildKey(Long tenantId, Long deviceId, Long pointId) { - return PrefixConstant.REAL_TIME_VALUE_KEY_PREFIX + tenantId + SymbolConstant.DOT + deviceId + SymbolConstant.DOT - + pointId; - } + private String buildKey(Long tenantId, Long deviceId, Long pointId) { + return PrefixConstant.REAL_TIME_VALUE_KEY_PREFIX + tenantId + SymbolConstant.DOT + deviceId + SymbolConstant.DOT + + pointId; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/constant/DashboardLimits.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/constant/DashboardLimits.java index 23f6a815d..375e27362 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/constant/DashboardLimits.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/constant/DashboardLimits.java @@ -34,88 +34,88 @@ package io.github.pnoker.common.data.constant; */ public final class DashboardLimits { - /** - * Lookback ceiling for daily-trend style queries. - */ - public static final int MAX_DAYS = 90; + /** + * Lookback ceiling for daily-trend style queries. + */ + public static final int MAX_DAYS = 90; - // ===== Generic clamp ceilings ============================================== - /** - * Default Top-N limit cap for ranking endpoints. - */ - public static final int MAX_LIMIT = 50; + // ===== Generic clamp ceilings ============================================== + /** + * Default Top-N limit cap for ranking endpoints. + */ + public static final int MAX_LIMIT = 50; - /** - * Hard cap on page size for the alert list (avoids accidental DOS via size=999999). - */ - public static final long MAX_PAGE_SIZE = 200L; + /** + * Hard cap on page size for the alert list (avoids accidental DOS via size=999999). + */ + public static final long MAX_PAGE_SIZE = 200L; - /** - * Cap on live-stream / alert-latest batch sizes. - */ - public static final int MAX_LIVE_SIZE = 100; + /** + * Cap on live-stream / alert-latest batch sizes. + */ + public static final int MAX_LIVE_SIZE = 100; - /** - * 7-day window expressed in hours. - */ - public static final int MAX_HOURS_7D = 24 * 7; + /** + * 7-day window expressed in hours. + */ + public static final int MAX_HOURS_7D = 24 * 7; - /** - * 30-day window expressed in hours. - */ - public static final int MAX_HOURS_30D = 24 * 30; + /** + * 30-day window expressed in hours. + */ + public static final int MAX_HOURS_30D = 24 * 30; - /** - * 90-day window expressed in hours. - */ - public static final int MAX_HOURS_90D = 24 * 90; + /** + * 90-day window expressed in hours. + */ + public static final int MAX_HOURS_90D = 24 * 90; - /** - * Silent threshold clamped to at most 24h (one day of silence). - */ - public static final int MAX_SILENT_MINUTES = 24 * 60; + /** + * Silent threshold clamped to at most 24h (one day of silence). + */ + public static final int MAX_SILENT_MINUTES = 24 * 60; - // ===== Insight-specific caps ============================================== - /** - * Baseline window for the silent-sources check (how far to look for "was active"). - */ - public static final int MAX_BASELINE_DAYS = 30; + // ===== Insight-specific caps ============================================== + /** + * Baseline window for the silent-sources check (how far to look for "was active"). + */ + public static final int MAX_BASELINE_DAYS = 30; - /** - * Peer-deviation lookback. - */ - public static final int MAX_PEER_DAYS = 30; + /** + * Peer-deviation lookback. + */ + public static final int MAX_PEER_DAYS = 30; - /** - * Correlation edge cap — payload stays manageable on a force-layout graph. - */ - public static final int MAX_CORRELATION_PAIRS = 30; + /** + * Correlation edge cap — payload stays manageable on a force-layout graph. + */ + public static final int MAX_CORRELATION_PAIRS = 30; - /** - * Flapping endpoint — count must be at least 2 to be flapping. - */ - public static final int MIN_FLAPPING_COUNT = 2; + /** + * Flapping endpoint — count must be at least 2 to be flapping. + */ + public static final int MIN_FLAPPING_COUNT = 2; - /** - * Correlation co-occurrence window in seconds — clamped bounds. - */ - public static final int MIN_CORRELATION_WINDOW_SEC = 5; + /** + * Correlation co-occurrence window in seconds — clamped bounds. + */ + public static final int MIN_CORRELATION_WINDOW_SEC = 5; - public static final int MAX_CORRELATION_WINDOW_SEC = 300; + public static final int MAX_CORRELATION_WINDOW_SEC = 300; - /** - * Storm / coverage-gap list limit upper bound (higher than MAX_LIMIT because - * coverage-gap can legitimately have hundreds of offenders). - */ - public static final int MAX_COVERAGE_GAP_LIMIT = 200; + /** + * Storm / coverage-gap list limit upper bound (higher than MAX_LIMIT because + * coverage-gap can legitimately have hundreds of offenders). + */ + public static final int MAX_COVERAGE_GAP_LIMIT = 200; - public static final String SOURCE_DEVICE = "device"; + public static final String SOURCE_DEVICE = "device"; - // ===== Whitelist values ================================================= - public static final String SOURCE_DRIVER = "driver"; + // ===== Whitelist values ================================================= + public static final String SOURCE_DRIVER = "driver"; - private DashboardLimits() { - // utility class — never instantiated - } + private DashboardLimits() { + // utility class — never instantiated + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DashboardController.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DashboardController.java index 1b5131eb2..b5f86926d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DashboardController.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DashboardController.java @@ -58,462 +58,434 @@ import java.util.Map; @RequestMapping(DataConstant.DASHBOARD_URL_PREFIX) public class DashboardController implements BaseController { - private final DashboardService dashboardService; + private final DashboardService dashboardService; - private final io.github.pnoker.common.data.biz.SystemHealthService systemHealthService; + private final io.github.pnoker.common.data.biz.SystemHealthService systemHealthService; - public DashboardController(DashboardService dashboardService, - io.github.pnoker.common.data.biz.SystemHealthService systemHealthService) { - this.dashboardService = dashboardService; - this.systemHealthService = systemHealthService; - } + public DashboardController(DashboardService dashboardService, + io.github.pnoker.common.data.biz.SystemHealthService systemHealthService) { + this.dashboardService = dashboardService; + this.systemHealthService = systemHealthService; + } - @GetMapping("/stats/today") - public Mono>> today() { - return getTenantId().flatMap(tenantId -> { - try { - long today = dashboardService.countToday(tenantId); - long yesterday = dashboardService.countYesterday(tenantId); - long total = dashboardService.countTotal(tenantId); - Map out = new HashMap<>(); - out.put("today", today); - out.put("yesterday", yesterday); - out.put("total", total); - // Convenience delta for the UI: +12% (positive) / -3% (negative) / 0. - if (yesterday > 0) { - out.put("percentChange", Math.round(((double) (today - yesterday) * 100.0) / yesterday)); - } - else { - out.put("percentChange", today > 0 ? 100 : 0); - } - return Mono.just(R.ok(out)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/stats/today") + public Mono>> today() { + return getTenantId().flatMap(tenantId -> { + try { + long today = dashboardService.countToday(tenantId); + long yesterday = dashboardService.countYesterday(tenantId); + long total = dashboardService.countTotal(tenantId); + Map out = new HashMap<>(); + out.put("today", today); + out.put("yesterday", yesterday); + out.put("total", total); + // Convenience delta for the UI: +12% (positive) / -3% (negative) / 0. + if (yesterday > 0) { + out.put("percentChange", Math.round(((double) (today - yesterday) * 100.0) / yesterday)); + } else { + out.put("percentChange", today > 0 ? 100 : 0); + } + return Mono.just(R.ok(out)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/stats/timeseries") - public Mono>> timeseries( - @RequestParam(value = "granularity", defaultValue = "hour") String granularity, - @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.timeseries(tenantId, granularity, effectiveHours))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/stats/timeseries") + public Mono>> timeseries( + @RequestParam(value = "granularity", defaultValue = "hour") String granularity, + @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.timeseries(tenantId, granularity, effectiveHours))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/top") - public Mono>> top(@RequestParam(value = "dimension", defaultValue = "device") String dimension, - @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, - @RequestParam(value = "rangeKey", required = false) String rangeKey, - @RequestParam(value = "limit", defaultValue = "10") int limit) { - int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.top(tenantId, dimension, effectiveHours, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/top") + public Mono>> top(@RequestParam(value = "dimension", defaultValue = "device") String dimension, + @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, + @RequestParam(value = "rangeKey", required = false) String rangeKey, + @RequestParam(value = "limit", defaultValue = "10") int limit) { + int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.top(tenantId, dimension, effectiveHours, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/stream") - public Mono>> stream(@RequestParam(value = "size", defaultValue = "20") int size) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.latestStream(tenantId, size))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/stream") + public Mono>> stream(@RequestParam(value = "size", defaultValue = "20") int size) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.latestStream(tenantId, size))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/stats") - public Mono> alertStats() { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertStats(tenantId))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/stats") + public Mono> alertStats() { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertStats(tenantId))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/latest") - public Mono>> alertLatest(@RequestParam(value = "size", defaultValue = "10") int size) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertLatest(tenantId, size))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/latest") + public Mono>> alertLatest(@RequestParam(value = "size", defaultValue = "10") int size) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertLatest(tenantId, size))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/stats/latency") - public Mono>> latencyHistogram( - @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.latencyHistogram(tenantId, effectiveHours))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/stats/latency") + public Mono>> latencyHistogram( + @RequestParam(value = "rangeHours", defaultValue = "24") int rangeHours, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.latencyHistogram(tenantId, effectiveHours))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/stats/activity") - public Mono>> hourlyActivity( - @RequestParam(value = "rangeHours", defaultValue = "168") int rangeHours, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.hourlyActivity(tenantId, effectiveHours))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/stats/activity") + public Mono>> hourlyActivity( + @RequestParam(value = "rangeHours", defaultValue = "168") int rangeHours, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveHours = resolveEffectiveHours(rangeKey, rangeHours); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.hourlyActivity(tenantId, effectiveHours))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * System-wide health snapshot for the home banner. Infra / center probes are - * platform-wide but driver / device fleet summaries are tenant-scoped, so we thread - * tenantId through to match the gRPC facades' tenant filter. - */ - @GetMapping("/system/health") - public Mono> systemHealth() { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(systemHealthService.snapshot(tenantId))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * System-wide health snapshot for the home banner. Infra / center probes are + * platform-wide but driver / device fleet summaries are tenant-scoped, so we thread + * tenantId through to match the gRPC facades' tenant filter. + */ + @GetMapping("/system/health") + public Mono> systemHealth() { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(systemHealthService.snapshot(tenantId))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @org.springframework.web.bind.annotation.PostMapping("/alert/page") - public Mono>> alertPage( - @org.springframework.web.bind.annotation.RequestBody( - required = false) io.github.pnoker.common.data.entity.query.AlertPageQuery query) { - return getTenantId().flatMap(tenantId -> { - try { - io.github.pnoker.common.data.entity.query.AlertPageQuery q = query == null - ? new io.github.pnoker.common.data.entity.query.AlertPageQuery() : query; - java.time.LocalDateTime from = TimeRangeUtil.resolveFrom(q.getRangeKey(), q.getRangeHours()); - long current = q.getCurrent() == null ? 1L : q.getCurrent(); - long size = q.getSize() == null ? 20L : q.getSize(); - return Mono.just(R.ok(dashboardService.alertPage(tenantId, q.getSource(), q.getEventTypeFlag(), - q.getConfirmFlag(), from, current, size))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @org.springframework.web.bind.annotation.PostMapping("/alert/page") + public Mono>> alertPage( + @org.springframework.web.bind.annotation.RequestBody( + required = false) io.github.pnoker.common.data.entity.query.AlertPageQuery query) { + return getTenantId().flatMap(tenantId -> { + try { + io.github.pnoker.common.data.entity.query.AlertPageQuery q = query == null + ? new io.github.pnoker.common.data.entity.query.AlertPageQuery() : query; + java.time.LocalDateTime from = TimeRangeUtil.resolveFrom(q.getRangeKey(), q.getRangeHours()); + long current = q.getCurrent() == null ? 1L : q.getCurrent(); + long size = q.getSize() == null ? 20L : q.getSize(); + return Mono.just(R.ok(dashboardService.alertPage(tenantId, q.getSource(), q.getEventTypeFlag(), + q.getConfirmFlag(), from, current, size))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @org.springframework.web.bind.annotation.PostMapping("/alert/confirm/{source}/{id}") - public Mono> alertConfirm(@org.springframework.web.bind.annotation.PathVariable String source, - @org.springframework.web.bind.annotation.PathVariable Long id) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.confirmAlert(tenantId, source, id))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @org.springframework.web.bind.annotation.PostMapping("/alert/confirm/{source}/{id}") + public Mono> alertConfirm(@org.springframework.web.bind.annotation.PathVariable String source, + @org.springframework.web.bind.annotation.PathVariable Long id) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.confirmAlert(tenantId, source, id))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @org.springframework.web.bind.annotation.PostMapping("/alert/unconfirm/{source}/{id}") - public Mono> alertUnconfirm(@org.springframework.web.bind.annotation.PathVariable String source, - @org.springframework.web.bind.annotation.PathVariable Long id) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.unconfirmAlert(tenantId, source, id))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @org.springframework.web.bind.annotation.PostMapping("/alert/unconfirm/{source}/{id}") + public Mono> alertUnconfirm(@org.springframework.web.bind.annotation.PathVariable String source, + @org.springframework.web.bind.annotation.PathVariable Long id) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.unconfirmAlert(tenantId, source, id))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Bulk confirm or unconfirm. Body = { confirm: true|false, items: [{source, id}, ...] - * }. Returns the number of rows actually changed. - */ - @org.springframework.web.bind.annotation.PostMapping("/alert/bulk-confirm") - public Mono> alertBulkConfirm( - @org.springframework.web.bind.annotation.RequestBody Map body) { - return getTenantId().flatMap(tenantId -> { - try { - @SuppressWarnings("unchecked") - List> items = (List>) body.getOrDefault("items", - java.util.Collections.emptyList()); - boolean confirm = body.get("confirm") == null || Boolean.parseBoolean(body.get("confirm").toString()); - return Mono.just(R.ok(dashboardService.bulkConfirmAlert(tenantId, items, confirm))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Bulk confirm or unconfirm. Body = { confirm: true|false, items: [{source, id}, ...] + * }. Returns the number of rows actually changed. + */ + @org.springframework.web.bind.annotation.PostMapping("/alert/bulk-confirm") + public Mono> alertBulkConfirm( + @org.springframework.web.bind.annotation.RequestBody Map body) { + return getTenantId().flatMap(tenantId -> { + try { + @SuppressWarnings("unchecked") + List> items = (List>) body.getOrDefault("items", + java.util.Collections.emptyList()); + boolean confirm = body.get("confirm") == null || Boolean.parseBoolean(body.get("confirm").toString()); + return Mono.just(R.ok(dashboardService.bulkConfirmAlert(tenantId, items, confirm))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/trend") - public Mono>> alertTrend(@RequestParam(value = "days", defaultValue = "30") int days, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveDays = resolveEffectiveDays(rangeKey, days); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertTrend(tenantId, effectiveDays))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/trend") + public Mono>> alertTrend(@RequestParam(value = "days", defaultValue = "30") int days, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveDays = resolveEffectiveDays(rangeKey, days); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertTrend(tenantId, effectiveDays))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/top-sources") - public Mono>> alertTopSources(@RequestParam(value = "days", defaultValue = "30") int days, - @RequestParam(value = "rangeKey", required = false) String rangeKey, - @RequestParam(value = "limit", defaultValue = "10") int limit) { - int effectiveDays = resolveEffectiveDays(rangeKey, days); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertTopSources(tenantId, effectiveDays, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/top-sources") + public Mono>> alertTopSources(@RequestParam(value = "days", defaultValue = "30") int days, + @RequestParam(value = "rangeKey", required = false) String rangeKey, + @RequestParam(value = "limit", defaultValue = "10") int limit) { + int effectiveDays = resolveEffectiveDays(rangeKey, days); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertTopSources(tenantId, effectiveDays, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Resolve the UI's {@code rangeKey} (preferred) against the legacy {@code rangeHours} - * integer. {@code TODAY} is mapped to the hours elapsed since local midnight so - * bucketed queries cover the full day so far; other keys use the canonical 24 / 168 / - * 720 hour spans. - */ - private int resolveEffectiveHours(String rangeKey, int rangeHours) { - Integer resolved = TimeRangeUtil.resolveHours(rangeKey, rangeHours); - return resolved != null ? resolved : rangeHours; - } + /** + * Resolve the UI's {@code rangeKey} (preferred) against the legacy {@code rangeHours} + * integer. {@code TODAY} is mapped to the hours elapsed since local midnight so + * bucketed queries cover the full day so far; other keys use the canonical 24 / 168 / + * 720 hour spans. + */ + private int resolveEffectiveHours(String rangeKey, int rangeHours) { + Integer resolved = TimeRangeUtil.resolveHours(rangeKey, rangeHours); + return resolved != null ? resolved : rangeHours; + } - /** - * Resolve the UI's {@code rangeKey} against the legacy {@code days} integer for - * day-bucketed endpoints. {@code TODAY} / {@code H24} both collapse to 1 day. - */ - private int resolveEffectiveDays(String rangeKey, int days) { - Integer resolved = TimeRangeUtil.resolveDays(rangeKey, days); - return resolved != null ? resolved : days; - } + /** + * Resolve the UI's {@code rangeKey} against the legacy {@code days} integer for + * day-bucketed endpoints. {@code TODAY} / {@code H24} both collapse to 1 day. + */ + private int resolveEffectiveDays(String rangeKey, int days) { + Integer resolved = TimeRangeUtil.resolveDays(rangeKey, days); + return resolved != null ? resolved : days; + } - @GetMapping("/alert/activity") - public Mono>> alertActivity(@RequestParam(value = "days", defaultValue = "7") int days, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveDays = resolveEffectiveDays(rangeKey, days); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertActivity(tenantId, effectiveDays))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/activity") + public Mono>> alertActivity(@RequestParam(value = "days", defaultValue = "7") int days, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveDays = resolveEffectiveDays(rangeKey, days); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertActivity(tenantId, effectiveDays))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/type-distribution") - public Mono>> alertTypeDistribution( - @RequestParam(value = "days", defaultValue = "30") int days, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - int effectiveDays = resolveEffectiveDays(rangeKey, days); - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertTypeDistribution(tenantId, effectiveDays))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/type-distribution") + public Mono>> alertTypeDistribution( + @RequestParam(value = "days", defaultValue = "30") int days, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + int effectiveDays = resolveEffectiveDays(rangeKey, days); + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertTypeDistribution(tenantId, effectiveDays))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/storm-sources") - public Mono>> alertStormSources( - @RequestParam(value = "hours", defaultValue = "1") int hours, - @RequestParam(value = "minCount", defaultValue = "10") int minCount, - @RequestParam(value = "limit", defaultValue = "10") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertStormSources(tenantId, hours, minCount, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/storm-sources") + public Mono>> alertStormSources( + @RequestParam(value = "hours", defaultValue = "1") int hours, + @RequestParam(value = "minCount", defaultValue = "10") int minCount, + @RequestParam(value = "limit", defaultValue = "10") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertStormSources(tenantId, hours, minCount, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - // ===== Phase-2 insights ===================================================== + // ===== Phase-2 insights ===================================================== - @GetMapping("/alert/flapping") - public Mono>> alertFlapping(@RequestParam(value = "hours", defaultValue = "6") int hours, - @RequestParam(value = "minCount", defaultValue = "5") int minCount, - @RequestParam(value = "limit", defaultValue = "20") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertFlapping(tenantId, hours, minCount, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/flapping") + public Mono>> alertFlapping(@RequestParam(value = "hours", defaultValue = "6") int hours, + @RequestParam(value = "minCount", defaultValue = "5") int minCount, + @RequestParam(value = "limit", defaultValue = "20") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertFlapping(tenantId, hours, minCount, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/correlation") - public Mono>> alertCorrelation( - @RequestParam(value = "hours", defaultValue = "24") int hours, - @RequestParam(value = "windowSec", defaultValue = "30") int windowSec, - @RequestParam(value = "limit", defaultValue = "15") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertCorrelation(tenantId, hours, windowSec, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/correlation") + public Mono>> alertCorrelation( + @RequestParam(value = "hours", defaultValue = "24") int hours, + @RequestParam(value = "windowSec", defaultValue = "30") int windowSec, + @RequestParam(value = "limit", defaultValue = "15") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertCorrelation(tenantId, hours, windowSec, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/peer-deviation") - public Mono>> alertPeerDeviation( - @RequestParam(value = "days", defaultValue = "7") int days) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertPeerDeviation(tenantId, days))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/peer-deviation") + public Mono>> alertPeerDeviation( + @RequestParam(value = "days", defaultValue = "7") int days) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertPeerDeviation(tenantId, days))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/aging") - public Mono> alertAging() { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertAgingBacklog(tenantId))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/aging") + public Mono> alertAging() { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertAgingBacklog(tenantId))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/mtta") - public Mono>> alertMtta(@RequestParam(value = "days", defaultValue = "30") int days) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.alertMtta(tenantId, days))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/mtta") + public Mono>> alertMtta(@RequestParam(value = "days", defaultValue = "30") int days) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.alertMtta(tenantId, days))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/protocol/health") - public Mono>> protocolHealth() { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.protocolHealth(tenantId))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/protocol/health") + public Mono>> protocolHealth() { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.protocolHealth(tenantId))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/alert/change-impact") - public Mono>> changeImpact(@RequestParam(value = "days", defaultValue = "30") int days, - @RequestParam(value = "limit", defaultValue = "30") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.changeImpact(tenantId, days, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/alert/change-impact") + public Mono>> changeImpact(@RequestParam(value = "days", defaultValue = "30") int days, + @RequestParam(value = "limit", defaultValue = "30") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.changeImpact(tenantId, days, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/silent/sources") - public Mono>> silentSources( - @RequestParam(value = "baselineDays", defaultValue = "7") int baselineDays, - @RequestParam(value = "silentMinutes", defaultValue = "15") int silentMinutes, - @RequestParam(value = "limit", defaultValue = "50") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.silentSources(tenantId, baselineDays, silentMinutes, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/silent/sources") + public Mono>> silentSources( + @RequestParam(value = "baselineDays", defaultValue = "7") int baselineDays, + @RequestParam(value = "silentMinutes", defaultValue = "15") int silentMinutes, + @RequestParam(value = "limit", defaultValue = "50") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.silentSources(tenantId, baselineDays, silentMinutes, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/coverage/gap") - public Mono> coverageGap(@RequestParam(value = "limit", defaultValue = "100") int limit) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.coverageGap(tenantId, limit))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/coverage/gap") + public Mono> coverageGap(@RequestParam(value = "limit", defaultValue = "100") int limit) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.coverageGap(tenantId, limit))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DeviceStatusController.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DeviceStatusController.java index 10c76c18b..6ba1722b1 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DeviceStatusController.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DeviceStatusController.java @@ -42,68 +42,68 @@ import java.util.Objects; @RequestMapping(DataConstant.DEVICE_STATUS_URL_PREFIX) public class DeviceStatusController implements BaseController { - private final DeviceStatusService deviceStatusService; + private final DeviceStatusService deviceStatusService; - public DeviceStatusController(DeviceStatusService deviceStatusService) { - this.deviceStatusService = deviceStatusService; - } + public DeviceStatusController(DeviceStatusService deviceStatusService) { + this.deviceStatusService = deviceStatusService; + } - /** - * Query device statuses ONLINE, OFFLINE, MAINTAIN, FAULT - * @param deviceQuery Device Dto - * @return Map String:String - */ - @PostMapping("/device") - public Mono>> deviceStatus(@RequestBody(required = false) DeviceQuery deviceQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DeviceQuery query = Objects.isNull(deviceQuery) ? new DeviceQuery() : deviceQuery; - query.setTenantId(tenantId); - Map statuses = deviceStatusService.selectByPage(query); - return Mono.just(R.ok(statuses)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Query device statuses ONLINE, OFFLINE, MAINTAIN, FAULT + * + * @param deviceQuery Device Dto + * @return Map String:String + */ + @PostMapping("/device") + public Mono>> deviceStatus(@RequestBody(required = false) DeviceQuery deviceQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DeviceQuery query = Objects.isNull(deviceQuery) ? new DeviceQuery() : deviceQuery; + query.setTenantId(tenantId); + Map statuses = deviceStatusService.selectByPage(query); + return Mono.just(R.ok(statuses)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Query device statuses by driver ID ONLINE, OFFLINE, MAINTAIN, FAULT - * @param driverId Driver ID - * @return Map String:String - */ - @GetMapping("/device/driver_id/{driverId}") - public Mono>> deviceStatusByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - DeviceQuery deviceQuery = new DeviceQuery(); - deviceQuery.setDriverId(driverId); - Map statuses = deviceStatusService.selectByPage(deviceQuery); - return Mono.just(R.ok(statuses)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Query device statuses by driver ID ONLINE, OFFLINE, MAINTAIN, FAULT + * + * @param driverId Driver ID + * @return Map String:String + */ + @GetMapping("/device/driver_id/{driverId}") + public Mono>> deviceStatusByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + DeviceQuery deviceQuery = new DeviceQuery(); + deviceQuery.setDriverId(driverId); + Map statuses = deviceStatusService.selectByPage(deviceQuery); + return Mono.just(R.ok(statuses)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Query device statuses by profile ID ONLINE, OFFLINE, MAINTAIN, FAULT - * @param profileId Profile ID - * @return Map String:String - */ - @GetMapping("/device/profile_id/{profileId}") - public Mono>> deviceStatusByProfileId( - @NotNull @PathVariable(value = "profileId") Long profileId) { - try { - Map statuses = deviceStatusService.selectByProfileId(profileId); - return Mono.just(R.ok(statuses)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Query device statuses by profile ID ONLINE, OFFLINE, MAINTAIN, FAULT + * + * @param profileId Profile ID + * @return Map String:String + */ + @GetMapping("/device/profile_id/{profileId}") + public Mono>> deviceStatusByProfileId( + @NotNull @PathVariable(value = "profileId") Long profileId) { + try { + Map statuses = deviceStatusService.selectByProfileId(profileId); + return Mono.just(R.ok(statuses)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DriverStatusController.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DriverStatusController.java index 1ea98dd27..3fa56672e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DriverStatusController.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/DriverStatusController.java @@ -42,65 +42,65 @@ import java.util.Objects; @RequestMapping(DataConstant.DRIVER_STATUS_URL_PREFIX) public class DriverStatusController implements BaseController { - private final DriverStatusService driverStatusService; + private final DriverStatusService driverStatusService; - public DriverStatusController(DriverStatusService driverStatusService) { - this.driverStatusService = driverStatusService; - } + public DriverStatusController(DriverStatusService driverStatusService) { + this.driverStatusService = driverStatusService; + } - /** - * Query driver statuses ONLINE, OFFLINE - * @param entityQuery Driver and pagination parameters - * @return Map String:String - */ - @PostMapping("/driver") - public Mono>> driverStatus(@RequestBody(required = false) DriverQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DriverQuery query = Objects.isNull(entityQuery) ? new DriverQuery() : entityQuery; - query.setTenantId(tenantId); - Map statuses = driverStatusService.selectByPage(query); - return Mono.just(R.ok(statuses)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Query driver statuses ONLINE, OFFLINE + * + * @param entityQuery Driver and pagination parameters + * @return Map String:String + */ + @PostMapping("/driver") + public Mono>> driverStatus(@RequestBody(required = false) DriverQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DriverQuery query = Objects.isNull(entityQuery) ? new DriverQuery() : entityQuery; + query.setTenantId(tenantId); + Map statuses = driverStatusService.selectByPage(query); + return Mono.just(R.ok(statuses)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Query the number of devices currently online under the Driver - * @param driverId Driver ID - * @return Number of devices currently online - */ - @GetMapping("/getDeviceOnlineByDriverId/{driverId}") - public Mono> getDeviceOnlineByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - String result = driverStatusService.getDeviceOnlineByDriverId(driverId); - return Mono.just(R.ok(result)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Query the number of devices currently online under the Driver + * + * @param driverId Driver ID + * @return Number of devices currently online + */ + @GetMapping("/getDeviceOnlineByDriverId/{driverId}") + public Mono> getDeviceOnlineByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + String result = driverStatusService.getDeviceOnlineByDriverId(driverId); + return Mono.just(R.ok(result)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Query the number of devices currently offline under the Driver - * @param driverId Driver ID - * @return Number of devices currently offline - */ - @GetMapping("/getDeviceOfflineByDriverId/{driverId}") - public Mono> getDeviceOfflineByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - String result = driverStatusService.getDeviceOfflineByDriverId(driverId); - return Mono.just(R.ok(result)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Query the number of devices currently offline under the Driver + * + * @param driverId Driver ID + * @return Number of devices currently offline + */ + @GetMapping("/getDeviceOfflineByDriverId/{driverId}") + public Mono> getDeviceOfflineByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + String result = driverStatusService.getDeviceOfflineByDriverId(driverId); + return Mono.just(R.ok(result)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueCommandController.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueCommandController.java index 72d03fe9b..a999a4a41 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueCommandController.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueCommandController.java @@ -43,44 +43,44 @@ import reactor.core.publisher.Mono; @RequestMapping(DataConstant.POINT_VALUE_COMMAND_URL_PREFIX) public class PointValueCommandController implements BaseController { - private final PointValueCommandService pointValueCommandService; + private final PointValueCommandService pointValueCommandService; - public PointValueCommandController(PointValueCommandService pointValueCommandService) { - this.pointValueCommandService = pointValueCommandService; - } + public PointValueCommandController(PointValueCommandService pointValueCommandService) { + this.pointValueCommandService = pointValueCommandService; + } - /** - * Read instruction - * @param entityVO PointValueReadVO - * @return PointValue - */ - @PostMapping("/read") - public Mono> read(@Validated @RequestBody PointValueReadVO entityVO) { - try { - pointValueCommandService.read(entityVO); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - return Mono.just(R.ok()); - } + /** + * Read instruction + * + * @param entityVO PointValueReadVO + * @return PointValue + */ + @PostMapping("/read") + public Mono> read(@Validated @RequestBody PointValueReadVO entityVO) { + try { + pointValueCommandService.read(entityVO); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + return Mono.just(R.ok()); + } - /** - * Write instruction - * @param entityVO PointValueWriteVO - * @return PointValue - */ - @PostMapping("/write") - public Mono> write(@Validated @RequestBody PointValueWriteVO entityVO) { - try { - pointValueCommandService.write(entityVO); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - return Mono.just(R.ok()); - } + /** + * Write instruction + * + * @param entityVO PointValueWriteVO + * @return PointValue + */ + @PostMapping("/write") + public Mono> write(@Validated @RequestBody PointValueWriteVO entityVO) { + try { + pointValueCommandService.write(entityVO); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + return Mono.just(R.ok()); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueController.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueController.java index 42a3b1dc3..1e09915ac 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueController.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/controller/PointValueController.java @@ -46,81 +46,81 @@ import java.util.Objects; @RequestMapping(DataConstant.POINT_VALUE_URL_PREFIX) public class PointValueController implements BaseController { - private final PointValueBuilder pointValueBuilder; + private final PointValueBuilder pointValueBuilder; - private final PointValueService pointValueService; + private final PointValueService pointValueService; - public PointValueController(PointValueBuilder pointValueBuilder, PointValueService pointValueService) { - this.pointValueBuilder = pointValueBuilder; - this.pointValueService = pointValueService; - } + public PointValueController(PointValueBuilder pointValueBuilder, PointValueService pointValueService) { + this.pointValueBuilder = pointValueBuilder; + this.pointValueService = pointValueService; + } - /** - * Query the latest PointValue for each point in the device - * @param entityQuery PointValueQuery, including pagination parameters - * @return Page of PointValueVO, where each PointValueVO contains the latest value for - * a point in the device - */ - @PostMapping("/latest") - public Mono>> latest(@RequestBody PointValueQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - PointValueQuery query = Objects.isNull(entityQuery) ? new PointValueQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = pointValueService.latest(query); - Page entityPageVO = pointValueBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Query the latest PointValue for each point in the device + * + * @param entityQuery PointValueQuery, including pagination parameters + * @return Page of PointValueVO, where each PointValueVO contains the latest value for + * a point in the device + */ + @PostMapping("/latest") + public Mono>> latest(@RequestBody PointValueQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + PointValueQuery query = Objects.isNull(entityQuery) ? new PointValueQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = pointValueService.latest(query); + Page entityPageVO = pointValueBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Query the historical PointValue for each point in the device - * @param entityQuery PointValueQuery, including pagination parameters - * @return Page of PointValueVO, where each PointValueVO contains the historical value - * for a point in the device - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) PointValueQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - PointValueQuery query = Objects.isNull(entityQuery) ? new PointValueQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = pointValueService.page(query); - Page entityPageVO = pointValueBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Query the historical PointValue for each point in the device + * + * @param entityQuery PointValueQuery, including pagination parameters + * @return Page of PointValueVO, where each PointValueVO contains the historical value + * for a point in the device + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) PointValueQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + PointValueQuery query = Objects.isNull(entityQuery) ? new PointValueQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = pointValueService.page(query); + Page entityPageVO = pointValueBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Query the historical PointValue for a specific point in the device - * @param deviceId Device ID - * @param pointId Point ID - * @return List of String, where each String is the historical value for the point - */ - @GetMapping("/history/device_id/{deviceId}/point_id/{pointId}") - public Mono>> history(@NotNull @PathVariable(name = "deviceId") Long deviceId, - @NotNull @PathVariable(name = "pointId") Long pointId, - @RequestParam(name = "count", required = false, defaultValue = "100") Integer count) { - return getTenantId().flatMap(tenantId -> { - try { - List history = pointValueService.history(tenantId, deviceId, pointId, count); - return Mono.just(R.ok(history)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Query the historical PointValue for a specific point in the device + * + * @param deviceId Device ID + * @param pointId Point ID + * @return List of String, where each String is the historical value for the point + */ + @GetMapping("/history/device_id/{deviceId}/point_id/{pointId}") + public Mono>> history(@NotNull @PathVariable(name = "deviceId") Long deviceId, + @NotNull @PathVariable(name = "pointId") Long pointId, + @RequestParam(name = "count", required = false, defaultValue = "100") Integer count) { + return getTenantId().flatMap(tenantId -> { + try { + List history = pointValueService.history(tenantId, deviceId, pointId, count); + return Mono.just(R.ok(history)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DeviceEventManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DeviceEventManagerImpl.java index 481044d0b..b44410fa6 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DeviceEventManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DeviceEventManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class DeviceEventManagerImpl extends ServiceImpl - implements DeviceEventManager { + implements DeviceEventManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DriverEventManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DriverEventManagerImpl.java index e32db5460..5bbd9ffcc 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DriverEventManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/DriverEventManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class DriverEventManagerImpl extends ServiceImpl - implements DriverEventManager { + implements DriverEventManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueBoolManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueBoolManagerImpl.java index 0c6610310..86d012c01 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueBoolManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueBoolManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueBoolManagerImpl extends ServiceImpl - implements PointValueBoolManager { + implements PointValueBoolManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueDoubleManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueDoubleManagerImpl.java index 18291232a..04cd4d723 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueDoubleManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueDoubleManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueDoubleManagerImpl extends ServiceImpl - implements PointValueDoubleManager { + implements PointValueDoubleManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueFloatManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueFloatManagerImpl.java index c7675e5d7..730bb62ab 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueFloatManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueFloatManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueFloatManagerImpl extends ServiceImpl - implements PointValueFloatManager { + implements PointValueFloatManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueIntManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueIntManagerImpl.java index 69f99b46b..fa05b33bc 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueIntManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueIntManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueIntManagerImpl extends ServiceImpl - implements PointValueIntManager { + implements PointValueIntManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueJsonManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueJsonManagerImpl.java index b5eca4dcc..78eccb553 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueJsonManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueJsonManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueJsonManagerImpl extends ServiceImpl - implements PointValueJsonManager { + implements PointValueJsonManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueLongManagerImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueLongManagerImpl.java index c54294b8d..4e3d9a213 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueLongManagerImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/dal/impl/PointValueLongManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointValueLongManagerImpl extends ServiceImpl - implements PointValueLongManager { + implements PointValueLongManager { } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/MessageBO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/MessageBO.java index cd144bd11..e2d05c0d9 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/MessageBO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/MessageBO.java @@ -39,34 +39,34 @@ import lombok.*; @ToString(callSuper = true) public class MessageBO extends BaseBO { - /** - * Alarm message template title - */ - private String messageName; + /** + * Alarm message template title + */ + private String messageName; - /** - * Alarm message template code - */ - private String messageCode; + /** + * Alarm message template code + */ + private String messageCode; - /** - * Alarm message template level - */ - private AlarmMessageLevelFlagEnum messageLevel; + /** + * Alarm message template level + */ + private AlarmMessageLevelFlagEnum messageLevel; - /** - * Alarm message template content - */ - private MessageExt messageExt; + /** + * Alarm message template content + */ + private MessageExt messageExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/NotifyBO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/NotifyBO.java index 7e5238187..04bd6dde5 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/NotifyBO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/NotifyBO.java @@ -39,39 +39,39 @@ import lombok.*; @ToString(callSuper = true) public class NotifyBO extends BaseBO { - /** - * Alarm notification template name - */ - private String notifyName; + /** + * Alarm notification template name + */ + private String notifyName; - /** - * Alarm notification template code - */ - private String notifyCode; + /** + * Alarm notification template code + */ + private String notifyCode; - /** - * Auto confirm flag - */ - private AutoConfirmFlagEnum autoConfirmFlag; + /** + * Auto confirm flag + */ + private AutoConfirmFlagEnum autoConfirmFlag; - /** - * Alarm notification interval, milliseconds - */ - private Long notifyInterval; + /** + * Alarm notification interval, milliseconds + */ + private Long notifyInterval; - /** - * Alarm notification template configuration - */ - private NotifyExt notifyExt; + /** + * Alarm notification template configuration + */ + private NotifyExt notifyExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/RuleBO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/RuleBO.java index 130e4b3a4..e64ea6230 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/RuleBO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/RuleBO.java @@ -39,49 +39,49 @@ import lombok.*; @ToString(callSuper = true) public class RuleBO extends BaseBO { - /** - * Entity type flag - */ - private AlarmTypeFlagEnum entityTypeFlag; + /** + * Entity type flag + */ + private AlarmTypeFlagEnum entityTypeFlag; - /** - * Rule name - */ - private String ruleName; + /** + * Rule name + */ + private String ruleName; - /** - * Rule code - */ - private String ruleCode; + /** + * Rule code + */ + private String ruleCode; - /** - * Entity ID - */ - private Long entityId; + /** + * Entity ID + */ + private Long entityId; - /** - * Alarm notification template ID - */ - private Long notifyId; + /** + * Alarm notification template ID + */ + private Long notifyId; - /** - * Alarm message template ID - */ - private Long messageId; + /** + * Alarm message template ID + */ + private Long messageId; - /** - * Alarm rule - */ - private RuleExt ruleExt; + /** + * Alarm rule + */ + private RuleExt ruleExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ActivityCellRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ActivityCellRow.java index a1c5d729c..5aff653d6 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ActivityCellRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ActivityCellRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class ActivityCellRow { - private int dow; + private int dow; - private int hour; + private int hour; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AgingBucketRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AgingBucketRow.java index 88a23e33a..3d91debfb 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AgingBucketRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AgingBucketRow.java @@ -29,14 +29,14 @@ import lombok.ToString; @ToString public class AgingBucketRow { - private long under1h; + private long under1h; - private long h1to6; + private long h1to6; - private long h6to24; + private long h6to24; - private long over24h; + private long over24h; - private long total; + private long total; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertCountersRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertCountersRow.java index 8b1a9ad6b..b5e2e28c3 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertCountersRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertCountersRow.java @@ -30,8 +30,8 @@ import lombok.ToString; @ToString public class AlertCountersRow { - private long total; + private long total; - private long unconfirmed; + private long unconfirmed; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertItemRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertItemRow.java index e454d4a3b..44eb6726e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertItemRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertItemRow.java @@ -31,20 +31,20 @@ import java.time.LocalDateTime; @ToString public class AlertItemRow { - private long id; + private long id; - private String source; + private String source; - private long sourceId; + private long sourceId; - private long pointId; + private long pointId; - private int eventTypeFlag; + private int eventTypeFlag; - private int confirmFlag; + private int confirmFlag; - private LocalDateTime createTime; + private LocalDateTime createTime; - private String message; + private String message; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertTrendRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertTrendRow.java index 3b765b9b1..619fff7f5 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertTrendRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/AlertTrendRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class AlertTrendRow { - private String date; + private String date; - private long deviceCount; + private long deviceCount; - private long driverCount; + private long driverCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/BucketRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/BucketRow.java index 485dae304..cf80748c7 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/BucketRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/BucketRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class BucketRow { - private Object key; + private Object key; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CorrelationPairRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CorrelationPairRow.java index e4e50f038..69e913f49 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CorrelationPairRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CorrelationPairRow.java @@ -29,18 +29,18 @@ import lombok.ToString; @ToString public class CorrelationPairRow { - private String aSource; + private String aSource; - private long aSourceId; + private long aSourceId; - private int aEventType; + private int aEventType; - private String bSource; + private String bSource; - private long bSourceId; + private long bSourceId; - private int bEventType; + private int bEventType; - private long coCount; + private long coCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CoverageGapRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CoverageGapRow.java index 13c82d688..2289bac43 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CoverageGapRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/CoverageGapRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class CoverageGapRow { - private long pointId; + private long pointId; - private long profileId; + private long profileId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/EntityCountRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/EntityCountRow.java index 9676c68a1..629930e0b 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/EntityCountRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/EntityCountRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class EntityCountRow { - private long entityId; + private long entityId; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/FlappingRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/FlappingRow.java index d5bedb9ff..51d5ab435 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/FlappingRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/FlappingRow.java @@ -29,12 +29,12 @@ import lombok.ToString; @ToString public class FlappingRow { - private String source; + private String source; - private long sourceId; + private long sourceId; - private int eventTypeFlag; + private int eventTypeFlag; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/HourCountRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/HourCountRow.java index bfa5e3a5c..ad424267d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/HourCountRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/HourCountRow.java @@ -32,8 +32,8 @@ import java.time.LocalDateTime; @ToString public class HourCountRow { - private LocalDateTime bucket; + private LocalDateTime bucket; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatencyBinRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatencyBinRow.java index 2b56d6b18..64ac6e022 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatencyBinRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatencyBinRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class LatencyBinRow { - private int bin; + private int bin; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatestPointValueRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatestPointValueRow.java index c644a4d40..fd21fa156 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatestPointValueRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/LatestPointValueRow.java @@ -32,20 +32,20 @@ import java.time.LocalDateTime; @ToString public class LatestPointValueRow { - private long tenantId; + private long tenantId; - private long deviceId; + private long deviceId; - private long pointId; + private long pointId; - private long driverId; + private long driverId; - private LocalDateTime createTime; + private LocalDateTime createTime; - private String rawValue; + private String rawValue; - private String calValue; + private String calValue; - private String valueType; + private String valueType; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/MttaTrendRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/MttaTrendRow.java index c14ecb716..e6ac674aa 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/MttaTrendRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/MttaTrendRow.java @@ -29,12 +29,12 @@ import lombok.ToString; @ToString public class MttaTrendRow { - private String date; + private String date; - private long p50Ms; + private long p50Ms; - private long p95Ms; + private long p95Ms; - private long confirmedCount; + private long confirmedCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/PeerAlarmRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/PeerAlarmRow.java index 78ffeee2d..01af64533 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/PeerAlarmRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/PeerAlarmRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class PeerAlarmRow { - private long profileId; + private long profileId; - private long deviceId; + private long deviceId; - private long alarmCount; + private long alarmCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ProtocolHealthRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ProtocolHealthRow.java index 8035b17ff..f92e199d8 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ProtocolHealthRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/ProtocolHealthRow.java @@ -29,12 +29,12 @@ import lombok.ToString; @ToString public class ProtocolHealthRow { - private String serviceName; + private String serviceName; - private long driverCount; + private long driverCount; - private long enabledCount; + private long enabledCount; - private long deviceCount; + private long deviceCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/RecentChangeRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/RecentChangeRow.java index 9426013ba..389139bee 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/RecentChangeRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/RecentChangeRow.java @@ -31,10 +31,10 @@ import java.time.LocalDateTime; @ToString public class RecentChangeRow { - private String kind; + private String kind; - private long entityId; + private long entityId; - private LocalDateTime operateTime; + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SilentSourceRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SilentSourceRow.java index 73f81019c..6e9c8c95f 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SilentSourceRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SilentSourceRow.java @@ -31,10 +31,10 @@ import java.time.LocalDateTime; @ToString public class SilentSourceRow { - private long deviceId; + private long deviceId; - private long pointId; + private long pointId; - private LocalDateTime lastSeen; + private LocalDateTime lastSeen; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceCountRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceCountRow.java index 923b73e48..d2a04caee 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceCountRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceCountRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class SourceCountRow { - private String source; + private String source; - private long sourceId; + private long sourceId; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceStatsRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceStatsRow.java index 658868f8c..d517eab54 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceStatsRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/SourceStatsRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class SourceStatsRow { - private String source; + private String source; - private long total; + private long total; - private long unconfirmed; + private long unconfirmed; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/TimeBucketRow.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/TimeBucketRow.java index 02768cef0..9e4b6cc47 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/TimeBucketRow.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/bo/dashboard/TimeBucketRow.java @@ -33,8 +33,8 @@ import java.time.LocalDateTime; @ToString public class TimeBucketRow { - private LocalDateTime bucket; + private LocalDateTime bucket; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/MessageBuilder.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/MessageBuilder.java index da2b10693..b542983a2 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/MessageBuilder.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/MessageBuilder.java @@ -45,146 +45,156 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface MessageBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - MessageBO buildBOByVO(MessageVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + MessageBO buildBOByVO(MessageVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "messageExt", ignore = true) - @Mapping(target = "messageLevel", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - MessageDO buildDOByBO(MessageBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "messageExt", ignore = true) + @Mapping(target = "messageLevel", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + MessageDO buildDOByBO(MessageBO entityBO); - @AfterMapping - default void afterProcess(MessageBO entityBO, @MappingTarget MessageDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getMessageCode())) { - entityDO.setMessageCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(MessageBO entityBO, @MappingTarget MessageDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getMessageCode())) { + entityDO.setMessageCode(CodeUtil.getCode()); + } - // Json Ext - MessageExt entityExt = entityBO.getMessageExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setMessageExt(ext); + // Json Ext + MessageExt entityExt = entityBO.getMessageExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setMessageExt(ext); - // AlarmMessageLevel Flag - AlarmMessageLevelFlagEnum alarmMessageLevel = entityBO.getMessageLevel(); - Optional.ofNullable(alarmMessageLevel).ifPresent(value -> entityDO.setMessageLevel(value.getIndex())); + // AlarmMessageLevel Flag + AlarmMessageLevelFlagEnum alarmMessageLevel = entityBO.getMessageLevel(); + Optional.ofNullable(alarmMessageLevel).ifPresent(value -> entityDO.setMessageLevel(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "messageExt", ignore = true) - @Mapping(target = "messageLevel", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - MessageBO buildBOByDO(MessageDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "messageExt", ignore = true) + @Mapping(target = "messageLevel", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + MessageBO buildBOByDO(MessageDO entityDO); - @AfterMapping - default void afterProcess(MessageDO entityDO, @MappingTarget MessageBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getMessageExt(); - if (Objects.nonNull(entityExt)) { - MessageExt ext = new MessageExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), MessageExt.Content.class)); - entityBO.setMessageExt(ext); - } + @AfterMapping + default void afterProcess(MessageDO entityDO, @MappingTarget MessageBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getMessageExt(); + if (Objects.nonNull(entityExt)) { + MessageExt ext = new MessageExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), MessageExt.Content.class)); + entityBO.setMessageExt(ext); + } - // AlarmMessageLevel Flag - Byte alarmMessageLevel = entityDO.getMessageLevel(); - entityBO.setMessageLevel(AlarmMessageLevelFlagEnum.ofIndex(alarmMessageLevel)); + // AlarmMessageLevel Flag + Byte alarmMessageLevel = entityDO.getMessageLevel(); + entityBO.setMessageLevel(AlarmMessageLevelFlagEnum.ofIndex(alarmMessageLevel)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - MessageVO buildVOByBO(MessageBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + MessageVO buildVOByBO(MessageBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/NotifyBuilder.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/NotifyBuilder.java index 9d326654a..4aea6eaad 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/NotifyBuilder.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/NotifyBuilder.java @@ -45,146 +45,156 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface NotifyBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - NotifyBO buildBOByVO(NotifyVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + NotifyBO buildBOByVO(NotifyVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "notifyExt", ignore = true) - @Mapping(target = "autoConfirmFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - NotifyDO buildDOByBO(NotifyBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "notifyExt", ignore = true) + @Mapping(target = "autoConfirmFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + NotifyDO buildDOByBO(NotifyBO entityBO); - @AfterMapping - default void afterProcess(NotifyBO entityBO, @MappingTarget NotifyDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getNotifyCode())) { - entityDO.setNotifyCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(NotifyBO entityBO, @MappingTarget NotifyDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getNotifyCode())) { + entityDO.setNotifyCode(CodeUtil.getCode()); + } - // Json Ext - NotifyExt entityExt = entityBO.getNotifyExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setNotifyExt(ext); + // Json Ext + NotifyExt entityExt = entityBO.getNotifyExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setNotifyExt(ext); - // AutoConfirm Flag - AutoConfirmFlagEnum autoConfirmFlag = entityBO.getAutoConfirmFlag(); - Optional.ofNullable(autoConfirmFlag).ifPresent(value -> entityDO.setAutoConfirmFlag(value.getIndex())); + // AutoConfirm Flag + AutoConfirmFlagEnum autoConfirmFlag = entityBO.getAutoConfirmFlag(); + Optional.ofNullable(autoConfirmFlag).ifPresent(value -> entityDO.setAutoConfirmFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "notifyExt", ignore = true) - @Mapping(target = "autoConfirmFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - NotifyBO buildBOByDO(NotifyDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "notifyExt", ignore = true) + @Mapping(target = "autoConfirmFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + NotifyBO buildBOByDO(NotifyDO entityDO); - @AfterMapping - default void afterProcess(NotifyDO entityDO, @MappingTarget NotifyBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getNotifyExt(); - if (Objects.nonNull(entityExt)) { - NotifyExt ext = new NotifyExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), NotifyExt.Content.class)); - entityBO.setNotifyExt(ext); - } + @AfterMapping + default void afterProcess(NotifyDO entityDO, @MappingTarget NotifyBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getNotifyExt(); + if (Objects.nonNull(entityExt)) { + NotifyExt ext = new NotifyExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), NotifyExt.Content.class)); + entityBO.setNotifyExt(ext); + } - // AutoConfirm Flag - Byte autoConfirmFlag = entityDO.getAutoConfirmFlag(); - entityBO.setAutoConfirmFlag(AutoConfirmFlagEnum.ofIndex(autoConfirmFlag)); + // AutoConfirm Flag + Byte autoConfirmFlag = entityDO.getAutoConfirmFlag(); + entityBO.setAutoConfirmFlag(AutoConfirmFlagEnum.ofIndex(autoConfirmFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - NotifyVO buildVOByBO(NotifyBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + NotifyVO buildVOByBO(NotifyBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/PointValueBuilder.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/PointValueBuilder.java index 781829018..c7189ed86 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/PointValueBuilder.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/PointValueBuilder.java @@ -34,89 +34,99 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface PointValueBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - PointValueBO buildBOByVO(PointValueVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + PointValueBO buildBOByVO(PointValueVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - PointValueDO buildDOByBO(PointValueBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + PointValueDO buildDOByBO(PointValueBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - PointValueBO buildBOByDO(PointValueDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + PointValueBO buildBOByDO(PointValueDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - PointValueVO buildVOByBO(PointValueBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + PointValueVO buildVOByBO(PointValueBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/RuleBuilder.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/RuleBuilder.java index 174bf33b3..d9120047e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/RuleBuilder.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/builder/RuleBuilder.java @@ -45,146 +45,156 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface RuleBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - RuleBO buildBOByVO(RuleVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + RuleBO buildBOByVO(RuleVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "ruleExt", ignore = true) - @Mapping(target = "entityTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - RuleDO buildDOByBO(RuleBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "ruleExt", ignore = true) + @Mapping(target = "entityTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + RuleDO buildDOByBO(RuleBO entityBO); - @AfterMapping - default void afterProcess(RuleBO entityBO, @MappingTarget RuleDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getRuleCode())) { - entityDO.setRuleCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(RuleBO entityBO, @MappingTarget RuleDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getRuleCode())) { + entityDO.setRuleCode(CodeUtil.getCode()); + } - // Json Ext - RuleExt entityExt = entityBO.getRuleExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setRuleExt(ext); + // Json Ext + RuleExt entityExt = entityBO.getRuleExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setRuleExt(ext); - // AlarmType Flag - AlarmTypeFlagEnum alarmTypeFlag = entityBO.getEntityTypeFlag(); - Optional.ofNullable(alarmTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); + // AlarmType Flag + AlarmTypeFlagEnum alarmTypeFlag = entityBO.getEntityTypeFlag(); + Optional.ofNullable(alarmTypeFlag).ifPresent(value -> entityDO.setEntityTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "ruleExt", ignore = true) - @Mapping(target = "entityTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - RuleBO buildBOByDO(RuleDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "ruleExt", ignore = true) + @Mapping(target = "entityTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + RuleBO buildBOByDO(RuleDO entityDO); - @AfterMapping - default void afterProcess(RuleDO entityDO, @MappingTarget RuleBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getRuleExt(); - if (Objects.nonNull(entityExt)) { - RuleExt ext = new RuleExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), RuleExt.Content.class)); - entityBO.setRuleExt(ext); - } + @AfterMapping + default void afterProcess(RuleDO entityDO, @MappingTarget RuleBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getRuleExt(); + if (Objects.nonNull(entityExt)) { + RuleExt ext = new RuleExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), RuleExt.Content.class)); + entityBO.setRuleExt(ext); + } - // AlarmType Flag - Byte alarmTypeFlag = entityDO.getEntityTypeFlag(); - entityBO.setEntityTypeFlag(AlarmTypeFlagEnum.ofIndex(alarmTypeFlag)); + // AlarmType Flag + Byte alarmTypeFlag = entityDO.getEntityTypeFlag(); + entityBO.setEntityTypeFlag(AlarmTypeFlagEnum.ofIndex(alarmTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - RuleVO buildVOByBO(RuleBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + RuleVO buildVOByBO(RuleBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DeviceEventDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DeviceEventDO.java index 540e4a1e3..4af1f813c 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DeviceEventDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DeviceEventDO.java @@ -43,74 +43,74 @@ import java.time.LocalDateTime; @TableName(value = "dc3_device_event", autoResultMap = true) public class DeviceEventDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Type - */ - @TableField("event_type_flag") - private Byte eventTypeFlag; + /** + * Type + */ + @TableField("event_type_flag") + private Byte eventTypeFlag; - /** - * - */ - @TableField(value = "event_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt eventExt; + /** + * + */ + @TableField(value = "event_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt eventExt; - /** - * , - */ - @TableField("expired_time") - private Long expiredTime; + /** + * , + */ + @TableField("expired_time") + private Long expiredTime; - /** - * , 0:, 1: - */ - @TableField("confirm_flag") - private Byte confirmFlag; + /** + * , 0:, 1: + */ + @TableField("confirm_flag") + private Byte confirmFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DriverEventDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DriverEventDO.java index a59430161..78d0fcc45 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DriverEventDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/DriverEventDO.java @@ -43,68 +43,68 @@ import java.time.LocalDateTime; @TableName(value = "dc3_driver_event", autoResultMap = true) public class DriverEventDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Type - */ - @TableField("event_type_flag") - private Byte eventTypeFlag; + /** + * Type + */ + @TableField("event_type_flag") + private Byte eventTypeFlag; - /** - * - */ - @TableField(value = "event_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt eventExt; + /** + * + */ + @TableField(value = "event_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt eventExt; - /** - * , - */ - @TableField("expired_time") - private Long expiredTime; + /** + * , + */ + @TableField("expired_time") + private Long expiredTime; - /** - * , 0:, 1: - */ - @TableField("confirm_flag") - private Byte confirmFlag; + /** + * , 0:, 1: + */ + @TableField("confirm_flag") + private Byte confirmFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/MessageDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/MessageDO.java index d1b3b6d4e..3536b71c5 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/MessageDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/MessageDO.java @@ -43,98 +43,98 @@ import java.time.LocalDateTime; @TableName(value = "dc3_message", autoResultMap = true) public class MessageDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("message_name") - private String messageName; + /** + * Name + */ + @TableField("message_name") + private String messageName; - /** - * Code - */ - @TableField("message_code") - private String messageCode; + /** + * Code + */ + @TableField("message_code") + private String messageCode; - /** - * - */ - @TableField("message_level") - private Byte messageLevel; + /** + * + */ + @TableField("message_level") + private Byte messageLevel; - /** - * - */ - @TableField(value = "message_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt messageExt; + /** + * + */ + @TableField(value = "message_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt messageExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/NotifyDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/NotifyDO.java index a6b7e5a60..f25e1a1ec 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/NotifyDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/NotifyDO.java @@ -43,104 +43,104 @@ import java.time.LocalDateTime; @TableName(value = "dc3_notify", autoResultMap = true) public class NotifyDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("notify_name") - private String notifyName; + /** + * Name + */ + @TableField("notify_name") + private String notifyName; - /** - * Code - */ - @TableField("notify_code") - private String notifyCode; + /** + * Code + */ + @TableField("notify_code") + private String notifyCode; - /** - * Auto confirm flag - */ - @TableField("auto_confirm_flag") - private Byte autoConfirmFlag; + /** + * Auto confirm flag + */ + @TableField("auto_confirm_flag") + private Byte autoConfirmFlag; - /** - * , - */ - @TableField("notify_interval") - private Long notifyInterval; + /** + * , + */ + @TableField("notify_interval") + private Long notifyInterval; - /** - * - */ - @TableField(value = "notify_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt notifyExt; + /** + * + */ + @TableField(value = "notify_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt notifyExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueBoolDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueBoolDO.java index b41a38b79..7fc44b6d5 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueBoolDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueBoolDO.java @@ -42,49 +42,49 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_bool") public class PointValueBoolDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Boolean rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Boolean rawValue; - /** - * - */ - @TableField("cal_value") - private Boolean calValue; + /** + * + */ + @TableField("cal_value") + private Boolean calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDO.java index 133e46681..aac0ef7c8 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDO.java @@ -42,55 +42,55 @@ import java.time.LocalDateTime; @TableName("dc3_point_value") public class PointValueDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private String rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private String rawValue; - /** - * - */ - @TableField("cal_value") - private String calValue; + /** + * + */ + @TableField("cal_value") + private String calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDoubleDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDoubleDO.java index 0709324e5..cfd0cfd9d 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDoubleDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueDoubleDO.java @@ -42,49 +42,49 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_double") public class PointValueDoubleDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Double rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Double rawValue; - /** - * - */ - @TableField("cal_value") - private Double calValue; + /** + * + */ + @TableField("cal_value") + private Double calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueFloatDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueFloatDO.java index e1bca9858..673cb9a7a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueFloatDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueFloatDO.java @@ -42,49 +42,49 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_float") public class PointValueFloatDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Double rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Double rawValue; - /** - * - */ - @TableField("cal_value") - private Double calValue; + /** + * + */ + @TableField("cal_value") + private Double calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueIntDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueIntDO.java index b1f675aeb..74e6e9e1e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueIntDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueIntDO.java @@ -42,49 +42,49 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_int") public class PointValueIntDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Integer rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Integer rawValue; - /** - * - */ - @TableField("cal_value") - private Integer calValue; + /** + * + */ + @TableField("cal_value") + private Integer calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueJsonDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueJsonDO.java index 89c14eb1b..51a7aa574 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueJsonDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueJsonDO.java @@ -44,52 +44,52 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_json") public class PointValueJsonDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Object rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Object rawValue; - /** - * - */ - @TableField("cal_value") - private Object calValue; + /** + * + */ + @TableField("cal_value") + private Object calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueLongDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueLongDO.java index 41ae81929..e1fc2f996 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueLongDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/PointValueLongDO.java @@ -42,49 +42,49 @@ import java.time.LocalDateTime; @TableName("dc3_point_value_long") public class PointValueLongDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Raw value - */ - @TableField("raw_value") - private Long rawValue; + /** + * Raw value + */ + @TableField("raw_value") + private Long rawValue; - /** - * - */ - @TableField("cal_value") - private Long calValue; + /** + * + */ + @TableField("cal_value") + private Long calValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/RuleDO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/RuleDO.java index ebb28ee87..b2909c8e8 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/RuleDO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/model/RuleDO.java @@ -43,116 +43,116 @@ import java.time.LocalDateTime; @TableName(value = "dc3_rule", autoResultMap = true) public class RuleDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Entity type flag - */ - @TableField("entity_type_flag") - private Byte entityTypeFlag; + /** + * Entity type flag + */ + @TableField("entity_type_flag") + private Byte entityTypeFlag; - /** - * Rule name - */ - @TableField("rule_name") - private String ruleName; + /** + * Rule name + */ + @TableField("rule_name") + private String ruleName; - /** - * Rule code - */ - @TableField("rule_code") - private String ruleCode; + /** + * Rule code + */ + @TableField("rule_code") + private String ruleCode; - /** - * Entity ID - */ - @TableField("entity_id") - private Long entityId; + /** + * Entity ID + */ + @TableField("entity_id") + private Long entityId; - /** - * ID - */ - @TableField("notify_id") - private Long notifyId; + /** + * ID + */ + @TableField("notify_id") + private Long notifyId; - /** - * ID - */ - @TableField("message_id") - private Long messageId; + /** + * ID + */ + @TableField("message_id") + private Long messageId; - /** - * - */ - @TableField(value = "rule_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt ruleExt; + /** + * + */ + @TableField(value = "rule_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt ruleExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/AlertPageQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/AlertPageQuery.java index 01067ccd1..b2ac92050 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/AlertPageQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/AlertPageQuery.java @@ -37,36 +37,36 @@ import java.io.Serializable; @ToString public class AlertPageQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * {@code "device"} / {@code "driver"} / {@code null} (both). - */ - private String source; + /** + * {@code "device"} / {@code "driver"} / {@code null} (both). + */ + private String source; - private Integer eventTypeFlag; + private Integer eventTypeFlag; - /** - * 0 = unconfirmed, 1 = confirmed, null = both. - */ - private Integer confirmFlag; + /** + * 0 = unconfirmed, 1 = confirmed, null = both. + */ + private Integer confirmFlag; - /** - * Legacy integer window; {@code rangeKey} wins when both set. - */ - private Integer rangeHours; + /** + * Legacy integer window; {@code rangeKey} wins when both set. + */ + private Integer rangeHours; - /** - * Preset time-range key — resolved server-side via TimeRangeUtil. - */ - private String rangeKey; + /** + * Preset time-range key — resolved server-side via TimeRangeUtil. + */ + private String rangeKey; - /** - * 1-based page index. Defaults to 1 if null or less. - */ - private Long current; + /** + * 1-based page index. Defaults to 1 if null or less. + */ + private Long current; - private Long size; + private Long size; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceEventQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceEventQuery.java index ce99b06ab..ec37550fb 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceEventQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceEventQuery.java @@ -38,26 +38,26 @@ import java.io.Serializable; @AllArgsConstructor public class DeviceEventQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceQuery.java index aec1f937b..8f9c8b037 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DeviceQuery.java @@ -39,48 +39,48 @@ import java.io.Serializable; @AllArgsConstructor public class DeviceQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Device Name - */ - private String deviceName; + /** + * Device Name + */ + private String deviceName; - /** - * Device ID - */ - private String deviceCode; + /** + * Device ID + */ + private String deviceCode; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // + // - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverEventQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverEventQuery.java index 7e7fe3816..07d98ef00 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverEventQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverEventQuery.java @@ -38,21 +38,21 @@ import java.io.Serializable; @AllArgsConstructor public class DriverEventQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverQuery.java index b0013c39b..3e15f6ce3 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/DriverQuery.java @@ -40,51 +40,51 @@ import java.io.Serializable; @AllArgsConstructor public class DriverQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String driverName; + /** + * Name + */ + private String driverName; - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * Driver service name - */ - private String serviceName; + /** + * Driver service name + */ + private String serviceName; - /** - * - */ - private String serviceHost; + /** + * + */ + private String serviceHost; - /** - * Type - */ - private DriverTypeFlagEnum driverTypeFlag; + /** + * Type + */ + private DriverTypeFlagEnum driverTypeFlag; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/MessageQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/MessageQuery.java index 7bdb0fd29..42e36893e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/MessageQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/MessageQuery.java @@ -44,36 +44,36 @@ import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class MessageQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Alarm message template title - */ - private String alarmMessageTitle; + /** + * Alarm message template title + */ + private String alarmMessageTitle; - /** - * Alarm message template code - */ - private String alarmMessageCode; + /** + * Alarm message template code + */ + private String alarmMessageCode; - /** - * Alarm message template level - */ - private AlarmMessageLevelFlagEnum alarmMessageLevel; + /** + * Alarm message template level + */ + private AlarmMessageLevelFlagEnum alarmMessageLevel; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/NotifyQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/NotifyQuery.java index 53923f5ca..a7c2a586a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/NotifyQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/NotifyQuery.java @@ -44,41 +44,41 @@ import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class NotifyQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Alarm notification template name - */ - private String alarmNotifyName; + /** + * Alarm notification template name + */ + private String alarmNotifyName; - /** - * Alarm notification template code - */ - private String alarmNotifyCode; + /** + * Alarm notification template code + */ + private String alarmNotifyCode; - /** - * Auto confirm flag - */ - private AutoConfirmFlagEnum autoConfirmFlag; + /** + * Auto confirm flag + */ + private AutoConfirmFlagEnum autoConfirmFlag; - /** - * Alarm notification interval, milliseconds - */ - private Long alarmNotifyInterval; + /** + * Alarm notification interval, milliseconds + */ + private Long alarmNotifyInterval; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/RuleQuery.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/RuleQuery.java index e700ca178..749a5a243 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/RuleQuery.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/query/RuleQuery.java @@ -44,41 +44,41 @@ import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RuleQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Rule name - */ - private String alarmRuleName; + /** + * Rule name + */ + private String alarmRuleName; - /** - * Rule code - */ - private String alarmRuleCode; + /** + * Rule code + */ + private String alarmRuleCode; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Entity type flag - */ - private AlarmTypeFlagEnum alarmTypeFlag; + /** + * Entity type flag + */ + private AlarmTypeFlagEnum alarmTypeFlag; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/MessageVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/MessageVO.java index b84734284..cd2f11b66 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/MessageVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/MessageVO.java @@ -41,29 +41,29 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class MessageVO extends BaseVO { - /** - * Alarm message template title - */ - private String messageName; + /** + * Alarm message template title + */ + private String messageName; - /** - * Alarm message template code - */ - private String messageCode; + /** + * Alarm message template code + */ + private String messageCode; - /** - * Alarm message template level - */ - private AlarmMessageLevelFlagEnum messageLevel; + /** + * Alarm message template level + */ + private AlarmMessageLevelFlagEnum messageLevel; - /** - * Alarm message template content - */ - private MessageExt messageExt; + /** + * Alarm message template content + */ + private MessageExt messageExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/NotifyVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/NotifyVO.java index ecff65537..3157bac6a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/NotifyVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/NotifyVO.java @@ -41,34 +41,34 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class NotifyVO extends BaseVO { - /** - * Alarm notification template name - */ - private String notifyName; + /** + * Alarm notification template name + */ + private String notifyName; - /** - * Alarm notification template code - */ - private String notifyCode; + /** + * Alarm notification template code + */ + private String notifyCode; - /** - * Auto confirm flag - */ - private AutoConfirmFlagEnum autoConfirmFlag; + /** + * Auto confirm flag + */ + private AutoConfirmFlagEnum autoConfirmFlag; - /** - * Alarm notification interval, milliseconds - */ - private Long notifyInterval; + /** + * Alarm notification interval, milliseconds + */ + private Long notifyInterval; - /** - * Alarm notification template configuration - */ - private NotifyExt notifyExt; + /** + * Alarm notification template configuration + */ + private NotifyExt notifyExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueReadVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueReadVO.java index 301b0402d..f10ce8857 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueReadVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueReadVO.java @@ -37,13 +37,13 @@ import java.io.Serializable; @AllArgsConstructor public class PointValueReadVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @NotNull(message = "设备ID不能为空") - private Long deviceId; + @NotNull(message = "设备ID不能为空") + private Long deviceId; - @NotNull(message = "位号ID不能为空") - private Long pointId; + @NotNull(message = "位号ID不能为空") + private Long pointId; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueVO.java index 75c476112..45e0fcab8 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueVO.java @@ -39,49 +39,49 @@ import java.time.LocalDateTime; @AllArgsConstructor public class PointValueVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Raw value - */ - private String rawValue; + /** + * Raw value + */ + private String rawValue; - /** - * Processed value - */ - private String calValue; + /** + * Processed value + */ + private String calValue; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * Create Time - */ - @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) - private LocalDateTime createTime; + /** + * Create Time + */ + @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) + private LocalDateTime createTime; - /** - * Operate Time - */ - @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) - private LocalDateTime operateTime; + /** + * Operate Time + */ + @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueWriteVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueWriteVO.java index 5ccc059cd..551097229 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueWriteVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/PointValueWriteVO.java @@ -38,16 +38,16 @@ import java.io.Serializable; @AllArgsConstructor public class PointValueWriteVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @NotNull(message = "设备ID不能为空") - private Long deviceId; + @NotNull(message = "设备ID不能为空") + private Long deviceId; - @NotNull(message = "位号ID不能为空") - private Long pointId; + @NotNull(message = "位号ID不能为空") + private Long pointId; - @NotBlank(message = "值不能为空") - private String value; + @NotBlank(message = "值不能为空") + private String value; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/RuleVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/RuleVO.java index e8b706e9d..d2b2aa95c 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/RuleVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/RuleVO.java @@ -41,44 +41,44 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class RuleVO extends BaseVO { - /** - * Entity type flag - */ - private AlarmTypeFlagEnum entityTypeFlag; + /** + * Entity type flag + */ + private AlarmTypeFlagEnum entityTypeFlag; - /** - * Rule name - */ - private String ruleName; + /** + * Rule name + */ + private String ruleName; - /** - * Rule code - */ - private String ruleCode; + /** + * Rule code + */ + private String ruleCode; - /** - * Entity ID - */ - private Long entityId; + /** + * Entity ID + */ + private Long entityId; - /** - * Alarm notification template ID - */ - private Long notifyId; + /** + * Alarm notification template ID + */ + private Long notifyId; - /** - * Alarm message template ID - */ - private Long messageId; + /** + * Alarm message template ID + */ + private Long messageId; - /** - * Alarm rule - */ - private RuleExt ruleExt; + /** + * Alarm rule + */ + private RuleExt ruleExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ActivityCellVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ActivityCellVO.java index b45f8aa97..ed06a165a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ActivityCellVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ActivityCellVO.java @@ -38,13 +38,13 @@ import java.io.Serializable; @NoArgsConstructor public class ActivityCellVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private int dow; + private int dow; - private int hour; + private int hour; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AgingBacklogVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AgingBacklogVO.java index a5b44a840..a87b6f6d1 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AgingBacklogVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AgingBacklogVO.java @@ -35,20 +35,20 @@ import java.io.Serializable; @NoArgsConstructor public class AgingBacklogVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long under1h; + private long under1h; - private long h1to6; + private long h1to6; - private long h6to24; + private long h6to24; - private long over24h; + private long over24h; - /** - * Convenience sum — equals the total unconfirmed count. - */ - private long total; + /** + * Convenience sum — equals the total unconfirmed count. + */ + private long total; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertActivityCellVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertActivityCellVO.java index 2f8479fb5..d30858ee7 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertActivityCellVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertActivityCellVO.java @@ -38,22 +38,22 @@ import java.io.Serializable; @NoArgsConstructor public class AlertActivityCellVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Day of week, 0..6 matching Postgres EXTRACT(DOW) (0 = Sunday). - */ - private int dow; + /** + * Day of week, 0..6 matching Postgres EXTRACT(DOW) (0 = Sunday). + */ + private int dow; - /** - * Hour of day, 0..23. - */ - private int hour; + /** + * Hour of day, 0..23. + */ + private int hour; - /** - * Alarm count in that cell. - */ - private long count; + /** + * Alarm count in that cell. + */ + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertItemVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertItemVO.java index 666ce77ea..916b9f9aa 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertItemVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertItemVO.java @@ -39,27 +39,27 @@ import java.time.LocalDateTime; @NoArgsConstructor public class AlertItemVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Long id; + private Long id; - private String source; + private String source; - private Long sourceId; + private Long sourceId; - private Long pointId; + private Long pointId; - private Integer eventTypeFlag; + private Integer eventTypeFlag; - private Integer confirmFlag; + private Integer confirmFlag; - private LocalDateTime createTime; + private LocalDateTime createTime; - /** - * Human-readable message extracted from event_ext->>'content'. Populated by the - * paging / list endpoints; latest(size=N) leaves it null. - */ - private String message; + /** + * Human-readable message extracted from event_ext->>'content'. Populated by the + * paging / list endpoints; latest(size=N) leaves it null. + */ + private String message; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertStatsVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertStatsVO.java index 3d0101871..bf4f052d0 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertStatsVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertStatsVO.java @@ -38,50 +38,50 @@ import java.util.List; @NoArgsConstructor public class AlertStatsVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long total; + private long total; - private long unconfirmed; + private long unconfirmed; - private long deviceAlerts; + private long deviceAlerts; - private long driverAlerts; + private long driverAlerts; - private long deviceUnconfirmed; + private long deviceUnconfirmed; - private long driverUnconfirmed; + private long driverUnconfirmed; - private long todayDeviceAlarms; + private long todayDeviceAlarms; - private long todayDriverAlarms; + private long todayDriverAlarms; - private long todayDeviceUnconfirmed; + private long todayDeviceUnconfirmed; - private long todayDriverUnconfirmed; + private long todayDriverUnconfirmed; - private List byType; + private List byType; - /** - * 24-element hourly count series for the alert indicator card sparkline, oldest - * first. Always length 24 — service zero-pads missing hours. - */ - private List sparkline24h; + /** + * 24-element hourly count series for the alert indicator card sparkline, oldest + * first. Always length 24 — service zero-pads missing hours. + */ + private List sparkline24h; - @Getter - @Setter - @ToString - @NoArgsConstructor - public static class BucketVO implements Serializable { + @Getter + @Setter + @ToString + @NoArgsConstructor + public static class BucketVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String key; + private String key; - private long count; + private long count; - } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTopSourceVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTopSourceVO.java index 80199440d..76153e259 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTopSourceVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTopSourceVO.java @@ -37,13 +37,13 @@ import java.io.Serializable; @NoArgsConstructor public class AlertTopSourceVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String source; + private String source; - private long sourceId; + private long sourceId; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTrendVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTrendVO.java index 4389c8a3a..b29cd152e 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTrendVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTrendVO.java @@ -37,13 +37,13 @@ import java.io.Serializable; @NoArgsConstructor public class AlertTrendVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String date; + private String date; - private long deviceCount; + private long deviceCount; - private long driverCount; + private long driverCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTypeBucketVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTypeBucketVO.java index df588eed9..381b74d76 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTypeBucketVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/AlertTypeBucketVO.java @@ -39,11 +39,11 @@ import java.io.Serializable; @NoArgsConstructor public class AlertTypeBucketVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String type; + private String type; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ChangeImpactVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ChangeImpactVO.java index c716b5918..006bc675a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ChangeImpactVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ChangeImpactVO.java @@ -37,16 +37,16 @@ import java.time.LocalDateTime; @NoArgsConstructor public class ChangeImpactVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * {@code driver} | {@code device} | {@code profile}. - */ - private String kind; + /** + * {@code driver} | {@code device} | {@code profile}. + */ + private String kind; - private long entityId; + private long entityId; - private LocalDateTime operateTime; + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CorrelationPairVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CorrelationPairVO.java index e6f9dda6e..88810389a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CorrelationPairVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CorrelationPairVO.java @@ -36,21 +36,21 @@ import java.io.Serializable; @NoArgsConstructor public class CorrelationPairVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String aSource; + private String aSource; - private long aSourceId; + private long aSourceId; - private int aEventType; + private int aEventType; - private String bSource; + private String bSource; - private long bSourceId; + private long bSourceId; - private int bEventType; + private int bEventType; - private long coCount; + private long coCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CoverageGapVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CoverageGapVO.java index 94a79aaed..81b0a2bec 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CoverageGapVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/CoverageGapVO.java @@ -38,28 +38,28 @@ import java.util.List; @NoArgsConstructor public class CoverageGapVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long totalPoints; + private long totalPoints; - private long missingPoints; + private long missingPoints; - private List items = new ArrayList<>(); + private List items = new ArrayList<>(); - @Getter - @Setter - @ToString - @NoArgsConstructor - public static class Item implements Serializable { + @Getter + @Setter + @ToString + @NoArgsConstructor + public static class Item implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long pointId; + private long pointId; - private long profileId; + private long profileId; - } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/FlappingSourceVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/FlappingSourceVO.java index bca7e9fd8..8ffe63831 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/FlappingSourceVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/FlappingSourceVO.java @@ -36,15 +36,15 @@ import java.io.Serializable; @NoArgsConstructor public class FlappingSourceVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String source; + private String source; - private long sourceId; + private long sourceId; - private int eventTypeFlag; + private int eventTypeFlag; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatencyBucketVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatencyBucketVO.java index a7f8bbd9f..9a0dc8d17 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatencyBucketVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatencyBucketVO.java @@ -39,11 +39,11 @@ import java.io.Serializable; @NoArgsConstructor public class LatencyBucketVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private int bin; + private int bin; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatestPointValueVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatestPointValueVO.java index 830ce4a2a..707fda68c 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatestPointValueVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/LatestPointValueVO.java @@ -38,42 +38,42 @@ import java.time.LocalDateTime; @AllArgsConstructor public class LatestPointValueVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Long deviceId; + private Long deviceId; - private Long pointId; + private Long pointId; - private Long driverId; + private Long driverId; - /** - * Display name for the device, resolved via {@code DeviceFacade}. May be {@code null} - * when the device has been deleted but historical point values still reference it. - */ - private String deviceName; + /** + * Display name for the device, resolved via {@code DeviceFacade}. May be {@code null} + * when the device has been deleted but historical point values still reference it. + */ + private String deviceName; - /** - * Display name for the point. - */ - private String pointName; + /** + * Display name for the point. + */ + private String pointName; - /** - * Display name for the driver that owns the device. - */ - private String driverName; + /** + * Display name for the driver that owns the device. + */ + private String driverName; - private String rawValue; + private String rawValue; - private String calValue; + private String calValue; - /** - * Which hypertable the row came from: STRING / INT / LONG / BOOL / FLOAT / DOUBLE / - * JSON. Lets the UI pick formatting without fetching the point's metadata. - */ - private String valueType; + /** + * Which hypertable the row came from: STRING / INT / LONG / BOOL / FLOAT / DOUBLE / + * JSON. Lets the UI pick formatting without fetching the point's metadata. + */ + private String valueType; - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private LocalDateTime createTime; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime createTime; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/MttaTrendVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/MttaTrendVO.java index cd8b8b6fe..06ffb601c 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/MttaTrendVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/MttaTrendVO.java @@ -36,21 +36,21 @@ import java.io.Serializable; @NoArgsConstructor public class MttaTrendVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * ISO date. - */ - private String date; + /** + * ISO date. + */ + private String date; - private long p50Ms; + private long p50Ms; - private long p95Ms; + private long p95Ms; - /** - * Count of confirmed events used in the percentile calc for this day. - */ - private long confirmedCount; + /** + * Count of confirmed events used in the percentile calc for this day. + */ + private long confirmedCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/PeerDeviationVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/PeerDeviationVO.java index f492dea47..5ec91a4ab 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/PeerDeviationVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/PeerDeviationVO.java @@ -35,20 +35,20 @@ import java.io.Serializable; @NoArgsConstructor public class PeerDeviationVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long profileId; + private long profileId; - private long deviceId; + private long deviceId; - private long alarmCount; + private long alarmCount; - private long peerMedian; + private long peerMedian; - /** - * alarmCount / peerMedian, 2-decimal. 0 means peerMedian was 0 (fresh profile). - */ - private double ratio; + /** + * alarmCount / peerMedian, 2-decimal. 0 means peerMedian was 0 (fresh profile). + */ + private double ratio; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ProtocolHealthVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ProtocolHealthVO.java index dbcc700b1..79ddf0a01 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ProtocolHealthVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/ProtocolHealthVO.java @@ -37,18 +37,18 @@ import java.io.Serializable; @NoArgsConstructor public class ProtocolHealthVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * e.g. {@code dc3-driver-modbus-tcp}; frontend strips the prefix. - */ - private String serviceName; + /** + * e.g. {@code dc3-driver-modbus-tcp}; frontend strips the prefix. + */ + private String serviceName; - private long driverCount; + private long driverCount; - private long enabledCount; + private long enabledCount; - private long deviceCount; + private long deviceCount; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SilentSourceVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SilentSourceVO.java index 5242d882b..7aa12487a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SilentSourceVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SilentSourceVO.java @@ -37,18 +37,18 @@ import java.time.LocalDateTime; @NoArgsConstructor public class SilentSourceVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long deviceId; + private long deviceId; - private long pointId; + private long pointId; - private LocalDateTime lastSeen; + private LocalDateTime lastSeen; - /** - * How many seconds since the last sample, rounded. - */ - private long silentSeconds; + /** + * How many seconds since the last sample, rounded. + */ + private long silentSeconds; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SystemHealthVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SystemHealthVO.java index 1928826b8..caa5638cd 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SystemHealthVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/SystemHealthVO.java @@ -44,54 +44,54 @@ import java.util.Map; @NoArgsConstructor public class SystemHealthVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Center service reachability (auth, data, manager). - */ - private Map center; + /** + * Center service reachability (auth, data, manager). + */ + private Map center; - /** - * Infrastructure reachability (database, mq, gateway). - */ - private Map infra; + /** + * Infrastructure reachability (database, mq, gateway). + */ + private Map infra; - /** - * Driver population summary. - */ - private FleetSummary drivers; + /** + * Driver population summary. + */ + private FleetSummary drivers; - /** - * Device population summary. - */ - private FleetSummary devices; + /** + * Device population summary. + */ + private FleetSummary devices; - /** - * Population summary shared by drivers and devices: count of records in the DB, how - * many of them reported ONLINE to the status cache, and how many rows resolved to a - * cache miss (never heartbeated since startup). - */ - @Getter - @Setter - @ToString - @NoArgsConstructor - public static class FleetSummary implements Serializable { + /** + * Population summary shared by drivers and devices: count of records in the DB, how + * many of them reported ONLINE to the status cache, and how many rows resolved to a + * cache miss (never heartbeated since startup). + */ + @Getter + @Setter + @ToString + @NoArgsConstructor + public static class FleetSummary implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private int total; + private int total; - private int online; + private int online; - } + } - /** - * Backwards-compat alias — drivers used to be typed as DriverSummary. - */ - public static class DriverSummary extends FleetSummary { + /** + * Backwards-compat alias — drivers used to be typed as DriverSummary. + */ + public static class DriverSummary extends FleetSummary { - } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TimeseriesPointVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TimeseriesPointVO.java index f74c8f30b..356fdc94a 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TimeseriesPointVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TimeseriesPointVO.java @@ -38,12 +38,12 @@ import java.time.LocalDateTime; @AllArgsConstructor public class TimeseriesPointVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - private LocalDateTime bucket; + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private LocalDateTime bucket; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TopEntityVO.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TopEntityVO.java index df756b1f1..288d57c6f 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TopEntityVO.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/entity/vo/dashboard/TopEntityVO.java @@ -36,15 +36,15 @@ import java.io.Serializable; @AllArgsConstructor public class TopEntityVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device / point / driver id — the service resolves the human-readable name - * asynchronously on the frontend via existing getXxxByIds APIs. - */ - private Long entityId; + /** + * Device / point / driver id — the service resolves the human-readable name + * asynchronously on the frontend via existing getXxxByIds APIs. + */ + private Long entityId; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/generator/MybatisGenerator.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/generator/MybatisGenerator.java index 703581c4d..2f84be998 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/generator/MybatisGenerator.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/generator/MybatisGenerator.java @@ -36,29 +36,29 @@ import io.github.pnoker.common.utils.MybatisUtil; */ public class MybatisGenerator { - public static void main(String[] args) { - generator(); - } + public static void main(String[] args) { + generator(); + } - public static void generator() { - String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-data/src/main"; - MybatisUtil.defaultGenerator("localhost", "35432", "dc3", "dc3_history", "dc3", "dc3dc3dc3") - .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) - .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) - .packageConfig(builder -> builder.parent("io.github.pnoker.common.data") - .entity("entity.model") - .service("dal") - .serviceImpl("dal.impl") - .mapper("mapper") - .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/data/dal", - OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/data/dal/impl", OutputFile.xml, - path + "/resources/mapping"))) - .templateEngine(new FreemarkerTemplateEngine()) - .strategyConfig(MybatisUtil::defaultStrategyConfig) - .strategyConfig(builder -> builder.addInclude("dc3_point_value_bool", "dc3_point_value_double", - "dc3_point_value_float", "dc3_point_value_int", "dc3_point_value_long", "dc3_point_value_json", - "dc3_point_value")) - .execute(); - } + public static void generator() { + String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-data/src/main"; + MybatisUtil.defaultGenerator("localhost", "35432", "dc3", "dc3_history", "dc3", "dc3dc3dc3") + .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) + .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) + .packageConfig(builder -> builder.parent("io.github.pnoker.common.data") + .entity("entity.model") + .service("dal") + .serviceImpl("dal.impl") + .mapper("mapper") + .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/data/dal", + OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/data/dal/impl", OutputFile.xml, + path + "/resources/mapping"))) + .templateEngine(new FreemarkerTemplateEngine()) + .strategyConfig(MybatisUtil::defaultStrategyConfig) + .strategyConfig(builder -> builder.addInclude("dc3_point_value_bool", "dc3_point_value_double", + "dc3_point_value_float", "dc3_point_value_int", "dc3_point_value_long", "dc3_point_value_json", + "dc3_point_value")) + .execute(); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/grpc/server/PointValueServer.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/grpc/server/PointValueServer.java index d24795de8..5753fc1b5 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/grpc/server/PointValueServer.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/grpc/server/PointValueServer.java @@ -37,163 +37,159 @@ import java.util.List; @Service public class PointValueServer extends PointValueApiGrpc.PointValueApiImplBase { - private final PointValueService pointValueService; + private final PointValueService pointValueService; - private final PointValueCommandService pointValueCommandService; + private final PointValueCommandService pointValueCommandService; - public PointValueServer(PointValueService pointValueService, PointValueCommandService pointValueCommandService) { - this.pointValueService = pointValueService; - this.pointValueCommandService = pointValueCommandService; - } + public PointValueServer(PointValueService pointValueService, PointValueCommandService pointValueCommandService) { + this.pointValueService = pointValueService; + this.pointValueCommandService = pointValueCommandService; + } - @Override - public void lastValue(GrpcPointValueQuery request, StreamObserver responseObserver) { - try { - // latest() with a page query — simplified: query by device+point, return - // first result - io.github.pnoker.common.entity.query.PointValueQuery query = new io.github.pnoker.common.entity.query.PointValueQuery(); - query.setDeviceId(request.getDeviceId()); - query.setPointId(request.getPointId()); - query.setTenantId(request.getTenantId()); - io.github.pnoker.common.entity.common.Pages pages = new io.github.pnoker.common.entity.common.Pages(); - pages.setCurrent(1); - pages.setSize(1); - query.setPage(pages); + @Override + public void lastValue(GrpcPointValueQuery request, StreamObserver responseObserver) { + try { + // latest() with a page query — simplified: query by device+point, return + // first result + io.github.pnoker.common.entity.query.PointValueQuery query = new io.github.pnoker.common.entity.query.PointValueQuery(); + query.setDeviceId(request.getDeviceId()); + query.setPointId(request.getPointId()); + query.setTenantId(request.getTenantId()); + io.github.pnoker.common.entity.common.Pages pages = new io.github.pnoker.common.entity.common.Pages(); + pages.setCurrent(1); + pages.setSize(1); + query.setPage(pages); - com.baomidou.mybatisplus.extension.plugins.pagination.Page page = pointValueService - .latest(query); + com.baomidou.mybatisplus.extension.plugins.pagination.Page page = pointValueService + .latest(query); - GrpcRPointValueDTO.Builder response = GrpcRPointValueDTO.newBuilder(); - response.setResult(GrpcR.newBuilder() - .setOk(true) - .setCode(ResponseEnum.OK.getCode()) - .setMessage(ResponseEnum.OK.getText()) - .build()); + GrpcRPointValueDTO.Builder response = GrpcRPointValueDTO.newBuilder(); + response.setResult(GrpcR.newBuilder() + .setOk(true) + .setCode(ResponseEnum.OK.getCode()) + .setMessage(ResponseEnum.OK.getText()) + .build()); - if (page != null && !page.getRecords().isEmpty()) { - io.github.pnoker.common.entity.bo.PointValueBO bo = page.getRecords().getFirst(); - response.setData(GrpcPointValueDTO.newBuilder() - .setId(0) - .setDeviceId(bo.getDeviceId() != null ? bo.getDeviceId() : 0) - .setPointId(bo.getPointId() != null ? bo.getPointId() : 0) - .setValue(bo.getCalValue() != null ? bo.getCalValue() : "") - .setRawValue(bo.getRawValue() != null ? bo.getRawValue() : "") - .setCreateTime( - bo.getCreateTime() != null ? bo.getCreateTime().toEpochSecond(java.time.ZoneOffset.UTC) : 0) - .build()); - } - responseObserver.onNext(response.build()); - responseObserver.onCompleted(); - } - catch (Exception e) { - log.error("PointValueServer.lastValue error: {}", e.getMessage(), e); - responseObserver.onNext(GrpcRPointValueDTO.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(false) - .setCode(ResponseEnum.FAILURE.getCode()) - .setMessage(e.getMessage()) - .build()) - .build()); - responseObserver.onCompleted(); - } - } + if (page != null && !page.getRecords().isEmpty()) { + io.github.pnoker.common.entity.bo.PointValueBO bo = page.getRecords().getFirst(); + response.setData(GrpcPointValueDTO.newBuilder() + .setId(0) + .setDeviceId(bo.getDeviceId() != null ? bo.getDeviceId() : 0) + .setPointId(bo.getPointId() != null ? bo.getPointId() : 0) + .setValue(bo.getCalValue() != null ? bo.getCalValue() : "") + .setRawValue(bo.getRawValue() != null ? bo.getRawValue() : "") + .setCreateTime( + bo.getCreateTime() != null ? bo.getCreateTime().toEpochSecond(java.time.ZoneOffset.UTC) : 0) + .build()); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } catch (Exception e) { + log.error("PointValueServer.lastValue error: {}", e.getMessage(), e); + responseObserver.onNext(GrpcRPointValueDTO.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(false) + .setCode(ResponseEnum.FAILURE.getCode()) + .setMessage(e.getMessage()) + .build()) + .build()); + responseObserver.onCompleted(); + } + } - @Override - public void historyValue(GrpcPointValueHistoryQuery request, - StreamObserver responseObserver) { - try { - List history = pointValueService.history(request.getTenantId(), request.getDeviceId(), - request.getPointId(), request.getCount()); + @Override + public void historyValue(GrpcPointValueHistoryQuery request, + StreamObserver responseObserver) { + try { + List history = pointValueService.history(request.getTenantId(), request.getDeviceId(), + request.getPointId(), request.getCount()); - GrpcRPointValueStringList.Builder response = GrpcRPointValueStringList.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(true) - .setCode(ResponseEnum.OK.getCode()) - .setMessage(ResponseEnum.OK.getText()) - .build()); + GrpcRPointValueStringList.Builder response = GrpcRPointValueStringList.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(true) + .setCode(ResponseEnum.OK.getCode()) + .setMessage(ResponseEnum.OK.getText()) + .build()); - if (history != null) { - response.addAllData(history); - } - responseObserver.onNext(response.build()); - responseObserver.onCompleted(); - } - catch (Exception e) { - log.error("PointValueServer.historyValue error: {}", e.getMessage(), e); - responseObserver.onNext(GrpcRPointValueStringList.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(false) - .setCode(ResponseEnum.FAILURE.getCode()) - .setMessage(e.getMessage()) - .build()) - .build()); - responseObserver.onCompleted(); - } - } + if (history != null) { + response.addAllData(history); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } catch (Exception e) { + log.error("PointValueServer.historyValue error: {}", e.getMessage(), e); + responseObserver.onNext(GrpcRPointValueStringList.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(false) + .setCode(ResponseEnum.FAILURE.getCode()) + .setMessage(e.getMessage()) + .build()) + .build()); + responseObserver.onCompleted(); + } + } - @Override - public void readCommand(GrpcPointValueCommandQuery request, StreamObserver responseObserver) { - try { - PointValueReadVO vo = new PointValueReadVO(); - vo.setDeviceId(request.getDeviceId()); - vo.setPointId(request.getPointId()); - pointValueCommandService.read(vo); + @Override + public void readCommand(GrpcPointValueCommandQuery request, StreamObserver responseObserver) { + try { + PointValueReadVO vo = new PointValueReadVO(); + vo.setDeviceId(request.getDeviceId()); + vo.setPointId(request.getPointId()); + pointValueCommandService.read(vo); - responseObserver.onNext(GrpcRBoolean.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(true) - .setCode(ResponseEnum.OK.getCode()) - .setMessage(ResponseEnum.OK.getText()) - .build()) - .setData(true) - .build()); - responseObserver.onCompleted(); - } - catch (Exception e) { - log.error("PointValueServer.readCommand error: {}", e.getMessage(), e); - responseObserver.onNext(GrpcRBoolean.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(false) - .setCode(ResponseEnum.FAILURE.getCode()) - .setMessage(e.getMessage()) - .build()) - .setData(false) - .build()); - responseObserver.onCompleted(); - } - } + responseObserver.onNext(GrpcRBoolean.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(true) + .setCode(ResponseEnum.OK.getCode()) + .setMessage(ResponseEnum.OK.getText()) + .build()) + .setData(true) + .build()); + responseObserver.onCompleted(); + } catch (Exception e) { + log.error("PointValueServer.readCommand error: {}", e.getMessage(), e); + responseObserver.onNext(GrpcRBoolean.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(false) + .setCode(ResponseEnum.FAILURE.getCode()) + .setMessage(e.getMessage()) + .build()) + .setData(false) + .build()); + responseObserver.onCompleted(); + } + } - @Override - public void writeCommand(GrpcPointValueWriteCommand request, StreamObserver responseObserver) { - try { - PointValueWriteVO vo = new PointValueWriteVO(); - vo.setDeviceId(request.getDeviceId()); - vo.setPointId(request.getPointId()); - vo.setValue(request.getValue()); - pointValueCommandService.write(vo); + @Override + public void writeCommand(GrpcPointValueWriteCommand request, StreamObserver responseObserver) { + try { + PointValueWriteVO vo = new PointValueWriteVO(); + vo.setDeviceId(request.getDeviceId()); + vo.setPointId(request.getPointId()); + vo.setValue(request.getValue()); + pointValueCommandService.write(vo); - responseObserver.onNext(GrpcRBoolean.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(true) - .setCode(ResponseEnum.OK.getCode()) - .setMessage(ResponseEnum.OK.getText()) - .build()) - .setData(true) - .build()); - responseObserver.onCompleted(); - } - catch (Exception e) { - log.error("PointValueServer.writeCommand error: {}", e.getMessage(), e); - responseObserver.onNext(GrpcRBoolean.newBuilder() - .setResult(GrpcR.newBuilder() - .setOk(false) - .setCode(ResponseEnum.FAILURE.getCode()) - .setMessage(e.getMessage()) - .build()) - .setData(false) - .build()); - responseObserver.onCompleted(); - } - } + responseObserver.onNext(GrpcRBoolean.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(true) + .setCode(ResponseEnum.OK.getCode()) + .setMessage(ResponseEnum.OK.getText()) + .build()) + .setData(true) + .build()); + responseObserver.onCompleted(); + } catch (Exception e) { + log.error("PointValueServer.writeCommand error: {}", e.getMessage(), e); + responseObserver.onNext(GrpcRBoolean.newBuilder() + .setResult(GrpcR.newBuilder() + .setOk(false) + .setCode(ResponseEnum.FAILURE.getCode()) + .setMessage(e.getMessage()) + .build()) + .setData(false) + .build()); + responseObserver.onCompleted(); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/HourlyJobForData.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/HourlyJobForData.java index 996335651..b7e70ecca 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/HourlyJobForData.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/HourlyJobForData.java @@ -35,17 +35,18 @@ import org.springframework.stereotype.Component; @Component public class HourlyJobForData extends QuartzJobBean { - /** - * - * * - *

- * * biz service - * @param context JobExecutionContext - * @throws JobExecutionException JobExecutionException - */ - @Override - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - log.info("hourlyJobHandler: {}", LocalDateTimeUtil.now()); - } + /** + * + * * + *

+ * * biz service + * + * @param context JobExecutionContext + * @throws JobExecutionException JobExecutionException + */ + @Override + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + log.info("hourlyJobHandler: {}", LocalDateTimeUtil.now()); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/PointValueJob.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/PointValueJob.java index ce47dd6a2..05e7cbf48 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/PointValueJob.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/job/PointValueJob.java @@ -42,77 +42,78 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; @Component public class PointValueJob extends QuartzJobBean { - public static final ReentrantReadWriteLock VALUE_LOCK = new ReentrantReadWriteLock(); + public static final ReentrantReadWriteLock VALUE_LOCK = new ReentrantReadWriteLock(); - public static final AtomicLong VALUE_COUNT = new AtomicLong(0); + public static final AtomicLong VALUE_COUNT = new AtomicLong(0); - public static final AtomicLong VALUE_SPEED = new AtomicLong(0); + public static final AtomicLong VALUE_SPEED = new AtomicLong(0); - private static final List POINT_VALUE_LIST = new ArrayList<>(); + private static final List POINT_VALUE_LIST = new ArrayList<>(); - @Value("${data.point.batch.speed}") - private Integer batchSpeed; + @Value("${data.point.batch.speed}") + private Integer batchSpeed; - @Value("${data.point.batch.interval}") - private Integer interval; + @Value("${data.point.batch.interval}") + private Integer interval; - @Resource - private PointValueService pointValueService; + @Resource + private PointValueService pointValueService; - @Resource - private ExecutorService virtualThreadExecutor; + @Resource + private ExecutorService virtualThreadExecutor; - /** - * PointValue - * @return Point Value Size - */ - public static int getPointValuesSize() { - return POINT_VALUE_LIST.size(); - } + /** + * PointValue + * + * @return Point Value Size + */ + public static int getPointValuesSize() { + return POINT_VALUE_LIST.size(); + } - /** - * PointValue - */ - public static void clearPointValues() { - POINT_VALUE_LIST.clear(); - } + /** + * PointValue + */ + public static void clearPointValues() { + POINT_VALUE_LIST.clear(); + } - /** - * PointValue - * @param pointValueBO PointValue - */ - public static void addPointValues(PointValueBO pointValueBO) { - POINT_VALUE_LIST.add(pointValueBO); - } + /** + * PointValue + * + * @param pointValueBO PointValue + */ + public static void addPointValues(PointValueBO pointValueBO) { + POINT_VALUE_LIST.add(pointValueBO); + } - @Override - protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { - // Statistical point value receive rate - long speed = VALUE_COUNT.getAndSet(0); - VALUE_SPEED.set(speed); - speed /= interval; - if (speed >= batchSpeed) { - log.debug("Point value receiver speed: {} /s, value size: {}, interval: {}", speed, getPointValuesSize(), - interval); - } + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException { + // Statistical point value receive rate + long speed = VALUE_COUNT.getAndSet(0); + VALUE_SPEED.set(speed); + speed /= interval; + if (speed >= batchSpeed) { + log.debug("Point value receiver speed: {} /s, value size: {}, interval: {}", speed, getPointValuesSize(), + interval); + } - // Swap out the accumulated buffer under the lock; run the save on a private - // snapshot outside the lock so concurrent addPointValues callers are not blocked - // by DB I/O. - List snapshot; - VALUE_LOCK.writeLock().lock(); - try { - if (POINT_VALUE_LIST.isEmpty()) { - return; - } - snapshot = new ArrayList<>(POINT_VALUE_LIST); - POINT_VALUE_LIST.clear(); - } - finally { - VALUE_LOCK.writeLock().unlock(); - } + // Swap out the accumulated buffer under the lock; run the save on a private + // snapshot outside the lock so concurrent addPointValues callers are not blocked + // by DB I/O. + List snapshot; + VALUE_LOCK.writeLock().lock(); + try { + if (POINT_VALUE_LIST.isEmpty()) { + return; + } + snapshot = new ArrayList<>(POINT_VALUE_LIST); + POINT_VALUE_LIST.clear(); + } finally { + VALUE_LOCK.writeLock().unlock(); + } - virtualThreadExecutor.execute(() -> pointValueService.save(snapshot)); - } + virtualThreadExecutor.execute(() -> pointValueService.save(snapshot)); + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/AlertMapper.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/AlertMapper.java index 988e42ade..e07971556 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/AlertMapper.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/AlertMapper.java @@ -35,59 +35,59 @@ import java.util.List; @Mapper public interface AlertMapper { - AlertCountersRow countAll(@Param("tenantId") Long tenantId); + AlertCountersRow countAll(@Param("tenantId") Long tenantId); - List countByType(@Param("tenantId") Long tenantId); + List countByType(@Param("tenantId") Long tenantId); - List countBySource(@Param("tenantId") Long tenantId); + List countBySource(@Param("tenantId") Long tenantId); - List latest(@Param("tenantId") Long tenantId, @Param("limit") int limit); + List latest(@Param("tenantId") Long tenantId, @Param("limit") int limit); - List hourlyCounts(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List hourlyCounts(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - List listPaged(@Param("tenantId") Long tenantId, @Param("source") String source, - @Param("eventTypeFlag") Integer eventTypeFlag, @Param("confirmFlag") Integer confirmFlag, - @Param("from") LocalDateTime from, @Param("offset") long offset, @Param("size") long size); + List listPaged(@Param("tenantId") Long tenantId, @Param("source") String source, + @Param("eventTypeFlag") Integer eventTypeFlag, @Param("confirmFlag") Integer confirmFlag, + @Param("from") LocalDateTime from, @Param("offset") long offset, @Param("size") long size); - long countFiltered(@Param("tenantId") Long tenantId, @Param("source") String source, - @Param("eventTypeFlag") Integer eventTypeFlag, @Param("confirmFlag") Integer confirmFlag, - @Param("from") LocalDateTime from); + long countFiltered(@Param("tenantId") Long tenantId, @Param("source") String source, + @Param("eventTypeFlag") Integer eventTypeFlag, @Param("confirmFlag") Integer confirmFlag, + @Param("from") LocalDateTime from); - List todayBySource(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List todayBySource(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - int confirmOne(@Param("tenantId") Long tenantId, @Param("source") String source, @Param("id") Long id); + int confirmOne(@Param("tenantId") Long tenantId, @Param("source") String source, @Param("id") Long id); - int unconfirmOne(@Param("tenantId") Long tenantId, @Param("source") String source, @Param("id") Long id); + int unconfirmOne(@Param("tenantId") Long tenantId, @Param("source") String source, @Param("id") Long id); - List dailyTrend(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List dailyTrend(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - List topSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("limit") int limit); + List topSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("limit") int limit); - List activityHeatmap(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List activityHeatmap(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - List typeDistribution(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List typeDistribution(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - List stormSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("minCount") int minCount, @Param("limit") int limit); + List stormSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("minCount") int minCount, @Param("limit") int limit); - // ===== Phase-2 insights ==================================================== + // ===== Phase-2 insights ==================================================== - List flappingSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("minCount") int minCount, @Param("limit") int limit); + List flappingSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("minCount") int minCount, @Param("limit") int limit); - List correlationPairs(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("windowSec") int windowSec, @Param("limit") int limit); + List correlationPairs(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("windowSec") int windowSec, @Param("limit") int limit); - List peerAlarmCounts(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List peerAlarmCounts(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - AgingBucketRow agingBuckets(@Param("tenantId") Long tenantId); + AgingBucketRow agingBuckets(@Param("tenantId") Long tenantId); - List mttaByDay(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + List mttaByDay(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); - List protocolHealth(@Param("tenantId") Long tenantId); + List protocolHealth(@Param("tenantId") Long tenantId); - List recentChanges(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("limit") int limit); + List recentChanges(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("limit") int limit); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/DashboardMapper.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/DashboardMapper.java index f3a0f7cd6..c06745a98 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/DashboardMapper.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/mapper/DashboardMapper.java @@ -37,32 +37,32 @@ import java.util.List; @DS("history") public interface DashboardMapper { - long countInRange(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("to") LocalDateTime to); + long countInRange(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to); - long countTotal(@Param("tenantId") Long tenantId); + long countTotal(@Param("tenantId") Long tenantId); - List timeseries(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("to") LocalDateTime to, @Param("bucket") String bucket); + List timeseries(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to, @Param("bucket") String bucket); - List top(@Param("tenantId") Long tenantId, @Param("dimension") String dimension, - @Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("limit") int limit); + List top(@Param("tenantId") Long tenantId, @Param("dimension") String dimension, + @Param("from") LocalDateTime from, @Param("to") LocalDateTime to, @Param("limit") int limit); - List latestStream(@Param("tenantId") Long tenantId, @Param("limit") int limit); + List latestStream(@Param("tenantId") Long tenantId, @Param("limit") int limit); - List latencyHistogram(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("to") LocalDateTime to); + List latencyHistogram(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to); - List hourlyActivity(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("to") LocalDateTime to); + List hourlyActivity(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("to") LocalDateTime to); - // ===== Phase-2 insights ==================================================== + // ===== Phase-2 insights ==================================================== - List silentSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, - @Param("silentThreshold") LocalDateTime silentThreshold, @Param("limit") int limit); + List silentSources(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from, + @Param("silentThreshold") LocalDateTime silentThreshold, @Param("limit") int limit); - List coverageGapItems(@Param("tenantId") Long tenantId, @Param("limit") int limit); + List coverageGapItems(@Param("tenantId") Long tenantId, @Param("limit") int limit); - long countPointsInTenant(@Param("tenantId") Long tenantId); + long countPointsInTenant(@Param("tenantId") Long tenantId); } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DeviceEventReceiver.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DeviceEventReceiver.java index 9614d71e5..1ee2468e7 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DeviceEventReceiver.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DeviceEventReceiver.java @@ -42,39 +42,38 @@ import java.util.Objects; @Component public class DeviceEventReceiver { - private final DeviceEventService deviceEventService; + private final DeviceEventService deviceEventService; - public DeviceEventReceiver(DeviceEventService deviceEventService) { - this.deviceEventService = deviceEventService; - } + public DeviceEventReceiver(DeviceEventService deviceEventService) { + this.deviceEventService = deviceEventService; + } - @RabbitHandler - @RabbitListener(queues = "#{deviceEventQueue.name}") - public void deviceEventReceive(Channel channel, Message message, DeviceEventDTO entityDTO) { - try { - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - log.debug("Receive device event: {}", JsonUtil.toJsonString(entityDTO)); - if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) - || StringUtils.isEmpty(entityDTO.getContent())) { - log.error("Invalid device event: {}", entityDTO); - return; - } + @RabbitHandler + @RabbitListener(queues = "#{deviceEventQueue.name}") + public void deviceEventReceive(Channel channel, Message message, DeviceEventDTO entityDTO) { + try { + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + log.debug("Receive device event: {}", JsonUtil.toJsonString(entityDTO)); + if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) + || StringUtils.isEmpty(entityDTO.getContent())) { + log.error("Invalid device event: {}", entityDTO); + return; + } - switch (entityDTO.getType()) { - case HEARTBEAT: - deviceEventService.heartbeatEvent(entityDTO); - break; - case ALARM: - deviceEventService.alarmEvent(entityDTO); - break; - default: - log.error("Invalid event type, {}", entityDTO.getType()); - break; - } - } - catch (IOException e) { - log.error(e.getMessage(), e); - } - } + switch (entityDTO.getType()) { + case HEARTBEAT: + deviceEventService.heartbeatEvent(entityDTO); + break; + case ALARM: + deviceEventService.alarmEvent(entityDTO); + break; + default: + log.error("Invalid event type, {}", entityDTO.getType()); + break; + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DriverEventReceiver.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DriverEventReceiver.java index d7ab611e9..cf4f46401 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DriverEventReceiver.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/DriverEventReceiver.java @@ -42,39 +42,38 @@ import java.util.Objects; @Component public class DriverEventReceiver { - private final DriverEventService driverEventService; + private final DriverEventService driverEventService; - public DriverEventReceiver(DriverEventService driverEventService) { - this.driverEventService = driverEventService; - } + public DriverEventReceiver(DriverEventService driverEventService) { + this.driverEventService = driverEventService; + } - @RabbitHandler - @RabbitListener(queues = "#{driverEventQueue.name}") - public void driverEventReceive(Channel channel, Message message, DriverEventDTO entityDTO) { - try { - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - log.debug("Receive driver event: {}", JsonUtil.toJsonString(entityDTO)); - if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) - || StringUtils.isEmpty(entityDTO.getContent())) { - log.error("Invalid driver event: {}", entityDTO); - return; - } + @RabbitHandler + @RabbitListener(queues = "#{driverEventQueue.name}") + public void driverEventReceive(Channel channel, Message message, DriverEventDTO entityDTO) { + try { + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + log.debug("Receive driver event: {}", JsonUtil.toJsonString(entityDTO)); + if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) + || StringUtils.isEmpty(entityDTO.getContent())) { + log.error("Invalid driver event: {}", entityDTO); + return; + } - switch (entityDTO.getType()) { - case HEARTBEAT: - driverEventService.heartbeatEvent(entityDTO); - break; - case ALARM: - driverEventService.alarmEvent(entityDTO); - break; - default: - log.error("Invalid event type, {}", entityDTO.getType()); - break; - } - } - catch (IOException e) { - log.error(e.getMessage(), e); - } - } + switch (entityDTO.getType()) { + case HEARTBEAT: + driverEventService.heartbeatEvent(entityDTO); + break; + case ALARM: + driverEventService.alarmEvent(entityDTO); + break; + default: + log.error("Invalid event type, {}", entityDTO.getType()); + break; + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/PointValueReceiver.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/PointValueReceiver.java index 911bb396c..2e7c24543 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/PointValueReceiver.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/rabbit/PointValueReceiver.java @@ -46,49 +46,46 @@ import java.util.concurrent.ExecutorService; @Component public class PointValueReceiver { - @Value("${data.point.batch.speed}") - private Integer batchSpeed; + @Value("${data.point.batch.speed}") + private Integer batchSpeed; - @Resource - private ExecutorService virtualThreadExecutor; + @Resource + private ExecutorService virtualThreadExecutor; - @Resource - private PointValueService pointValueService; + @Resource + private PointValueService pointValueService; - @RabbitHandler - @RabbitListener(queues = "#{pointValueQueue.name}") - public void pointValueReceive(Channel channel, Message message, PointValueBO pointValueBO) { - try { - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - if (Objects.isNull(pointValueBO) || Objects.isNull(pointValueBO.getDeviceId())) { - log.error("Invalid point value: {}", pointValueBO); - return; - } - PointValueJob.VALUE_COUNT.getAndIncrement(); - log.debug("Receive point value from: {}, {}", message.getMessageProperties().getReceivedRoutingKey(), - JsonUtil.toJsonString(pointValueBO)); + @RabbitHandler + @RabbitListener(queues = "#{pointValueQueue.name}") + public void pointValueReceive(Channel channel, Message message, PointValueBO pointValueBO) { + try { + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + if (Objects.isNull(pointValueBO) || Objects.isNull(pointValueBO.getDeviceId())) { + log.error("Invalid point value: {}", pointValueBO); + return; + } + PointValueJob.VALUE_COUNT.getAndIncrement(); + log.debug("Receive point value from: {}, {}", message.getMessageProperties().getReceivedRoutingKey(), + JsonUtil.toJsonString(pointValueBO)); - // Judge whether to process data in batch according to the data transmission - // speed - if (PointValueJob.VALUE_SPEED.get() < batchSpeed) { - virtualThreadExecutor.execute(() -> - // Save point value to Redis & PostgreSQL - pointValueService.save(pointValueBO)); - } - else { - // Save point value to schedule - PointValueJob.VALUE_LOCK.writeLock().lock(); - try { - PointValueJob.addPointValues(pointValueBO); - } - finally { - PointValueJob.VALUE_LOCK.writeLock().unlock(); - } - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - } + // Judge whether to process data in batch according to the data transmission + // speed + if (PointValueJob.VALUE_SPEED.get() < batchSpeed) { + virtualThreadExecutor.execute(() -> + // Save point value to Redis & PostgreSQL + pointValueService.save(pointValueBO)); + } else { + // Save point value to schedule + PointValueJob.VALUE_LOCK.writeLock().lock(); + try { + PointValueJob.addPointValues(pointValueBO); + } finally { + PointValueJob.VALUE_LOCK.writeLock().unlock(); + } + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/MessageServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/MessageServiceImpl.java index eb3f8e389..e7006d3d4 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/MessageServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/MessageServiceImpl.java @@ -51,114 +51,115 @@ import java.util.Objects; @Service public class MessageServiceImpl implements MessageService { - @Resource - private MessageBuilder messageBuilder; + @Resource + private MessageBuilder messageBuilder; - @Resource - private MessageManager messageManager; + @Resource + private MessageManager messageManager; - @Override - public void save(MessageBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(MessageBO entityBO) { + checkDuplicate(entityBO, false, true); - MessageDO entityDO = messageBuilder.buildDOByBO(entityBO); - if (!messageManager.save(entityDO)) { - throw new AddException("Failed to create group"); - } - } + MessageDO entityDO = messageBuilder.buildDOByBO(entityBO); + if (!messageManager.save(entityDO)) { + throw new AddException("Failed to create group"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // - LambdaQueryChainWrapper wrapper = messageManager.lambdaQuery().eq(MessageDO::getTenantId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove group: there are subgroups under the group"); - } + // + LambdaQueryChainWrapper wrapper = messageManager.lambdaQuery().eq(MessageDO::getTenantId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove group: there are subgroups under the group"); + } - if (!messageManager.removeById(id)) { - throw new DeleteException("Failed to remove group"); - } - } + if (!messageManager.removeById(id)) { + throw new DeleteException("Failed to remove group"); + } + } - @Override - public void update(MessageBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(MessageBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - MessageDO entityDO = messageBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!messageManager.updateById(entityDO)) { - throw new UpdateException("Failed to update group"); - } - } + MessageDO entityDO = messageBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!messageManager.updateById(entityDO)) { + throw new UpdateException("Failed to update group"); + } + } - @Override - public MessageBO selectById(Long id) { - MessageDO entityDO = getDOById(id, true); - return messageBuilder.buildBOByDO(entityDO); - } + @Override + public MessageBO selectById(Long id) { + MessageDO entityDO = getDOById(id, true); + return messageBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(MessageQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = messageManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return messageBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(MessageQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = messageManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return messageBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link MessageQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(MessageQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmMessageTitle()), MessageDO::getMessageName, - entityQuery.getAlarmMessageTitle()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), MessageDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link MessageQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(MessageQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmMessageTitle()), MessageDO::getMessageName, + entityQuery.getAlarmMessageTitle()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), MessageDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link MessageBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(MessageBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(MessageDO::getMessageName, entityBO.getMessageName()); - wrapper.eq(MessageDO::getMessageCode, entityBO.getMessageCode()); - wrapper.eq(MessageDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - MessageDO one = messageManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Alarm message profile has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link MessageBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(MessageBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(MessageDO::getMessageName, entityBO.getMessageName()); + wrapper.eq(MessageDO::getMessageCode, entityBO.getMessageCode()); + wrapper.eq(MessageDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + MessageDO one = messageManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Alarm message profile has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link MessageDO} - */ - private MessageDO getDOById(Long id, boolean throwException) { - MessageDO entityDO = messageManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Alarm message profile does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link MessageDO} + */ + private MessageDO getDOById(Long id, boolean throwException) { + MessageDO entityDO = messageManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Alarm message profile does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/NotifyServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/NotifyServiceImpl.java index b08fcb984..318879bb7 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/NotifyServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/NotifyServiceImpl.java @@ -51,114 +51,115 @@ import java.util.Objects; @Service public class NotifyServiceImpl implements NotifyService { - @Resource - private NotifyBuilder notifyBuilder; + @Resource + private NotifyBuilder notifyBuilder; - @Resource - private NotifyManager notifyManager; + @Resource + private NotifyManager notifyManager; - @Override - public void save(NotifyBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(NotifyBO entityBO) { + checkDuplicate(entityBO, false, true); - NotifyDO entityDO = notifyBuilder.buildDOByBO(entityBO); - if (!notifyManager.save(entityDO)) { - throw new AddException("Failed to create alarm notify profile"); - } - } + NotifyDO entityDO = notifyBuilder.buildDOByBO(entityBO); + if (!notifyManager.save(entityDO)) { + throw new AddException("Failed to create alarm notify profile"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // Alarm notificationAlarm notification - LambdaQueryChainWrapper wrapper = notifyManager.lambdaQuery().eq(NotifyDO::getTenantId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException( - "Failed to remove alarm notify profile: some sub alarm notify profiles exists in the alarm notify profile"); - } + // Alarm notificationAlarm notification + LambdaQueryChainWrapper wrapper = notifyManager.lambdaQuery().eq(NotifyDO::getTenantId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException( + "Failed to remove alarm notify profile: some sub alarm notify profiles exists in the alarm notify profile"); + } - if (!notifyManager.removeById(id)) { - throw new DeleteException("Failed to remove alarm notify profile"); - } - } + if (!notifyManager.removeById(id)) { + throw new DeleteException("Failed to remove alarm notify profile"); + } + } - @Override - public void update(NotifyBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(NotifyBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - NotifyDO entityDO = notifyBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!notifyManager.updateById(entityDO)) { - throw new UpdateException("Failed to update alarm notify profile"); - } - } + NotifyDO entityDO = notifyBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!notifyManager.updateById(entityDO)) { + throw new UpdateException("Failed to update alarm notify profile"); + } + } - @Override - public NotifyBO selectById(Long id) { - NotifyDO entityDO = getDOById(id, true); - return notifyBuilder.buildBOByDO(entityDO); - } + @Override + public NotifyBO selectById(Long id) { + NotifyDO entityDO = getDOById(id, true); + return notifyBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(NotifyQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = notifyManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return notifyBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(NotifyQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = notifyManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return notifyBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link NotifyQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(NotifyQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmNotifyName()), NotifyDO::getNotifyName, - entityQuery.getAlarmNotifyName()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), NotifyDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link NotifyQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(NotifyQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmNotifyName()), NotifyDO::getNotifyName, + entityQuery.getAlarmNotifyName()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), NotifyDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link NotifyBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(NotifyBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(NotifyDO::getNotifyName, entityBO.getNotifyName()); - wrapper.eq(NotifyDO::getNotifyCode, entityBO.getNotifyCode()); - wrapper.eq(NotifyDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - NotifyDO one = notifyManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Alarm notify profile has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link NotifyBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(NotifyBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(NotifyDO::getNotifyName, entityBO.getNotifyName()); + wrapper.eq(NotifyDO::getNotifyCode, entityBO.getNotifyCode()); + wrapper.eq(NotifyDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + NotifyDO one = notifyManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Alarm notify profile has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link NotifyDO} - */ - private NotifyDO getDOById(Long id, boolean throwException) { - NotifyDO entityDO = notifyManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Alarm notify profile does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link NotifyDO} + */ + private NotifyDO getDOById(Long id, boolean throwException) { + NotifyDO entityDO = notifyManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Alarm notify profile does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/RuleServiceImpl.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/RuleServiceImpl.java index 13e052153..b89af75fa 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/RuleServiceImpl.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/data/service/impl/RuleServiceImpl.java @@ -51,114 +51,115 @@ import java.util.Objects; @Service public class RuleServiceImpl implements RuleService { - @Resource - private RuleBuilder ruleBuilder; + @Resource + private RuleBuilder ruleBuilder; - @Resource - private RuleManager ruleManager; + @Resource + private RuleManager ruleManager; - @Override - public void save(RuleBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(RuleBO entityBO) { + checkDuplicate(entityBO, false, true); - RuleDO entityDO = ruleBuilder.buildDOByBO(entityBO); - if (!ruleManager.save(entityDO)) { - throw new AddException("Failed to create alarm rule"); - } - } + RuleDO entityDO = ruleBuilder.buildDOByBO(entityBO); + if (!ruleManager.save(entityDO)) { + throw new AddException("Failed to create alarm rule"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // Alarm ruleAlarm rule - LambdaQueryChainWrapper wrapper = ruleManager.lambdaQuery().eq(RuleDO::getEntityId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove alarm rule: some sub alarm rules exists in the alarm rule"); - } + // Alarm ruleAlarm rule + LambdaQueryChainWrapper wrapper = ruleManager.lambdaQuery().eq(RuleDO::getEntityId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove alarm rule: some sub alarm rules exists in the alarm rule"); + } - if (!ruleManager.removeById(id)) { - throw new DeleteException("Failed to remove alarm rule"); - } - } + if (!ruleManager.removeById(id)) { + throw new DeleteException("Failed to remove alarm rule"); + } + } - @Override - public void update(RuleBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(RuleBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - RuleDO entityDO = ruleBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!ruleManager.updateById(entityDO)) { - throw new UpdateException("Failed to update alarm rule"); - } - } + RuleDO entityDO = ruleBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!ruleManager.updateById(entityDO)) { + throw new UpdateException("Failed to update alarm rule"); + } + } - @Override - public RuleBO selectById(Long id) { - RuleDO entityDO = getDOById(id, true); - return ruleBuilder.buildBOByDO(entityDO); - } + @Override + public RuleBO selectById(Long id) { + RuleDO entityDO = getDOById(id, true); + return ruleBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(RuleQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = ruleManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return ruleBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(RuleQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = ruleManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return ruleBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link RuleQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(RuleQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmRuleName()), RuleDO::getRuleName, - entityQuery.getAlarmRuleName()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), RuleDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link RuleQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(RuleQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAlarmRuleName()), RuleDO::getRuleName, + entityQuery.getAlarmRuleName()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), RuleDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link RuleBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(RuleBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(RuleDO::getRuleName, entityBO.getRuleName()); - wrapper.eq(RuleDO::getRuleCode, entityBO.getRuleCode()); - wrapper.eq(RuleDO::getEntityId, entityBO.getEntityId()); - wrapper.eq(RuleDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - RuleDO one = ruleManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Alarm rule has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link RuleBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(RuleBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(RuleDO::getRuleName, entityBO.getRuleName()); + wrapper.eq(RuleDO::getRuleCode, entityBO.getRuleCode()); + wrapper.eq(RuleDO::getEntityId, entityBO.getEntityId()); + wrapper.eq(RuleDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + RuleDO one = ruleManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Alarm rule has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link RuleDO} - */ - private RuleDO getDOById(Long id, boolean throwException) { - RuleDO entityDO = ruleManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Alarm rule does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link RuleDO} + */ + private RuleDO getDOById(Long id, boolean throwException) { + RuleDO entityDO = ruleManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Alarm rule does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/init/DataInitRunner.java b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/init/DataInitRunner.java index 3cbcc8c20..91bf6a8ab 100644 --- a/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/init/DataInitRunner.java +++ b/dc3-common/dc3-common-data/src/main/java/io/github/pnoker/common/init/DataInitRunner.java @@ -34,28 +34,30 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.data" }) -@MapperScan(basePackages = { "io.github.pnoker.common.data.mapper" }) +@ComponentScan(basePackages = {"io.github.pnoker.common.data"}) +@MapperScan(basePackages = {"io.github.pnoker.common.data.mapper"}) public class DataInitRunner implements ApplicationRunner { - private final ScheduleForDataService scheduleForDataService; + private final ScheduleForDataService scheduleForDataService; - /** - * Constructor for DataInitRunner - * @param scheduleForDataService Service for handling data scheduling operations - */ - public DataInitRunner(ScheduleForDataService scheduleForDataService) { - this.scheduleForDataService = scheduleForDataService; - } + /** + * Constructor for DataInitRunner + * + * @param scheduleForDataService Service for handling data scheduling operations + */ + public DataInitRunner(ScheduleForDataService scheduleForDataService) { + this.scheduleForDataService = scheduleForDataService; + } - /** - * Executes the data initialization process when the application starts - * @param args Application arguments passed during startup - * @throws Exception If an error occurs during initialization - */ - @Override - public void run(ApplicationArguments args) throws Exception { - scheduleForDataService.initial(); - } + /** + * Executes the data initialization process when the application starts + * + * @param args Application arguments passed during startup + * @throws Exception If an error occurs during initialization + */ + @Override + public void run(ApplicationArguments args) throws Exception { + scheduleForDataService.initial(); + } } diff --git a/dc3-common/dc3-common-data/src/main/resources/mapping/AlertMapper.xml b/dc3-common/dc3-common-data/src/main/resources/mapping/AlertMapper.xml index 7c63f2f80..e4aed371d 100644 --- a/dc3-common/dc3-common-data/src/main/resources/mapping/AlertMapper.xml +++ b/dc3-common/dc3-common-data/src/main/resources/mapping/AlertMapper.xml @@ -547,11 +547,13 @@ open. Both event tables contribute; return one row with 4 counts. --> - SELECT to_char(DATE(create_time), 'YYYY-MM-DD') AS date, - PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (operate_time - create_time)) * 1000) AS p50_ms, - PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (operate_time - create_time)) * 1000) AS p95_ms, - COUNT(*) AS confirmed_count + SELECT to_char(DATE(create_time), 'YYYY-MM-DD') AS date, + PERCENTILE_CONT(0.5) + WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (operate_time - create_time)) * 1000) AS p50_ms, + PERCENTILE_CONT(0.95) + WITHIN GROUP (ORDER BY EXTRACT(EPOCH FROM (operate_time - create_time)) * 1000) AS p95_ms, + COUNT(*) AS confirmed_count FROM (SELECT create_time, operate_time FROM dc3_device_event WHERE deleted = 0 diff --git a/dc3-common/dc3-common-driver/README.md b/dc3-common/dc3-common-driver/README.md index af1128736..9c44df1e2 100644 --- a/dc3-common/dc3-common-driver/README.md +++ b/dc3-common/dc3-common-driver/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-driver` is the shared driver dependency module of the IoT DC3 platform. It provides the driver SDK shared by all protocol drivers, including auto-registration with the +`dc3-common-driver` is the shared driver dependency module of the IoT DC3 platform. It provides the driver SDK shared by +all protocol drivers, including auto-registration with the Manager Center, metadata sync, RabbitMQ command handling, and scheduled data collection. ## Module Information diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/ActiveDriverProfileConfig.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/ActiveDriverProfileConfig.java index 3b68715d2..a5ef19d3b 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/ActiveDriverProfileConfig.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/ActiveDriverProfileConfig.java @@ -34,9 +34,9 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveDriverProfileConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("driver"); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("driver"); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverEnvironmentConfig.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverEnvironmentConfig.java index 29565e545..9a8f954ef 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverEnvironmentConfig.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverEnvironmentConfig.java @@ -44,25 +44,25 @@ import java.util.Map; @Order(Ordered.LOWEST_PRECEDENCE - 100) public class DriverEnvironmentConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - String node = environment.getProperty(EnvironmentConstant.DRIVER_NODE, String.class); - if (StringUtils.isEmpty(node)) { - node = EnvironmentUtil.getNodeId(); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + String node = environment.getProperty(EnvironmentConstant.DRIVER_NODE, String.class); + if (StringUtils.isEmpty(node)) { + node = EnvironmentUtil.getNodeId(); + } - String tenant = environment.getProperty(EnvironmentConstant.DRIVER_TENANT, String.class); - String name = environment.getProperty(EnvironmentConstant.SPRING_APPLICATION_NAME, String.class); - String client = MessageFormat.format("{0}/{1}/{2}", tenant, name, node); - String service = MessageFormat.format("{0}/{1}", tenant, name); + String tenant = environment.getProperty(EnvironmentConstant.DRIVER_TENANT, String.class); + String name = environment.getProperty(EnvironmentConstant.SPRING_APPLICATION_NAME, String.class); + String client = MessageFormat.format("{0}/{1}/{2}", tenant, name, node); + String service = MessageFormat.format("{0}/{1}", tenant, name); - Map source = new HashMap<>(4); - source.put(EnvironmentConstant.DRIVER_NODE, node); - source.put(EnvironmentConstant.DRIVER_SERVICE, service); - source.put(EnvironmentConstant.DRIVER_HOST, HostUtil.localHost()); - source.put(EnvironmentConstant.DRIVER_CLIENT, client); - MutablePropertySources propertySources = environment.getPropertySources(); - propertySources.addFirst(new MapPropertySource("driver", source)); - } + Map source = new HashMap<>(4); + source.put(EnvironmentConstant.DRIVER_NODE, node); + source.put(EnvironmentConstant.DRIVER_SERVICE, service); + source.put(EnvironmentConstant.DRIVER_HOST, HostUtil.localHost()); + source.put(EnvironmentConstant.DRIVER_CLIENT, client); + MutablePropertySources propertySources = environment.getPropertySources(); + propertySources.addFirst(new MapPropertySource("driver", source)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverTopicConfig.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverTopicConfig.java index cf154257f..20dc2762e 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverTopicConfig.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/config/DriverTopicConfig.java @@ -40,98 +40,104 @@ import java.util.Map; @ConditionalOnClass(ExchangeConfig.class) public class DriverTopicConfig { - private final DriverProperties driverProperties; + private final DriverProperties driverProperties; - private final TopicExchange metadataExchange; + private final TopicExchange metadataExchange; - private final TopicExchange commandExchange; + private final TopicExchange commandExchange; - public DriverTopicConfig(DriverProperties driverProperties, TopicExchange metadataExchange, - TopicExchange commandExchange) { - this.driverProperties = driverProperties; - this.metadataExchange = metadataExchange; - this.commandExchange = commandExchange; - } + public DriverTopicConfig(DriverProperties driverProperties, TopicExchange metadataExchange, + TopicExchange commandExchange) { + this.driverProperties = driverProperties; + this.metadataExchange = metadataExchange; + this.commandExchange = commandExchange; + } - /** - * Creates the metadata queue used to receive driver metadata synchronization events. - * @return metadata queue - */ - @Bean - Queue metadataQueue() { - Map arguments = new HashMap<>(); - // 30 seconds: 30 * 1000 = 30000L - arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); - return new Queue(RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX + driverProperties.getClient(), true, false, true, - arguments); - } + /** + * Creates the metadata queue used to receive driver metadata synchronization events. + * + * @return metadata queue + */ + @Bean + Queue metadataQueue() { + Map arguments = new HashMap<>(); + // 30 seconds: 30 * 1000 = 30000L + arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); + return new Queue(RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX + driverProperties.getClient(), true, false, true, + arguments); + } - /** - * Binds the metadata queue to the metadata exchange. - * @param metadataQueue metadata queue - * @return queue binding - */ - @Bean - Binding metadataBinding(Queue metadataQueue) { - Binding binding = BindingBuilder.bind(metadataQueue) - .to(metadataExchange) - .with(RabbitConstant.ROUTING_DRIVER_METADATA_PREFIX + driverProperties.getService()); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + /** + * Binds the metadata queue to the metadata exchange. + * + * @param metadataQueue metadata queue + * @return queue binding + */ + @Bean + Binding metadataBinding(Queue metadataQueue) { + Binding binding = BindingBuilder.bind(metadataQueue) + .to(metadataExchange) + .with(RabbitConstant.ROUTING_DRIVER_METADATA_PREFIX + driverProperties.getService()); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } - /** - * Creates the driver command queue used to receive driver-level commands. - * @return driver command queue - */ - @Bean - Queue driverCommandQueue() { - Map arguments = new HashMap<>(); - // 30 seconds: 30 * 1000 = 30000L - arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); - return new Queue(RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX + driverProperties.getService(), true, false, false, - arguments); - } + /** + * Creates the driver command queue used to receive driver-level commands. + * + * @return driver command queue + */ + @Bean + Queue driverCommandQueue() { + Map arguments = new HashMap<>(); + // 30 seconds: 30 * 1000 = 30000L + arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); + return new Queue(RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX + driverProperties.getService(), true, false, false, + arguments); + } - /** - * Binds the driver command queue to the command exchange. - * @param driverCommandQueue driver command queue - * @return queue binding - */ - @Bean - Binding driverCommandBinding(Queue driverCommandQueue) { - Binding binding = BindingBuilder.bind(driverCommandQueue) - .to(commandExchange) - .with(RabbitConstant.ROUTING_DRIVER_COMMAND_PREFIX + driverProperties.getService()); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + /** + * Binds the driver command queue to the command exchange. + * + * @param driverCommandQueue driver command queue + * @return queue binding + */ + @Bean + Binding driverCommandBinding(Queue driverCommandQueue) { + Binding binding = BindingBuilder.bind(driverCommandQueue) + .to(commandExchange) + .with(RabbitConstant.ROUTING_DRIVER_COMMAND_PREFIX + driverProperties.getService()); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } - /** - * Creates the device command queue used to receive device read and write commands. - * @return device command queue - */ - @Bean - Queue deviceCommandQueue() { - Map arguments = new HashMap<>(); - // 30 seconds: 30 * 1000 = 30000L - arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); - return new Queue(RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX + driverProperties.getService(), true, false, false, - arguments); - } + /** + * Creates the device command queue used to receive device read and write commands. + * + * @return device command queue + */ + @Bean + Queue deviceCommandQueue() { + Map arguments = new HashMap<>(); + // 30 seconds: 30 * 1000 = 30000L + arguments.put(RabbitConstant.MESSAGE_TTL, 30000L); + return new Queue(RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX + driverProperties.getService(), true, false, false, + arguments); + } - /** - * Binds the device command queue to the command exchange. - * @param deviceCommandQueue device command queue - * @return queue binding - */ - @Bean - Binding deviceCommandBinding(Queue deviceCommandQueue) { - Binding binding = BindingBuilder.bind(deviceCommandQueue) - .to(commandExchange) - .with(RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driverProperties.getService()); - binding.addArgument(RabbitConstant.AUTO_DELETE, false); - return binding; - } + /** + * Binds the device command queue to the command exchange. + * + * @param deviceCommandQueue device command queue + * @return queue binding + */ + @Bean + Binding deviceCommandBinding(Queue deviceCommandQueue) { + Binding binding = BindingBuilder.bind(deviceCommandQueue) + .to(commandExchange) + .with(RabbitConstant.ROUTING_DEVICE_COMMAND_PREFIX + driverProperties.getService()); + binding.addArgument(RabbitConstant.AUTO_DELETE, false); + return binding; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/PointValue.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/PointValue.java index a43a8b8b3..a9fd9be52 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/PointValue.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/PointValue.java @@ -42,52 +42,52 @@ import java.time.LocalDateTime; @JsonInclude(JsonInclude.Include.NON_NULL) public class PointValue implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Driver ID that collected the data. Populated by the sender before the message is - * published. - */ - private Long driverId; + /** + * Driver ID that collected the data. Populated by the sender before the message is + * published. + */ + private Long driverId; - /** - * Tenant ID the data belongs to. Populated by the sender before the message is - * published. - */ - private Long tenantId; + /** + * Tenant ID the data belongs to. Populated by the sender before the message is + * published. + */ + private Long tenantId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Raw value - */ - private String rawValue; + /** + * Raw value + */ + private String rawValue; - /** - * Calculated point value after applying scaling and type conversion. - */ - private String calValue; + /** + * Calculated point value after applying scaling and type conversion. + */ + private String calValue; - /** - * Time when the point value message was created. - */ - private LocalDateTime createTime; + /** + * Time when the point value message was created. + */ + private LocalDateTime createTime; - public PointValue(RValue calValue) { - this.deviceId = calValue.getDevice().getId(); - this.pointId = calValue.getPoint().getId(); - this.rawValue = calValue.getValue(); - this.calValue = calValue.getFinalValue(); - this.createTime = LocalDateTimeUtil.now(); - } + public PointValue(RValue calValue) { + this.deviceId = calValue.getDevice().getId(); + this.pointId = calValue.getPoint().getId(); + this.rawValue = calValue.getValue(); + this.calValue = calValue.getFinalValue(); + this.createTime = LocalDateTimeUtil.now(); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/RValue.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/RValue.java index a2f80f18c..205a7299d 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/RValue.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/RValue.java @@ -47,186 +47,189 @@ import java.util.Optional; @AllArgsConstructor public class RValue implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private static final BigDecimal defaultBase = new BigDecimal(0); + private static final BigDecimal defaultBase = new BigDecimal(0); - private static final BigDecimal defaultMultiple = new BigDecimal(1); + private static final BigDecimal defaultMultiple = new BigDecimal(1); - /** - * Source device that produced the value. - */ - private DeviceBO device; + /** + * Source device that produced the value. + */ + private DeviceBO device; - /** - * Point definition associated with the value. - */ - private PointBO point; + /** + * Point definition associated with the value. + */ + private PointBO point; - /** - * Raw point value represented as a string. - */ - private String value; + /** + * Raw point value represented as a string. + */ + private String value; - /** - * Returns the final point value after applying scaling and type conversion rules - * defined by the point metadata. - * @return final point value as a string - */ - public String getFinalValue() { - if (Objects.isNull(point)) { - throw new EmptyException("Point is empty"); - } + /** + * Returns the final point value after applying scaling and type conversion rules + * defined by the point metadata. + * + * @return final point value as a string + */ + public String getFinalValue() { + if (Objects.isNull(point)) { + throw new EmptyException("Point is empty"); + } - PointTypeFlagEnum valueType = Optional.ofNullable(point.getPointTypeFlag()).orElse(PointTypeFlagEnum.STRING); - BigDecimal base = Optional.ofNullable(point.getBaseValue()).orElse(defaultBase); - BigDecimal multiple = Optional.ofNullable(point.getMultiple()).orElse(defaultMultiple); - byte decimal = Optional.ofNullable(point.getValueDecimal()).orElse((byte) 6); + PointTypeFlagEnum valueType = Optional.ofNullable(point.getPointTypeFlag()).orElse(PointTypeFlagEnum.STRING); + BigDecimal base = Optional.ofNullable(point.getBaseValue()).orElse(defaultBase); + BigDecimal multiple = Optional.ofNullable(point.getMultiple()).orElse(defaultMultiple); + byte decimal = Optional.ofNullable(point.getValueDecimal()).orElse((byte) 6); - return switch (valueType) { - case STRING -> value; - case BYTE -> String.valueOf(getByteValue(value, base, multiple)); - case SHORT -> String.valueOf(getShortValue(value, base, multiple)); - case INT -> String.valueOf(getIntegerValue(value, base, multiple)); - case LONG -> String.valueOf(getLongValue(value, base, multiple)); - case FLOAT -> String.valueOf(getFloatValue(value, base, multiple, decimal)); - case DOUBLE -> String.valueOf(getDoubleValue(value, base, multiple, decimal)); - case BOOLEAN -> String.valueOf(getBooleanValue(value)); - }; - } + return switch (valueType) { + case STRING -> value; + case BYTE -> String.valueOf(getByteValue(value, base, multiple)); + case SHORT -> String.valueOf(getShortValue(value, base, multiple)); + case INT -> String.valueOf(getIntegerValue(value, base, multiple)); + case LONG -> String.valueOf(getLongValue(value, base, multiple)); + case FLOAT -> String.valueOf(getFloatValue(value, base, multiple, decimal)); + case DOUBLE -> String.valueOf(getDoubleValue(value, base, multiple, decimal)); + case BOOLEAN -> String.valueOf(getBooleanValue(value)); + }; + } - /** - * Applies a linear transformation using the formula {@code y = ax + b}. - * @param a multiplier - * @param x raw value - * @param b offset - * @return transformed decimal value - */ - private BigDecimal getLinearValue(BigDecimal a, String x, BigDecimal b) { - BigDecimal bigDecimal = new BigDecimal(x); - if (defaultMultiple.compareTo(a) == 0 && defaultBase.compareTo(b) == 0) { - return bigDecimal; - } - if (defaultMultiple.compareTo(a) != 0 && defaultBase.compareTo(b) == 0) { - return bigDecimal.multiply(a); - } - if (defaultMultiple.compareTo(a) == 0 && defaultBase.compareTo(b) != 0) { - return bigDecimal.add(b); - } - BigDecimal multiply = a.multiply(bigDecimal); - return multiply.add(b); - } + /** + * Applies a linear transformation using the formula {@code y = ax + b}. + * + * @param a multiplier + * @param x raw value + * @param b offset + * @return transformed decimal value + */ + private BigDecimal getLinearValue(BigDecimal a, String x, BigDecimal b) { + BigDecimal bigDecimal = new BigDecimal(x); + if (defaultMultiple.compareTo(a) == 0 && defaultBase.compareTo(b) == 0) { + return bigDecimal; + } + if (defaultMultiple.compareTo(a) != 0 && defaultBase.compareTo(b) == 0) { + return bigDecimal.multiply(a); + } + if (defaultMultiple.compareTo(a) == 0 && defaultBase.compareTo(b) != 0) { + return bigDecimal.add(b); + } + BigDecimal multiply = a.multiply(bigDecimal); + return multiply.add(b); + } - /** - * Converts the raw value to a byte after linear scaling. - * @param rawValue raw value - * @return converted byte value - */ - private byte getByteValue(String rawValue, BigDecimal base, BigDecimal multiple) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - return multiply.byteValue(); - } - catch (Exception e) { - throw new OutRangeException("Out of byte range: {} ~ {}, current: {}", Byte.MIN_VALUE, Byte.MAX_VALUE, - rawValue); - } - } + /** + * Converts the raw value to a byte after linear scaling. + * + * @param rawValue raw value + * @return converted byte value + */ + private byte getByteValue(String rawValue, BigDecimal base, BigDecimal multiple) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + return multiply.byteValue(); + } catch (Exception e) { + throw new OutRangeException("Out of byte range: {} ~ {}, current: {}", Byte.MIN_VALUE, Byte.MAX_VALUE, + rawValue); + } + } - /** - * Converts the raw value to a short after linear scaling. - * @param rawValue raw value - * @return converted short value - */ - private short getShortValue(String rawValue, BigDecimal base, BigDecimal multiple) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - return multiply.shortValue(); - } - catch (Exception e) { - throw new OutRangeException("Out of short range: {} ~ {}, current: {}", Short.MIN_VALUE, Short.MAX_VALUE, - rawValue); - } - } + /** + * Converts the raw value to a short after linear scaling. + * + * @param rawValue raw value + * @return converted short value + */ + private short getShortValue(String rawValue, BigDecimal base, BigDecimal multiple) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + return multiply.shortValue(); + } catch (Exception e) { + throw new OutRangeException("Out of short range: {} ~ {}, current: {}", Short.MIN_VALUE, Short.MAX_VALUE, + rawValue); + } + } - /** - * Converts the raw value to an integer after linear scaling. - * @param rawValue raw value - * @return converted integer value - */ - private int getIntegerValue(String rawValue, BigDecimal base, BigDecimal multiple) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - return multiply.intValue(); - } - catch (Exception e) { - throw new OutRangeException("Out of int range: {} ~ {}, current: {}", Integer.MIN_VALUE, Integer.MAX_VALUE, - rawValue); - } - } + /** + * Converts the raw value to an integer after linear scaling. + * + * @param rawValue raw value + * @return converted integer value + */ + private int getIntegerValue(String rawValue, BigDecimal base, BigDecimal multiple) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + return multiply.intValue(); + } catch (Exception e) { + throw new OutRangeException("Out of int range: {} ~ {}, current: {}", Integer.MIN_VALUE, Integer.MAX_VALUE, + rawValue); + } + } - /** - * Converts the raw value to a long after linear scaling. - * @param rawValue raw value - * @return converted long value - */ - private long getLongValue(String rawValue, BigDecimal base, BigDecimal multiple) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - return multiply.longValue(); - } - catch (Exception e) { - throw new OutRangeException("Out of long range: {} ~ {}, current: {}", Long.MIN_VALUE, Long.MAX_VALUE, - rawValue); - } - } + /** + * Converts the raw value to a long after linear scaling. + * + * @param rawValue raw value + * @return converted long value + */ + private long getLongValue(String rawValue, BigDecimal base, BigDecimal multiple) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + return multiply.longValue(); + } catch (Exception e) { + throw new OutRangeException("Out of long range: {} ~ {}, current: {}", Long.MIN_VALUE, Long.MAX_VALUE, + rawValue); + } + } - /** - * Converts the raw value to a rounded float after linear scaling. - * @param rawValue raw value - * @return converted float value - */ - private float getFloatValue(String rawValue, BigDecimal base, BigDecimal multiple, byte decimal) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - if (Float.isInfinite(multiply.floatValue())) { - throw new OutRangeException(); - } - return ArithmeticUtil.round(multiply.floatValue(), decimal); - } - catch (Exception e) { - throw new OutRangeException("Out of float range: |{} ~ {}|, current: {}", Float.MIN_VALUE, Float.MAX_VALUE, - rawValue); - } - } + /** + * Converts the raw value to a rounded float after linear scaling. + * + * @param rawValue raw value + * @return converted float value + */ + private float getFloatValue(String rawValue, BigDecimal base, BigDecimal multiple, byte decimal) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + if (Float.isInfinite(multiply.floatValue())) { + throw new OutRangeException(); + } + return ArithmeticUtil.round(multiply.floatValue(), decimal); + } catch (Exception e) { + throw new OutRangeException("Out of float range: |{} ~ {}|, current: {}", Float.MIN_VALUE, Float.MAX_VALUE, + rawValue); + } + } - /** - * Converts the raw value to a rounded double after linear scaling. - * @param rawValue raw value - * @return converted double value - */ - private double getDoubleValue(String rawValue, BigDecimal base, BigDecimal multiple, byte decimal) { - try { - BigDecimal multiply = getLinearValue(multiple, rawValue, base); - if (Double.isInfinite(multiply.doubleValue())) { - throw new OutRangeException(); - } - return ArithmeticUtil.round(multiply.doubleValue(), decimal); - } - catch (Exception e) { - throw new OutRangeException("Out of double range: |{} ~ {}|, current: {}", Double.MIN_VALUE, - Double.MAX_VALUE, rawValue); - } - } + /** + * Converts the raw value to a rounded double after linear scaling. + * + * @param rawValue raw value + * @return converted double value + */ + private double getDoubleValue(String rawValue, BigDecimal base, BigDecimal multiple, byte decimal) { + try { + BigDecimal multiply = getLinearValue(multiple, rawValue, base); + if (Double.isInfinite(multiply.doubleValue())) { + throw new OutRangeException(); + } + return ArithmeticUtil.round(multiply.doubleValue(), decimal); + } catch (Exception e) { + throw new OutRangeException("Out of double range: |{} ~ {}|, current: {}", Double.MIN_VALUE, + Double.MAX_VALUE, rawValue); + } + } - /** - * Converts the raw value to a boolean. - * @param rawValue raw value - * @return converted boolean value - */ - private boolean getBooleanValue(String rawValue) { - return Boolean.parseBoolean(rawValue); - } + /** + * Converts the raw value to a boolean. + * + * @param rawValue raw value + * @return converted boolean value + */ + private boolean getBooleanValue(String rawValue) { + return Boolean.parseBoolean(rawValue); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/WValue.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/WValue.java index f499a5af7..0c8e0f701 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/WValue.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bean/WValue.java @@ -43,85 +43,86 @@ import java.util.Objects; @AllArgsConstructor public class WValue implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Raw value content stored as a string before type conversion. - */ - private String value; + /** + * Raw value content stored as a string before type conversion. + */ + private String value; - /** - * Declared point type used to convert the raw string value. - */ - private PointTypeFlagEnum type; + /** + * Declared point type used to convert the raw string value. + */ + private PointTypeFlagEnum type; - /** - * Converts the stored string value to the requested boxed Java type. - * @param clazz target boxed type - * @param target type parameter - * @return converted value - */ - @SuppressWarnings("unchecked") - public T getValue(Class clazz) { - if (Objects.isNull(type)) { - throw new UnSupportException("Unsupported point type of " + type); - } - if (StringUtils.isEmpty(value)) { - throw new EmptyException("Point value is empty"); - } + /** + * Converts the stored string value to the requested boxed Java type. + * + * @param clazz target boxed type + * @param target type parameter + * @return converted value + */ + @SuppressWarnings("unchecked") + public T getValue(Class clazz) { + if (Objects.isNull(type)) { + throw new UnSupportException("Unsupported point type of " + type); + } + if (StringUtils.isEmpty(value)) { + throw new EmptyException("Point value is empty"); + } - final String message = "Point type is: {}, can't be cast to class: {}"; - return switch (type) { - case STRING -> { - if (!clazz.equals(String.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) value; - } - case BYTE -> { - if (!clazz.equals(Byte.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Byte.valueOf(value); - } - case SHORT -> { - if (!clazz.equals(Short.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Short.valueOf(value); - } - case INT -> { - if (!clazz.equals(Integer.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Integer.valueOf(value); - } - case LONG -> { - if (!clazz.equals(Long.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Long.valueOf(value); - } - case FLOAT -> { - if (!clazz.equals(Float.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Float.valueOf(value); - } - case DOUBLE -> { - if (!clazz.equals(Double.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Double.valueOf(value); - } - case BOOLEAN -> { - if (!clazz.equals(Boolean.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Boolean.valueOf(value); - } - }; - } + final String message = "Point type is: {}, can't be cast to class: {}"; + return switch (type) { + case STRING -> { + if (!clazz.equals(String.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) value; + } + case BYTE -> { + if (!clazz.equals(Byte.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Byte.valueOf(value); + } + case SHORT -> { + if (!clazz.equals(Short.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Short.valueOf(value); + } + case INT -> { + if (!clazz.equals(Integer.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Integer.valueOf(value); + } + case LONG -> { + if (!clazz.equals(Long.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Long.valueOf(value); + } + case FLOAT -> { + if (!clazz.equals(Float.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Float.valueOf(value); + } + case DOUBLE -> { + if (!clazz.equals(Double.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Double.valueOf(value); + } + case BOOLEAN -> { + if (!clazz.equals(Boolean.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Boolean.valueOf(value); + } + }; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/AttributeBO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/AttributeBO.java index 0915907b5..d216fb886 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/AttributeBO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/AttributeBO.java @@ -43,85 +43,86 @@ import java.util.Objects; @AllArgsConstructor public class AttributeBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Raw attribute value stored as a string. - */ - private String value; + /** + * Raw attribute value stored as a string. + */ + private String value; - /** - * Declared attribute type used for conversion. - */ - private AttributeTypeFlagEnum type; + /** + * Declared attribute type used for conversion. + */ + private AttributeTypeFlagEnum type; - /** - * Converts the attribute value to the requested boxed Java type. - * @param clazz target boxed type - * @param target type parameter - * @return converted value - */ - @SuppressWarnings("unchecked") - public T getValue(Class clazz) { - if (Objects.isNull(type)) { - throw new UnSupportException("Unsupported attribute type of " + type); - } - if (StringUtils.isEmpty(value)) { - throw new EmptyException("Attribute value is empty"); - } + /** + * Converts the attribute value to the requested boxed Java type. + * + * @param clazz target boxed type + * @param target type parameter + * @return converted value + */ + @SuppressWarnings("unchecked") + public T getValue(Class clazz) { + if (Objects.isNull(type)) { + throw new UnSupportException("Unsupported attribute type of " + type); + } + if (StringUtils.isEmpty(value)) { + throw new EmptyException("Attribute value is empty"); + } - final String message = "Attribute type is: {}, can't be cast to class: {}"; - return switch (type) { - case STRING -> { - if (!clazz.equals(String.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) value; - } - case BYTE -> { - if (!clazz.equals(Byte.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Byte.valueOf(value); - } - case SHORT -> { - if (!clazz.equals(Short.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Short.valueOf(value); - } - case INT -> { - if (!clazz.equals(Integer.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Integer.valueOf(value); - } - case LONG -> { - if (!clazz.equals(Long.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Long.valueOf(value); - } - case FLOAT -> { - if (!clazz.equals(Float.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Float.valueOf(value); - } - case DOUBLE -> { - if (!clazz.equals(Double.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Double.valueOf(value); - } - case BOOLEAN -> { - if (!clazz.equals(Boolean.class)) { - throw new TypeException(message, type.getCode(), clazz.getName()); - } - yield (T) Boolean.valueOf(value); - } - }; - } + final String message = "Attribute type is: {}, can't be cast to class: {}"; + return switch (type) { + case STRING -> { + if (!clazz.equals(String.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) value; + } + case BYTE -> { + if (!clazz.equals(Byte.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Byte.valueOf(value); + } + case SHORT -> { + if (!clazz.equals(Short.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Short.valueOf(value); + } + case INT -> { + if (!clazz.equals(Integer.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Integer.valueOf(value); + } + case LONG -> { + if (!clazz.equals(Long.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Long.valueOf(value); + } + case FLOAT -> { + if (!clazz.equals(Float.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Float.valueOf(value); + } + case DOUBLE -> { + if (!clazz.equals(Double.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Double.valueOf(value); + } + case BOOLEAN -> { + if (!clazz.equals(Boolean.class)) { + throw new TypeException(message, type.getCode(), clazz.getName()); + } + yield (T) Boolean.valueOf(value); + } + }; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DeviceBO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DeviceBO.java index 9de9acf50..4f71104fe 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DeviceBO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DeviceBO.java @@ -42,65 +42,65 @@ import java.util.Set; @ToString(callSuper = true) public class DeviceBO extends BaseBO { - /** - * Device display name. - */ - private String deviceName; + /** + * Device display name. + */ + private String deviceName; - /** - * Device code defined in the platform. - */ - private String deviceCode; + /** + * Device code defined in the platform. + */ + private String deviceCode; - /** - * Owning driver identifier. - */ - private Long driverId; + /** + * Owning driver identifier. + */ + private Long driverId; - /** - * Extended device metadata. - */ - private DeviceExt deviceExt; + /** + * Extended device metadata. + */ + private DeviceExt deviceExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; - /** - * Assigned profile identifiers. - */ - private Set profileIds; + /** + * Assigned profile identifiers. + */ + private Set profileIds; - /** - * Identifiers of points owned by the device. - */ - private Set pointIds; + /** + * Identifiers of points owned by the device. + */ + private Set pointIds; - /** - * Driver attribute configuration map keyed by attribute identifier. - */ - private Map driverAttributeConfigIdMap; + /** + * Driver attribute configuration map keyed by attribute identifier. + */ + private Map driverAttributeConfigIdMap; - /** - * Point attribute configuration map keyed by point identifier and then attribute - * identifier. - */ - private Map> pointAttributeConfigIdMap; + /** + * Point attribute configuration map keyed by point identifier and then attribute + * identifier. + */ + private Map> pointAttributeConfigIdMap; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DriverBO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DriverBO.java index 754c06a13..079d3c427 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DriverBO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/DriverBO.java @@ -37,54 +37,54 @@ import lombok.*; @ToString(callSuper = true) public class DriverBO extends BaseBO { - /** - * Driver display name. - */ - private String driverName; + /** + * Driver display name. + */ + private String driverName; - /** - * Driver code defined in configuration. - */ - private String driverCode; + /** + * Driver code defined in configuration. + */ + private String driverCode; - /** - * Driver service name used for registration and routing. - */ - private String serviceName; + /** + * Driver service name used for registration and routing. + */ + private String serviceName; - /** - * Driver service host address. - */ - private String serviceHost; + /** + * Driver service host address. + */ + private String serviceHost; - /** - * Driver runtime type. - */ - private DriverTypeFlagEnum driverTypeFlag; + /** + * Driver runtime type. + */ + private DriverTypeFlagEnum driverTypeFlag; - /** - * Extended driver metadata. - */ - private DriverExt driverExt; + /** + * Extended driver metadata. + */ + private DriverExt driverExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/PointBO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/PointBO.java index a5c14b67e..704e28350 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/PointBO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/PointBO.java @@ -41,74 +41,74 @@ import java.math.BigDecimal; @ToString(callSuper = true) public class PointBO extends BaseBO { - /** - * Point display name. - */ - private String pointName; + /** + * Point display name. + */ + private String pointName; - /** - * Point code defined in the platform. - */ - private String pointCode; + /** + * Point code defined in the platform. + */ + private String pointCode; - /** - * Point data type. - */ - private PointTypeFlagEnum pointTypeFlag; + /** + * Point data type. + */ + private PointTypeFlagEnum pointTypeFlag; - /** - * Read/write capability of the point. - */ - private RwFlagEnum rwFlag; + /** + * Read/write capability of the point. + */ + private RwFlagEnum rwFlag; - /** - * Base offset applied during value conversion. - */ - private BigDecimal baseValue; + /** + * Base offset applied during value conversion. + */ + private BigDecimal baseValue; - /** - * Multiplier applied during value conversion. - */ - private BigDecimal multiple; + /** + * Multiplier applied during value conversion. + */ + private BigDecimal multiple; - /** - * Decimal precision used for floating-point rounding. - */ - private Byte valueDecimal; + /** + * Decimal precision used for floating-point rounding. + */ + private Byte valueDecimal; - /** - * Engineering unit of the point value. - */ - private String unit; + /** + * Engineering unit of the point value. + */ + private String unit; - /** - * Associated profile identifier. - */ - private Long profileId; + /** + * Associated profile identifier. + */ + private Long profileId; - /** - * Extended point metadata. - */ - private PointExt pointExt; + /** + * Extended point metadata. + */ + private PointExt pointExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/RegisterBO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/RegisterBO.java index f94e040fc..6cbabf1f9 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/RegisterBO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/bo/RegisterBO.java @@ -41,32 +41,32 @@ import java.util.List; @AllArgsConstructor public class RegisterBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Tenant name of the driver instance. - */ - private String tenant; + /** + * Tenant name of the driver instance. + */ + private String tenant; - /** - * Driver client identifier. - */ - private String client; + /** + * Driver client identifier. + */ + private String client; - /** - * Driver definition to register. - */ - private DriverBO driver; + /** + * Driver definition to register. + */ + private DriverBO driver; - /** - * Driver-level attribute definitions. - */ - private List driverAttributes; + /** + * Driver-level attribute definitions. + */ + private List driverAttributes; - /** - * Point-level attribute definitions. - */ - private List pointAttributes; + /** + * Point-level attribute definitions. + */ + private List pointAttributes; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DeviceBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DeviceBuilder.java index ddd2b1243..a8176f08f 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DeviceBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DeviceBuilder.java @@ -40,34 +40,34 @@ import java.util.HashSet; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DeviceBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "deviceExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "profileIds", ignore = true) - @Mapping(target = "pointIds", ignore = true) - @Mapping(target = "driverAttributeConfigIdMap", ignore = true) - @Mapping(target = "pointAttributeConfigIdMap", ignore = true) - DeviceBO buildDTOByGrpcDTO(GrpcDeviceDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "deviceExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "profileIds", ignore = true) + @Mapping(target = "pointIds", ignore = true) + @Mapping(target = "driverAttributeConfigIdMap", ignore = true) + @Mapping(target = "pointAttributeConfigIdMap", ignore = true) + DeviceBO buildDTOByGrpcDTO(GrpcDeviceDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDeviceDTO entityGrpc, @MappingTarget DeviceBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcDeviceDTO entityGrpc, @MappingTarget DeviceBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - CollectionOptional.ofNullable(entityGrpc.getProfileIdsList()) - .ifPresent(value -> entityBO.setProfileIds(new HashSet<>(value))); - JsonOptional.ofNullable(entityGrpc.getDeviceExt()) - .ifPresent(value -> entityBO.setDeviceExt(JsonUtil.parseObject(value, DeviceExt.class))); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + CollectionOptional.ofNullable(entityGrpc.getProfileIdsList()) + .ifPresent(value -> entityBO.setProfileIds(new HashSet<>(value))); + JsonOptional.ofNullable(entityGrpc.getDeviceExt()) + .ifPresent(value -> entityBO.setDeviceExt(JsonUtil.parseObject(value, DeviceExt.class))); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DriverBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DriverBuilder.java index 8b994a771..b14dfa571 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DriverBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/DriverBuilder.java @@ -43,65 +43,65 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DriverBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverBO buildDTOByGrpcDTO(GrpcDriverDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverBO buildDTOByGrpcDTO(GrpcDriverDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDriverDTO entityGrpc, @MappingTarget DriverBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcDriverDTO entityGrpc, @MappingTarget DriverBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - JsonOptional.ofNullable(entityGrpc.getDriverExt()) - .ifPresent(value -> entityBO.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); - Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) - .ifPresent(entityBO::setDriverTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getDriverExt()) + .ifPresent(value -> entityBO.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); + Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) + .ifPresent(entityBO::setDriverTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "driverNameBytes", ignore = true) - @Mapping(target = "driverCodeBytes", ignore = true) - @Mapping(target = "serviceNameBytes", ignore = true) - @Mapping(target = "serviceHostBytes", ignore = true) - @Mapping(target = "driverExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDriverDTO buildGrpcDTOByDTO(DriverBO entityDTO); + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "driverNameBytes", ignore = true) + @Mapping(target = "driverCodeBytes", ignore = true) + @Mapping(target = "serviceNameBytes", ignore = true) + @Mapping(target = "serviceHostBytes", ignore = true) + @Mapping(target = "driverExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDriverDTO buildGrpcDTOByDTO(DriverBO entityDTO); - @AfterMapping - default void afterProcess(DriverBO entityDTO, @MappingTarget GrpcDriverDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityDTO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DriverBO entityDTO, @MappingTarget GrpcDriverDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityDTO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityDTO.getDriverExt()) - .ifPresent(value -> entityGrpc.setDriverExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityDTO.getDriverTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setDriverTypeFlag(value.getIndex()), - () -> entityGrpc.setDriverTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityDTO.getDriverExt()) + .ifPresent(value -> entityGrpc.setDriverExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityDTO.getDriverTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setDriverTypeFlag(value.getIndex()), + () -> entityGrpc.setDriverTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeBuilder.java index 13856c1cd..b73329820 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeBuilder.java @@ -43,64 +43,64 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDriverAttributeBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverAttributeDTO buildDTOByGrpcDTO(GrpcDriverAttributeDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverAttributeDTO buildDTOByGrpcDTO(GrpcDriverAttributeDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDriverAttributeDTO entityGrpc, @MappingTarget DriverAttributeDTO entityDTO) { - GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); + @AfterMapping + default void afterProcess(GrpcDriverAttributeDTO entityGrpc, @MappingTarget DriverAttributeDTO entityDTO) { + GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); - JsonOptional.ofNullable(entityGrpc.getAttributeExt()) - .ifPresent(value -> entityDTO.setAttributeExt(JsonUtil.parseObject(value, DriverAttributeExt.class))); - Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) - .ifPresent(entityDTO::setAttributeTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getAttributeExt()) + .ifPresent(value -> entityDTO.setAttributeExt(JsonUtil.parseObject(value, DriverAttributeExt.class))); + Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) + .ifPresent(entityDTO::setAttributeTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); + } - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "attributeNameBytes", ignore = true) - @Mapping(target = "attributeCodeBytes", ignore = true) - @Mapping(target = "defaultValueBytes", ignore = true) - @Mapping(target = "attributeExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDriverAttributeDTO buildGrpcDTOByDTO(DriverAttributeDTO entityDTO); + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "attributeNameBytes", ignore = true) + @Mapping(target = "attributeCodeBytes", ignore = true) + @Mapping(target = "defaultValueBytes", ignore = true) + @Mapping(target = "attributeExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDriverAttributeDTO buildGrpcDTOByDTO(DriverAttributeDTO entityDTO); - @AfterMapping - default void afterProcess(DriverAttributeDTO entityDTO, @MappingTarget GrpcDriverAttributeDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByDTO(entityDTO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DriverAttributeDTO entityDTO, @MappingTarget GrpcDriverAttributeDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByDTO(entityDTO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityDTO.getAttributeExt()) - .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityDTO.getAttributeTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), - () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityDTO.getAttributeExt()) + .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityDTO.getAttributeTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), + () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeConfigBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeConfigBuilder.java index 755504b2d..e008b1e64 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcDriverAttributeConfigBuilder.java @@ -35,26 +35,26 @@ import org.mapstruct.MappingTarget; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDriverAttributeConfigBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverAttributeConfigDTO buildDTOByGrpcDTO(GrpcDriverAttributeConfigDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverAttributeConfigDTO buildDTOByGrpcDTO(GrpcDriverAttributeConfigDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDriverAttributeConfigDTO entityGrpc, - @MappingTarget DriverAttributeConfigDTO entityDTO) { - GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); + @AfterMapping + default void afterProcess(GrpcDriverAttributeConfigDTO entityGrpc, + @MappingTarget DriverAttributeConfigDTO entityDTO) { + GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); - } + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeBuilder.java index 2d971bc81..70207c81a 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeBuilder.java @@ -43,64 +43,64 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcPointAttributeBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointAttributeDTO buildDTOByGrpcDTO(GrpcPointAttributeDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointAttributeDTO buildDTOByGrpcDTO(GrpcPointAttributeDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcPointAttributeDTO entityGrpc, @MappingTarget PointAttributeDTO entityDTO) { - GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); + @AfterMapping + default void afterProcess(GrpcPointAttributeDTO entityGrpc, @MappingTarget PointAttributeDTO entityDTO) { + GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); - JsonOptional.ofNullable(entityGrpc.getAttributeExt()) - .ifPresent(value -> entityDTO.setAttributeExt(JsonUtil.parseObject(value, PointAttributeExt.class))); - Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) - .ifPresent(entityDTO::setAttributeTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getAttributeExt()) + .ifPresent(value -> entityDTO.setAttributeExt(JsonUtil.parseObject(value, PointAttributeExt.class))); + Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) + .ifPresent(entityDTO::setAttributeTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); + } - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "attributeNameBytes", ignore = true) - @Mapping(target = "attributeCodeBytes", ignore = true) - @Mapping(target = "defaultValueBytes", ignore = true) - @Mapping(target = "attributeExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcPointAttributeDTO buildGrpcDTOByDTO(PointAttributeDTO entityDTO); + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "attributeNameBytes", ignore = true) + @Mapping(target = "attributeCodeBytes", ignore = true) + @Mapping(target = "defaultValueBytes", ignore = true) + @Mapping(target = "attributeExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcPointAttributeDTO buildGrpcDTOByDTO(PointAttributeDTO entityDTO); - @AfterMapping - default void afterProcess(PointAttributeDTO entityDTO, @MappingTarget GrpcPointAttributeDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByDTO(entityDTO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(PointAttributeDTO entityDTO, @MappingTarget GrpcPointAttributeDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByDTO(entityDTO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityDTO.getAttributeExt()) - .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityDTO.getAttributeTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), - () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityDTO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityDTO.getAttributeExt()) + .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityDTO.getAttributeTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), + () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityDTO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeConfigBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeConfigBuilder.java index 3a8fbc202..9620d1092 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/GrpcPointAttributeConfigBuilder.java @@ -34,26 +34,26 @@ import org.mapstruct.MappingTarget; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcPointAttributeConfigBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointAttributeConfigDTO buildDTOByGrpcDTO(GrpcPointAttributeConfigDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointAttributeConfigDTO buildDTOByGrpcDTO(GrpcPointAttributeConfigDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcPointAttributeConfigDTO entityGrpc, - @MappingTarget PointAttributeConfigDTO entityDTO) { - GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); + @AfterMapping + default void afterProcess(GrpcPointAttributeConfigDTO entityGrpc, + @MappingTarget PointAttributeConfigDTO entityDTO) { + GrpcBuilderUtil.buildBaseDTOByGrpcBase(entityGrpc.getBase(), entityDTO); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); - } + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityDTO::setEnableFlag); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/PointBuilder.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/PointBuilder.java index 8c68d7b4a..3d8efec99 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/PointBuilder.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/builder/PointBuilder.java @@ -41,33 +41,33 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface PointBuilder { - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "pointExt", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointBO buildDTOByGrpcDTO(GrpcPointDTO entityGrpc); + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "pointExt", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointBO buildDTOByGrpcDTO(GrpcPointDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcPointDTO entityGrpc, @MappingTarget PointBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcPointDTO entityGrpc, @MappingTarget PointBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - JsonOptional.ofNullable(entityGrpc.getPointExt()) - .ifPresent(value -> entityBO.setPointExt(JsonUtil.parseObject(value, PointExt.class))); - Optional.ofNullable(RwFlagEnum.ofIndex((byte) entityGrpc.getRwFlag())).ifPresent(entityBO::setRwFlag); - Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) entityGrpc.getPointTypeFlag())) - .ifPresent(entityBO::setPointTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getPointExt()) + .ifPresent(value -> entityBO.setPointExt(JsonUtil.parseObject(value, PointExt.class))); + Optional.ofNullable(RwFlagEnum.ofIndex((byte) entityGrpc.getRwFlag())).ifPresent(entityBO::setRwFlag); + Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) entityGrpc.getPointTypeFlag())) + .ifPresent(entityBO::setPointTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeConfigDTO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeConfigDTO.java index 7c4ab98e3..76e1d272f 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeConfigDTO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeConfigDTO.java @@ -38,39 +38,39 @@ import lombok.Setter; @AllArgsConstructor public class DriverAttributeConfigDTO extends BaseDTO { - /** - * Referenced attribute identifier. - */ - private Long attributeId; + /** + * Referenced attribute identifier. + */ + private Long attributeId; - /** - * Configured attribute value. - */ - private String configValue; + /** + * Configured attribute value. + */ + private String configValue; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeDTO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeDTO.java index 4c708a5f5..419f75923 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeDTO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/DriverAttributeDTO.java @@ -39,54 +39,54 @@ import lombok.Setter; @AllArgsConstructor public class DriverAttributeDTO extends BaseDTO { - /** - * Attribute display name. - */ - private String attributeName; + /** + * Attribute display name. + */ + private String attributeName; - /** - * Attribute code used in configuration maps. - */ - private String attributeCode; + /** + * Attribute code used in configuration maps. + */ + private String attributeCode; - /** - * Attribute value type. - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Attribute value type. + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * Default value used when no explicit configuration is provided. - */ - private String defaultValue; + /** + * Default value used when no explicit configuration is provided. + */ + private String defaultValue; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Extended attribute metadata. - */ - private DriverAttributeExt attributeExt; + /** + * Extended attribute metadata. + */ + private DriverAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeConfigDTO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeConfigDTO.java index 940cbf735..f70636398 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeConfigDTO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeConfigDTO.java @@ -38,44 +38,44 @@ import lombok.Setter; @AllArgsConstructor public class PointAttributeConfigDTO extends BaseDTO { - /** - * Referenced attribute identifier. - */ - private Long attributeId; + /** + * Referenced attribute identifier. + */ + private Long attributeId; - /** - * Configured attribute value. - */ - private String configValue; + /** + * Configured attribute value. + */ + private String configValue; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeDTO.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeDTO.java index 63b5e05cb..f0afe6982 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeDTO.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/dto/PointAttributeDTO.java @@ -39,54 +39,54 @@ import lombok.Setter; @AllArgsConstructor public class PointAttributeDTO extends BaseDTO { - /** - * Attribute display name. - */ - private String attributeName; + /** + * Attribute display name. + */ + private String attributeName; - /** - * Attribute code used in configuration maps. - */ - private String attributeCode; + /** + * Attribute code used in configuration maps. + */ + private String attributeCode; - /** - * Attribute value type. - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Attribute value type. + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * Default value used when no explicit configuration is provided. - */ - private String defaultValue; + /** + * Default value used when no explicit configuration is provided. + */ + private String defaultValue; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Extended attribute metadata. - */ - private PointAttributeExt attributeExt; + /** + * Extended attribute metadata. + */ + private PointAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant identifier. - */ - private Long tenantId; + /** + * Tenant identifier. + */ + private Long tenantId; - /** - * Data signature used for optimistic checks or synchronization. - */ - private String signature; + /** + * Data signature used for optimistic checks or synchronization. + */ + private String signature; - /** - * Data version. - */ - private Integer version; + /** + * Data version. + */ + private Integer version; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/property/DriverProperties.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/property/DriverProperties.java index e4a2c5876..15e4e7798 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/property/DriverProperties.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/entity/property/DriverProperties.java @@ -45,116 +45,116 @@ import java.util.List; @ConfigurationProperties(prefix = "driver") public class DriverProperties { - /** - * Tenant name of the driver instance. - */ - @NotBlank(message = "租户不能为空") - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的租户") - private String tenant; + /** + * Tenant name of the driver instance. + */ + @NotBlank(message = "租户不能为空") + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的租户") + private String tenant; - /** - * Driver runtime type. - */ - @NotNull(message = "驱动类型不能为空") - private DriverTypeFlagEnum type = DriverTypeFlagEnum.DRIVER_CLIENT; + /** + * Driver runtime type. + */ + @NotNull(message = "驱动类型不能为空") + private DriverTypeFlagEnum type = DriverTypeFlagEnum.DRIVER_CLIENT; - /** - * Driver display name. - */ - @NotBlank(message = "驱动名称不能为空") - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "驱动名称格式无效") - private String name; + /** + * Driver display name. + */ + @NotBlank(message = "驱动名称不能为空") + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "驱动名称格式无效") + private String name; - /** - * Driver code defined in configuration. - */ - @NotBlank(message = "驱动编号不能为空") - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的驱动编号") - private String code; + /** + * Driver code defined in configuration. + */ + @NotBlank(message = "驱动编号不能为空") + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "无效的驱动编号") + private String code; - /** - * Description - */ - private String remark; + /** + * Description + */ + private String remark; - /** - * Schedule configuration for periodic driver tasks. - */ - private ScheduleProperties schedule; + /** + * Schedule configuration for periodic driver tasks. + */ + private ScheduleProperties schedule; - /** - * Driver-level attribute definitions declared in configuration. - */ - private List driverAttribute; + /** + * Driver-level attribute definitions declared in configuration. + */ + private List driverAttribute; - /** - * Point-level attribute definitions declared in configuration. - */ - private List pointAttribute; + /** + * Point-level attribute definitions declared in configuration. + */ + private List pointAttribute; - /** - * Generated or configured driver node identifier. - */ - private String node; + /** + * Generated or configured driver node identifier. + */ + private String node; - /** - * Driver service name, typically composed from tenant and application name. - */ - private String service; + /** + * Driver service name, typically composed from tenant and application name. + */ + private String service; - /** - * Host address exposed by the driver process. - */ - private String host; + /** + * Host address exposed by the driver process. + */ + private String host; - /** - * Service port exposed by the driver process. - */ - private Integer port; + /** + * Service port exposed by the driver process. + */ + private Integer port; - /** - * Driver client identifier used for queue and registration routing. - */ - private String client; + /** + * Driver client identifier used for queue and registration routing. + */ + private String client; - /** - * Scheduling options for built-in driver jobs. - */ - @Getter - @Setter - public static class ScheduleProperties { + /** + * Scheduling options for built-in driver jobs. + */ + @Getter + @Setter + public static class ScheduleProperties { - /** - * Periodic read job configuration. - */ - private ScheduleConfig read; + /** + * Periodic read job configuration. + */ + private ScheduleConfig read; - /** - * Custom job configuration. - */ - private ScheduleConfig custom; + /** + * Custom job configuration. + */ + private ScheduleConfig custom; - /** - * Cron-based schedule definition. - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class ScheduleConfig { + /** + * Cron-based schedule definition. + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class ScheduleConfig { - /** - * Whether the job is enabled. - */ - private Boolean enable = false; + /** + * Whether the job is enabled. + */ + private Boolean enable = false; - /** - * Quartz cron expression used by the job. - */ - private String cron = "* */15 * * * ?"; + /** + * Quartz cron expression used by the job. + */ + private String cron = "* */15 * * * ?"; - } + } - } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventListener.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventListener.java index 93fed0818..f5c0932a5 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventListener.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventListener.java @@ -38,30 +38,29 @@ import org.springframework.stereotype.Component; @Component public class MetadataEventListener implements ApplicationListener { - private final DriverCustomService driverCustomService; + private final DriverCustomService driverCustomService; - public MetadataEventListener(DriverCustomService driverCustomService) { - this.driverCustomService = driverCustomService; - } + public MetadataEventListener(DriverCustomService driverCustomService) { + this.driverCustomService = driverCustomService; + } - @Override - public void onApplicationEvent(MetadataEvent metadataEvent) { - log.info("Metadata event listener received: {}", JsonUtil.toJsonString(metadataEvent)); - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - MetadataEventDTO entityEvent = new MetadataEventDTO(); - entityEvent.setId(metadataEvent.getId()); - entityEvent.setMetadataType(MetadataTypeEnum.DEVICE); - entityEvent.setOperateType(metadataEvent.getOperateType()); - driverCustomService.event(entityEvent); - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - MetadataEventDTO entityEvent = new MetadataEventDTO(); - entityEvent.setId(metadataEvent.getId()); - entityEvent.setMetadataType(MetadataTypeEnum.POINT); - entityEvent.setOperateType(metadataEvent.getOperateType()); - driverCustomService.event(entityEvent); - } - } + @Override + public void onApplicationEvent(MetadataEvent metadataEvent) { + log.info("Metadata event listener received: {}", JsonUtil.toJsonString(metadataEvent)); + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + MetadataEventDTO entityEvent = new MetadataEventDTO(); + entityEvent.setId(metadataEvent.getId()); + entityEvent.setMetadataType(MetadataTypeEnum.DEVICE); + entityEvent.setOperateType(metadataEvent.getOperateType()); + driverCustomService.event(entityEvent); + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + MetadataEventDTO entityEvent = new MetadataEventDTO(); + entityEvent.setId(metadataEvent.getId()); + entityEvent.setMetadataType(MetadataTypeEnum.POINT); + entityEvent.setOperateType(metadataEvent.getOperateType()); + driverCustomService.event(entityEvent); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventPublisher.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventPublisher.java index bb8b7e537..4372f9e4a 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventPublisher.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/event/metadata/MetadataEventPublisher.java @@ -35,19 +35,20 @@ import org.springframework.stereotype.Component; @Component public class MetadataEventPublisher { - private final ApplicationEventPublisher applicationEventPublisher; + private final ApplicationEventPublisher applicationEventPublisher; - public MetadataEventPublisher(ApplicationEventPublisher applicationEventPublisher) { - this.applicationEventPublisher = applicationEventPublisher; - } + public MetadataEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } - /** - * Publishes the supplied metadata event to the Spring application context. - * @param metadataEvent metadata event - */ - public void publishEvent(MetadataEvent metadataEvent) { - log.info("Metadata event publisher publishEvent: {}", JsonUtil.toJsonString(metadataEvent)); - applicationEventPublisher.publishEvent(metadataEvent); - } + /** + * Publishes the supplied metadata event to the Spring application context. + * + * @param metadataEvent metadata event + */ + public void publishEvent(MetadataEvent metadataEvent) { + log.info("Metadata event publisher publishEvent: {}", JsonUtil.toJsonString(metadataEvent)); + applicationEventPublisher.publishEvent(metadataEvent); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DeviceClient.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DeviceClient.java index 35e87ec7a..77d546343 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DeviceClient.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DeviceClient.java @@ -53,94 +53,95 @@ import java.util.stream.Collectors; @Component public class DeviceClient { - @Resource - private DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub; + @Resource + private DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub; - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DeviceBuilder deviceBuilder; + @Resource + private DeviceBuilder deviceBuilder; - @Resource - private GrpcDriverAttributeConfigBuilder grpcDriverAttributeConfigBuilder; + @Resource + private GrpcDriverAttributeConfigBuilder grpcDriverAttributeConfigBuilder; - @Resource - private GrpcPointAttributeConfigBuilder grpcPointAttributeConfigBuilder; + @Resource + private GrpcPointAttributeConfigBuilder grpcPointAttributeConfigBuilder; - public List list() { - long current = 1; - GrpcRPageDeviceDTO rPageDeviceDTO = getGrpcRPageDeviceDTO(current); - GrpcPageDeviceDTO pageDTO = rPageDeviceDTO.getData(); - List dataList = pageDTO.getDataList(); - List deviceBOList = dataList.stream().map(this::buildDTOByGrpcAttachDTO).toList(); - List allDeviceBOList = new ArrayList<>(deviceBOList); + public List list() { + long current = 1; + GrpcRPageDeviceDTO rPageDeviceDTO = getGrpcRPageDeviceDTO(current); + GrpcPageDeviceDTO pageDTO = rPageDeviceDTO.getData(); + List dataList = pageDTO.getDataList(); + List deviceBOList = dataList.stream().map(this::buildDTOByGrpcAttachDTO).toList(); + List allDeviceBOList = new ArrayList<>(deviceBOList); - long pages = pageDTO.getPage().getPages(); - while (current < pages) { - current++; - GrpcRPageDeviceDTO tPageDeviceDTO = getGrpcRPageDeviceDTO(current); - GrpcPageDeviceDTO tPageDTO = tPageDeviceDTO.getData(); - List tDataList = tPageDTO.getDataList(); - List tDeviceBOList = tDataList.stream().map(this::buildDTOByGrpcAttachDTO).toList(); - allDeviceBOList.addAll(tDeviceBOList); - pages = tPageDTO.getPage().getPages(); - } - return allDeviceBOList; - } + long pages = pageDTO.getPage().getPages(); + while (current < pages) { + current++; + GrpcRPageDeviceDTO tPageDeviceDTO = getGrpcRPageDeviceDTO(current); + GrpcPageDeviceDTO tPageDTO = tPageDeviceDTO.getData(); + List tDataList = tPageDTO.getDataList(); + List tDeviceBOList = tDataList.stream().map(this::buildDTOByGrpcAttachDTO).toList(); + allDeviceBOList.addAll(tDeviceBOList); + pages = tPageDTO.getPage().getPages(); + } + return allDeviceBOList; + } - /** - * Device ID - * @param id Device ID - * @return DeviceBO - */ - public DeviceBO selectById(Long id) { - GrpcDeviceQuery.Builder query = GrpcDeviceQuery.newBuilder(); - query.setDeviceId(id); - GrpcRDeviceDTO rDeviceDTO = deviceApiBlockingStub.selectById(query.build()); - if (!rDeviceDTO.getResult().getOk()) { - log.error("Device doesn't exist: {}", id); - return null; - } + /** + * Device ID + * + * @param id Device ID + * @return DeviceBO + */ + public DeviceBO selectById(Long id) { + GrpcDeviceQuery.Builder query = GrpcDeviceQuery.newBuilder(); + query.setDeviceId(id); + GrpcRDeviceDTO rDeviceDTO = deviceApiBlockingStub.selectById(query.build()); + if (!rDeviceDTO.getResult().getOk()) { + log.error("Device doesn't exist: {}", id); + return null; + } - GrpcRDeviceAttachDTO rDeviceAttachDTO = rDeviceDTO.getData(); - return buildDTOByGrpcAttachDTO(rDeviceAttachDTO); - } + GrpcRDeviceAttachDTO rDeviceAttachDTO = rDeviceDTO.getData(); + return buildDTOByGrpcAttachDTO(rDeviceAttachDTO); + } - private GrpcRPageDeviceDTO getGrpcRPageDeviceDTO(long current) { - GrpcPageDeviceQuery.Builder query = GrpcPageDeviceQuery.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(current); - query.setTenantId(driverMetadata.getDriver().getTenantId()) - .setDriverId(driverMetadata.getDriver().getId()) - .setPage(page); - GrpcRPageDeviceDTO rPageDeviceDTO = deviceApiBlockingStub.selectByPage(query.build()); - if (!rPageDeviceDTO.getResult().getOk()) { - throw new ServiceException("获取设备列表失败"); - } - return rPageDeviceDTO; - } + private GrpcRPageDeviceDTO getGrpcRPageDeviceDTO(long current) { + GrpcPageDeviceQuery.Builder query = GrpcPageDeviceQuery.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(current); + query.setTenantId(driverMetadata.getDriver().getTenantId()) + .setDriverId(driverMetadata.getDriver().getId()) + .setPage(page); + GrpcRPageDeviceDTO rPageDeviceDTO = deviceApiBlockingStub.selectByPage(query.build()); + if (!rPageDeviceDTO.getResult().getOk()) { + throw new ServiceException("获取设备列表失败"); + } + return rPageDeviceDTO; + } - private DeviceBO buildDTOByGrpcAttachDTO(GrpcRDeviceAttachDTO rDeviceAttachDTO) { - DeviceBO deviceBO = deviceBuilder.buildDTOByGrpcDTO(rDeviceAttachDTO.getDevice()); - deviceBO.setPointIds(new HashSet<>(rDeviceAttachDTO.getPointIdsList())); + private DeviceBO buildDTOByGrpcAttachDTO(GrpcRDeviceAttachDTO rDeviceAttachDTO) { + DeviceBO deviceBO = deviceBuilder.buildDTOByGrpcDTO(rDeviceAttachDTO.getDevice()); + deviceBO.setPointIds(new HashSet<>(rDeviceAttachDTO.getPointIdsList())); - CollectionOptional.ofNullable(rDeviceAttachDTO.getDriverConfigsList()).ifPresent(value -> { - Map driverAttributeConfigMap = value.stream() - .collect(Collectors.toMap(GrpcDriverAttributeConfigDTO::getAttributeId, - grpcDriverAttributeConfigBuilder::buildDTOByGrpcDTO)); - deviceBO.setDriverAttributeConfigIdMap(driverAttributeConfigMap); - }); + CollectionOptional.ofNullable(rDeviceAttachDTO.getDriverConfigsList()).ifPresent(value -> { + Map driverAttributeConfigMap = value.stream() + .collect(Collectors.toMap(GrpcDriverAttributeConfigDTO::getAttributeId, + grpcDriverAttributeConfigBuilder::buildDTOByGrpcDTO)); + deviceBO.setDriverAttributeConfigIdMap(driverAttributeConfigMap); + }); - CollectionOptional.ofNullable(rDeviceAttachDTO.getPointConfigsList()).ifPresent(value -> { - Map> pointAttributeConfigMap = value.stream() - .collect(Collectors.groupingBy(GrpcPointAttributeConfigDTO::getPointId, - Collectors.toMap(GrpcPointAttributeConfigDTO::getAttributeId, - grpcPointAttributeConfigBuilder::buildDTOByGrpcDTO))); - deviceBO.setPointAttributeConfigIdMap(pointAttributeConfigMap); - }); + CollectionOptional.ofNullable(rDeviceAttachDTO.getPointConfigsList()).ifPresent(value -> { + Map> pointAttributeConfigMap = value.stream() + .collect(Collectors.groupingBy(GrpcPointAttributeConfigDTO::getPointId, + Collectors.toMap(GrpcPointAttributeConfigDTO::getAttributeId, + grpcPointAttributeConfigBuilder::buildDTOByGrpcDTO))); + deviceBO.setPointAttributeConfigIdMap(pointAttributeConfigMap); + }); - return deviceBO; - } + return deviceBO; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DriverClient.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DriverClient.java index 6c5d6cdeb..440d8332b 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DriverClient.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/DriverClient.java @@ -56,77 +56,78 @@ import java.util.stream.Collectors; @Component public class DriverClient { - @Resource - private DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub; + @Resource + private DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub; - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DriverBuilder driverBuilder; + @Resource + private DriverBuilder driverBuilder; - @Resource - private GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; + @Resource + private GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; - @Resource - private GrpcPointAttributeBuilder grpcPointAttributeBuilder; + @Resource + private GrpcPointAttributeBuilder grpcPointAttributeBuilder; - /** - * Registers the current driver and stores the returned metadata in the shared driver - * cache. - * @param entityBO driver registration payload - */ - public void driverRegister(RegisterBO entityBO) { - // Build driver registration information - GrpcDriverRegisterDTO.Builder builder = GrpcDriverRegisterDTO.newBuilder(); - GrpcDriverDTO grpcDriverDTO = driverBuilder.buildGrpcDTOByDTO(entityBO.getDriver()); - builder.setTenant(entityBO.getTenant()).setClient(entityBO.getClient()).setDriver(grpcDriverDTO); + /** + * Registers the current driver and stores the returned metadata in the shared driver + * cache. + * + * @param entityBO driver registration payload + */ + public void driverRegister(RegisterBO entityBO) { + // Build driver registration information + GrpcDriverRegisterDTO.Builder builder = GrpcDriverRegisterDTO.newBuilder(); + GrpcDriverDTO grpcDriverDTO = driverBuilder.buildGrpcDTOByDTO(entityBO.getDriver()); + builder.setTenant(entityBO.getTenant()).setClient(entityBO.getClient()).setDriver(grpcDriverDTO); - CollectionOptional.ofNullable(entityBO.getDriverAttributes()).ifPresent(value -> { - List grpcDriverAttributeDTOList = value.stream() - .map(grpcDriverAttributeBuilder::buildGrpcDTOByDTO) - .toList(); - builder.addAllDriverAttributes(grpcDriverAttributeDTOList); - }); - CollectionOptional.ofNullable(entityBO.getPointAttributes()).ifPresent(value -> { - List grpcPointAttributeDTOList = value.stream() - .map(grpcPointAttributeBuilder::buildGrpcDTOByDTO) - .toList(); - builder.addAllPointAttributes(grpcPointAttributeDTOList); - }); + CollectionOptional.ofNullable(entityBO.getDriverAttributes()).ifPresent(value -> { + List grpcDriverAttributeDTOList = value.stream() + .map(grpcDriverAttributeBuilder::buildGrpcDTOByDTO) + .toList(); + builder.addAllDriverAttributes(grpcDriverAttributeDTOList); + }); + CollectionOptional.ofNullable(entityBO.getPointAttributes()).ifPresent(value -> { + List grpcPointAttributeDTOList = value.stream() + .map(grpcPointAttributeBuilder::buildGrpcDTOByDTO) + .toList(); + builder.addAllPointAttributes(grpcPointAttributeDTOList); + }); - // Initiate driver registration - GrpcRDriverRegisterDTO rDriverRegisterDTO = driverApiBlockingStub.driverRegister(builder.build()); - if (!rDriverRegisterDTO.getResult().getOk()) { - throw new RegisterException(rDriverRegisterDTO.getResult().getMessage()); - } + // Initiate driver registration + GrpcRDriverRegisterDTO rDriverRegisterDTO = driverApiBlockingStub.driverRegister(builder.build()); + if (!rDriverRegisterDTO.getResult().getOk()) { + throw new RegisterException(rDriverRegisterDTO.getResult().getMessage()); + } - DriverBO driverBO = driverBuilder.buildDTOByGrpcDTO(rDriverRegisterDTO.getDriver()); - driverMetadata.setDriver(driverBO); + DriverBO driverBO = driverBuilder.buildDTOByGrpcDTO(rDriverRegisterDTO.getDriver()); + driverMetadata.setDriver(driverBO); - driverMetadata.setDeviceIds(new HashSet<>(rDriverRegisterDTO.getDeviceIdsList())); + driverMetadata.setDeviceIds(new HashSet<>(rDriverRegisterDTO.getDeviceIdsList())); - List driverAttributesList = rDriverRegisterDTO.getDriverAttributesList(); - Map driverAttributeIdMap = driverAttributesList.stream() - .collect(Collectors.toMap(entity -> entity.getBase().getId(), - grpcDriverAttributeBuilder::buildDTOByGrpcDTO)); - Map driverAttributeNameMap = driverAttributesList.stream() - .collect(Collectors.toMap(GrpcDriverAttributeDTO::getAttributeCode, - grpcDriverAttributeBuilder::buildDTOByGrpcDTO)); - driverMetadata.setDriverAttributeIdMap(driverAttributeIdMap); - driverMetadata.setDriverAttributeNameMap(driverAttributeNameMap); + List driverAttributesList = rDriverRegisterDTO.getDriverAttributesList(); + Map driverAttributeIdMap = driverAttributesList.stream() + .collect(Collectors.toMap(entity -> entity.getBase().getId(), + grpcDriverAttributeBuilder::buildDTOByGrpcDTO)); + Map driverAttributeNameMap = driverAttributesList.stream() + .collect(Collectors.toMap(GrpcDriverAttributeDTO::getAttributeCode, + grpcDriverAttributeBuilder::buildDTOByGrpcDTO)); + driverMetadata.setDriverAttributeIdMap(driverAttributeIdMap); + driverMetadata.setDriverAttributeNameMap(driverAttributeNameMap); - List pointAttributesList = rDriverRegisterDTO.getPointAttributesList(); - Map pointAttributeIdMap = pointAttributesList.stream() - .collect( - Collectors.toMap(entity -> entity.getBase().getId(), grpcPointAttributeBuilder::buildDTOByGrpcDTO)); - Map pointAttributeNameMap = pointAttributesList.stream() - .collect(Collectors.toMap(GrpcPointAttributeDTO::getAttributeCode, - grpcPointAttributeBuilder::buildDTOByGrpcDTO)); - driverMetadata.setPointAttributeIdMap(pointAttributeIdMap); - driverMetadata.setPointAttributeNameMap(pointAttributeNameMap); + List pointAttributesList = rDriverRegisterDTO.getPointAttributesList(); + Map pointAttributeIdMap = pointAttributesList.stream() + .collect( + Collectors.toMap(entity -> entity.getBase().getId(), grpcPointAttributeBuilder::buildDTOByGrpcDTO)); + Map pointAttributeNameMap = pointAttributesList.stream() + .collect(Collectors.toMap(GrpcPointAttributeDTO::getAttributeCode, + grpcPointAttributeBuilder::buildDTOByGrpcDTO)); + driverMetadata.setPointAttributeIdMap(pointAttributeIdMap); + driverMetadata.setPointAttributeNameMap(pointAttributeNameMap); - driverMetadata.setDriverStatus(DriverStatusEnum.ONLINE); - } + driverMetadata.setDriverStatus(DriverStatusEnum.ONLINE); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/PointClient.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/PointClient.java index af8778d85..700f4568d 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/PointClient.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/PointClient.java @@ -43,65 +43,66 @@ import java.util.List; @Component public class PointClient { - @Resource - private PointApiGrpc.PointApiBlockingStub pointApiBlockingStub; + @Resource + private PointApiGrpc.PointApiBlockingStub pointApiBlockingStub; - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private PointBuilder pointBuilder; + @Resource + private PointBuilder pointBuilder; - public List list() { - long current = 1; - GrpcRPagePointDTO rPagePointDTO = getGrpcRPagePointDTO(current); - GrpcPagePointDTO pageDTO = rPagePointDTO.getData(); - List dataList = pageDTO.getDataList(); - List pointBOList = dataList.stream().map(pointBuilder::buildDTOByGrpcDTO).toList(); - ArrayList allPointBOList = new ArrayList<>(pointBOList); + public List list() { + long current = 1; + GrpcRPagePointDTO rPagePointDTO = getGrpcRPagePointDTO(current); + GrpcPagePointDTO pageDTO = rPagePointDTO.getData(); + List dataList = pageDTO.getDataList(); + List pointBOList = dataList.stream().map(pointBuilder::buildDTOByGrpcDTO).toList(); + ArrayList allPointBOList = new ArrayList<>(pointBOList); - long pages = pageDTO.getPage().getPages(); - while (current < pages) { - current++; - GrpcRPagePointDTO tPagePointDTO = getGrpcRPagePointDTO(current); - GrpcPagePointDTO tPageDTO = tPagePointDTO.getData(); - List tDataList = tPageDTO.getDataList(); - List tPointBOList = tDataList.stream().map(pointBuilder::buildDTOByGrpcDTO).toList(); - allPointBOList.addAll(tPointBOList); - pages = tPageDTO.getPage().getPages(); - } - return allPointBOList; - } + long pages = pageDTO.getPage().getPages(); + while (current < pages) { + current++; + GrpcRPagePointDTO tPagePointDTO = getGrpcRPagePointDTO(current); + GrpcPagePointDTO tPageDTO = tPagePointDTO.getData(); + List tDataList = tPageDTO.getDataList(); + List tPointBOList = tDataList.stream().map(pointBuilder::buildDTOByGrpcDTO).toList(); + allPointBOList.addAll(tPointBOList); + pages = tPageDTO.getPage().getPages(); + } + return allPointBOList; + } - /** - * Point ID - * @param id Point ID - * @return PointDTO - */ - public PointBO selectById(Long id) { - GrpcPointQuery.Builder query = GrpcPointQuery.newBuilder(); - query.setPointId(id); - GrpcRPointDTO rPointDTO = pointApiBlockingStub.selectById(query.build()); - if (!rPointDTO.getResult().getOk()) { - log.error("Point doesn't exist: {}", id); - return null; - } + /** + * Point ID + * + * @param id Point ID + * @return PointDTO + */ + public PointBO selectById(Long id) { + GrpcPointQuery.Builder query = GrpcPointQuery.newBuilder(); + query.setPointId(id); + GrpcRPointDTO rPointDTO = pointApiBlockingStub.selectById(query.build()); + if (!rPointDTO.getResult().getOk()) { + log.error("Point doesn't exist: {}", id); + return null; + } - return pointBuilder.buildDTOByGrpcDTO(rPointDTO.getData()); - } + return pointBuilder.buildDTOByGrpcDTO(rPointDTO.getData()); + } - private GrpcRPagePointDTO getGrpcRPagePointDTO(long current) { - GrpcPagePointQuery.Builder query = GrpcPagePointQuery.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(current); - query.setTenantId(driverMetadata.getDriver().getTenantId()) - .setDriverId(driverMetadata.getDriver().getId()) - .setPage(page); - GrpcRPagePointDTO rPagePointDTO = pointApiBlockingStub.selectByPage(query.build()); - if (!rPagePointDTO.getResult().getOk()) { - throw new ServiceException("获取设备列表失败"); - } - return rPagePointDTO; - } + private GrpcRPagePointDTO getGrpcRPagePointDTO(long current) { + GrpcPagePointQuery.Builder query = GrpcPagePointQuery.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(current); + query.setTenantId(driverMetadata.getDriver().getTenantId()) + .setDriverId(driverMetadata.getDriver().getId()) + .setPage(page); + GrpcRPagePointDTO rPagePointDTO = pointApiBlockingStub.selectByPage(query.build()); + if (!rPagePointDTO.getResult().getOk()) { + throw new ServiceException("获取设备列表失败"); + } + return rPagePointDTO; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/config/GrpcStubConfig.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/config/GrpcStubConfig.java index 4b5d63d3d..91db70a27 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/config/GrpcStubConfig.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/grpc/client/config/GrpcStubConfig.java @@ -32,19 +32,19 @@ import org.springframework.grpc.client.GrpcChannelFactory; @Configuration public class GrpcStubConfig { - @Bean - public DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub(GrpcChannelFactory channels) { - return DriverApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub(GrpcChannelFactory channels) { + return DriverApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } - @Bean - public DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub(GrpcChannelFactory channels) { - return DeviceApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub(GrpcChannelFactory channels) { + return DeviceApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } - @Bean - public PointApiGrpc.PointApiBlockingStub pointApiBlockingStub(GrpcChannelFactory channels) { - return PointApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public PointApiGrpc.PointApiBlockingStub pointApiBlockingStub(GrpcChannelFactory channels) { + return PointApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverCustomScheduleJob.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverCustomScheduleJob.java index 7ead29703..940163f52 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverCustomScheduleJob.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverCustomScheduleJob.java @@ -34,20 +34,19 @@ import org.springframework.stereotype.Component; @Component public class DriverCustomScheduleJob extends QuartzJobBean { - private final DriverCustomService driverCustomService; + private final DriverCustomService driverCustomService; - public DriverCustomScheduleJob(DriverCustomService driverCustomService) { - this.driverCustomService = driverCustomService; - } + public DriverCustomScheduleJob(DriverCustomService driverCustomService) { + this.driverCustomService = driverCustomService; + } - @Override - protected void executeInternal(JobExecutionContext jobExecutionContext) { - try { - driverCustomService.schedule(); - } - catch (Exception e) { - log.error("Failed to execute custom schedule job: {}", e.getMessage(), e); - } - } + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) { + try { + driverCustomService.schedule(); + } catch (Exception e) { + log.error("Failed to execute custom schedule job: {}", e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverReadScheduleJob.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverReadScheduleJob.java index 1883a51c3..ae97253f4 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverReadScheduleJob.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverReadScheduleJob.java @@ -45,40 +45,39 @@ import java.util.Set; @Component public class DriverReadScheduleJob extends QuartzJobBean { - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DeviceMetadata deviceMetadata; + @Resource + private DeviceMetadata deviceMetadata; - @Resource - private DriverReadService driverReadService; + @Resource + private DriverReadService driverReadService; - @Override - protected void executeInternal(JobExecutionContext jobExecutionContext) { - Set deviceIds = driverMetadata.getDeviceIds(); - if (CollectionUtils.isEmpty(deviceIds)) { - return; - } + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) { + Set deviceIds = driverMetadata.getDeviceIds(); + if (CollectionUtils.isEmpty(deviceIds)) { + return; + } - for (Long deviceId : deviceIds) { - DeviceBO entityBO = deviceMetadata.getCache(deviceId); - if (Objects.nonNull(entityBO) && EnableFlagEnum.ENABLE.equals(entityBO.getEnableFlag()) - && CollectionUtils.isNotEmpty(entityBO.getProfileIds()) - && CollectionUtils.isNotEmpty(entityBO.getPointIds()) - && MapUtils.isNotEmpty(entityBO.getDriverAttributeConfigIdMap()) - && MapUtils.isNotEmpty(entityBO.getPointAttributeConfigIdMap())) { - Set pointIds = entityBO.getPointIds(); - for (Long pointId : pointIds) { - try { - driverReadService.read(deviceId, pointId); - } - catch (Exception e) { - log.error("Read device[{}], point[{}] error: {}", deviceId, pointId, e.getMessage(), e); - } - } - } - } - } + for (Long deviceId : deviceIds) { + DeviceBO entityBO = deviceMetadata.getCache(deviceId); + if (Objects.nonNull(entityBO) && EnableFlagEnum.ENABLE.equals(entityBO.getEnableFlag()) + && CollectionUtils.isNotEmpty(entityBO.getProfileIds()) + && CollectionUtils.isNotEmpty(entityBO.getPointIds()) + && MapUtils.isNotEmpty(entityBO.getDriverAttributeConfigIdMap()) + && MapUtils.isNotEmpty(entityBO.getPointAttributeConfigIdMap())) { + Set pointIds = entityBO.getPointIds(); + for (Long pointId : pointIds) { + try { + driverReadService.read(deviceId, pointId); + } catch (Exception e) { + log.error("Read device[{}], point[{}] error: {}", deviceId, pointId, e.getMessage(), e); + } + } + } + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverStatusScheduleJob.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverStatusScheduleJob.java index 9e12273b8..decb5bfd8 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverStatusScheduleJob.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/job/DriverStatusScheduleJob.java @@ -40,23 +40,23 @@ import org.springframework.stereotype.Component; @Component public class DriverStatusScheduleJob extends QuartzJobBean { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - @Override - protected void executeInternal(JobExecutionContext jobExecutionContext) { - DriverBO driver = driverMetadata.getDriver(); - DriverEventDTO.DriverStatus driverStatus = new DriverEventDTO.DriverStatus(driver.getId(), - driverMetadata.getDriverStatus()); - driverStatus.setTenantId(driver.getTenantId()); - DriverEventDTO driverEventDTO = new DriverEventDTO(DriverEventTypeEnum.HEARTBEAT, - JsonUtil.toJsonString(driverStatus)); - log.info("Report driver event: {}, event content: {}", driverEventDTO.getType().getCode(), - JsonUtil.toJsonString(driverEventDTO)); - driverSenderService.driverEventSender(driverEventDTO); - } + @Override + protected void executeInternal(JobExecutionContext jobExecutionContext) { + DriverBO driver = driverMetadata.getDriver(); + DriverEventDTO.DriverStatus driverStatus = new DriverEventDTO.DriverStatus(driver.getId(), + driverMetadata.getDriverStatus()); + driverStatus.setTenantId(driver.getTenantId()); + DriverEventDTO driverEventDTO = new DriverEventDTO(DriverEventTypeEnum.HEARTBEAT, + JsonUtil.toJsonString(driverStatus)); + log.info("Report driver event: {}, event content: {}", driverEventDTO.getType().getCode(), + JsonUtil.toJsonString(driverEventDTO)); + driverSenderService.driverEventSender(driverEventDTO); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DeviceMetadata.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DeviceMetadata.java index d99080c2f..30215eb1b 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DeviceMetadata.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DeviceMetadata.java @@ -52,175 +52,180 @@ import java.util.stream.Collectors; @Component public final class DeviceMetadata { - /** - * Asynchronous cache keyed by device identifier. - */ - private final AsyncLoadingCache cache; + /** + * Asynchronous cache keyed by device identifier. + */ + private final AsyncLoadingCache cache; - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DeviceClient deviceClient; + @Resource + private DeviceClient deviceClient; - private DeviceMetadata() { - this.cache = Caffeine.newBuilder() - .maximumSize(5000) - .expireAfterWrite(24, TimeUnit.HOURS) - .removalListener( - (key, value, cause) -> log.info("Remove key={}, value={} cache, reason is: {}", key, value, cause)) - .buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> { - log.info("Load device metadata by id: {}", key); - DeviceBO deviceBO = deviceClient.selectById(key); - log.info("Cache device metadata: {}", JsonUtil.toJsonString(deviceBO)); - return deviceBO; - }, executor)); - } + private DeviceMetadata() { + this.cache = Caffeine.newBuilder() + .maximumSize(5000) + .expireAfterWrite(24, TimeUnit.HOURS) + .removalListener( + (key, value, cause) -> log.info("Remove key={}, value={} cache, reason is: {}", key, value, cause)) + .buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> { + log.info("Load device metadata by id: {}", key); + DeviceBO deviceBO = deviceClient.selectById(key); + log.info("Cache device metadata: {}", JsonUtil.toJsonString(deviceBO)); + return deviceBO; + }, executor)); + } - /** - * Returns the cached device metadata for the specified device identifier. - * @param id device identifier - * @return cached device business object - */ - public DeviceBO getCache(long id) { - try { - CompletableFuture future = cache.get(id); - return future.get(); - } - catch (InterruptedException | ExecutionException e) { - Thread.currentThread().interrupt(); - log.error("Failed to get the device cache: {}", e.getMessage(), e); - return null; - } - } + /** + * Returns the cached device metadata for the specified device identifier. + * + * @param id device identifier + * @return cached device business object + */ + public DeviceBO getCache(long id) { + try { + CompletableFuture future = cache.get(id); + return future.get(); + } catch (InterruptedException | ExecutionException e) { + Thread.currentThread().interrupt(); + log.error("Failed to get the device cache: {}", e.getMessage(), e); + return null; + } + } - /** - * Reloads the cache entry for the specified device identifier. - * @param id device identifier - */ - public void loadCache(long id) { - CompletableFuture future = CompletableFuture.supplyAsync(() -> deviceClient.selectById(id)); - cache.put(id, future); - } + /** + * Reloads the cache entry for the specified device identifier. + * + * @param id device identifier + */ + public void loadCache(long id) { + CompletableFuture future = CompletableFuture.supplyAsync(() -> deviceClient.selectById(id)); + cache.put(id, future); + } - /** - * Removes the cache entry for the specified device identifier. - * @param id device identifier - */ - public void removeCache(long id) { - cache.put(id, CompletableFuture.completedFuture(null)); - } + /** + * Removes the cache entry for the specified device identifier. + * + * @param id device identifier + */ + public void removeCache(long id) { + cache.put(id, CompletableFuture.completedFuture(null)); + } - /** - * Resolves driver attribute configuration for the specified device and verifies that - * all required attributes are present. - * @param deviceId device identifier - * @return driver configuration map keyed by attribute code - */ - public Map getDriverConfig(long deviceId) { - Map attributeMap = driverMetadata.getDriverAttributeIdMap(); - if (MapUtils.isEmpty(attributeMap)) { - return Map.of(); - } + /** + * Resolves driver attribute configuration for the specified device and verifies that + * all required attributes are present. + * + * @param deviceId device identifier + * @return driver configuration map keyed by attribute code + */ + public Map getDriverConfig(long deviceId) { + Map attributeMap = driverMetadata.getDriverAttributeIdMap(); + if (MapUtils.isEmpty(attributeMap)) { + return Map.of(); + } - DeviceBO device = getCache(deviceId); - if (Objects.isNull(device)) { - throw new ConfigException("Failed to get driver config, the device is empty"); - } + DeviceBO device = getCache(deviceId); + if (Objects.isNull(device)) { + throw new ConfigException("Failed to get driver config, the device is empty"); + } - Map attributeConfigMap = device.getDriverAttributeConfigIdMap(); - if (MapUtils.isEmpty(attributeConfigMap)) { - throw new ConfigException("Failed to get driver config, the driver attribute config is empty"); - } - if (!attributeConfigMap.keySet().containsAll(attributeMap.keySet())) { - throw new ConfigException("Failed to get driver config, the driver attribute config is incomplete"); - } + Map attributeConfigMap = device.getDriverAttributeConfigIdMap(); + if (MapUtils.isEmpty(attributeConfigMap)) { + throw new ConfigException("Failed to get driver config, the driver attribute config is empty"); + } + if (!attributeConfigMap.keySet().containsAll(attributeMap.keySet())) { + throw new ConfigException("Failed to get driver config, the driver attribute config is incomplete"); + } - return attributeMap.entrySet() - .stream() - .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), - entry -> AttributeBO.builder() - .type(entry.getValue().getAttributeTypeFlag()) - .value(attributeConfigMap.get(entry.getKey()).getConfigValue()) - .build())); - } + return attributeMap.entrySet() + .stream() + .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), + entry -> AttributeBO.builder() + .type(entry.getValue().getAttributeTypeFlag()) + .value(attributeConfigMap.get(entry.getKey()).getConfigValue()) + .build())); + } - /** - * Resolves point attribute configuration for all points of the specified device. - * @param deviceId device identifier - * @return point configuration map keyed by point identifier and attribute code - */ - public Map> getPointConfig(long deviceId) { - Map attributeMap = driverMetadata.getPointAttributeIdMap(); - if (MapUtils.isEmpty(attributeMap)) { - return Map.of(); - } + /** + * Resolves point attribute configuration for all points of the specified device. + * + * @param deviceId device identifier + * @return point configuration map keyed by point identifier and attribute code + */ + public Map> getPointConfig(long deviceId) { + Map attributeMap = driverMetadata.getPointAttributeIdMap(); + if (MapUtils.isEmpty(attributeMap)) { + return Map.of(); + } - DeviceBO device = getCache(deviceId); - if (Objects.isNull(device)) { - throw new ConfigException("Failed to get point config[{}], the device is empty", deviceId); - } + DeviceBO device = getCache(deviceId); + if (Objects.isNull(device)) { + throw new ConfigException("Failed to get point config[{}], the device is empty", deviceId); + } - Map> pointAttributeConfigMap = device.getPointAttributeConfigIdMap(); - if (Objects.isNull(pointAttributeConfigMap)) { - throw new ConfigException("Failed to get point config[{}], the device point attribute config is empty", - deviceId); - } + Map> pointAttributeConfigMap = device.getPointAttributeConfigIdMap(); + if (Objects.isNull(pointAttributeConfigMap)) { + throw new ConfigException("Failed to get point config[{}], the device point attribute config is empty", + deviceId); + } - return pointAttributeConfigMap.entrySet() - .stream() - .filter(entry -> MapUtils.isEmpty(entry.getValue()) - && entry.getValue().keySet().containsAll(attributeMap.keySet())) - .collect(Collectors.toMap(Map.Entry::getKey, - entryMap -> attributeMap.entrySet() - .stream() - .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), - entry -> AttributeBO.builder() - .type(entry.getValue().getAttributeTypeFlag()) - .value(entryMap.getValue().get(entry.getKey()).getConfigValue()) - .build())))); - } + return pointAttributeConfigMap.entrySet() + .stream() + .filter(entry -> MapUtils.isEmpty(entry.getValue()) + && entry.getValue().keySet().containsAll(attributeMap.keySet())) + .collect(Collectors.toMap(Map.Entry::getKey, + entryMap -> attributeMap.entrySet() + .stream() + .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), + entry -> AttributeBO.builder() + .type(entry.getValue().getAttributeTypeFlag()) + .value(entryMap.getValue().get(entry.getKey()).getConfigValue()) + .build())))); + } - /** - * Resolves point attribute configuration for a single point of the specified device. - * @param deviceId device identifier - * @param pointId point identifier - * @return point configuration map keyed by attribute code - */ - public Map getPointConfig(long deviceId, long pointId) { - Map attributeMap = driverMetadata.getPointAttributeIdMap(); - if (MapUtils.isEmpty(attributeMap)) { - return Map.of(); - } + /** + * Resolves point attribute configuration for a single point of the specified device. + * + * @param deviceId device identifier + * @param pointId point identifier + * @return point configuration map keyed by attribute code + */ + public Map getPointConfig(long deviceId, long pointId) { + Map attributeMap = driverMetadata.getPointAttributeIdMap(); + if (MapUtils.isEmpty(attributeMap)) { + return Map.of(); + } - DeviceBO device = getCache(deviceId); - if (Objects.isNull(device)) { - throw new ConfigException("Failed to get point config[{}:{}], the device is empty", deviceId, pointId); - } + DeviceBO device = getCache(deviceId); + if (Objects.isNull(device)) { + throw new ConfigException("Failed to get point config[{}:{}], the device is empty", deviceId, pointId); + } - Map> pointAttributeConfigMap = device.getPointAttributeConfigIdMap(); - if (Objects.isNull(pointAttributeConfigMap)) { - throw new ConfigException("Failed to get point config[{}:{}], the device point attribute config is empty", - deviceId, pointId); - } + Map> pointAttributeConfigMap = device.getPointAttributeConfigIdMap(); + if (Objects.isNull(pointAttributeConfigMap)) { + throw new ConfigException("Failed to get point config[{}:{}], the device point attribute config is empty", + deviceId, pointId); + } - Map attributeConfigMap = pointAttributeConfigMap.get(pointId); - if (MapUtils.isEmpty(attributeConfigMap)) { - throw new ConfigException("Failed to get point config[{}:{}], the point attribute config is empty", - deviceId, pointId); - } - if (!attributeConfigMap.keySet().containsAll(attributeMap.keySet())) { - throw new ConfigException("Failed to get point config[{}:{}], the point attribute config is incomplete", - deviceId, pointId); - } + Map attributeConfigMap = pointAttributeConfigMap.get(pointId); + if (MapUtils.isEmpty(attributeConfigMap)) { + throw new ConfigException("Failed to get point config[{}:{}], the point attribute config is empty", + deviceId, pointId); + } + if (!attributeConfigMap.keySet().containsAll(attributeMap.keySet())) { + throw new ConfigException("Failed to get point config[{}:{}], the point attribute config is incomplete", + deviceId, pointId); + } - return attributeMap.entrySet() - .stream() - .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), - entry -> AttributeBO.builder() - .type(entry.getValue().getAttributeTypeFlag()) - .value(attributeConfigMap.get(entry.getKey()).getConfigValue()) - .build())); - } + return attributeMap.entrySet() + .stream() + .collect(Collectors.toMap(entry -> entry.getValue().getAttributeCode(), + entry -> AttributeBO.builder() + .type(entry.getValue().getAttributeTypeFlag()) + .value(attributeConfigMap.get(entry.getKey()).getConfigValue()) + .build())); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DriverMetadata.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DriverMetadata.java index 4035fd997..d44604976 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DriverMetadata.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/DriverMetadata.java @@ -43,39 +43,39 @@ import java.util.Set; @Component public final class DriverMetadata { - /** - * Current driver status. - */ - private DriverStatusEnum driverStatus = DriverStatusEnum.OFFLINE; + /** + * Current driver status. + */ + private DriverStatusEnum driverStatus = DriverStatusEnum.OFFLINE; - /** - * Registered driver definition. - */ - private DriverBO driver; + /** + * Registered driver definition. + */ + private DriverBO driver; - /** - * Identifiers of devices owned by the driver. - */ - private Set deviceIds; + /** + * Identifiers of devices owned by the driver. + */ + private Set deviceIds; - /** - * Driver attributes keyed by attribute identifier. - */ - private Map driverAttributeIdMap; + /** + * Driver attributes keyed by attribute identifier. + */ + private Map driverAttributeIdMap; - /** - * Driver attributes keyed by attribute code. - */ - private Map driverAttributeNameMap; + /** + * Driver attributes keyed by attribute code. + */ + private Map driverAttributeNameMap; - /** - * Point attributes keyed by attribute identifier. - */ - private Map pointAttributeIdMap; + /** + * Point attributes keyed by attribute identifier. + */ + private Map pointAttributeIdMap; - /** - * Point attributes keyed by attribute code. - */ - private Map pointAttributeNameMap; + /** + * Point attributes keyed by attribute code. + */ + private Map pointAttributeNameMap; } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/PointMetadata.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/PointMetadata.java index f1b4670f1..b6cbe1ec7 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/PointMetadata.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/metadata/PointMetadata.java @@ -41,60 +41,62 @@ import java.util.concurrent.TimeUnit; @Component public final class PointMetadata { - /** - * Asynchronous cache keyed by point identifier. - */ - private final AsyncLoadingCache cache; + /** + * Asynchronous cache keyed by point identifier. + */ + private final AsyncLoadingCache cache; - private final PointClient pointClient; + private final PointClient pointClient; - public PointMetadata(PointClient pointClient) { - this.pointClient = pointClient; - this.cache = Caffeine.newBuilder() - .maximumSize(5000) - .expireAfterWrite(24, TimeUnit.HOURS) - .removalListener( - (key, value, cause) -> log.info("Remove key={}, value={} cache, reason is: {}", key, value, cause)) - .buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> { - log.info("Load point metadata by id: {}", key); - PointBO pointBO = this.pointClient.selectById(key); - log.info("Cache point metadata: {}", JsonUtil.toJsonString(pointBO)); - return pointBO; - }, executor)); - } + public PointMetadata(PointClient pointClient) { + this.pointClient = pointClient; + this.cache = Caffeine.newBuilder() + .maximumSize(5000) + .expireAfterWrite(24, TimeUnit.HOURS) + .removalListener( + (key, value, cause) -> log.info("Remove key={}, value={} cache, reason is: {}", key, value, cause)) + .buildAsync((key, executor) -> CompletableFuture.supplyAsync(() -> { + log.info("Load point metadata by id: {}", key); + PointBO pointBO = this.pointClient.selectById(key); + log.info("Cache point metadata: {}", JsonUtil.toJsonString(pointBO)); + return pointBO; + }, executor)); + } - /** - * Returns the cached point metadata for the specified point identifier. - * @param id point identifier - * @return cached point business object - */ - public PointBO getCache(long id) { - try { - CompletableFuture future = cache.get(id); - return future.get(); - } - catch (InterruptedException | ExecutionException e) { - Thread.currentThread().interrupt(); - log.error("Failed to get the point cache: {}", e.getMessage(), e); - return null; - } - } + /** + * Returns the cached point metadata for the specified point identifier. + * + * @param id point identifier + * @return cached point business object + */ + public PointBO getCache(long id) { + try { + CompletableFuture future = cache.get(id); + return future.get(); + } catch (InterruptedException | ExecutionException e) { + Thread.currentThread().interrupt(); + log.error("Failed to get the point cache: {}", e.getMessage(), e); + return null; + } + } - /** - * Reloads the cache entry for the specified point identifier. - * @param id point identifier - */ - public void loadCache(long id) { - CompletableFuture future = CompletableFuture.supplyAsync(() -> pointClient.selectById(id)); - cache.put(id, future); - } + /** + * Reloads the cache entry for the specified point identifier. + * + * @param id point identifier + */ + public void loadCache(long id) { + CompletableFuture future = CompletableFuture.supplyAsync(() -> pointClient.selectById(id)); + cache.put(id, future); + } - /** - * Removes the cache entry for the specified point identifier. - * @param id point identifier - */ - public void removeCache(long id) { - cache.put(id, CompletableFuture.completedFuture(null)); - } + /** + * Removes the cache entry for the specified point identifier. + * + * @param id point identifier + */ + public void removeCache(long id) { + cache.put(id, CompletableFuture.completedFuture(null)); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DeviceCommandReceiver.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DeviceCommandReceiver.java index b0d0f6ebc..19e537841 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DeviceCommandReceiver.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DeviceCommandReceiver.java @@ -44,53 +44,53 @@ import java.util.Objects; @Component public class DeviceCommandReceiver { - @Resource - private DriverReadService driverReadService; + @Resource + private DriverReadService driverReadService; - @Resource - private DriverWriteService driverWriteService; + @Resource + private DriverWriteService driverWriteService; - /** - * Receive and process device commands from RabbitMQ queue - * @param channel RabbitMQ channel for message acknowledgment - * @param message Raw RabbitMQ message containing delivery information - * @param entityDTO Device command data transfer object containing command details - */ - @RabbitHandler - @RabbitListener(queues = "#{deviceCommandQueue.name}") - public void deviceCommandReceive(Channel channel, Message message, DeviceCommandDTO entityDTO) { - try { - // Acknowledge message receipt - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - log.info("Receive device command: {}", JsonUtil.toJsonString(entityDTO)); + /** + * Receive and process device commands from RabbitMQ queue + * + * @param channel RabbitMQ channel for message acknowledgment + * @param message Raw RabbitMQ message containing delivery information + * @param entityDTO Device command data transfer object containing command details + */ + @RabbitHandler + @RabbitListener(queues = "#{deviceCommandQueue.name}") + public void deviceCommandReceive(Channel channel, Message message, DeviceCommandDTO entityDTO) { + try { + // Acknowledge message receipt + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + log.info("Receive device command: {}", JsonUtil.toJsonString(entityDTO)); - // Validate command data - if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) - || StringUtils.isEmpty(entityDTO.getContent())) { - log.error("Invalid device command: {}", entityDTO); - return; - } + // Validate command data + if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getType()) + || StringUtils.isEmpty(entityDTO.getContent())) { + log.error("Invalid device command: {}", entityDTO); + return; + } - // Process command based on type - switch (entityDTO.getType()) { - case READ: - // Execute read operation - driverReadService.read(entityDTO); - break; - case WRITE: - // Execute write operation - driverWriteService.write(entityDTO); - break; - case CONFIG: - // to do something - break; - default: - break; - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - } + // Process command based on type + switch (entityDTO.getType()) { + case READ: + // Execute read operation + driverReadService.read(entityDTO); + break; + case WRITE: + // Execute write operation + driverWriteService.write(entityDTO); + break; + case CONFIG: + // to do something + break; + default: + break; + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DriverCommandReceiver.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DriverCommandReceiver.java index 9b1ee0ed5..0949c8874 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DriverCommandReceiver.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/DriverCommandReceiver.java @@ -36,25 +36,25 @@ import org.springframework.stereotype.Component; @Component public class DriverCommandReceiver { - /** - * Receive and process driver commands from RabbitMQ queue - * @param channel RabbitMQ channel - * @param message RabbitMQ message - * @param driverCommandDTO Driver command data transfer object - */ - @RabbitHandler - @RabbitListener(queues = "#{driverCommandQueue.name}") - public void driverCommandReceive(Channel channel, Message message, DriverCommandDTO driverCommandDTO) { - try { - // Acknowledge the message receipt to RabbitMQ - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - // Log the received driver command - log.info("driver command: {}", driverCommandDTO); - } - catch (Exception e) { - // Log any errors that occur during message processing - log.error(e.getMessage(), e); - } - } + /** + * Receive and process driver commands from RabbitMQ queue + * + * @param channel RabbitMQ channel + * @param message RabbitMQ message + * @param driverCommandDTO Driver command data transfer object + */ + @RabbitHandler + @RabbitListener(queues = "#{driverCommandQueue.name}") + public void driverCommandReceive(Channel channel, Message message, DriverCommandDTO driverCommandDTO) { + try { + // Acknowledge the message receipt to RabbitMQ + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + // Log the received driver command + log.info("driver command: {}", driverCommandDTO); + } catch (Exception e) { + // Log any errors that occur during message processing + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/MetadataReceiver.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/MetadataReceiver.java index 9da4104c2..2fc48f571 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/MetadataReceiver.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/receiver/rabbit/MetadataReceiver.java @@ -48,77 +48,75 @@ import java.util.Objects; @Component public class MetadataReceiver { - @Resource - PointMetadata pointMetadata; + @Resource + PointMetadata pointMetadata; - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DeviceMetadata deviceMetadata; + @Resource + private DeviceMetadata deviceMetadata; - @Resource - private MetadataEventPublisher metadataEventPublisher; + @Resource + private MetadataEventPublisher metadataEventPublisher; - /** - * Receive and process metadata events from RabbitMQ queue - * @param channel RabbitMQ channel - * @param message RabbitMQ message - * @param entityDTO Metadata event data transfer object - */ - @RabbitHandler - @RabbitListener(queues = "#{metadataQueue.name}") - public void metadataReceive(Channel channel, Message message, MetadataEventDTO entityDTO) { - try { - // Acknowledge message receipt - channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); - log.info("Receive driver metadata: {}", JsonUtil.toJsonString(entityDTO)); + /** + * Receive and process metadata events from RabbitMQ queue + * + * @param channel RabbitMQ channel + * @param message RabbitMQ message + * @param entityDTO Metadata event data transfer object + */ + @RabbitHandler + @RabbitListener(queues = "#{metadataQueue.name}") + public void metadataReceive(Channel channel, Message message, MetadataEventDTO entityDTO) { + try { + // Acknowledge message receipt + channel.basicAck(message.getMessageProperties().getDeliveryTag(), true); + log.info("Receive driver metadata: {}", JsonUtil.toJsonString(entityDTO)); - // Validate metadata event - if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getMetadataType()) - || Objects.isNull(entityDTO.getOperateType())) { - log.error("Invalid driver metadata: {}", entityDTO); - return; - } + // Validate metadata event + if (Objects.isNull(entityDTO) || Objects.isNull(entityDTO.getMetadataType()) + || Objects.isNull(entityDTO.getOperateType())) { + log.error("Invalid driver metadata: {}", entityDTO); + return; + } - // Handle device metadata events - if (MetadataTypeEnum.DEVICE.equals(entityDTO.getMetadataType())) { - if (MetadataOperateTypeEnum.ADD.equals(entityDTO.getOperateType()) - || MetadataOperateTypeEnum.UPDATE.equals(entityDTO.getOperateType())) { - log.info("Upsert device: {}", entityDTO.getId()); - deviceMetadata.loadCache(entityDTO.getId()); - driverMetadata.getDeviceIds().add(entityDTO.getId()); - } - else if (MetadataOperateTypeEnum.DELETE.equals(entityDTO.getOperateType())) { - log.info("Delete device: {}", entityDTO.getId()); - deviceMetadata.removeCache(entityDTO.getId()); - driverMetadata.getDeviceIds().remove(entityDTO.getId()); - } + // Handle device metadata events + if (MetadataTypeEnum.DEVICE.equals(entityDTO.getMetadataType())) { + if (MetadataOperateTypeEnum.ADD.equals(entityDTO.getOperateType()) + || MetadataOperateTypeEnum.UPDATE.equals(entityDTO.getOperateType())) { + log.info("Upsert device: {}", entityDTO.getId()); + deviceMetadata.loadCache(entityDTO.getId()); + driverMetadata.getDeviceIds().add(entityDTO.getId()); + } else if (MetadataOperateTypeEnum.DELETE.equals(entityDTO.getOperateType())) { + log.info("Delete device: {}", entityDTO.getId()); + deviceMetadata.removeCache(entityDTO.getId()); + driverMetadata.getDeviceIds().remove(entityDTO.getId()); + } - // Publish device metadata event - metadataEventPublisher.publishEvent(new MetadataEvent(this, entityDTO.getId(), MetadataTypeEnum.DEVICE, - entityDTO.getOperateType())); - } - // Handle point metadata events - else if (MetadataTypeEnum.POINT.equals(entityDTO.getMetadataType())) { - if (MetadataOperateTypeEnum.ADD.equals(entityDTO.getOperateType()) - || MetadataOperateTypeEnum.UPDATE.equals(entityDTO.getOperateType())) { - log.info("Upsert point: {}", entityDTO.getId()); - pointMetadata.loadCache(entityDTO.getId()); - } - else if (MetadataOperateTypeEnum.DELETE.equals(entityDTO.getOperateType())) { - log.info("Delete point: {}", entityDTO.getId()); - pointMetadata.removeCache(entityDTO.getId()); - } + // Publish device metadata event + metadataEventPublisher.publishEvent(new MetadataEvent(this, entityDTO.getId(), MetadataTypeEnum.DEVICE, + entityDTO.getOperateType())); + } + // Handle point metadata events + else if (MetadataTypeEnum.POINT.equals(entityDTO.getMetadataType())) { + if (MetadataOperateTypeEnum.ADD.equals(entityDTO.getOperateType()) + || MetadataOperateTypeEnum.UPDATE.equals(entityDTO.getOperateType())) { + log.info("Upsert point: {}", entityDTO.getId()); + pointMetadata.loadCache(entityDTO.getId()); + } else if (MetadataOperateTypeEnum.DELETE.equals(entityDTO.getOperateType())) { + log.info("Delete point: {}", entityDTO.getId()); + pointMetadata.removeCache(entityDTO.getId()); + } - // Publish point metadata event - metadataEventPublisher.publishEvent( - new MetadataEvent(this, entityDTO.getId(), MetadataTypeEnum.POINT, entityDTO.getOperateType())); - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - } + // Publish point metadata event + metadataEventPublisher.publishEvent( + new MetadataEvent(this, entityDTO.getId(), MetadataTypeEnum.POINT, entityDTO.getOperateType())); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverCustomService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverCustomService.java index 6f30ccc86..b943012ab 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverCustomService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverCustomService.java @@ -36,78 +36,81 @@ import java.util.Map; */ public interface DriverCustomService { - /** - * Driver Initialization Interface - *

- * This interface is automatically called when the driver starts up, used to perform - * necessary initialization operations for the driver. Developers can configure - * essential resources or prepare the environment in this method. - */ - void initial(); + /** + * Driver Initialization Interface + *

+ * This interface is automatically called when the driver starts up, used to perform + * necessary initialization operations for the driver. Developers can configure + * essential resources or prepare the environment in this method. + */ + void initial(); - /** - * Custom Scheduling Interface - *

- * This interface is used to execute custom scheduling tasks, which can be configured - * through the configuration file {@code driver.schedule.custom}. Developers can - * implement custom scheduling logic here, such as timed tasks, periodic tasks, etc. - *

- * Note: The execution frequency and trigger conditions of scheduling tasks should be - * configured reasonably according to actual requirements. - */ - void schedule(); + /** + * Custom Scheduling Interface + *

+ * This interface is used to execute custom scheduling tasks, which can be configured + * through the configuration file {@code driver.schedule.custom}. Developers can + * implement custom scheduling logic here, such as timed tasks, periodic tasks, etc. + *

+ * Note: The execution frequency and trigger conditions of scheduling tasks should be + * configured reasonably according to actual requirements. + */ + void schedule(); - /** - * Handle Metadata Events for Driver, Device, and Point - *

- * This event is triggered when metadata for driver, device, or point undergoes - * addition, update, or deletion operations. The specific event type (driver, device, - * or point) is determined by {@link io.github.pnoker.common.enums.MetadataTypeEnum}. - * @param metadataEvent metadata event object containing detailed event information - * {@link MetadataEventDTO} - */ - void event(MetadataEventDTO metadataEvent); + /** + * Handle Metadata Events for Driver, Device, and Point + *

+ * This event is triggered when metadata for driver, device, or point undergoes + * addition, update, or deletion operations. The specific event type (driver, device, + * or point) is determined by {@link io.github.pnoker.common.enums.MetadataTypeEnum}. + * + * @param metadataEvent metadata event object containing detailed event information + * {@link MetadataEventDTO} + */ + void event(MetadataEventDTO metadataEvent); - /** - * Execute Read Operation - *

- * This interface is used to read point data from the specified device. Due to - * differences in device types and communication protocols, read operations may not be - * directly executable, please handle flexibly according to actual situations. - *

- * Note: Read operations may throw exceptions, callers need to handle exceptions - * properly. - * @param driverConfig driver property configuration containing driver-related - * configuration information - * @param pointConfig point property configuration containing point-related - * configuration information - * @param device device object containing basic device information and properties - * @param point point object containing basic point information and properties - * @return returns the read data encapsulated in a {@link RValue} object - */ - RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point); + /** + * Execute Read Operation + *

+ * This interface is used to read point data from the specified device. Due to + * differences in device types and communication protocols, read operations may not be + * directly executable, please handle flexibly according to actual situations. + *

+ * Note: Read operations may throw exceptions, callers need to handle exceptions + * properly. + * + * @param driverConfig driver property configuration containing driver-related + * configuration information + * @param pointConfig point property configuration containing point-related + * configuration information + * @param device device object containing basic device information and properties + * @param point point object containing basic point information and properties + * @return returns the read data encapsulated in a {@link RValue} object + */ + RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point); - /** - * Execute Write Operation - *

- * This interface is used to write data to a point in the specified device. Due to - * differences in device types and communication protocols, write operations may not - * be directly executable, please handle flexibly according to actual situations. - *

- * Note: Write operations may throw exceptions, callers need to handle exceptions - * properly. - * @param driverConfig driver property configuration containing driver-related - * configuration information - * @param pointConfig point property configuration containing point-related - * configuration information - * @param device device object containing basic device information and properties - * @param point point object containing basic point information and properties - * @param wValue data to be written encapsulated in a {@link WValue} object - * @return returns whether the write operation was successful, returns {@code true} if - * successful, otherwise returns {@code false} or throws an exception - */ - Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue); + /** + * Execute Write Operation + *

+ * This interface is used to write data to a point in the specified device. Due to + * differences in device types and communication protocols, write operations may not + * be directly executable, please handle flexibly according to actual situations. + *

+ * Note: Write operations may throw exceptions, callers need to handle exceptions + * properly. + * + * @param driverConfig driver property configuration containing driver-related + * configuration information + * @param pointConfig point property configuration containing point-related + * configuration information + * @param device device object containing basic device information and properties + * @param point point object containing basic point information and properties + * @param wValue data to be written encapsulated in a {@link WValue} object + * @return returns whether the write operation was successful, returns {@code true} if + * successful, otherwise returns {@code false} or throws an exception + */ + Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverReadService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverReadService.java index c0ab593ec..f0a3249de 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverReadService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverReadService.java @@ -24,17 +24,19 @@ import io.github.pnoker.common.entity.dto.DeviceCommandDTO; */ public interface DriverReadService { - /** - * Reads the current value of the specified point on the specified device. - * @param deviceId device identifier - * @param pointId point identifier - */ - void read(Long deviceId, Long pointId); + /** + * Reads the current value of the specified point on the specified device. + * + * @param deviceId device identifier + * @param pointId point identifier + */ + void read(Long deviceId, Long pointId); - /** - * Executes a read command received from the command queue. - * @param commandDTO device command payload - */ - void read(DeviceCommandDTO commandDTO); + /** + * Executes a read command received from the command queue. + * + * @param commandDTO device command payload + */ + void read(DeviceCommandDTO commandDTO); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverRegisterService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverRegisterService.java index 8c2791c2e..1c314b5e3 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverRegisterService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverRegisterService.java @@ -26,9 +26,9 @@ package io.github.pnoker.common.driver.service; */ public interface DriverRegisterService { - /** - * Performs driver registration during application startup. - */ - void initial(); + /** + * Performs driver registration during application startup. + */ + void initial(); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverScheduleService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverScheduleService.java index b04ce1867..d326be391 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverScheduleService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverScheduleService.java @@ -26,9 +26,9 @@ package io.github.pnoker.common.driver.service; */ public interface DriverScheduleService { - /** - * Initializes and schedules all enabled driver jobs. - */ - void initial(); + /** + * Initializes and schedules all enabled driver jobs. + */ + void initial(); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverSenderService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverSenderService.java index 59d7547fd..946311eed 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverSenderService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverSenderService.java @@ -34,58 +34,66 @@ import java.util.concurrent.TimeUnit; */ public interface DriverSenderService { - /** - * Publishes a driver event. - * @param entityDTO driver event payload - */ - void driverEventSender(DriverEventDTO entityDTO); + /** + * Publishes a driver event. + * + * @param entityDTO driver event payload + */ + void driverEventSender(DriverEventDTO entityDTO); - /** - * Publishes a device event. - * @param entityDTO device event payload - */ - void deviceEventSender(DeviceEventDTO entityDTO); + /** + * Publishes a device event. + * + * @param entityDTO device event payload + */ + void deviceEventSender(DeviceEventDTO entityDTO); - /** - * Publishes a device status event using the default timeout. - * @param deviceId device identifier - * @param status device status - */ - void deviceStatusSender(Long deviceId, DeviceStatusEnum status); + /** + * Publishes a device status event using the default timeout. + * + * @param deviceId device identifier + * @param status device status + */ + void deviceStatusSender(Long deviceId, DeviceStatusEnum status); - /** - * Publishes a device status event using the supplied timeout. - * @param deviceId device identifier - * @param status device status - * @param timeOut timeout value - * @param timeUnit timeout unit - */ - void deviceStatusSender(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit); + /** + * Publishes a device status event using the supplied timeout. + * + * @param deviceId device identifier + * @param status device status + * @param timeOut timeout value + * @param timeUnit timeout unit + */ + void deviceStatusSender(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit); - /** - * Publishes a driver-level ALARM event. Used by protocol drivers when a connection / - * read / write fails or a runtime guard trips. - * @param message human-readable reason, e.g. "OPC UA session dropped" - */ - void driverAlarmSender(String message); + /** + * Publishes a driver-level ALARM event. Used by protocol drivers when a connection / + * read / write fails or a runtime guard trips. + * + * @param message human-readable reason, e.g. "OPC UA session dropped" + */ + void driverAlarmSender(String message); - /** - * Publishes a device-level ALARM event scoped to the given device. - * @param deviceId device identifier - * @param message human-readable reason - */ - void deviceAlarmSender(Long deviceId, String message); + /** + * Publishes a device-level ALARM event scoped to the given device. + * + * @param deviceId device identifier + * @param message human-readable reason + */ + void deviceAlarmSender(Long deviceId, String message); - /** - * Publishes a single point value. - * @param entityDTO point value payload - */ - void pointValueSender(PointValue entityDTO); + /** + * Publishes a single point value. + * + * @param entityDTO point value payload + */ + void pointValueSender(PointValue entityDTO); - /** - * Publishes multiple point values. - * @param entityDTOList point value payloads - */ - void pointValueSender(List entityDTOList); + /** + * Publishes multiple point values. + * + * @param entityDTOList point value payloads + */ + void pointValueSender(List entityDTOList); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverWriteService.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverWriteService.java index 28ba34da4..85b5746ec 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverWriteService.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/DriverWriteService.java @@ -28,18 +28,20 @@ import io.github.pnoker.common.entity.dto.DeviceCommandDTO; */ public interface DriverWriteService { - /** - * Writes a value to the specified point on the specified device. - * @param deviceId device identifier - * @param pointId point identifier - * @param value raw value to write - */ - void write(Long deviceId, Long pointId, String value); + /** + * Writes a value to the specified point on the specified device. + * + * @param deviceId device identifier + * @param pointId point identifier + * @param value raw value to write + */ + void write(Long deviceId, Long pointId, String value); - /** - * Executes a write command received from the command queue. - * @param commandDTO device command payload - */ - void write(DeviceCommandDTO commandDTO); + /** + * Executes a write command received from the command queue. + * + * @param commandDTO device command payload + */ + void write(DeviceCommandDTO commandDTO); } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverReadServiceImpl.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverReadServiceImpl.java index 5e3f30941..c4b502db9 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverReadServiceImpl.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverReadServiceImpl.java @@ -45,69 +45,69 @@ import java.util.Objects; @Service public class DriverReadServiceImpl implements DriverReadService { - @Resource - private DeviceMetadata deviceMetadata; + @Resource + private DeviceMetadata deviceMetadata; - @Resource - private PointMetadata pointMetadata; + @Resource + private PointMetadata pointMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - @Resource - private DriverCustomService driverCustomService; + @Resource + private DriverCustomService driverCustomService; - @Override - public void read(Long deviceId, Long pointId) { - // Get device from metadata cache - DeviceBO device = deviceMetadata.getCache(deviceId); - if (Objects.isNull(device)) { - throw new ReadPointException("Failed to read point value, device[{}] is null", deviceId); - } + @Override + public void read(Long deviceId, Long pointId) { + // Get device from metadata cache + DeviceBO device = deviceMetadata.getCache(deviceId); + if (Objects.isNull(device)) { + throw new ReadPointException("Failed to read point value, device[{}] is null", deviceId); + } - // Check if device contains the specified point - if (!device.getPointIds().contains(pointId)) { - throw new ReadPointException("Failed to read point value, device[{}] not contained point[{}]", deviceId, - pointId); - } + // Check if device contains the specified point + if (!device.getPointIds().contains(pointId)) { + throw new ReadPointException("Failed to read point value, device[{}] not contained point[{}]", deviceId, + pointId); + } - // Get driver and point configurations - Map driverConfig = deviceMetadata.getDriverConfig(deviceId); - Map pointConfig = deviceMetadata.getPointConfig(deviceId, pointId); + // Get driver and point configurations + Map driverConfig = deviceMetadata.getDriverConfig(deviceId); + Map pointConfig = deviceMetadata.getPointConfig(deviceId, pointId); - // Get point from metadata cache - PointBO point = pointMetadata.getCache(pointId); - if (Objects.isNull(point)) { - throw new ReadPointException("Failed to read point value, point[{}] is null" + deviceId); - } + // Get point from metadata cache + PointBO point = pointMetadata.getCache(pointId); + if (Objects.isNull(point)) { + throw new ReadPointException("Failed to read point value, point[{}] is null" + deviceId); + } - // Read point value using custom driver service - RValue rValue = driverCustomService.read(driverConfig, pointConfig, device, point); - if (Objects.isNull(rValue)) { - throw new ReadPointException("Failed to read point value, point value is null"); - } + // Read point value using custom driver service + RValue rValue = driverCustomService.read(driverConfig, pointConfig, device, point); + if (Objects.isNull(rValue)) { + throw new ReadPointException("Failed to read point value, point value is null"); + } - // Send point value to message queue - driverSenderService.pointValueSender(new PointValue(rValue)); - } + // Send point value to message queue + driverSenderService.pointValueSender(new PointValue(rValue)); + } - @Override - public void read(DeviceCommandDTO commandDTO) { - // Parse device read command from command DTO - // Deserialize the command content into DeviceRead object - DeviceCommandDTO.DeviceRead deviceRead = JsonUtil.parseObject(commandDTO.getContent(), - DeviceCommandDTO.DeviceRead.class); - if (Objects.isNull(deviceRead)) { - return; - } + @Override + public void read(DeviceCommandDTO commandDTO) { + // Parse device read command from command DTO + // Deserialize the command content into DeviceRead object + DeviceCommandDTO.DeviceRead deviceRead = JsonUtil.parseObject(commandDTO.getContent(), + DeviceCommandDTO.DeviceRead.class); + if (Objects.isNull(deviceRead)) { + return; + } - // Execute read command and log the process - // Log the start of command execution with command details - log.info("Start command of read: {}", JsonUtil.toJsonString(commandDTO)); - // Call the read method with device and point IDs - read(deviceRead.getDeviceId(), deviceRead.getPointId()); - // Log the completion of command execution - log.info("End command of read"); - } + // Execute read command and log the process + // Log the start of command execution with command details + log.info("Start command of read: {}", JsonUtil.toJsonString(commandDTO)); + // Call the read method with device and point IDs + read(deviceRead.getDeviceId(), deviceRead.getPointId()); + // Log the completion of command execution + log.info("End command of read"); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverRegisterServiceImpl.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverRegisterServiceImpl.java index 2e0f23635..27d46397b 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverRegisterServiceImpl.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverRegisterServiceImpl.java @@ -36,52 +36,52 @@ import org.springframework.stereotype.Service; @Service public class DriverRegisterServiceImpl implements DriverRegisterService { - @Resource - private DriverProperties driverProperties; + @Resource + private DriverProperties driverProperties; - @Resource - private DriverClient driverClient; + @Resource + private DriverClient driverClient; - @Override - public void initial() { - try { - // Build driver registration information from properties - RegisterBO entityBO = buildRegisterBOByProperty(); - // Log driver information for debugging - log.info("The driver information is: {}", JsonUtil.toJsonString(entityBO)); - // Register driver with the driver client - driverClient.driverRegister(entityBO); - } - catch (Exception e) { - // Log error and exit if initialization fails - log.error("Driver initialization failed: {}", e.getMessage(), e); - System.exit(1); - } - } + @Override + public void initial() { + try { + // Build driver registration information from properties + RegisterBO entityBO = buildRegisterBOByProperty(); + // Log driver information for debugging + log.info("The driver information is: {}", JsonUtil.toJsonString(entityBO)); + // Register driver with the driver client + driverClient.driverRegister(entityBO); + } catch (Exception e) { + // Log error and exit if initialization fails + log.error("Driver initialization failed: {}", e.getMessage(), e); + System.exit(1); + } + } - /** - * - * Build driver registration information from properties - * @return DriverRegisterBO Driver registration business object - */ - private RegisterBO buildRegisterBOByProperty() { - // Create and populate driver business object with properties - DriverBO driverBO = new DriverBO(); - driverBO.setDriverName(driverProperties.getName()); - driverBO.setDriverCode(driverProperties.getCode()); - driverBO.setServiceName(driverProperties.getService()); - driverBO.setServiceHost(driverProperties.getHost()); - driverBO.setDriverTypeFlag(driverProperties.getType()); - driverBO.setRemark(driverProperties.getRemark()); + /** + * + * Build driver registration information from properties + * + * @return DriverRegisterBO Driver registration business object + */ + private RegisterBO buildRegisterBOByProperty() { + // Create and populate driver business object with properties + DriverBO driverBO = new DriverBO(); + driverBO.setDriverName(driverProperties.getName()); + driverBO.setDriverCode(driverProperties.getCode()); + driverBO.setServiceName(driverProperties.getService()); + driverBO.setServiceHost(driverProperties.getHost()); + driverBO.setDriverTypeFlag(driverProperties.getType()); + driverBO.setRemark(driverProperties.getRemark()); - // Create and populate registration business object - RegisterBO entityBO = new RegisterBO(); - entityBO.setDriver(driverBO); - entityBO.setTenant(driverProperties.getTenant()); - entityBO.setClient(driverProperties.getClient()); - entityBO.setDriverAttributes(driverProperties.getDriverAttribute()); - entityBO.setPointAttributes(driverProperties.getPointAttribute()); - return entityBO; - } + // Create and populate registration business object + RegisterBO entityBO = new RegisterBO(); + entityBO.setDriver(driverBO); + entityBO.setTenant(driverProperties.getTenant()); + entityBO.setClient(driverProperties.getClient()); + entityBO.setDriverAttributes(driverProperties.getDriverAttribute()); + entityBO.setPointAttributes(driverProperties.getPointAttribute()); + return entityBO; + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverScheduleServiceImpl.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverScheduleServiceImpl.java index 4a5968cab..2d6dbf20c 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverScheduleServiceImpl.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverScheduleServiceImpl.java @@ -40,58 +40,57 @@ import java.util.Objects; @Service public class DriverScheduleServiceImpl implements DriverScheduleService { - private final DriverProperties driverProperties; + private final DriverProperties driverProperties; - private final QuartzService quartzService; + private final QuartzService quartzService; - public DriverScheduleServiceImpl(DriverProperties driverProperties, QuartzService quartzService) { - this.driverProperties = driverProperties; - this.quartzService = quartzService; - } + public DriverScheduleServiceImpl(DriverProperties driverProperties, QuartzService quartzService) { + this.driverProperties = driverProperties; + this.quartzService = quartzService; + } - @Override - public void initial() { - // Get schedule properties from driver configuration - DriverProperties.ScheduleProperties property = driverProperties.getSchedule(); - if (Objects.isNull(property)) { - return; - } + @Override + public void initial() { + // Get schedule properties from driver configuration + DriverProperties.ScheduleProperties property = driverProperties.getSchedule(); + if (Objects.isNull(property)) { + return; + } - try { - // Create and schedule the driver status monitoring job - quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, - ScheduleConstant.DRIVER_STATUS_SCHEDULE_JOB, ScheduleConstant.DRIVER_STATUS_SCHEDULE_CRON, - DriverStatusScheduleJob.class); + try { + // Create and schedule the driver status monitoring job + quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, + ScheduleConstant.DRIVER_STATUS_SCHEDULE_JOB, ScheduleConstant.DRIVER_STATUS_SCHEDULE_CRON, + DriverStatusScheduleJob.class); - // Create and schedule the read job if enabled - if (Boolean.TRUE.equals(property.getRead().getEnable())) { - // Validate read job cron expression - if (!CronExpression.isValidExpression(property.getRead().getCron())) { - throw new CronException("Read schedule cron expression is invalid"); - } - quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, - ScheduleConstant.DRIVER_READ_SCHEDULE_JOB, property.getRead().getCron(), - DriverReadScheduleJob.class); - } + // Create and schedule the read job if enabled + if (Boolean.TRUE.equals(property.getRead().getEnable())) { + // Validate read job cron expression + if (!CronExpression.isValidExpression(property.getRead().getCron())) { + throw new CronException("Read schedule cron expression is invalid"); + } + quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, + ScheduleConstant.DRIVER_READ_SCHEDULE_JOB, property.getRead().getCron(), + DriverReadScheduleJob.class); + } - // Create and schedule the custom job if enabled - if (Boolean.TRUE.equals(property.getCustom().getEnable())) { - // Validate custom job cron expression - if (!CronExpression.isValidExpression(property.getCustom().getCron())) { - throw new CronException("Custom schedule cron expression is invalid"); - } - quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, - ScheduleConstant.DRIVER_CUSTOM_SCHEDULE_JOB, property.getCustom().getCron(), - DriverCustomScheduleJob.class); - } + // Create and schedule the custom job if enabled + if (Boolean.TRUE.equals(property.getCustom().getEnable())) { + // Validate custom job cron expression + if (!CronExpression.isValidExpression(property.getCustom().getCron())) { + throw new CronException("Custom schedule cron expression is invalid"); + } + quartzService.createJobWithCron(ScheduleConstant.DRIVER_SCHEDULE_GROUP, + ScheduleConstant.DRIVER_CUSTOM_SCHEDULE_JOB, property.getCustom().getCron(), + DriverCustomScheduleJob.class); + } - // Start the scheduler after all jobs are configured - quartzService.startScheduler(); - } - catch (SchedulerException e) { - // Log any scheduler initialization errors - log.error("Driver schedule initial error: {}", e.getMessage(), e); - } - } + // Start the scheduler after all jobs are configured + quartzService.startScheduler(); + } catch (SchedulerException e) { + // Log any scheduler initialization errors + log.error("Driver schedule initial error: {}", e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverSenderServiceImpl.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverSenderServiceImpl.java index 679833ba2..55317c6da 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverSenderServiceImpl.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverSenderServiceImpl.java @@ -45,162 +45,167 @@ import java.util.concurrent.TimeUnit; @Service public class DriverSenderServiceImpl implements DriverSenderService { - private final DriverProperties driverProperties; + private final DriverProperties driverProperties; - private final DriverMetadata driverMetadata; + private final DriverMetadata driverMetadata; - private final RabbitTemplate rabbitTemplate; + private final RabbitTemplate rabbitTemplate; - public DriverSenderServiceImpl(DriverProperties driverProperties, DriverMetadata driverMetadata, - RabbitTemplate rabbitTemplate) { - this.driverProperties = driverProperties; - this.driverMetadata = driverMetadata; - this.rabbitTemplate = rabbitTemplate; - } + public DriverSenderServiceImpl(DriverProperties driverProperties, DriverMetadata driverMetadata, + RabbitTemplate rabbitTemplate) { + this.driverProperties = driverProperties; + this.driverMetadata = driverMetadata; + this.rabbitTemplate = rabbitTemplate; + } - /** - * Send driver event to message queue - * @param entityDTO Driver event data transfer object - */ - @Override - public void driverEventSender(DriverEventDTO entityDTO) { - if (Objects.isNull(entityDTO)) { - return; - } + /** + * Send driver event to message queue + * + * @param entityDTO Driver event data transfer object + */ + @Override + public void driverEventSender(DriverEventDTO entityDTO) { + if (Objects.isNull(entityDTO)) { + return; + } - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_EVENT, - RabbitConstant.ROUTING_DRIVER_EVENT_PREFIX + driverProperties.getService(), entityDTO); - } + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_EVENT, + RabbitConstant.ROUTING_DRIVER_EVENT_PREFIX + driverProperties.getService(), entityDTO); + } - /** - * Send device event to message queue - * @param entityDTO Device event data transfer object - */ - @Override - public void deviceEventSender(DeviceEventDTO entityDTO) { - if (!Objects.nonNull(entityDTO)) { - return; - } + /** + * Send device event to message queue + * + * @param entityDTO Device event data transfer object + */ + @Override + public void deviceEventSender(DeviceEventDTO entityDTO) { + if (!Objects.nonNull(entityDTO)) { + return; + } - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_EVENT, - RabbitConstant.ROUTING_DEVICE_EVENT_PREFIX + driverProperties.getService(), entityDTO); - } + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_EVENT, + RabbitConstant.ROUTING_DEVICE_EVENT_PREFIX + driverProperties.getService(), entityDTO); + } - /** - * Send device status with default timeout (15 minutes) - * @param deviceId Device ID - * @param status Device status enum - */ - @Override - public void deviceStatusSender(Long deviceId, DeviceStatusEnum status) { - sendDeviceStatus(deviceId, status, 15, TimeUnit.MINUTES); - } + /** + * Send device status with default timeout (15 minutes) + * + * @param deviceId Device ID + * @param status Device status enum + */ + @Override + public void deviceStatusSender(Long deviceId, DeviceStatusEnum status) { + sendDeviceStatus(deviceId, status, 15, TimeUnit.MINUTES); + } - /** - * Send device status with custom timeout - * @param deviceId Device ID - * @param status Device status enum - * @param timeOut Timeout value - * @param timeUnit Time unit for timeout - */ - @Override - public void deviceStatusSender(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { - sendDeviceStatus(deviceId, status, timeOut, timeUnit); - } + /** + * Send device status with custom timeout + * + * @param deviceId Device ID + * @param status Device status enum + * @param timeOut Timeout value + * @param timeUnit Time unit for timeout + */ + @Override + public void deviceStatusSender(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { + sendDeviceStatus(deviceId, status, timeOut, timeUnit); + } - @Override - public void driverAlarmSender(String message) { - DriverBO driver = driverMetadata.getDriver(); - if (Objects.isNull(driver)) { - log.warn("Driver not registered yet; drop alarm: {}", message); - return; - } - DriverEventDTO.DriverStatus payload = new DriverEventDTO.DriverStatus(driver.getId(), - driverMetadata.getDriverStatus()); - payload.setTenantId(driver.getTenantId()); - payload.setMessage(message); - DriverEventDTO event = new DriverEventDTO(DriverEventTypeEnum.ALARM, JsonUtil.toJsonString(payload)); - log.info("Report driver alarm: {}", message); - driverEventSender(event); - } + @Override + public void driverAlarmSender(String message) { + DriverBO driver = driverMetadata.getDriver(); + if (Objects.isNull(driver)) { + log.warn("Driver not registered yet; drop alarm: {}", message); + return; + } + DriverEventDTO.DriverStatus payload = new DriverEventDTO.DriverStatus(driver.getId(), + driverMetadata.getDriverStatus()); + payload.setTenantId(driver.getTenantId()); + payload.setMessage(message); + DriverEventDTO event = new DriverEventDTO(DriverEventTypeEnum.ALARM, JsonUtil.toJsonString(payload)); + log.info("Report driver alarm: {}", message); + driverEventSender(event); + } - @Override - public void deviceAlarmSender(Long deviceId, String message) { - if (Objects.isNull(deviceId)) { - return; - } - DeviceEventDTO.DeviceStatus payload = new DeviceEventDTO.DeviceStatus(deviceId, null); - DriverBO driver = driverMetadata.getDriver(); - if (Objects.nonNull(driver)) { - payload.setDriverId(driver.getId()); - payload.setTenantId(driver.getTenantId()); - } - payload.setMessage(message); - DeviceEventDTO event = new DeviceEventDTO(DeviceEventTypeEnum.ALARM, JsonUtil.toJsonString(payload)); - log.info("Report device alarm: deviceId={}, message={}", deviceId, message); - deviceEventSender(event); - } + @Override + public void deviceAlarmSender(Long deviceId, String message) { + if (Objects.isNull(deviceId)) { + return; + } + DeviceEventDTO.DeviceStatus payload = new DeviceEventDTO.DeviceStatus(deviceId, null); + DriverBO driver = driverMetadata.getDriver(); + if (Objects.nonNull(driver)) { + payload.setDriverId(driver.getId()); + payload.setTenantId(driver.getTenantId()); + } + payload.setMessage(message); + DeviceEventDTO event = new DeviceEventDTO(DeviceEventTypeEnum.ALARM, JsonUtil.toJsonString(payload)); + log.info("Report device alarm: deviceId={}, message={}", deviceId, message); + deviceEventSender(event); + } - /** - * Send single point value to message queue - * @param entityDTO Point value data transfer object - */ - @Override - public void pointValueSender(PointValue entityDTO) { - if (Objects.nonNull(entityDTO)) { - DriverBO driver = driverMetadata.getDriver(); - if (Objects.nonNull(driver)) { - if (Objects.isNull(entityDTO.getDriverId())) { - entityDTO.setDriverId(driver.getId()); - } - if (Objects.isNull(entityDTO.getTenantId())) { - entityDTO.setTenantId(driver.getTenantId()); - } - } - else { - log.warn( - "DriverMetadata has no registered driver yet; point value will be published without driverId/tenantId"); - } - log.info("Send point value: {}", JsonUtil.toJsonString(entityDTO)); - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_VALUE, - RabbitConstant.ROUTING_POINT_VALUE_PREFIX + driverProperties.getService(), entityDTO); - } - } + /** + * Send single point value to message queue + * + * @param entityDTO Point value data transfer object + */ + @Override + public void pointValueSender(PointValue entityDTO) { + if (Objects.nonNull(entityDTO)) { + DriverBO driver = driverMetadata.getDriver(); + if (Objects.nonNull(driver)) { + if (Objects.isNull(entityDTO.getDriverId())) { + entityDTO.setDriverId(driver.getId()); + } + if (Objects.isNull(entityDTO.getTenantId())) { + entityDTO.setTenantId(driver.getTenantId()); + } + } else { + log.warn( + "DriverMetadata has no registered driver yet; point value will be published without driverId/tenantId"); + } + log.info("Send point value: {}", JsonUtil.toJsonString(entityDTO)); + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_VALUE, + RabbitConstant.ROUTING_POINT_VALUE_PREFIX + driverProperties.getService(), entityDTO); + } + } - /** - * Send multiple point values to message queue - * @param entityDTOList List of point value data transfer objects - */ - @Override - public void pointValueSender(List entityDTOList) { - if (Objects.nonNull(entityDTOList)) { - entityDTOList.forEach(this::pointValueSender); - } - } + /** + * Send multiple point values to message queue + * + * @param entityDTOList List of point value data transfer objects + */ + @Override + public void pointValueSender(List entityDTOList) { + if (Objects.nonNull(entityDTOList)) { + entityDTOList.forEach(this::pointValueSender); + } + } - /** - * Helper method to send device status event - * @param deviceId Device ID - * @param status Device status enum - * @param timeOut Timeout value - * @param timeUnit Time unit for timeout - */ - private void sendDeviceStatus(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { - DeviceEventDTO.DeviceStatus deviceStatus = new DeviceEventDTO.DeviceStatus(deviceId, status, timeOut, timeUnit); - DriverBO driver = driverMetadata.getDriver(); - if (Objects.nonNull(driver)) { - deviceStatus.setDriverId(driver.getId()); - deviceStatus.setTenantId(driver.getTenantId()); - } - else { - log.warn( - "DriverMetadata has no registered driver yet; device status will be published without driverId/tenantId"); - } - DeviceEventDTO deviceEventDTO = new DeviceEventDTO(DeviceEventTypeEnum.HEARTBEAT, - JsonUtil.toJsonString(deviceStatus)); - log.info("Report device event: {}, event content: {}", deviceEventDTO.getType().getCode(), - JsonUtil.toJsonString(deviceEventDTO)); - deviceEventSender(deviceEventDTO); - } + /** + * Helper method to send device status event + * + * @param deviceId Device ID + * @param status Device status enum + * @param timeOut Timeout value + * @param timeUnit Time unit for timeout + */ + private void sendDeviceStatus(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { + DeviceEventDTO.DeviceStatus deviceStatus = new DeviceEventDTO.DeviceStatus(deviceId, status, timeOut, timeUnit); + DriverBO driver = driverMetadata.getDriver(); + if (Objects.nonNull(driver)) { + deviceStatus.setDriverId(driver.getId()); + deviceStatus.setTenantId(driver.getTenantId()); + } else { + log.warn( + "DriverMetadata has no registered driver yet; device status will be published without driverId/tenantId"); + } + DeviceEventDTO deviceEventDTO = new DeviceEventDTO(DeviceEventTypeEnum.HEARTBEAT, + JsonUtil.toJsonString(deviceStatus)); + log.info("Report device event: {}, event content: {}", deviceEventDTO.getType().getCode(), + JsonUtil.toJsonString(deviceEventDTO)); + deviceEventSender(deviceEventDTO); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverWriteServiceImpl.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverWriteServiceImpl.java index 7a9106766..a1f42c7bc 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverWriteServiceImpl.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/driver/service/impl/DriverWriteServiceImpl.java @@ -49,67 +49,66 @@ import java.util.Objects; @Service public class DriverWriteServiceImpl implements DriverWriteService { - @Resource - private DriverMetadata driverMetadata; + @Resource + private DriverMetadata driverMetadata; - @Resource - private DeviceMetadata deviceMetadata; + @Resource + private DeviceMetadata deviceMetadata; - @Resource - private PointMetadata pointMetadata; + @Resource + private PointMetadata pointMetadata; - @Resource - private DriverCustomService driverCustomService; + @Resource + private DriverCustomService driverCustomService; - @Override - public void write(Long deviceId, Long pointId, String value) { - try { - // Get device from metadata cache - DeviceBO device = deviceMetadata.getCache(deviceId); - if (Objects.isNull(device)) { - throw new ReadPointException("Failed to write point value, device[{}] is null", deviceId); - } + @Override + public void write(Long deviceId, Long pointId, String value) { + try { + // Get device from metadata cache + DeviceBO device = deviceMetadata.getCache(deviceId); + if (Objects.isNull(device)) { + throw new ReadPointException("Failed to write point value, device[{}] is null", deviceId); + } - // Check if device contains the specified point - if (!device.getPointIds().contains(pointId)) { - throw new ReadPointException("Failed to write point value, device[{}] not contained point[{}]", - deviceId, pointId); - } + // Check if device contains the specified point + if (!device.getPointIds().contains(pointId)) { + throw new ReadPointException("Failed to write point value, device[{}] not contained point[{}]", + deviceId, pointId); + } - // Get driver and point configurations - Map driverConfig = deviceMetadata.getDriverConfig(deviceId); - Map pointConfig = deviceMetadata.getPointConfig(deviceId, pointId); + // Get driver and point configurations + Map driverConfig = deviceMetadata.getDriverConfig(deviceId); + Map pointConfig = deviceMetadata.getPointConfig(deviceId, pointId); - // Get point from metadata cache - PointBO point = pointMetadata.getCache(pointId); - if (Objects.isNull(point)) { - throw new ReadPointException("Failed to write point value, point[{}] is null" + deviceId); - } + // Get point from metadata cache + PointBO point = pointMetadata.getCache(pointId); + if (Objects.isNull(point)) { + throw new ReadPointException("Failed to write point value, point[{}] is null" + deviceId); + } - // Write value to device through custom driver service - driverCustomService.write(driverConfig, pointConfig, device, point, - new WValue(value, point.getPointTypeFlag())); - } - catch (Exception e) { - throw new ServiceException(e.getMessage()); - } - } + // Write value to device through custom driver service + driverCustomService.write(driverConfig, pointConfig, device, point, + new WValue(value, point.getPointTypeFlag())); + } catch (Exception e) { + throw new ServiceException(e.getMessage()); + } + } - @Override - public void write(DeviceCommandDTO commandDTO) { - // Parse device write command from DTO content - DeviceCommandDTO.DeviceWrite deviceWrite = JsonUtil.parseObject(commandDTO.getContent(), - DeviceCommandDTO.DeviceWrite.class); - if (Objects.isNull(deviceWrite)) { - return; - } + @Override + public void write(DeviceCommandDTO commandDTO) { + // Parse device write command from DTO content + DeviceCommandDTO.DeviceWrite deviceWrite = JsonUtil.parseObject(commandDTO.getContent(), + DeviceCommandDTO.DeviceWrite.class); + if (Objects.isNull(deviceWrite)) { + return; + } - // Log command execution start - log.info("Start command of write: {}", JsonUtil.toJsonString(commandDTO)); - // Execute write operation - write(deviceWrite.getDeviceId(), deviceWrite.getPointId(), deviceWrite.getValue()); - // Log command execution end - log.info("End command of write: write"); - } + // Log command execution start + log.info("Start command of write: {}", JsonUtil.toJsonString(commandDTO)); + // Execute write operation + write(deviceWrite.getDeviceId(), deviceWrite.getPointId(), deviceWrite.getValue()); + // Log command execution end + log.info("End command of write: write"); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/init/DriverInitRunner.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/init/DriverInitRunner.java index b567652b7..61ff825fe 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/init/DriverInitRunner.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/init/DriverInitRunner.java @@ -37,31 +37,31 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.driver" }) -@EnableConfigurationProperties({ DriverProperties.class }) +@ComponentScan(basePackages = {"io.github.pnoker.common.driver"}) +@EnableConfigurationProperties({DriverProperties.class}) public class DriverInitRunner implements ApplicationRunner { - @Resource - private DriverRegisterService driverRegisterService; + @Resource + private DriverRegisterService driverRegisterService; - @Resource - private DriverCustomService driverCustomService; + @Resource + private DriverCustomService driverCustomService; - @Resource - private DriverScheduleService driverScheduleService; + @Resource + private DriverScheduleService driverScheduleService; - @Override - public void run(ApplicationArguments args) throws Exception { - // Initialize driver registration and synchronize basic information with the - // platform - driverRegisterService.initial(); + @Override + public void run(ApplicationArguments args) throws Exception { + // Initialize driver registration and synchronize basic information with the + // platform + driverRegisterService.initial(); - // Execute custom initialization functions specific to this driver module - driverCustomService.initial(); + // Execute custom initialization functions specific to this driver module + driverCustomService.initial(); - // Initialize driver tasks including status monitoring, reading operations and - // custom tasks - driverScheduleService.initial(); - } + // Initialize driver tasks including status monitoring, reading operations and + // custom tasks + driverScheduleService.initial(); + } } diff --git a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/utils/CodecUtil.java b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/utils/CodecUtil.java index c53e815b8..c2a726dd8 100644 --- a/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/utils/CodecUtil.java +++ b/dc3-common/dc3-common-driver/src/main/java/io/github/pnoker/common/utils/CodecUtil.java @@ -30,207 +30,212 @@ import java.util.Base64; @Slf4j public class CodecUtil { - private CodecUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private CodecUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Encodes the provided string into a Base64 string. - * @param content input string - * @return Base64-encoded string - */ - public static String base64Encode(String content) { - byte[] bytes = DecodeUtil.stringToByte(content); - return Base64.getEncoder().encodeToString(bytes); - } + /** + * Encodes the provided string into a Base64 string. + * + * @param content input string + * @return Base64-encoded string + */ + public static String base64Encode(String content) { + byte[] bytes = DecodeUtil.stringToByte(content); + return Base64.getEncoder().encodeToString(bytes); + } - /** - * Decodes a Base64 string into its original form. - * @param content Base64 string - * @return decoded string - */ - public static String base64Decode(String content) { - byte[] bytes = DecodeUtil.stringToByte(content); - return new String(Base64.getDecoder().decode(bytes)); - } + /** + * Decodes a Base64 string into its original form. + * + * @param content Base64 string + * @return decoded string + */ + public static String base64Decode(String content) { + byte[] bytes = DecodeUtil.stringToByte(content); + return new String(Base64.getDecoder().decode(bytes)); + } - /** - * Converts BCD bytes to a decimal string. - */ - public static String bcdBytesToString(byte[] bytes) { - StringBuilder sb = new StringBuilder(bytes.length * 2); - for (byte aByte : bytes) { - sb.append((byte) ((aByte & 0xf0) >>> 4)); - sb.append((byte) (aByte & 0x0f)); - } - return sb.substring(0, 1).equalsIgnoreCase("0") ? sb.substring(1) : sb.toString(); - } + /** + * Converts BCD bytes to a decimal string. + */ + public static String bcdBytesToString(byte[] bytes) { + StringBuilder sb = new StringBuilder(bytes.length * 2); + for (byte aByte : bytes) { + sb.append((byte) ((aByte & 0xf0) >>> 4)); + sb.append((byte) (aByte & 0x0f)); + } + return sb.substring(0, 1).equalsIgnoreCase("0") ? sb.substring(1) : sb.toString(); + } - /** - * Converts a decimal string to BCD bytes. - */ - public static byte[] strToBcdBytes(String decimalString) { - int length = decimalString.length(); - int mod = length % 2; - if (mod != 0) { - decimalString = "0" + decimalString; - length = decimalString.length(); - } - if (length >= 2) { - length = length / 2; - } - byte[] bcdBytes = new byte[length]; - byte[] decimalBytes = DecodeUtil.stringToByte(decimalString); - int j; - int k; - for (int i = 0; i < decimalString.length() / 2; i++) { - if ((decimalBytes[2 * i] >= '0') && (decimalBytes[2 * i] <= '9')) { - j = decimalBytes[2 * i] - '0'; - } - else if ((decimalBytes[2 * i] >= 'a') && (decimalBytes[2 * i] <= 'z')) { - j = decimalBytes[2 * i] - 'a' + 0x0a; - } - else { - j = decimalBytes[2 * i] - 'A' + 0x0a; - } - if ((decimalBytes[2 * i + 1] >= '0') && (decimalBytes[2 * i + 1] <= '9')) { - k = decimalBytes[2 * i + 1] - '0'; - } - else if ((decimalBytes[2 * i + 1] >= 'a') && (decimalBytes[2 * i + 1] <= 'z')) { - k = decimalBytes[2 * i + 1] - 'a' + 0x0a; - } - else { - k = decimalBytes[2 * i + 1] - 'A' + 0x0a; - } - bcdBytes[i] = (byte) ((j << 4) + k); - } - return bcdBytes; - } + /** + * Converts a decimal string to BCD bytes. + */ + public static byte[] strToBcdBytes(String decimalString) { + int length = decimalString.length(); + int mod = length % 2; + if (mod != 0) { + decimalString = "0" + decimalString; + length = decimalString.length(); + } + if (length >= 2) { + length = length / 2; + } + byte[] bcdBytes = new byte[length]; + byte[] decimalBytes = DecodeUtil.stringToByte(decimalString); + int j; + int k; + for (int i = 0; i < decimalString.length() / 2; i++) { + if ((decimalBytes[2 * i] >= '0') && (decimalBytes[2 * i] <= '9')) { + j = decimalBytes[2 * i] - '0'; + } else if ((decimalBytes[2 * i] >= 'a') && (decimalBytes[2 * i] <= 'z')) { + j = decimalBytes[2 * i] - 'a' + 0x0a; + } else { + j = decimalBytes[2 * i] - 'A' + 0x0a; + } + if ((decimalBytes[2 * i + 1] >= '0') && (decimalBytes[2 * i + 1] <= '9')) { + k = decimalBytes[2 * i + 1] - '0'; + } else if ((decimalBytes[2 * i + 1] >= 'a') && (decimalBytes[2 * i + 1] <= 'z')) { + k = decimalBytes[2 * i + 1] - 'a' + 0x0a; + } else { + k = decimalBytes[2 * i + 1] - 'A' + 0x0a; + } + bcdBytes[i] = (byte) ((j << 4) + k); + } + return bcdBytes; + } - /** - * Converts bytes to a hexadecimal string. - */ - public static String bytesToHex(byte[] bytes) { - StringBuilder sb = new StringBuilder(); - for (byte aByte : bytes) { - String hex = Integer.toHexString(aByte & 0xFF); - if (hex.length() < 2) { - sb.append(0); - } - sb.append(hex); - } - return sb.toString(); - } + /** + * Converts bytes to a hexadecimal string. + */ + public static String bytesToHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte aByte : bytes) { + String hex = Integer.toHexString(aByte & 0xFF); + if (hex.length() < 2) { + sb.append(0); + } + sb.append(hex); + } + return sb.toString(); + } - /** - * Converts a byte array to a big-endian integer. - * @param bytes byte array - * @return integer value - */ - public static int bytesToInt(byte[] bytes) { - byte[] temp = new byte[4]; - int length = bytes.length; - System.arraycopy(bytes, 0, temp, 0, length); - for (int i = length; i < 4; i++) { - temp[i] = 0x00; - } - int int1 = temp[3] & 0xff; - int int2 = (temp[2] & 0xff) << 8; - int int3 = (temp[1] & 0xff) << 16; - int int4 = (temp[0] & 0xff) << 24; + /** + * Converts a byte array to a big-endian integer. + * + * @param bytes byte array + * @return integer value + */ + public static int bytesToInt(byte[] bytes) { + byte[] temp = new byte[4]; + int length = bytes.length; + System.arraycopy(bytes, 0, temp, 0, length); + for (int i = length; i < 4; i++) { + temp[i] = 0x00; + } + int int1 = temp[3] & 0xff; + int int2 = (temp[2] & 0xff) << 8; + int int3 = (temp[1] & 0xff) << 16; + int int4 = (temp[0] & 0xff) << 24; - return int1 | int2 | int3 | int4; - } + return int1 | int2 | int3 | int4; + } - /** - * Converts a byte array to a little-endian integer. - * @param bytes byte array - * @return integer value - */ - public static int bytesToIntLE(byte[] bytes) { - byte[] temp = new byte[4]; - int length = bytes.length; - System.arraycopy(bytes, 0, temp, 0, length); - for (int i = length; i < 4; i++) { - temp[i] = 0x00; - } - int int1 = temp[0] & 0xff; - int int2 = (temp[1] & 0xff) << 8; - int int3 = (temp[2] & 0xff) << 16; - int int4 = (temp[3] & 0xff) << 24; - return int1 | int2 | int3 | int4; - } + /** + * Converts a byte array to a little-endian integer. + * + * @param bytes byte array + * @return integer value + */ + public static int bytesToIntLE(byte[] bytes) { + byte[] temp = new byte[4]; + int length = bytes.length; + System.arraycopy(bytes, 0, temp, 0, length); + for (int i = length; i < 4; i++) { + temp[i] = 0x00; + } + int int1 = temp[0] & 0xff; + int int2 = (temp[1] & 0xff) << 8; + int int3 = (temp[2] & 0xff) << 16; + int int4 = (temp[3] & 0xff) << 24; + return int1 | int2 | int3 | int4; + } - /** - * Converts bytes to an ISO-8859-1 string. - * @param bytes byte array - * @return decoded string - */ - public static String bytesToAscii(byte[] bytes) { - return new String(bytes, StandardCharsets.ISO_8859_1); - } + /** + * Converts bytes to an ISO-8859-1 string. + * + * @param bytes byte array + * @return decoded string + */ + public static String bytesToAscii(byte[] bytes) { + return new String(bytes, StandardCharsets.ISO_8859_1); + } - /** - * Reverses the order of the supplied bytes. - * @param bytes byte array - * @return reversed byte array - */ - public static byte[] byteReverse(byte[] bytes) { - int length = bytes.length; - byte[] reverse = new byte[length]; - for (int i = 0; i < length; i++) { - reverse[length - 1 - i] = bytes[i]; - } - return reverse; - } + /** + * Reverses the order of the supplied bytes. + * + * @param bytes byte array + * @return reversed byte array + */ + public static byte[] byteReverse(byte[] bytes) { + int length = bytes.length; + byte[] reverse = new byte[length]; + for (int i = 0; i < length; i++) { + reverse[length - 1 - i] = bytes[i]; + } + return reverse; + } - /** - * Merges multiple byte arrays into a single array. - * @param bytes byte arrays - * @return merged byte array - */ - public static byte[] mergerBytes(byte[]... bytes) { - int lengthByte = 0; - for (byte[] value : bytes) { - lengthByte += value.length; - } - byte[] allByte = new byte[lengthByte]; - int countLength = 0; - for (byte[] b : bytes) { - System.arraycopy(b, 0, allByte, countLength, b.length); - countLength += b.length; - } - return allByte; - } + /** + * Merges multiple byte arrays into a single array. + * + * @param bytes byte arrays + * @return merged byte array + */ + public static byte[] mergerBytes(byte[]... bytes) { + int lengthByte = 0; + for (byte[] value : bytes) { + lengthByte += value.length; + } + byte[] allByte = new byte[lengthByte]; + int countLength = 0; + for (byte[] b : bytes) { + System.arraycopy(b, 0, allByte, countLength, b.length); + countLength += b.length; + } + return allByte; + } - /** - * Calculates the XOR checksum of the supplied byte arrays. - * @param bytes byte arrays - * @return XOR checksum - */ - public static byte xorBytes(byte[]... bytes) { - byte xor = 0x00; - for (byte[] value : bytes) { - for (byte b : value) { - xor ^= b; - } - } - return xor; - } + /** + * Calculates the XOR checksum of the supplied byte arrays. + * + * @param bytes byte arrays + * @return XOR checksum + */ + public static byte xorBytes(byte[]... bytes) { + byte xor = 0x00; + for (byte[] value : bytes) { + for (byte b : value) { + xor ^= b; + } + } + return xor; + } - /** - * Calculates the additive checksum of the supplied byte arrays. - * @param bytes byte arrays - * @return additive checksum - */ - public static byte sumBytes(byte[]... bytes) { - byte xor = 0x00; - for (byte[] value : bytes) { - for (byte b : value) { - xor += b; - } - } - return xor; - } + /** + * Calculates the additive checksum of the supplied byte arrays. + * + * @param bytes byte arrays + * @return additive checksum + */ + public static byte sumBytes(byte[]... bytes) { + byte xor = 0x00; + for (byte[] value : bytes) { + for (byte b : value) { + xor += b; + } + } + return xor; + } } diff --git a/dc3-common/dc3-common-exception/README.md b/dc3-common/dc3-common-exception/README.md index b7802bad4..0baac4b48 100644 --- a/dc3-common/dc3-common-exception/README.md +++ b/dc3-common/dc3-common-exception/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-exception` defines the standard exception types and exception utility class for the IoT DC3 platform. All services and modules use these exceptions to signal business +`dc3-common-exception` defines the standard exception types and exception utility class for the IoT DC3 platform. All +services and modules use these exceptions to signal business errors consistently. ## Module Information diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/constant/common/ExceptionConstant.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/constant/common/ExceptionConstant.java index 4ef385fbb..491143d13 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/constant/common/ExceptionConstant.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/constant/common/ExceptionConstant.java @@ -24,23 +24,23 @@ package io.github.pnoker.common.constant.common; */ public class ExceptionConstant { - /** - * - */ - public static final String UTILITY_CLASS = "Utility class"; + /** + * + */ + public static final String UTILITY_CLASS = "Utility class"; - /** - * - */ - public static final String NO_AVAILABLE_SERVER = "No available server for client"; + /** + * + */ + public static final String NO_AVAILABLE_SERVER = "No available server for client"; - /** - * Tenant, - */ - public static final String NO_AVAILABLE_AUTH = "Tenant, user information does not match"; + /** + * Tenant, + */ + public static final String NO_AVAILABLE_AUTH = "Tenant, user information does not match"; - private ExceptionConstant() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ExceptionConstant() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AddException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AddException.java index 20c339ef2..1cf73fcdf 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AddException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AddException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class AddException extends RuntimeException { - public AddException() { - this(null); - } + public AddException() { + this(null); + } - public AddException(Throwable cause) { - super(cause); - } + public AddException(Throwable cause) { + super(cause); + } - public AddException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public AddException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AssociatedException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AssociatedException.java index c102aff12..94fc12682 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AssociatedException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/AssociatedException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class AssociatedException extends RuntimeException { - public AssociatedException() { - this(null); - } + public AssociatedException() { + this(null); + } - public AssociatedException(Throwable cause) { - super(cause); - } + public AssociatedException(Throwable cause) { + super(cause); + } - public AssociatedException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public AssociatedException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConfigException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConfigException.java index 10ca602ec..980f25a15 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConfigException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConfigException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class ConfigException extends RuntimeException { - public ConfigException() { - this(null); - } + public ConfigException() { + this(null); + } - public ConfigException(Throwable cause) { - super(cause); - } + public ConfigException(Throwable cause) { + super(cause); + } - public ConfigException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public ConfigException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConnectorException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConnectorException.java index 2db1d01a1..57ccefe8c 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConnectorException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ConnectorException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class ConnectorException extends RuntimeException { - public ConnectorException() { - this(null); - } + public ConnectorException() { + this(null); + } - public ConnectorException(Throwable cause) { - super(cause); - } + public ConnectorException(Throwable cause) { + super(cause); + } - public ConnectorException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public ConnectorException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/CronException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/CronException.java index 16ff86ede..8ac13017c 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/CronException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/CronException.java @@ -28,16 +28,16 @@ import java.text.MessageFormat; */ public class CronException extends RuntimeException { - public CronException() { - this(null); - } + public CronException() { + this(null); + } - public CronException(Throwable cause) { - super(cause); - } + public CronException(Throwable cause) { + super(cause); + } - public CronException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public CronException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DeleteException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DeleteException.java index 536696bcb..868f63e5c 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DeleteException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DeleteException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class DeleteException extends RuntimeException { - public DeleteException() { - this(null); - } + public DeleteException() { + this(null); + } - public DeleteException(Throwable cause) { - super(cause); - } + public DeleteException(Throwable cause) { + super(cause); + } - public DeleteException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public DeleteException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DuplicateException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DuplicateException.java index 2ce230237..724cb7c77 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DuplicateException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/DuplicateException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class DuplicateException extends RuntimeException { - public DuplicateException() { - this(null); - } + public DuplicateException() { + this(null); + } - public DuplicateException(Throwable cause) { - super(cause); - } + public DuplicateException(Throwable cause) { + super(cause); + } - public DuplicateException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public DuplicateException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/EmptyException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/EmptyException.java index 968e0b412..fd88e46ea 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/EmptyException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/EmptyException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class EmptyException extends RuntimeException { - public EmptyException() { - this(null); - } + public EmptyException() { + this(null); + } - public EmptyException(Throwable cause) { - super(cause); - } + public EmptyException(Throwable cause) { + super(cause); + } - public EmptyException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public EmptyException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ImportException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ImportException.java index b278acfe1..530ab24af 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ImportException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ImportException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class ImportException extends RuntimeException { - public ImportException() { - this(null); - } + public ImportException() { + this(null); + } - public ImportException(Throwable cause) { - super(cause); - } + public ImportException(Throwable cause) { + super(cause); + } - public ImportException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public ImportException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/JsonException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/JsonException.java index b8363a329..3d25a6b2f 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/JsonException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/JsonException.java @@ -28,16 +28,16 @@ import java.text.MessageFormat; */ public class JsonException extends RuntimeException { - public JsonException() { - this(null); - } + public JsonException() { + this(null); + } - public JsonException(Throwable cause) { - super(cause); - } + public JsonException(Throwable cause) { + super(cause); + } - public JsonException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public JsonException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/NotFoundException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/NotFoundException.java index bd84e9eb9..299e01494 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/NotFoundException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/NotFoundException.java @@ -28,16 +28,16 @@ import java.text.MessageFormat; */ public class NotFoundException extends RuntimeException { - public NotFoundException() { - this(null); - } + public NotFoundException() { + this(null); + } - public NotFoundException(Throwable cause) { - super(cause); - } + public NotFoundException(Throwable cause) { + super(cause); + } - public NotFoundException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public NotFoundException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/OutRangeException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/OutRangeException.java index 0e55e3506..3b5e9d4f9 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/OutRangeException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/OutRangeException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class OutRangeException extends RuntimeException { - public OutRangeException() { - this(null); - } + public OutRangeException() { + this(null); + } - public OutRangeException(Throwable cause) { - super(cause); - } + public OutRangeException(Throwable cause) { + super(cause); + } - public OutRangeException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public OutRangeException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ReadPointException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ReadPointException.java index 3c007defc..1cdf21798 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ReadPointException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ReadPointException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class ReadPointException extends RuntimeException { - public ReadPointException() { - this(null); - } + public ReadPointException() { + this(null); + } - public ReadPointException(Throwable cause) { - super(cause); - } + public ReadPointException(Throwable cause) { + super(cause); + } - public ReadPointException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public ReadPointException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RegisterException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RegisterException.java index 5d8ea1b00..e1136871f 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RegisterException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RegisterException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class RegisterException extends RuntimeException { - public RegisterException() { - this(null); - } + public RegisterException() { + this(null); + } - public RegisterException(Throwable cause) { - super(cause); - } + public RegisterException(Throwable cause) { + super(cause); + } - public RegisterException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public RegisterException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RepositoryException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RepositoryException.java index f98d08364..307aff6c6 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RepositoryException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RepositoryException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class RepositoryException extends RuntimeException { - public RepositoryException() { - this(null); - } + public RepositoryException() { + this(null); + } - public RepositoryException(Throwable cause) { - super(cause); - } + public RepositoryException(Throwable cause) { + super(cause); + } - public RepositoryException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public RepositoryException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RequestException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RequestException.java index 1432b4840..c078449ca 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RequestException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/RequestException.java @@ -28,16 +28,16 @@ import java.text.MessageFormat; */ public class RequestException extends RuntimeException { - public RequestException() { - this(null); - } + public RequestException() { + this(null); + } - public RequestException(Throwable cause) { - super(cause); - } + public RequestException(Throwable cause) { + super(cause); + } - public RequestException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public RequestException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/SecurityException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/SecurityException.java index 6ce9fcf1e..1784d4960 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/SecurityException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/SecurityException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class SecurityException extends RuntimeException { - public SecurityException() { - this(null); - } + public SecurityException() { + this(null); + } - public SecurityException(Throwable cause) { - super(cause); - } + public SecurityException(Throwable cause) { + super(cause); + } - public SecurityException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public SecurityException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ServiceException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ServiceException.java index 7cb53f45d..0983a23b7 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ServiceException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/ServiceException.java @@ -31,29 +31,31 @@ import java.text.MessageFormat; */ public class ServiceException extends RuntimeException { - /** - * Constructs a ServiceException with no detail message. - */ - public ServiceException() { - this(null); - } + /** + * Constructs a ServiceException with no detail message. + */ + public ServiceException() { + this(null); + } - /** - * Constructs a ServiceException with the specified cause. - * @param cause the cause of the exception - */ - public ServiceException(Throwable cause) { - super(cause); - } + /** + * Constructs a ServiceException with the specified cause. + * + * @param cause the cause of the exception + */ + public ServiceException(Throwable cause) { + super(cause); + } - /** - * Constructs a ServiceException with the specified template message and parameters. - * The template will be formatted using MessageFormat with the provided parameters. - * @param template the message template - * @param params the parameters to format the template - */ - public ServiceException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + /** + * Constructs a ServiceException with the specified template message and parameters. + * The template will be formatted using MessageFormat with the provided parameters. + * + * @param template the message template + * @param params the parameters to format the template + */ + public ServiceException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/TypeException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/TypeException.java index 295afd193..b26ead5af 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/TypeException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/TypeException.java @@ -28,16 +28,16 @@ import java.text.MessageFormat; */ public class TypeException extends RuntimeException { - public TypeException() { - this(null); - } + public TypeException() { + this(null); + } - public TypeException(Throwable cause) { - super(cause); - } + public TypeException(Throwable cause) { + super(cause); + } - public TypeException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public TypeException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnAuthorizedException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnAuthorizedException.java index 182ab085c..1eb35cad4 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnAuthorizedException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnAuthorizedException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class UnAuthorizedException extends RuntimeException { - public UnAuthorizedException() { - this(null); - } + public UnAuthorizedException() { + this(null); + } - public UnAuthorizedException(Throwable cause) { - super(cause); - } + public UnAuthorizedException(Throwable cause) { + super(cause); + } - public UnAuthorizedException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public UnAuthorizedException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnSupportException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnSupportException.java index 22416f61c..93a428434 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnSupportException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UnSupportException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class UnSupportException extends RuntimeException { - public UnSupportException() { - this(null); - } + public UnSupportException() { + this(null); + } - public UnSupportException(Throwable cause) { - super(cause); - } + public UnSupportException(Throwable cause) { + super(cause); + } - public UnSupportException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public UnSupportException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UpdateException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UpdateException.java index 569861259..0ca3d0273 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UpdateException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/UpdateException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class UpdateException extends RuntimeException { - public UpdateException() { - this(null); - } + public UpdateException() { + this(null); + } - public UpdateException(Throwable cause) { - super(cause); - } + public UpdateException(Throwable cause) { + super(cause); + } - public UpdateException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public UpdateException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/WritePointException.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/WritePointException.java index f92722390..8c271cf32 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/WritePointException.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/exception/WritePointException.java @@ -26,16 +26,16 @@ import java.text.MessageFormat; */ public class WritePointException extends RuntimeException { - public WritePointException() { - this(null); - } + public WritePointException() { + this(null); + } - public WritePointException(Throwable cause) { - super(cause); - } + public WritePointException(Throwable cause) { + super(cause); + } - public WritePointException(String template, Object... params) { - super(MessageFormat.format(template, params)); - } + public WritePointException(String template, Object... params) { + super(MessageFormat.format(template, params)); + } } diff --git a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/utils/ExceptionUtil.java b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/utils/ExceptionUtil.java index c4006292e..47cb066de 100644 --- a/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/utils/ExceptionUtil.java +++ b/dc3-common/dc3-common-exception/src/main/java/io/github/pnoker/common/utils/ExceptionUtil.java @@ -31,20 +31,20 @@ import java.text.MessageFormat; @Slf4j public class ExceptionUtil { - private ExceptionUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ExceptionUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * @param service Name - * @param message - * @return - */ - public static String getNotAvailableServiceMessage(String service, String message) { - if (StringUtils.isEmpty(message)) { - message = MessageFormat.format("{0}: {1}", ExceptionConstant.NO_AVAILABLE_SERVER, service); - } - return message; - } + /** + * @param service Name + * @param message + * @return + */ + public static String getNotAvailableServiceMessage(String service, String message) { + if (StringUtils.isEmpty(message)) { + message = MessageFormat.format("{0}: {1}", ExceptionConstant.NO_AVAILABLE_SERVER, service); + } + return message; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DeviceFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DeviceFacade.java index 76e548fa9..d530222f0 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DeviceFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DeviceFacade.java @@ -41,28 +41,32 @@ import java.util.List; */ public interface DeviceFacade { - /** - * Query a single device by id. - * @return the device, or {@code null} when the device does not exist. - */ - FacadeDeviceBO selectById(Long id); + /** + * Query a single device by id. + * + * @return the device, or {@code null} when the device does not exist. + */ + FacadeDeviceBO selectById(Long id); - /** - * Paginated query. - * @return a page of devices (never {@code null}; empty page when nothing matches). - */ - FacadePage selectByPage(FacadeDeviceQuery query); + /** + * Paginated query. + * + * @return a page of devices (never {@code null}; empty page when nothing matches). + */ + FacadePage selectByPage(FacadeDeviceQuery query); - /** - * List devices attached to a given profile. - * @return an immutable list (never {@code null}; empty when nothing matches). - */ - List selectByProfileId(Long profileId); + /** + * List devices attached to a given profile. + * + * @return an immutable list (never {@code null}; empty when nothing matches). + */ + List selectByProfileId(Long profileId); - /** - * List devices attached to a given driver. - * @return an immutable list (never {@code null}; empty when nothing matches). - */ - List selectByDriverId(Long driverId); + /** + * List devices attached to a given driver. + * + * @return an immutable list (never {@code null}; empty when nothing matches). + */ + List selectByDriverId(Long driverId); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DriverFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DriverFacade.java index 74bc48ae1..add711458 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DriverFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/DriverFacade.java @@ -32,20 +32,21 @@ import io.github.pnoker.common.facade.entity.query.FacadeDriverQuery; */ public interface DriverFacade { - /** - * @return the driver, or {@code null} when it does not exist. - */ - FacadeDriverBO selectById(Long id); + /** + * @return the driver, or {@code null} when it does not exist. + */ + FacadeDriverBO selectById(Long id); - /** - * @return a page of drivers (never {@code null}; empty page when nothing matches). - */ - FacadePage selectByPage(FacadeDriverQuery query); + /** + * @return a page of drivers (never {@code null}; empty page when nothing matches). + */ + FacadePage selectByPage(FacadeDriverQuery query); - /** - * Resolve the driver that owns a given device. - * @return the driver, or {@code null} when the device has no bound driver. - */ - FacadeDriverBO selectByDeviceId(Long deviceId); + /** + * Resolve the driver that owns a given device. + * + * @return the driver, or {@code null} when the device has no bound driver. + */ + FacadeDriverBO selectByDeviceId(Long deviceId); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointFacade.java index d4b2be7fe..ecb0aa2df 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointFacade.java @@ -30,14 +30,14 @@ import io.github.pnoker.common.facade.entity.query.FacadePointQuery; */ public interface PointFacade { - /** - * @return the point, or {@code null} when it does not exist. - */ - FacadePointBO selectById(Long id); + /** + * @return the point, or {@code null} when it does not exist. + */ + FacadePointBO selectById(Long id); - /** - * @return a page of points (never {@code null}; empty page when nothing matches). - */ - FacadePage selectByPage(FacadePointQuery query); + /** + * @return a page of points (never {@code null}; empty page when nothing matches). + */ + FacadePage selectByPage(FacadePointQuery query); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueCommandFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueCommandFacade.java index fb6a2caae..4dc9251c3 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueCommandFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueCommandFacade.java @@ -36,16 +36,18 @@ package io.github.pnoker.common.facade.api; */ public interface PointValueCommandFacade { - /** - * Send a read command to a device for a specific point. - * @return {@code true} if the command was accepted. - */ - boolean read(Long deviceId, Long pointId); + /** + * Send a read command to a device for a specific point. + * + * @return {@code true} if the command was accepted. + */ + boolean read(Long deviceId, Long pointId); - /** - * Send a write command to a device for a specific point. - * @return {@code true} if the command was accepted. - */ - boolean write(Long deviceId, Long pointId, String value); + /** + * Send a write command to a device for a specific point. + * + * @return {@code true} if the command was accepted. + */ + boolean write(Long deviceId, Long pointId, String value); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueFacade.java index de9bfbb33..562e550a0 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/PointValueFacade.java @@ -39,17 +39,19 @@ import java.util.List; */ public interface PointValueFacade { - /** - * Query the latest collected value of a device point. - * @return the point value, or {@code null} when no value exists. - */ - FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId); + /** + * Query the latest collected value of a device point. + * + * @return the point value, or {@code null} when no value exists. + */ + FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId); - /** - * Query historical values of a device point. - * @return an immutable list of value strings (never {@code null}; empty when nothing - * matches). - */ - List history(Long tenantId, Long deviceId, Long pointId, int count); + /** + * Query historical values of a device point. + * + * @return an immutable list of value strings (never {@code null}; empty when nothing + * matches). + */ + List history(Long tenantId, Long deviceId, Long pointId, int count); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/ResourceRegistryFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/ResourceRegistryFacade.java index 3b02c9d64..956ee8c92 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/ResourceRegistryFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/ResourceRegistryFacade.java @@ -29,10 +29,10 @@ import io.github.pnoker.common.facade.entity.bo.FacadeResourceRegistrySyncResult */ public interface ResourceRegistryFacade { - /** - * Submit the caller's full API inventory. The auth-side server reconciles it against - * the dc3_api and dc3_resource tables and returns counters. - */ - FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command); + /** + * Submit the caller's full API inventory. The auth-side server reconciles it against + * the dc3_api and dc3_resource tables and returns counters. + */ + FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TenantFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TenantFacade.java index f2876a33d..ad79d1db8 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TenantFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TenantFacade.java @@ -27,9 +27,9 @@ import io.github.pnoker.common.facade.entity.bo.FacadeTenantBO; */ public interface TenantFacade { - /** - * @return the tenant, or {@code null} when no tenant carries the given code. - */ - FacadeTenantBO selectByCode(String code); + /** + * @return the tenant, or {@code null} when no tenant carries the given code. + */ + FacadeTenantBO selectByCode(String code); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TokenFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TokenFacade.java index 8b92479b1..80786dbd9 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TokenFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/TokenFacade.java @@ -29,14 +29,15 @@ package io.github.pnoker.common.facade.api; */ public interface TokenFacade { - /** - * Validate a token triple against the backing auth service. - * @param tenant tenant code - * @param name login name - * @param salt salt the client holds - * @param token token the client holds - * @return {@code true} when the triple is valid and unexpired - */ - boolean checkValid(String tenant, String name, String salt, String token); + /** + * Validate a token triple against the backing auth service. + * + * @param tenant tenant code + * @param name login name + * @param salt salt the client holds + * @param token token the client holds + * @return {@code true} when the triple is valid and unexpired + */ + boolean checkValid(String tenant, String name, String salt, String token); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserFacade.java index 5415f17a5..420576bc9 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserFacade.java @@ -27,9 +27,9 @@ import io.github.pnoker.common.facade.entity.bo.FacadeUserBO; */ public interface UserFacade { - /** - * @return the user, or {@code null} when the id does not match any user. - */ - FacadeUserBO selectById(Long id); + /** + * @return the user, or {@code null} when the id does not match any user. + */ + FacadeUserBO selectById(Long id); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserLoginFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserLoginFacade.java index b7f446ef2..820953747 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserLoginFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/api/UserLoginFacade.java @@ -27,9 +27,9 @@ import io.github.pnoker.common.facade.entity.bo.FacadeUserLoginBO; */ public interface UserLoginFacade { - /** - * @return the user-login record, or {@code null} when the login name does not exist. - */ - FacadeUserLoginBO selectByName(String name); + /** + * @return the user-login record, or {@code null} when the login name does not exist. + */ + FacadeUserLoginBO selectByName(String name); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDeviceBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDeviceBO.java index 29545073d..ee61d690e 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDeviceBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDeviceBO.java @@ -41,22 +41,22 @@ import java.util.List; @ToString(callSuper = true) public class FacadeDeviceBO extends BaseBO { - private String deviceName; + private String deviceName; - private String deviceCode; + private String deviceCode; - private Long driverId; + private Long driverId; - private DeviceExt deviceExt; + private DeviceExt deviceExt; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Long tenantId; + private Long tenantId; - private String signature; + private String signature; - private Integer version; + private Integer version; - private List profileIds; + private List profileIds; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDriverBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDriverBO.java index f28092c72..cb2aae786 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDriverBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeDriverBO.java @@ -36,24 +36,24 @@ import lombok.*; @ToString(callSuper = true) public class FacadeDriverBO extends BaseBO { - private String driverName; + private String driverName; - private String driverCode; + private String driverCode; - private String serviceName; + private String serviceName; - private String serviceHost; + private String serviceHost; - private DriverTypeFlagEnum driverTypeFlag; + private DriverTypeFlagEnum driverTypeFlag; - private DriverExt driverExt; + private DriverExt driverExt; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Long tenantId; + private Long tenantId; - private String signature; + private String signature; - private Integer version; + private Integer version; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointBO.java index 01bf0f959..1ca9b7724 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointBO.java @@ -39,32 +39,32 @@ import java.math.BigDecimal; @ToString(callSuper = true) public class FacadePointBO extends BaseBO { - private String pointName; + private String pointName; - private String pointCode; + private String pointCode; - private PointTypeFlagEnum pointTypeFlag; + private PointTypeFlagEnum pointTypeFlag; - private RwFlagEnum rwFlag; + private RwFlagEnum rwFlag; - private BigDecimal baseValue; + private BigDecimal baseValue; - private BigDecimal multiple; + private BigDecimal multiple; - private Byte valueDecimal; + private Byte valueDecimal; - private String unit; + private String unit; - private Long profileId; + private Long profileId; - private PointExt pointExt; + private PointExt pointExt; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Long tenantId; + private Long tenantId; - private String signature; + private String signature; - private Integer version; + private Integer version; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointValueBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointValueBO.java index 023ba0bc5..bb9003be5 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointValueBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadePointValueBO.java @@ -37,29 +37,29 @@ import lombok.*; @AllArgsConstructor public class FacadePointValueBO { - /** - * Device ID associated with the point value - */ - private Long deviceId; + /** + * Device ID associated with the point value + */ + private Long deviceId; - /** - * Point ID associated with the value - */ - private Long pointId; + /** + * Point ID associated with the value + */ + private Long pointId; - /** - * Processed/calculated value after transformations - */ - private String value; + /** + * Processed/calculated value after transformations + */ + private String value; - /** - * Raw value as received from the device - */ - private String rawValue; + /** + * Raw value as received from the device + */ + private String rawValue; - /** - * Storage timestamp (epoch seconds) - */ - private long createTime; + /** + * Storage timestamp (epoch seconds) + */ + private long createTime; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncCommandBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncCommandBO.java index dd42bdedf..31db0f610 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncCommandBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncCommandBO.java @@ -35,10 +35,10 @@ import java.util.List; @AllArgsConstructor public class FacadeResourceRegistrySyncCommandBO { - private String serviceName; + private String serviceName; - private boolean deleteMissing; + private boolean deleteMissing; - private List apis; + private List apis; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncResultBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncResultBO.java index 17f23d5fc..6ff652579 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncResultBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeResourceRegistrySyncResultBO.java @@ -33,12 +33,12 @@ import lombok.*; @AllArgsConstructor public class FacadeResourceRegistrySyncResultBO { - private int inserted; + private int inserted; - private int updated; + private int updated; - private int deleted; + private int deleted; - private int unchanged; + private int unchanged; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeScannedApiBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeScannedApiBO.java index 256c0b0e1..20322f6de 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeScannedApiBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeScannedApiBO.java @@ -33,19 +33,19 @@ import lombok.*; @AllArgsConstructor public class FacadeScannedApiBO { - private String method; + private String method; - private String path; + private String path; - private String apiName; + private String apiName; - private String title; + private String title; - private String remark; + private String remark; - /** - * API grouping label — usually the owning controller's simple class name. - */ - private String apiGroup; + /** + * API grouping label — usually the owning controller's simple class name. + */ + private String apiGroup; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeTenantBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeTenantBO.java index f0a93911c..e29014079 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeTenantBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeTenantBO.java @@ -35,10 +35,10 @@ import lombok.*; @ToString(callSuper = true) public class FacadeTenantBO extends BaseBO { - private String tenantName; + private String tenantName; - private String tenantCode; + private String tenantCode; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserBO.java index 3a6b8ee14..18c55dd53 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserBO.java @@ -35,16 +35,16 @@ import lombok.*; @ToString(callSuper = true) public class FacadeUserBO extends BaseBO { - private String nickName; + private String nickName; - private String userName; + private String userName; - private String phone; + private String phone; - private String email; + private String email; - private String socialExt; + private String socialExt; - private String identityExt; + private String identityExt; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserLoginBO.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserLoginBO.java index dad6bdf6f..23664268c 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserLoginBO.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/bo/FacadeUserLoginBO.java @@ -35,12 +35,12 @@ import lombok.*; @ToString(callSuper = true) public class FacadeUserLoginBO extends BaseBO { - private String loginName; + private String loginName; - private Long userId; + private Long userId; - private Long userPasswordId; + private Long userPasswordId; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/common/FacadePage.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/common/FacadePage.java index 00e205904..007c826bc 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/common/FacadePage.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/common/FacadePage.java @@ -40,21 +40,21 @@ import java.util.List; @ToString public class FacadePage implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long current; + private long current; - private long size; + private long size; - private long total; + private long total; - private long pages; + private long pages; - private List records; + private List records; - public static FacadePage empty() { - return new FacadePage<>(1L, 0L, 0L, 0L, Collections.emptyList()); - } + public static FacadePage empty() { + return new FacadePage<>(1L, 0L, 0L, 0L, Collections.emptyList()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDeviceQuery.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDeviceQuery.java index ae0f6e63c..ce65c1c50 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDeviceQuery.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDeviceQuery.java @@ -40,23 +40,23 @@ import java.io.Serializable; @AllArgsConstructor public class FacadeDeviceQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - private Long tenantId; + private Long tenantId; - private String deviceName; + private String deviceName; - private String deviceCode; + private String deviceCode; - private Long driverId; + private Long driverId; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Integer version; + private Integer version; - private Long profileId; + private Long profileId; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDriverQuery.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDriverQuery.java index 329c4ecdb..206597c5a 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDriverQuery.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadeDriverQuery.java @@ -39,25 +39,25 @@ import java.io.Serializable; @AllArgsConstructor public class FacadeDriverQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - private Long tenantId; + private Long tenantId; - private String driverName; + private String driverName; - private String driverCode; + private String driverCode; - private String serviceName; + private String serviceName; - private String serviceHost; + private String serviceHost; - private DriverTypeFlagEnum driverTypeFlag; + private DriverTypeFlagEnum driverTypeFlag; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Integer version; + private Integer version; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointQuery.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointQuery.java index 963bd77c1..f5f5f4d32 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointQuery.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointQuery.java @@ -40,30 +40,30 @@ import java.io.Serializable; @AllArgsConstructor public class FacadePointQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - private Long tenantId; + private Long tenantId; - private String pointName; + private String pointName; - private String pointCode; + private String pointCode; - private PointTypeFlagEnum pointTypeFlag; + private PointTypeFlagEnum pointTypeFlag; - private RwFlagEnum rwFlag; + private RwFlagEnum rwFlag; - private Long profileId; + private Long profileId; - private EnableFlagEnum enableFlag; + private EnableFlagEnum enableFlag; - private Integer version; + private Integer version; - /** - * Device ID — filter points bound to a specific device. - */ - private Long deviceId; + /** + * Device ID — filter points bound to a specific device. + */ + private Long deviceId; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointValueQuery.java b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointValueQuery.java index 29f47ef32..cefbf6ca4 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointValueQuery.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-api/src/main/java/io/github/pnoker/common/facade/entity/query/FacadePointValueQuery.java @@ -37,15 +37,15 @@ import java.io.Serializable; @AllArgsConstructor public class FacadePointValueQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - private Long tenantId; + private Long tenantId; - private Long deviceId; + private Long deviceId; - private Long pointId; + private Long pointId; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DeviceGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DeviceGrpcFacade.java index 53b457762..ab1d24713 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DeviceGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DeviceGrpcFacade.java @@ -47,73 +47,73 @@ import java.util.List; @Component public class DeviceGrpcFacade implements DeviceFacade { - @Resource - private DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub; + @Resource + private DeviceApiGrpc.DeviceApiBlockingStub deviceApiBlockingStub; - @Resource - private FacadeGrpcDeviceBuilder facadeGrpcDeviceBuilder; + @Resource + private FacadeGrpcDeviceBuilder facadeGrpcDeviceBuilder; - @Override - public FacadeDeviceBO selectById(Long id) { - GrpcDeviceQuery request = GrpcDeviceQuery.newBuilder().setDeviceId(id).build(); - GrpcRDeviceDTO response = deviceApiBlockingStub.selectByDeviceId(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectById"); - return null; - } - return facadeGrpcDeviceBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeDeviceBO selectById(Long id) { + GrpcDeviceQuery request = GrpcDeviceQuery.newBuilder().setDeviceId(id).build(); + GrpcRDeviceDTO response = deviceApiBlockingStub.selectByDeviceId(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectById"); + return null; + } + return facadeGrpcDeviceBuilder.toFacadeBO(response.getData()); + } - @Override - public FacadePage selectByPage(FacadeDeviceQuery query) { - GrpcPageDeviceQuery request = facadeGrpcDeviceBuilder.toGrpcPageQuery(query); - GrpcRPageDeviceDTO response = deviceApiBlockingStub.selectByPage(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByPage"); - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadeDeviceQuery query) { + GrpcPageDeviceQuery request = facadeGrpcDeviceBuilder.toGrpcPageQuery(query); + GrpcRPageDeviceDTO response = deviceApiBlockingStub.selectByPage(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByPage"); + return FacadePage.empty(); + } - GrpcPageDeviceDTO pageDTO = response.getData(); - List records = pageDTO.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); + GrpcPageDeviceDTO pageDTO = response.getData(); + List records = pageDTO.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); - return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), - pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); - } + return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), + pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); + } - @Override - public List selectByProfileId(Long profileId) { - GrpcProfileQuery request = GrpcProfileQuery.newBuilder().setProfileId(profileId).build(); - GrpcRDeviceListDTO response = deviceApiBlockingStub.selectByProfileId(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByProfileId"); - return Collections.emptyList(); - } - return response.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); - } + @Override + public List selectByProfileId(Long profileId) { + GrpcProfileQuery request = GrpcProfileQuery.newBuilder().setProfileId(profileId).build(); + GrpcRDeviceListDTO response = deviceApiBlockingStub.selectByProfileId(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByProfileId"); + return Collections.emptyList(); + } + return response.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); + } - @Override - public List selectByDriverId(Long driverId) { - GrpcDriverQuery request = GrpcDriverQuery.newBuilder().setDriverId(driverId).build(); - GrpcRDeviceListDTO response = deviceApiBlockingStub.selectByDriverId(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByDriverId"); - return Collections.emptyList(); - } - return response.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); - } + @Override + public List selectByDriverId(Long driverId) { + GrpcDriverQuery request = GrpcDriverQuery.newBuilder().setDriverId(driverId).build(); + GrpcRDeviceListDTO response = deviceApiBlockingStub.selectByDriverId(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByDriverId"); + return Collections.emptyList(); + } + return response.getDataList().stream().map(facadeGrpcDeviceBuilder::toFacadeBO).toList(); + } - /** - * NO_RESOURCE is a normal "not found" signal — swallow and let the caller see null / - * empty. Any other non-OK code (server error, param error, etc.) escalates to an - * exception. - */ - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("DeviceGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("DeviceFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + /** + * NO_RESOURCE is a normal "not found" signal — swallow and let the caller see null / + * empty. Any other non-OK code (server error, param error, etc.) escalates to an + * exception. + */ + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("DeviceGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("DeviceFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DriverGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DriverGrpcFacade.java index 825b018fd..21210988a 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DriverGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/DriverGrpcFacade.java @@ -43,57 +43,57 @@ import java.util.List; @Component public class DriverGrpcFacade implements DriverFacade { - @Resource - private DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub; + @Resource + private DriverApiGrpc.DriverApiBlockingStub driverApiBlockingStub; - @Resource - private FacadeGrpcDriverBuilder facadeGrpcDriverBuilder; + @Resource + private FacadeGrpcDriverBuilder facadeGrpcDriverBuilder; - @Override - public FacadeDriverBO selectById(Long id) { - GrpcDriverQuery request = GrpcDriverQuery.newBuilder().setDriverId(id).build(); - GrpcRDriverDTO response = driverApiBlockingStub.selectByDriverId(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectById"); - return null; - } - return facadeGrpcDriverBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeDriverBO selectById(Long id) { + GrpcDriverQuery request = GrpcDriverQuery.newBuilder().setDriverId(id).build(); + GrpcRDriverDTO response = driverApiBlockingStub.selectByDriverId(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectById"); + return null; + } + return facadeGrpcDriverBuilder.toFacadeBO(response.getData()); + } - @Override - public FacadePage selectByPage(FacadeDriverQuery query) { - GrpcPageDriverQuery request = facadeGrpcDriverBuilder.toGrpcPageQuery(query); - GrpcRPageDriverDTO response = driverApiBlockingStub.selectByPage(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByPage"); - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadeDriverQuery query) { + GrpcPageDriverQuery request = facadeGrpcDriverBuilder.toGrpcPageQuery(query); + GrpcRPageDriverDTO response = driverApiBlockingStub.selectByPage(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByPage"); + return FacadePage.empty(); + } - GrpcPageDriverDTO pageDTO = response.getData(); - List records = pageDTO.getDataList().stream().map(facadeGrpcDriverBuilder::toFacadeBO).toList(); + GrpcPageDriverDTO pageDTO = response.getData(); + List records = pageDTO.getDataList().stream().map(facadeGrpcDriverBuilder::toFacadeBO).toList(); - return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), - pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); - } + return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), + pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); + } - @Override - public FacadeDriverBO selectByDeviceId(Long deviceId) { - GrpcDeviceQuery request = GrpcDeviceQuery.newBuilder().setDeviceId(deviceId).build(); - GrpcRDriverDTO response = driverApiBlockingStub.selectByDeviceId(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByDeviceId"); - return null; - } - return facadeGrpcDriverBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeDriverBO selectByDeviceId(Long deviceId) { + GrpcDeviceQuery request = GrpcDeviceQuery.newBuilder().setDeviceId(deviceId).build(); + GrpcRDriverDTO response = driverApiBlockingStub.selectByDeviceId(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByDeviceId"); + return null; + } + return facadeGrpcDriverBuilder.toFacadeBO(response.getData()); + } - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("DriverGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("DriverFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("DriverGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("DriverFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointGrpcFacade.java index 484af7f95..7d46d02da 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointGrpcFacade.java @@ -43,46 +43,46 @@ import java.util.List; @Component public class PointGrpcFacade implements PointFacade { - @Resource - private PointApiGrpc.PointApiBlockingStub pointApiBlockingStub; + @Resource + private PointApiGrpc.PointApiBlockingStub pointApiBlockingStub; - @Resource - private FacadeGrpcPointBuilder facadeGrpcPointBuilder; + @Resource + private FacadeGrpcPointBuilder facadeGrpcPointBuilder; - @Override - public FacadePointBO selectById(Long id) { - GrpcPointQuery request = GrpcPointQuery.newBuilder().setPointId(id).build(); - GrpcRPointDTO response = pointApiBlockingStub.selectById(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectById"); - return null; - } - return facadeGrpcPointBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadePointBO selectById(Long id) { + GrpcPointQuery request = GrpcPointQuery.newBuilder().setPointId(id).build(); + GrpcRPointDTO response = pointApiBlockingStub.selectById(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectById"); + return null; + } + return facadeGrpcPointBuilder.toFacadeBO(response.getData()); + } - @Override - public FacadePage selectByPage(FacadePointQuery query) { - GrpcPagePointQuery request = facadeGrpcPointBuilder.toGrpcPageQuery(query); - GrpcRPagePointDTO response = pointApiBlockingStub.selectByPage(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByPage"); - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadePointQuery query) { + GrpcPagePointQuery request = facadeGrpcPointBuilder.toGrpcPageQuery(query); + GrpcRPagePointDTO response = pointApiBlockingStub.selectByPage(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByPage"); + return FacadePage.empty(); + } - GrpcPagePointDTO pageDTO = response.getData(); - List records = pageDTO.getDataList().stream().map(facadeGrpcPointBuilder::toFacadeBO).toList(); + GrpcPagePointDTO pageDTO = response.getData(); + List records = pageDTO.getDataList().stream().map(facadeGrpcPointBuilder::toFacadeBO).toList(); - return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), - pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); - } + return new FacadePage<>(pageDTO.getPage().getCurrent(), pageDTO.getPage().getSize(), + pageDTO.getPage().getTotal(), pageDTO.getPage().getPages(), records); + } - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("PointGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("PointFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("PointGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("PointFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueCommandGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueCommandGrpcFacade.java index a695b4226..83dc4887d 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueCommandGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueCommandGrpcFacade.java @@ -40,28 +40,28 @@ import org.springframework.stereotype.Component; @Component public class PointValueCommandGrpcFacade implements PointValueCommandFacade { - @Resource - private PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub; + @Resource + private PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub; - @Override - public boolean read(Long deviceId, Long pointId) { - GrpcPointValueCommandQuery request = GrpcPointValueCommandQuery.newBuilder() - .setDeviceId(deviceId) - .setPointId(pointId) - .build(); - GrpcRBoolean response = pointValueApiBlockingStub.readCommand(request); - return response.getResult().getOk() && response.getData(); - } + @Override + public boolean read(Long deviceId, Long pointId) { + GrpcPointValueCommandQuery request = GrpcPointValueCommandQuery.newBuilder() + .setDeviceId(deviceId) + .setPointId(pointId) + .build(); + GrpcRBoolean response = pointValueApiBlockingStub.readCommand(request); + return response.getResult().getOk() && response.getData(); + } - @Override - public boolean write(Long deviceId, Long pointId, String value) { - GrpcPointValueWriteCommand request = GrpcPointValueWriteCommand.newBuilder() - .setDeviceId(deviceId) - .setPointId(pointId) - .setValue(value) - .build(); - GrpcRBoolean response = pointValueApiBlockingStub.writeCommand(request); - return response.getResult().getOk() && response.getData(); - } + @Override + public boolean write(Long deviceId, Long pointId, String value) { + GrpcPointValueWriteCommand request = GrpcPointValueWriteCommand.newBuilder() + .setDeviceId(deviceId) + .setPointId(pointId) + .setValue(value) + .build(); + GrpcRBoolean response = pointValueApiBlockingStub.writeCommand(request); + return response.getResult().getOk() && response.getData(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueGrpcFacade.java index 937219041..e36374340 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/PointValueGrpcFacade.java @@ -45,55 +45,55 @@ import java.util.List; @Component public class PointValueGrpcFacade implements PointValueFacade { - @Resource - private PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub; + @Resource + private PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub; - @Resource - private FacadeGrpcPointValueBuilder facadeGrpcPointValueBuilder; + @Resource + private FacadeGrpcPointValueBuilder facadeGrpcPointValueBuilder; - @Override - public FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId) { - GrpcPointValueQuery request = GrpcPointValueQuery.newBuilder() - .setDeviceId(deviceId) - .setPointId(pointId) - .setTenantId(tenantId) - .build(); - GrpcRPointValueDTO response = pointValueApiBlockingStub.lastValue(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "lastValue"); - return null; - } - return facadeGrpcPointValueBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId) { + GrpcPointValueQuery request = GrpcPointValueQuery.newBuilder() + .setDeviceId(deviceId) + .setPointId(pointId) + .setTenantId(tenantId) + .build(); + GrpcRPointValueDTO response = pointValueApiBlockingStub.lastValue(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "lastValue"); + return null; + } + return facadeGrpcPointValueBuilder.toFacadeBO(response.getData()); + } - @Override - public List history(Long tenantId, Long deviceId, Long pointId, int count) { - GrpcPointValueHistoryQuery request = GrpcPointValueHistoryQuery.newBuilder() - .setDeviceId(deviceId) - .setPointId(pointId) - .setTenantId(tenantId) - .setCount(count) - .build(); - GrpcRPointValueStringList response = pointValueApiBlockingStub.historyValue(request); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "history"); - return Collections.emptyList(); - } - return response.getDataList(); - } + @Override + public List history(Long tenantId, Long deviceId, Long pointId, int count) { + GrpcPointValueHistoryQuery request = GrpcPointValueHistoryQuery.newBuilder() + .setDeviceId(deviceId) + .setPointId(pointId) + .setTenantId(tenantId) + .setCount(count) + .build(); + GrpcRPointValueStringList response = pointValueApiBlockingStub.historyValue(request); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "history"); + return Collections.emptyList(); + } + return response.getDataList(); + } - /** - * NO_RESOURCE is a normal "not found" signal — swallow and let the caller see null / - * empty. Any other non-OK code (server error, param error, etc.) escalates to an - * exception. - */ - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("PointValueGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("PointValueFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + /** + * NO_RESOURCE is a normal "not found" signal — swallow and let the caller see null / + * empty. Any other non-OK code (server error, param error, etc.) escalates to an + * exception. + */ + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("PointValueGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("PointValueFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/ResourceRegistryGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/ResourceRegistryGrpcFacade.java index 304558a54..104ffc524 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/ResourceRegistryGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/ResourceRegistryGrpcFacade.java @@ -43,38 +43,38 @@ import java.util.Objects; @Component public class ResourceRegistryGrpcFacade implements ResourceRegistryFacade { - @Resource - private ResourceRegistryApiGrpc.ResourceRegistryApiBlockingStub resourceRegistryApiBlockingStub; + @Resource + private ResourceRegistryApiGrpc.ResourceRegistryApiBlockingStub resourceRegistryApiBlockingStub; - @Override - public FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command) { - GrpcSyncRequest.Builder request = GrpcSyncRequest.newBuilder() - .setServiceName(Objects.requireNonNullElse(command.getServiceName(), "")) - .setDeleteMissing(command.isDeleteMissing()); - List apis = command.getApis(); - if (apis != null) { - for (FacadeScannedApiBO api : apis) { - request.addApis(GrpcScannedApiDTO.newBuilder() - .setMethod(Objects.requireNonNullElse(api.getMethod(), "")) - .setPath(Objects.requireNonNullElse(api.getPath(), "")) - .setApiName(Objects.requireNonNullElse(api.getApiName(), "")) - .setTitle(Objects.requireNonNullElse(api.getTitle(), "")) - .setRemark(Objects.requireNonNullElse(api.getRemark(), "")) - .setApiGroup(Objects.requireNonNullElse(api.getApiGroup(), "")) - .build()); - } - } - GrpcRSyncResult response = resourceRegistryApiBlockingStub.sync(request.build()); - if (!response.getResult().getOk()) { - throw new ServiceException("ResourceRegistryFacade.sync failed: [" + response.getResult().getCode() + "] " - + response.getResult().getMessage()); - } - return FacadeResourceRegistrySyncResultBO.builder() - .inserted(response.getData().getInserted()) - .updated(response.getData().getUpdated()) - .deleted(response.getData().getDeleted()) - .unchanged(response.getData().getUnchanged()) - .build(); - } + @Override + public FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command) { + GrpcSyncRequest.Builder request = GrpcSyncRequest.newBuilder() + .setServiceName(Objects.requireNonNullElse(command.getServiceName(), "")) + .setDeleteMissing(command.isDeleteMissing()); + List apis = command.getApis(); + if (apis != null) { + for (FacadeScannedApiBO api : apis) { + request.addApis(GrpcScannedApiDTO.newBuilder() + .setMethod(Objects.requireNonNullElse(api.getMethod(), "")) + .setPath(Objects.requireNonNullElse(api.getPath(), "")) + .setApiName(Objects.requireNonNullElse(api.getApiName(), "")) + .setTitle(Objects.requireNonNullElse(api.getTitle(), "")) + .setRemark(Objects.requireNonNullElse(api.getRemark(), "")) + .setApiGroup(Objects.requireNonNullElse(api.getApiGroup(), "")) + .build()); + } + } + GrpcRSyncResult response = resourceRegistryApiBlockingStub.sync(request.build()); + if (!response.getResult().getOk()) { + throw new ServiceException("ResourceRegistryFacade.sync failed: [" + response.getResult().getCode() + "] " + + response.getResult().getMessage()); + } + return FacadeResourceRegistrySyncResultBO.builder() + .inserted(response.getData().getInserted()) + .updated(response.getData().getUpdated()) + .deleted(response.getData().getDeleted()) + .unchanged(response.getData().getUnchanged()) + .build(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TenantGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TenantGrpcFacade.java index 84eb7b436..04ec00044 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TenantGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TenantGrpcFacade.java @@ -40,29 +40,29 @@ import org.springframework.stereotype.Component; @Component public class TenantGrpcFacade implements TenantFacade { - @Resource - private TenantApiGrpc.TenantApiBlockingStub tenantApiBlockingStub; + @Resource + private TenantApiGrpc.TenantApiBlockingStub tenantApiBlockingStub; - @Resource - private FacadeGrpcTenantBuilder facadeGrpcTenantBuilder; + @Resource + private FacadeGrpcTenantBuilder facadeGrpcTenantBuilder; - @Override - public FacadeTenantBO selectByCode(String code) { - GrpcRTenantDTO response = tenantApiBlockingStub.selectByCode(GrpcCodeQuery.newBuilder().setCode(code).build()); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByCode"); - return null; - } - return facadeGrpcTenantBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeTenantBO selectByCode(String code) { + GrpcRTenantDTO response = tenantApiBlockingStub.selectByCode(GrpcCodeQuery.newBuilder().setCode(code).build()); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByCode"); + return null; + } + return facadeGrpcTenantBuilder.toFacadeBO(response.getData()); + } - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("TenantGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("TenantFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("TenantGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("TenantFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TokenGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TokenGrpcFacade.java index cca470520..4d4663095 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TokenGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/TokenGrpcFacade.java @@ -35,19 +35,19 @@ import org.springframework.stereotype.Component; @Component public class TokenGrpcFacade implements TokenFacade { - @Resource - private TokenApiGrpc.TokenApiBlockingStub tokenApiBlockingStub; + @Resource + private TokenApiGrpc.TokenApiBlockingStub tokenApiBlockingStub; - @Override - public boolean checkValid(String tenant, String name, String salt, String token) { - GrpcLoginQuery login = GrpcLoginQuery.newBuilder() - .setTenant(tenant) - .setName(name) - .setSalt(salt) - .setToken(token) - .build(); - GrpcRTokenDTO response = tokenApiBlockingStub.checkValid(login); - return response.getResult().getOk(); - } + @Override + public boolean checkValid(String tenant, String name, String salt, String token) { + GrpcLoginQuery login = GrpcLoginQuery.newBuilder() + .setTenant(tenant) + .setName(name) + .setSalt(salt) + .setToken(token) + .build(); + GrpcRTokenDTO response = tokenApiBlockingStub.checkValid(login); + return response.getResult().getOk(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserGrpcFacade.java index 8887950d2..c51420bc9 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserGrpcFacade.java @@ -40,29 +40,29 @@ import org.springframework.stereotype.Component; @Component public class UserGrpcFacade implements UserFacade { - @Resource - private UserApiGrpc.UserApiBlockingStub userApiBlockingStub; + @Resource + private UserApiGrpc.UserApiBlockingStub userApiBlockingStub; - @Resource - private FacadeGrpcUserBuilder facadeGrpcUserBuilder; + @Resource + private FacadeGrpcUserBuilder facadeGrpcUserBuilder; - @Override - public FacadeUserBO selectById(Long id) { - GrpcRUserDTO response = userApiBlockingStub.selectById(GrpcIdQuery.newBuilder().setId(id).build()); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectById"); - return null; - } - return facadeGrpcUserBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeUserBO selectById(Long id) { + GrpcRUserDTO response = userApiBlockingStub.selectById(GrpcIdQuery.newBuilder().setId(id).build()); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectById"); + return null; + } + return facadeGrpcUserBuilder.toFacadeBO(response.getData()); + } - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("UserGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("UserFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("UserGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("UserFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserLoginGrpcFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserLoginGrpcFacade.java index 793787c79..ebdfb1748 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserLoginGrpcFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/UserLoginGrpcFacade.java @@ -40,30 +40,30 @@ import org.springframework.stereotype.Component; @Component public class UserLoginGrpcFacade implements UserLoginFacade { - @Resource - private UserLoginApiGrpc.UserLoginApiBlockingStub userLoginApiBlockingStub; + @Resource + private UserLoginApiGrpc.UserLoginApiBlockingStub userLoginApiBlockingStub; - @Resource - private FacadeGrpcUserLoginBuilder facadeGrpcUserLoginBuilder; + @Resource + private FacadeGrpcUserLoginBuilder facadeGrpcUserLoginBuilder; - @Override - public FacadeUserLoginBO selectByName(String name) { - GrpcRUserLoginDTO response = userLoginApiBlockingStub - .selectByName(GrpcNameQuery.newBuilder().setName(name).build()); - if (!response.getResult().getOk()) { - guardOrThrow(response.getResult(), "selectByName"); - return null; - } - return facadeGrpcUserLoginBuilder.toFacadeBO(response.getData()); - } + @Override + public FacadeUserLoginBO selectByName(String name) { + GrpcRUserLoginDTO response = userLoginApiBlockingStub + .selectByName(GrpcNameQuery.newBuilder().setName(name).build()); + if (!response.getResult().getOk()) { + guardOrThrow(response.getResult(), "selectByName"); + return null; + } + return facadeGrpcUserLoginBuilder.toFacadeBO(response.getData()); + } - private void guardOrThrow(GrpcR result, String op) { - String code = result.getCode(); - if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { - log.debug("UserLoginGrpcFacade.{} => no resource", op); - return; - } - throw new ServiceException("UserLoginFacade." + op + " failed: [" + code + "] " + result.getMessage()); - } + private void guardOrThrow(GrpcR result, String op) { + String code = result.getCode(); + if (ResponseEnum.NO_RESOURCE.getCode().equals(code)) { + log.debug("UserLoginGrpcFacade.{} => no resource", op); + return; + } + throw new ServiceException("UserLoginFacade." + op + " failed: [" + code + "] " + result.getMessage()); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDeviceBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDeviceBuilder.java index f3d9b1559..141e8392e 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDeviceBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDeviceBuilder.java @@ -50,54 +50,54 @@ import java.util.Optional; @Component public class FacadeGrpcDeviceBuilder { - public GrpcPageDeviceQuery toGrpcPageQuery(FacadeDeviceQuery query) { - GrpcPageDeviceQuery.Builder builder = GrpcPageDeviceQuery.newBuilder(); + public GrpcPageDeviceQuery toGrpcPageQuery(FacadeDeviceQuery query) { + GrpcPageDeviceQuery.Builder builder = GrpcPageDeviceQuery.newBuilder(); - Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); - GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); - builder.setPage(page); + Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); + GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); + builder.setPage(page); - LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); - StringOptional.ofNullable(query.getDeviceName()).ifPresent(builder::setDeviceName); - StringOptional.ofNullable(query.getDeviceCode()).ifPresent(builder::setDeviceCode); - LongOptional.ofNullable(query.getDriverId()).ifPresent(builder::setDriverId); - LongOptional.ofNullable(query.getProfileId()).ifPresent(builder::setProfileId); - Optional.ofNullable(query.getEnableFlag()) - .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), - () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); + LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); + StringOptional.ofNullable(query.getDeviceName()).ifPresent(builder::setDeviceName); + StringOptional.ofNullable(query.getDeviceCode()).ifPresent(builder::setDeviceCode); + LongOptional.ofNullable(query.getDriverId()).ifPresent(builder::setDriverId); + LongOptional.ofNullable(query.getProfileId()).ifPresent(builder::setProfileId); + Optional.ofNullable(query.getEnableFlag()) + .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), + () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); - return builder.build(); - } + return builder.build(); + } - public FacadeDeviceBO toFacadeBO(GrpcDeviceDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadeDeviceBO toFacadeBO(GrpcDeviceDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadeDeviceBO bo = new FacadeDeviceBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadeDeviceBO bo = new FacadeDeviceBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getDeviceName()).ifPresent(bo::setDeviceName); - StringOptional.ofNullable(dto.getDeviceCode()).ifPresent(bo::setDeviceCode); - LongOptional.ofNullable(dto.getDriverId()).ifPresent(bo::setDriverId); - StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); - LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); + StringOptional.ofNullable(dto.getDeviceName()).ifPresent(bo::setDeviceName); + StringOptional.ofNullable(dto.getDeviceCode()).ifPresent(bo::setDeviceCode); + LongOptional.ofNullable(dto.getDriverId()).ifPresent(bo::setDriverId); + StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); + LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); - if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { - bo.setVersion(dto.getVersion()); - } + if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { + bo.setVersion(dto.getVersion()); + } - byte enableIndex = (byte) dto.getEnableFlag(); - Optional.ofNullable(EnableFlagEnum.ofIndex(enableIndex)).ifPresent(bo::setEnableFlag); + byte enableIndex = (byte) dto.getEnableFlag(); + Optional.ofNullable(EnableFlagEnum.ofIndex(enableIndex)).ifPresent(bo::setEnableFlag); - StringOptional.ofNullable(dto.getDeviceExt()) - .ifPresent(value -> bo.setDeviceExt(JsonUtil.parseObject(value, DeviceExt.class))); + StringOptional.ofNullable(dto.getDeviceExt()) + .ifPresent(value -> bo.setDeviceExt(JsonUtil.parseObject(value, DeviceExt.class))); - if (dto.getProfileIdsCount() > 0) { - bo.setProfileIds(new ArrayList<>(dto.getProfileIdsList())); - } + if (dto.getProfileIdsCount() > 0) { + bo.setProfileIds(new ArrayList<>(dto.getProfileIdsList())); + } - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDriverBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDriverBuilder.java index abc72b357..54e01da52 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDriverBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcDriverBuilder.java @@ -48,58 +48,58 @@ import java.util.Optional; @Component public class FacadeGrpcDriverBuilder { - public GrpcPageDriverQuery toGrpcPageQuery(FacadeDriverQuery query) { - GrpcPageDriverQuery.Builder builder = GrpcPageDriverQuery.newBuilder(); + public GrpcPageDriverQuery toGrpcPageQuery(FacadeDriverQuery query) { + GrpcPageDriverQuery.Builder builder = GrpcPageDriverQuery.newBuilder(); - Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); - GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); - builder.setPage(page); + Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); + GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); + builder.setPage(page); - LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); - StringOptional.ofNullable(query.getDriverName()).ifPresent(builder::setDriverName); - StringOptional.ofNullable(query.getDriverCode()).ifPresent(builder::setDriverCode); - StringOptional.ofNullable(query.getServiceName()).ifPresent(builder::setServiceName); - StringOptional.ofNullable(query.getServiceHost()).ifPresent(builder::setServiceHost); - Optional.ofNullable(query.getDriverTypeFlag()) - .ifPresentOrElse(value -> builder.setDriverTypeFlag(value.getIndex()), - () -> builder.setDriverTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(query.getEnableFlag()) - .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), - () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); + LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); + StringOptional.ofNullable(query.getDriverName()).ifPresent(builder::setDriverName); + StringOptional.ofNullable(query.getDriverCode()).ifPresent(builder::setDriverCode); + StringOptional.ofNullable(query.getServiceName()).ifPresent(builder::setServiceName); + StringOptional.ofNullable(query.getServiceHost()).ifPresent(builder::setServiceHost); + Optional.ofNullable(query.getDriverTypeFlag()) + .ifPresentOrElse(value -> builder.setDriverTypeFlag(value.getIndex()), + () -> builder.setDriverTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(query.getEnableFlag()) + .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), + () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); - return builder.build(); - } + return builder.build(); + } - public FacadeDriverBO toFacadeBO(GrpcDriverDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadeDriverBO toFacadeBO(GrpcDriverDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadeDriverBO bo = new FacadeDriverBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadeDriverBO bo = new FacadeDriverBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getDriverName()).ifPresent(bo::setDriverName); - StringOptional.ofNullable(dto.getDriverCode()).ifPresent(bo::setDriverCode); - StringOptional.ofNullable(dto.getServiceName()).ifPresent(bo::setServiceName); - StringOptional.ofNullable(dto.getServiceHost()).ifPresent(bo::setServiceHost); - StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); - LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); + StringOptional.ofNullable(dto.getDriverName()).ifPresent(bo::setDriverName); + StringOptional.ofNullable(dto.getDriverCode()).ifPresent(bo::setDriverCode); + StringOptional.ofNullable(dto.getServiceName()).ifPresent(bo::setServiceName); + StringOptional.ofNullable(dto.getServiceHost()).ifPresent(bo::setServiceHost); + StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); + LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); - if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { - bo.setVersion(dto.getVersion()); - } + if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { + bo.setVersion(dto.getVersion()); + } - int driverType = dto.getDriverTypeFlag(); - if (driverType != DefaultConstant.NULL_INT) { - Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) driverType)).ifPresent(bo::setDriverTypeFlag); - } + int driverType = dto.getDriverTypeFlag(); + if (driverType != DefaultConstant.NULL_INT) { + Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) driverType)).ifPresent(bo::setDriverTypeFlag); + } - Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); + Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); - StringOptional.ofNullable(dto.getDriverExt()) - .ifPresent(value -> bo.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); + StringOptional.ofNullable(dto.getDriverExt()) + .ifPresent(value -> bo.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointBuilder.java index 8dbf673ea..5eb6b543d 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointBuilder.java @@ -54,72 +54,72 @@ import java.util.Optional; @Component public class FacadeGrpcPointBuilder { - public GrpcPagePointQuery toGrpcPageQuery(FacadePointQuery query) { - GrpcPagePointQuery.Builder builder = GrpcPagePointQuery.newBuilder(); + public GrpcPagePointQuery toGrpcPageQuery(FacadePointQuery query) { + GrpcPagePointQuery.Builder builder = GrpcPagePointQuery.newBuilder(); - Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); - GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); - builder.setPage(page); + Pages pages = Objects.isNull(query.getPage()) ? new Pages() : query.getPage(); + GrpcPage.Builder page = GrpcPage.newBuilder().setCurrent(pages.getCurrent()).setSize(pages.getSize()); + builder.setPage(page); - LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); - StringOptional.ofNullable(query.getPointName()).ifPresent(builder::setPointName); - StringOptional.ofNullable(query.getPointCode()).ifPresent(builder::setPointCode); - LongOptional.ofNullable(query.getDeviceId()).ifPresent(builder::setDeviceId); + LongOptional.ofNullable(query.getTenantId()).ifPresent(builder::setTenantId); + StringOptional.ofNullable(query.getPointName()).ifPresent(builder::setPointName); + StringOptional.ofNullable(query.getPointCode()).ifPresent(builder::setPointCode); + LongOptional.ofNullable(query.getDeviceId()).ifPresent(builder::setDeviceId); - Optional.ofNullable(query.getPointTypeFlag()) - .ifPresentOrElse(value -> builder.setPointTypeFlag(value.getIndex()), - () -> builder.setPointTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(query.getRwFlag()) - .ifPresentOrElse(value -> builder.setRwFlag(value.getIndex()), - () -> builder.setRwFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(query.getProfileId()) - .ifPresentOrElse(builder::setProfileId, () -> builder.setProfileId(DefaultConstant.NULL_INT)); - Optional.ofNullable(query.getEnableFlag()) - .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), - () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); + Optional.ofNullable(query.getPointTypeFlag()) + .ifPresentOrElse(value -> builder.setPointTypeFlag(value.getIndex()), + () -> builder.setPointTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(query.getRwFlag()) + .ifPresentOrElse(value -> builder.setRwFlag(value.getIndex()), + () -> builder.setRwFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(query.getProfileId()) + .ifPresentOrElse(builder::setProfileId, () -> builder.setProfileId(DefaultConstant.NULL_INT)); + Optional.ofNullable(query.getEnableFlag()) + .ifPresentOrElse(value -> builder.setEnableFlag(value.getIndex()), + () -> builder.setEnableFlag(DefaultConstant.DEFAULT_INT)); - return builder.build(); - } + return builder.build(); + } - public FacadePointBO toFacadeBO(GrpcPointDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadePointBO toFacadeBO(GrpcPointDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadePointBO bo = new FacadePointBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadePointBO bo = new FacadePointBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getPointName()).ifPresent(bo::setPointName); - StringOptional.ofNullable(dto.getPointCode()).ifPresent(bo::setPointCode); - StringOptional.ofNullable(dto.getUnit()).ifPresent(bo::setUnit); - StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); - LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); - LongOptional.ofNullable(dto.getProfileId()).ifPresent(bo::setProfileId); + StringOptional.ofNullable(dto.getPointName()).ifPresent(bo::setPointName); + StringOptional.ofNullable(dto.getPointCode()).ifPresent(bo::setPointCode); + StringOptional.ofNullable(dto.getUnit()).ifPresent(bo::setUnit); + StringOptional.ofNullable(dto.getSignature()).ifPresent(bo::setSignature); + LongOptional.ofNullable(dto.getTenantId()).ifPresent(bo::setTenantId); + LongOptional.ofNullable(dto.getProfileId()).ifPresent(bo::setProfileId); - bo.setBaseValue(BigDecimal.valueOf(dto.getBaseValue())); - bo.setMultiple(BigDecimal.valueOf(dto.getMultiple())); - bo.setValueDecimal((byte) dto.getValueDecimal()); + bo.setBaseValue(BigDecimal.valueOf(dto.getBaseValue())); + bo.setMultiple(BigDecimal.valueOf(dto.getMultiple())); + bo.setValueDecimal((byte) dto.getValueDecimal()); - if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { - bo.setVersion(dto.getVersion()); - } + if (dto.getVersion() != DefaultConstant.DEFAULT_INT) { + bo.setVersion(dto.getVersion()); + } - int pointType = dto.getPointTypeFlag(); - if (pointType != DefaultConstant.NULL_INT) { - Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) pointType)).ifPresent(bo::setPointTypeFlag); - } + int pointType = dto.getPointTypeFlag(); + if (pointType != DefaultConstant.NULL_INT) { + Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) pointType)).ifPresent(bo::setPointTypeFlag); + } - int rw = dto.getRwFlag(); - if (rw != DefaultConstant.NULL_INT) { - Optional.ofNullable(RwFlagEnum.ofIndex((byte) rw)).ifPresent(bo::setRwFlag); - } + int rw = dto.getRwFlag(); + if (rw != DefaultConstant.NULL_INT) { + Optional.ofNullable(RwFlagEnum.ofIndex((byte) rw)).ifPresent(bo::setRwFlag); + } - Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); + Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); - StringOptional.ofNullable(dto.getPointExt()) - .ifPresent(value -> bo.setPointExt(JsonUtil.parseObject(value, PointExt.class))); + StringOptional.ofNullable(dto.getPointExt()) + .ifPresent(value -> bo.setPointExt(JsonUtil.parseObject(value, PointExt.class))); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointValueBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointValueBuilder.java index c51b366f0..c1d781667 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointValueBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcPointValueBuilder.java @@ -37,28 +37,29 @@ import java.util.Objects; @Component public class FacadeGrpcPointValueBuilder { - /** - * Convert a gRPC {@link GrpcPointValueDTO} to a facade-level BO. - * @param dto the gRPC DTO (may be {@code null}) - * @return the facade BO, or {@code null} when the input is {@code null} - */ - public FacadePointValueBO toFacadeBO(GrpcPointValueDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + /** + * Convert a gRPC {@link GrpcPointValueDTO} to a facade-level BO. + * + * @param dto the gRPC DTO (may be {@code null}) + * @return the facade BO, or {@code null} when the input is {@code null} + */ + public FacadePointValueBO toFacadeBO(GrpcPointValueDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadePointValueBO bo = FacadePointValueBO.builder().createTime(dto.getCreateTime()).build(); + FacadePointValueBO bo = FacadePointValueBO.builder().createTime(dto.getCreateTime()).build(); - if (dto.getDeviceId() > 0) { - bo.setDeviceId(dto.getDeviceId()); - } - if (dto.getPointId() > 0) { - bo.setPointId(dto.getPointId()); - } - StringOptional.ofNullable(dto.getValue()).ifPresent(bo::setValue); - StringOptional.ofNullable(dto.getRawValue()).ifPresent(bo::setRawValue); + if (dto.getDeviceId() > 0) { + bo.setDeviceId(dto.getDeviceId()); + } + if (dto.getPointId() > 0) { + bo.setPointId(dto.getPointId()); + } + StringOptional.ofNullable(dto.getValue()).ifPresent(bo::setValue); + StringOptional.ofNullable(dto.getRawValue()).ifPresent(bo::setRawValue); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcTenantBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcTenantBuilder.java index 71d4fb9a3..e909717f1 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcTenantBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcTenantBuilder.java @@ -36,19 +36,19 @@ import java.util.Optional; @Component public class FacadeGrpcTenantBuilder { - public FacadeTenantBO toFacadeBO(GrpcTenantDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadeTenantBO toFacadeBO(GrpcTenantDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadeTenantBO bo = new FacadeTenantBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadeTenantBO bo = new FacadeTenantBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getTenantName()).ifPresent(bo::setTenantName); - StringOptional.ofNullable(dto.getTenantCode()).ifPresent(bo::setTenantCode); - Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); + StringOptional.ofNullable(dto.getTenantName()).ifPresent(bo::setTenantName); + StringOptional.ofNullable(dto.getTenantCode()).ifPresent(bo::setTenantCode); + Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserBuilder.java index 18e3701db..f2198b958 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserBuilder.java @@ -35,22 +35,22 @@ import java.util.Objects; @Component public class FacadeGrpcUserBuilder { - public FacadeUserBO toFacadeBO(GrpcUserDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadeUserBO toFacadeBO(GrpcUserDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadeUserBO bo = new FacadeUserBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadeUserBO bo = new FacadeUserBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getNickName()).ifPresent(bo::setNickName); - StringOptional.ofNullable(dto.getUserName()).ifPresent(bo::setUserName); - StringOptional.ofNullable(dto.getPhone()).ifPresent(bo::setPhone); - StringOptional.ofNullable(dto.getEmail()).ifPresent(bo::setEmail); - StringOptional.ofNullable(dto.getSocialExt()).ifPresent(bo::setSocialExt); - StringOptional.ofNullable(dto.getIdentityExt()).ifPresent(bo::setIdentityExt); + StringOptional.ofNullable(dto.getNickName()).ifPresent(bo::setNickName); + StringOptional.ofNullable(dto.getUserName()).ifPresent(bo::setUserName); + StringOptional.ofNullable(dto.getPhone()).ifPresent(bo::setPhone); + StringOptional.ofNullable(dto.getEmail()).ifPresent(bo::setEmail); + StringOptional.ofNullable(dto.getSocialExt()).ifPresent(bo::setSocialExt); + StringOptional.ofNullable(dto.getIdentityExt()).ifPresent(bo::setIdentityExt); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserLoginBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserLoginBuilder.java index 801c94f0b..ba82f703d 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserLoginBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/builder/FacadeGrpcUserLoginBuilder.java @@ -37,20 +37,20 @@ import java.util.Optional; @Component public class FacadeGrpcUserLoginBuilder { - public FacadeUserLoginBO toFacadeBO(GrpcUserLoginDTO dto) { - if (Objects.isNull(dto)) { - return null; - } + public FacadeUserLoginBO toFacadeBO(GrpcUserLoginDTO dto) { + if (Objects.isNull(dto)) { + return null; + } - FacadeUserLoginBO bo = new FacadeUserLoginBO(); - GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); + FacadeUserLoginBO bo = new FacadeUserLoginBO(); + GrpcBuilderUtil.buildBaseBOByGrpcBase(dto.getBase(), bo); - StringOptional.ofNullable(dto.getLoginName()).ifPresent(bo::setLoginName); - LongOptional.ofNullable(dto.getUserId()).ifPresent(bo::setUserId); - LongOptional.ofNullable(dto.getUserPasswordId()).ifPresent(bo::setUserPasswordId); - Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); + StringOptional.ofNullable(dto.getLoginName()).ifPresent(bo::setLoginName); + LongOptional.ofNullable(dto.getUserId()).ifPresent(bo::setUserId); + LongOptional.ofNullable(dto.getUserPasswordId()).ifPresent(bo::setUserPasswordId); + Optional.ofNullable(EnableFlagEnum.ofIndex((byte) dto.getEnableFlag())).ifPresent(bo::setEnableFlag); - return bo; - } + return bo; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/config/GrpcStubConfig.java b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/config/GrpcStubConfig.java index c37f49d35..82ed6be94 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/config/GrpcStubConfig.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-grpc/src/main/java/io/github/pnoker/common/facade/grpc/config/GrpcStubConfig.java @@ -32,50 +32,50 @@ import org.springframework.grpc.client.GrpcChannelFactory; @Configuration public class GrpcStubConfig { - @Bean - public TenantApiGrpc.TenantApiBlockingStub tenantApiBlockingStub(GrpcChannelFactory channels) { - return TenantApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); - } + @Bean + public TenantApiGrpc.TenantApiBlockingStub tenantApiBlockingStub(GrpcChannelFactory channels) { + return TenantApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); + } - @Bean - public UserApiGrpc.UserApiBlockingStub userApiBlockingStub(GrpcChannelFactory channels) { - return UserApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); - } + @Bean + public UserApiGrpc.UserApiBlockingStub userApiBlockingStub(GrpcChannelFactory channels) { + return UserApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); + } - @Bean - public TokenApiGrpc.TokenApiBlockingStub tokenApiBlockingStub(GrpcChannelFactory channels) { - return TokenApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); - } + @Bean + public TokenApiGrpc.TokenApiBlockingStub tokenApiBlockingStub(GrpcChannelFactory channels) { + return TokenApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); + } - @Bean - public UserLoginApiGrpc.UserLoginApiBlockingStub userLoginApiBlockingStub(GrpcChannelFactory channels) { - return UserLoginApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); - } + @Bean + public UserLoginApiGrpc.UserLoginApiBlockingStub userLoginApiBlockingStub(GrpcChannelFactory channels) { + return UserLoginApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); + } - @Bean - public ResourceRegistryApiGrpc.ResourceRegistryApiBlockingStub resourceRegistryApiBlockingStub( - GrpcChannelFactory channels) { - return ResourceRegistryApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); - } + @Bean + public ResourceRegistryApiGrpc.ResourceRegistryApiBlockingStub resourceRegistryApiBlockingStub( + GrpcChannelFactory channels) { + return ResourceRegistryApiGrpc.newBlockingStub(channels.createChannel(AuthConstant.SERVICE_NAME)); + } - @Bean - public DriverApiGrpc.DriverApiBlockingStub managerDriverApiBlockingStub(GrpcChannelFactory channels) { - return DriverApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public DriverApiGrpc.DriverApiBlockingStub managerDriverApiBlockingStub(GrpcChannelFactory channels) { + return DriverApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } - @Bean - public DeviceApiGrpc.DeviceApiBlockingStub managerDeviceApiBlockingStub(GrpcChannelFactory channels) { - return DeviceApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public DeviceApiGrpc.DeviceApiBlockingStub managerDeviceApiBlockingStub(GrpcChannelFactory channels) { + return DeviceApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } - @Bean - public PointApiGrpc.PointApiBlockingStub managerPointApiBlockingStub(GrpcChannelFactory channels) { - return PointApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); - } + @Bean + public PointApiGrpc.PointApiBlockingStub managerPointApiBlockingStub(GrpcChannelFactory channels) { + return PointApiGrpc.newBlockingStub(channels.createChannel(ManagerConstant.SERVICE_NAME)); + } - @Bean - public PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub(GrpcChannelFactory channels) { - return PointValueApiGrpc.newBlockingStub(channels.createChannel(DataConstant.SERVICE_NAME)); - } + @Bean + public PointValueApiGrpc.PointValueApiBlockingStub pointValueApiBlockingStub(GrpcChannelFactory channels) { + return PointValueApiGrpc.newBlockingStub(channels.createChannel(DataConstant.SERVICE_NAME)); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/ResourceRegistryLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/ResourceRegistryLocalFacade.java index 3316efbbc..3bd4a2e81 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/ResourceRegistryLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/ResourceRegistryLocalFacade.java @@ -44,41 +44,41 @@ import java.util.Objects; @Component public class ResourceRegistryLocalFacade implements ResourceRegistryFacade { - @Resource - private ResourceRegistrySyncService resourceRegistrySyncService; + @Resource + private ResourceRegistrySyncService resourceRegistrySyncService; - private static List toScannedApis(List apis) { - if (Objects.isNull(apis) || apis.isEmpty()) { - return List.of(); - } - List out = new ArrayList<>(apis.size()); - for (FacadeScannedApiBO bo : apis) { - out.add(ResourceRegistryScannedApi.builder() - .method(bo.getMethod()) - .path(bo.getPath()) - .apiName(bo.getApiName()) - .title(bo.getTitle()) - .remark(bo.getRemark()) - .apiGroup(bo.getApiGroup()) - .build()); - } - return out; - } + private static List toScannedApis(List apis) { + if (Objects.isNull(apis) || apis.isEmpty()) { + return List.of(); + } + List out = new ArrayList<>(apis.size()); + for (FacadeScannedApiBO bo : apis) { + out.add(ResourceRegistryScannedApi.builder() + .method(bo.getMethod()) + .path(bo.getPath()) + .apiName(bo.getApiName()) + .title(bo.getTitle()) + .remark(bo.getRemark()) + .apiGroup(bo.getApiGroup()) + .build()); + } + return out; + } - @Override - public FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command) { - ResourceRegistrySyncCommand cmd = ResourceRegistrySyncCommand.builder() - .serviceName(command.getServiceName()) - .deleteMissing(command.isDeleteMissing()) - .apis(toScannedApis(command.getApis())) - .build(); - ResourceRegistrySyncResult result = resourceRegistrySyncService.sync(cmd); - return FacadeResourceRegistrySyncResultBO.builder() - .inserted(result.getInserted()) - .updated(result.getUpdated()) - .deleted(result.getDeleted()) - .unchanged(result.getUnchanged()) - .build(); - } + @Override + public FacadeResourceRegistrySyncResultBO sync(FacadeResourceRegistrySyncCommandBO command) { + ResourceRegistrySyncCommand cmd = ResourceRegistrySyncCommand.builder() + .serviceName(command.getServiceName()) + .deleteMissing(command.isDeleteMissing()) + .apis(toScannedApis(command.getApis())) + .build(); + ResourceRegistrySyncResult result = resourceRegistrySyncService.sync(cmd); + return FacadeResourceRegistrySyncResultBO.builder() + .inserted(result.getInserted()) + .updated(result.getUpdated()) + .deleted(result.getDeleted()) + .unchanged(result.getUnchanged()) + .build(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TenantLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TenantLocalFacade.java index 7484a20d4..a610705b3 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TenantLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TenantLocalFacade.java @@ -38,16 +38,16 @@ import java.util.Objects; @Component public class TenantLocalFacade implements TenantFacade { - @Resource - private TenantService tenantService; + @Resource + private TenantService tenantService; - @Resource - private FacadeTenantBuilder facadeTenantBuilder; + @Resource + private FacadeTenantBuilder facadeTenantBuilder; - @Override - public FacadeTenantBO selectByCode(String code) { - TenantBO bo = tenantService.selectByCode(code); - return Objects.isNull(bo) ? null : facadeTenantBuilder.toFacadeBO(bo); - } + @Override + public FacadeTenantBO selectByCode(String code) { + TenantBO bo = tenantService.selectByCode(code); + return Objects.isNull(bo) ? null : facadeTenantBuilder.toFacadeBO(bo); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TokenLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TokenLocalFacade.java index 93e4b1dac..3c1798bdd 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TokenLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/TokenLocalFacade.java @@ -37,13 +37,13 @@ import java.util.Objects; @Component public class TokenLocalFacade implements TokenFacade { - @Resource - private TokenService tokenService; + @Resource + private TokenService tokenService; - @Override - public boolean checkValid(String tenant, String name, String salt, String token) { - TokenValid entity = tokenService.checkValid(name, salt, token, tenant); - return Objects.nonNull(entity) && entity.isValid(); - } + @Override + public boolean checkValid(String tenant, String name, String salt, String token) { + TokenValid entity = tokenService.checkValid(name, salt, token, tenant); + return Objects.nonNull(entity) && entity.isValid(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLocalFacade.java index f4d17453e..b98956cf8 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLocalFacade.java @@ -38,16 +38,16 @@ import java.util.Objects; @Component public class UserLocalFacade implements UserFacade { - @Resource - private UserService userService; + @Resource + private UserService userService; - @Resource - private FacadeUserBuilder facadeUserBuilder; + @Resource + private FacadeUserBuilder facadeUserBuilder; - @Override - public FacadeUserBO selectById(Long id) { - UserBO bo = userService.selectById(id); - return Objects.isNull(bo) ? null : facadeUserBuilder.toFacadeBO(bo); - } + @Override + public FacadeUserBO selectById(Long id) { + UserBO bo = userService.selectById(id); + return Objects.isNull(bo) ? null : facadeUserBuilder.toFacadeBO(bo); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLoginLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLoginLocalFacade.java index 6f97dfb6e..ec4134ae2 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLoginLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/UserLoginLocalFacade.java @@ -39,16 +39,16 @@ import java.util.Objects; @Component public class UserLoginLocalFacade implements UserLoginFacade { - @Resource - private UserLoginService userLoginService; + @Resource + private UserLoginService userLoginService; - @Resource - private FacadeUserLoginBuilder facadeUserLoginBuilder; + @Resource + private FacadeUserLoginBuilder facadeUserLoginBuilder; - @Override - public FacadeUserLoginBO selectByName(String name) { - UserLoginBO bo = userLoginService.selectByLoginName(name, false); - return Objects.isNull(bo) ? null : facadeUserLoginBuilder.toFacadeBO(bo); - } + @Override + public FacadeUserLoginBO selectByName(String name) { + UserLoginBO bo = userLoginService.selectByLoginName(name, false); + return Objects.isNull(bo) ? null : facadeUserLoginBuilder.toFacadeBO(bo); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeTenantBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeTenantBuilder.java index 9876a3633..b70508d8f 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeTenantBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeTenantBuilder.java @@ -29,9 +29,9 @@ import org.mapstruct.Mapper; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadeTenantBuilder { - FacadeTenantBO toFacadeBO(TenantBO authBO); + FacadeTenantBO toFacadeBO(TenantBO authBO); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserBuilder.java index 05cb8667b..705a355a7 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserBuilder.java @@ -40,24 +40,24 @@ import java.util.Objects; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadeUserBuilder { - @Mapping(target = "socialExt", ignore = true) - @Mapping(target = "identityExt", ignore = true) - FacadeUserBO toFacadeBO(UserBO authBO); + @Mapping(target = "socialExt", ignore = true) + @Mapping(target = "identityExt", ignore = true) + FacadeUserBO toFacadeBO(UserBO authBO); - @AfterMapping - default void afterProcess(UserBO authBO, @MappingTarget FacadeUserBO facadeBO) { - UserSocialExt social = authBO.getSocialExt(); - if (Objects.nonNull(social)) { - facadeBO.setSocialExt(JsonUtil.toJsonString(social)); - } + @AfterMapping + default void afterProcess(UserBO authBO, @MappingTarget FacadeUserBO facadeBO) { + UserSocialExt social = authBO.getSocialExt(); + if (Objects.nonNull(social)) { + facadeBO.setSocialExt(JsonUtil.toJsonString(social)); + } - UserIdentityExt identity = authBO.getIdentityExt(); - if (Objects.nonNull(identity)) { - facadeBO.setIdentityExt(JsonUtil.toJsonString(identity)); - } - } + UserIdentityExt identity = authBO.getIdentityExt(); + if (Objects.nonNull(identity)) { + facadeBO.setIdentityExt(JsonUtil.toJsonString(identity)); + } + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserLoginBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserLoginBuilder.java index cd1c0ed46..9ef6e299e 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserLoginBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeUserLoginBuilder.java @@ -28,9 +28,9 @@ import org.mapstruct.Mapper; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadeUserLoginBuilder { - FacadeUserLoginBO toFacadeBO(UserLoginBO authBO); + FacadeUserLoginBO toFacadeBO(UserLoginBO authBO); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeAuthAutoConfiguration.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeAuthAutoConfiguration.java index f5d5ababf..e4b2b2219 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeAuthAutoConfiguration.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-auth/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeAuthAutoConfiguration.java @@ -40,20 +40,20 @@ import org.springframework.context.annotation.FilterType; @AutoConfiguration @ConditionalOnProperty(name = "dc3.facade.mode", havingValue = "local") @ComponentScan(basePackages = "io.github.pnoker.common.facade.local", useDefaultFilters = false, - includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = { io.github.pnoker.common.facade.local.TenantLocalFacade.class, - io.github.pnoker.common.facade.local.TokenLocalFacade.class, - io.github.pnoker.common.facade.local.UserLocalFacade.class, - io.github.pnoker.common.facade.local.UserLoginLocalFacade.class, - io.github.pnoker.common.facade.local.ResourceRegistryLocalFacade.class, - FacadeTenantBuilder.class, FacadeUserBuilder.class, FacadeUserLoginBuilder.class, })) + includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, + classes = {io.github.pnoker.common.facade.local.TenantLocalFacade.class, + io.github.pnoker.common.facade.local.TokenLocalFacade.class, + io.github.pnoker.common.facade.local.UserLocalFacade.class, + io.github.pnoker.common.facade.local.UserLoginLocalFacade.class, + io.github.pnoker.common.facade.local.ResourceRegistryLocalFacade.class, + FacadeTenantBuilder.class, FacadeUserBuilder.class, FacadeUserLoginBuilder.class,})) public class LocalFacadeAuthAutoConfiguration { - /** - * Referenced only to ensure the {@link TenantLocalFacade} symbol is linked against - * this module's compiled classes at AutoConfiguration load time. - */ - @SuppressWarnings("unused") - private static final Class CANARY = TenantLocalFacade.class; + /** + * Referenced only to ensure the {@link TenantLocalFacade} symbol is linked against + * this module's compiled classes at AutoConfiguration load time. + */ + @SuppressWarnings("unused") + private static final Class CANARY = TenantLocalFacade.class; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueCommandLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueCommandLocalFacade.java index 904d1daca..d331d5725 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueCommandLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueCommandLocalFacade.java @@ -39,26 +39,26 @@ import org.springframework.stereotype.Component; @Component public class PointValueCommandLocalFacade implements PointValueCommandFacade { - @Resource - private PointValueCommandService pointValueCommandService; + @Resource + private PointValueCommandService pointValueCommandService; - @Override - public boolean read(Long deviceId, Long pointId) { - PointValueReadVO readVO = new PointValueReadVO(); - readVO.setDeviceId(deviceId); - readVO.setPointId(pointId); - pointValueCommandService.read(readVO); - return true; - } + @Override + public boolean read(Long deviceId, Long pointId) { + PointValueReadVO readVO = new PointValueReadVO(); + readVO.setDeviceId(deviceId); + readVO.setPointId(pointId); + pointValueCommandService.read(readVO); + return true; + } - @Override - public boolean write(Long deviceId, Long pointId, String value) { - PointValueWriteVO writeVO = new PointValueWriteVO(); - writeVO.setDeviceId(deviceId); - writeVO.setPointId(pointId); - writeVO.setValue(value); - pointValueCommandService.write(writeVO); - return true; - } + @Override + public boolean write(Long deviceId, Long pointId, String value) { + PointValueWriteVO writeVO = new PointValueWriteVO(); + writeVO.setDeviceId(deviceId); + writeVO.setPointId(pointId); + writeVO.setValue(value); + pointValueCommandService.write(writeVO); + return true; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueLocalFacade.java index 34b535cc1..c36e15af5 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/PointValueLocalFacade.java @@ -45,33 +45,33 @@ import java.util.Objects; @Component public class PointValueLocalFacade implements PointValueFacade { - @Resource - private PointValueService pointValueService; + @Resource + private PointValueService pointValueService; - @Resource - private FacadePointValueBuilder facadePointValueBuilder; + @Resource + private FacadePointValueBuilder facadePointValueBuilder; - @Override - public FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId) { - PointValueQuery query = PointValueQuery.builder() - .tenantId(tenantId) - .deviceId(deviceId) - .pointId(pointId) - .build(); - Page page = pointValueService.latest(query); - if (Objects.isNull(page) || page.getRecords().isEmpty()) { - return null; - } - return facadePointValueBuilder.toFacadeBO(page.getRecords().getFirst()); - } + @Override + public FacadePointValueBO lastValue(Long tenantId, Long deviceId, Long pointId) { + PointValueQuery query = PointValueQuery.builder() + .tenantId(tenantId) + .deviceId(deviceId) + .pointId(pointId) + .build(); + Page page = pointValueService.latest(query); + if (Objects.isNull(page) || page.getRecords().isEmpty()) { + return null; + } + return facadePointValueBuilder.toFacadeBO(page.getRecords().getFirst()); + } - @Override - public List history(Long tenantId, Long deviceId, Long pointId, int count) { - List result = pointValueService.history(tenantId, deviceId, pointId, count); - if (Objects.isNull(result) || result.isEmpty()) { - return Collections.emptyList(); - } - return result; - } + @Override + public List history(Long tenantId, Long deviceId, Long pointId, int count) { + List result = pointValueService.history(tenantId, deviceId, pointId, count); + if (Objects.isNull(result) || result.isEmpty()) { + return Collections.emptyList(); + } + return result; + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointValueBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointValueBuilder.java index a0da7d350..d6aa014e3 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointValueBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointValueBuilder.java @@ -35,21 +35,21 @@ import java.time.ZoneOffset; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadePointValueBuilder { - @Mapping(source = "calValue", target = "value") - @Mapping(source = "createTime", target = "createTime") - FacadePointValueBO toFacadeBO(PointValueBO bo); + @Mapping(source = "calValue", target = "value") + @Mapping(source = "createTime", target = "createTime") + FacadePointValueBO toFacadeBO(PointValueBO bo); - /** - * Convert LocalDateTime to epoch seconds. - */ - default long map(LocalDateTime value) { - if (value == null) { - return 0L; - } - return value.toEpochSecond(ZoneOffset.UTC); - } + /** + * Convert LocalDateTime to epoch seconds. + */ + default long map(LocalDateTime value) { + if (value == null) { + return 0L; + } + return value.toEpochSecond(ZoneOffset.UTC); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeDataAutoConfiguration.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeDataAutoConfiguration.java index 9786fcb33..e23a0646d 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeDataAutoConfiguration.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-data/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeDataAutoConfiguration.java @@ -39,15 +39,15 @@ import org.springframework.context.annotation.FilterType; @AutoConfiguration @ConditionalOnProperty(name = "dc3.facade.mode", havingValue = "local") @ComponentScan(basePackages = "io.github.pnoker.common.facade.local", useDefaultFilters = false, - includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { - PointValueLocalFacade.class, PointValueCommandLocalFacade.class, FacadePointValueBuilder.class, })) + includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { + PointValueLocalFacade.class, PointValueCommandLocalFacade.class, FacadePointValueBuilder.class,})) public class LocalFacadeDataAutoConfiguration { - /** - * Referenced only to ensure the {@link PointValueLocalFacade} symbol is linked - * against this module's compiled classes at AutoConfiguration load time. - */ - @SuppressWarnings("unused") - private static final Class CANARY = PointValueLocalFacade.class; + /** + * Referenced only to ensure the {@link PointValueLocalFacade} symbol is linked + * against this module's compiled classes at AutoConfiguration load time. + */ + @SuppressWarnings("unused") + private static final Class CANARY = PointValueLocalFacade.class; } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DeviceLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DeviceLocalFacade.java index 56cbcdb47..62f9de454 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DeviceLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DeviceLocalFacade.java @@ -47,46 +47,46 @@ import java.util.Objects; @Component public class DeviceLocalFacade implements DeviceFacade { - @Resource - private DeviceService deviceService; + @Resource + private DeviceService deviceService; - @Resource - private FacadeDeviceBuilder facadeDeviceBuilder; + @Resource + private FacadeDeviceBuilder facadeDeviceBuilder; - @Override - public FacadeDeviceBO selectById(Long id) { - DeviceBO managerBO = deviceService.selectById(id); - return Objects.isNull(managerBO) ? null : facadeDeviceBuilder.toFacadeBO(managerBO); - } + @Override + public FacadeDeviceBO selectById(Long id) { + DeviceBO managerBO = deviceService.selectById(id); + return Objects.isNull(managerBO) ? null : facadeDeviceBuilder.toFacadeBO(managerBO); + } - @Override - public FacadePage selectByPage(FacadeDeviceQuery query) { - DeviceQuery managerQuery = facadeDeviceBuilder.toManagerQuery(query); - Page page = deviceService.selectByPage(managerQuery); - if (Objects.isNull(page)) { - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadeDeviceQuery query) { + DeviceQuery managerQuery = facadeDeviceBuilder.toManagerQuery(query); + Page page = deviceService.selectByPage(managerQuery); + if (Objects.isNull(page)) { + return FacadePage.empty(); + } - List records = page.getRecords().stream().map(facadeDeviceBuilder::toFacadeBO).toList(); - return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); - } + List records = page.getRecords().stream().map(facadeDeviceBuilder::toFacadeBO).toList(); + return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); + } - @Override - public List selectByProfileId(Long profileId) { - List list = deviceService.selectByProfileId(profileId); - if (Objects.isNull(list) || list.isEmpty()) { - return Collections.emptyList(); - } - return list.stream().map(facadeDeviceBuilder::toFacadeBO).toList(); - } + @Override + public List selectByProfileId(Long profileId) { + List list = deviceService.selectByProfileId(profileId); + if (Objects.isNull(list) || list.isEmpty()) { + return Collections.emptyList(); + } + return list.stream().map(facadeDeviceBuilder::toFacadeBO).toList(); + } - @Override - public List selectByDriverId(Long driverId) { - List list = deviceService.selectByDriverId(driverId); - if (Objects.isNull(list) || list.isEmpty()) { - return Collections.emptyList(); - } - return list.stream().map(facadeDeviceBuilder::toFacadeBO).toList(); - } + @Override + public List selectByDriverId(Long driverId) { + List list = deviceService.selectByDriverId(driverId); + if (Objects.isNull(list) || list.isEmpty()) { + return Collections.emptyList(); + } + return list.stream().map(facadeDeviceBuilder::toFacadeBO).toList(); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DriverLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DriverLocalFacade.java index f4042699a..71f312abc 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DriverLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/DriverLocalFacade.java @@ -43,34 +43,34 @@ import java.util.Objects; @Component public class DriverLocalFacade implements DriverFacade { - @Resource - private DriverService driverService; + @Resource + private DriverService driverService; - @Resource - private FacadeDriverBuilder facadeDriverBuilder; + @Resource + private FacadeDriverBuilder facadeDriverBuilder; - @Override - public FacadeDriverBO selectById(Long id) { - DriverBO managerBO = driverService.selectById(id); - return Objects.isNull(managerBO) ? null : facadeDriverBuilder.toFacadeBO(managerBO); - } + @Override + public FacadeDriverBO selectById(Long id) { + DriverBO managerBO = driverService.selectById(id); + return Objects.isNull(managerBO) ? null : facadeDriverBuilder.toFacadeBO(managerBO); + } - @Override - public FacadePage selectByPage(FacadeDriverQuery query) { - DriverQuery managerQuery = facadeDriverBuilder.toManagerQuery(query); - Page page = driverService.selectByPage(managerQuery); - if (Objects.isNull(page)) { - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadeDriverQuery query) { + DriverQuery managerQuery = facadeDriverBuilder.toManagerQuery(query); + Page page = driverService.selectByPage(managerQuery); + if (Objects.isNull(page)) { + return FacadePage.empty(); + } - List records = page.getRecords().stream().map(facadeDriverBuilder::toFacadeBO).toList(); - return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); - } + List records = page.getRecords().stream().map(facadeDriverBuilder::toFacadeBO).toList(); + return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); + } - @Override - public FacadeDriverBO selectByDeviceId(Long deviceId) { - DriverBO managerBO = driverService.selectByDeviceId(deviceId); - return Objects.isNull(managerBO) ? null : facadeDriverBuilder.toFacadeBO(managerBO); - } + @Override + public FacadeDriverBO selectByDeviceId(Long deviceId) { + DriverBO managerBO = driverService.selectByDeviceId(deviceId); + return Objects.isNull(managerBO) ? null : facadeDriverBuilder.toFacadeBO(managerBO); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/PointLocalFacade.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/PointLocalFacade.java index 2ad1e41b7..54f5e01b4 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/PointLocalFacade.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/PointLocalFacade.java @@ -43,28 +43,28 @@ import java.util.Objects; @Component public class PointLocalFacade implements PointFacade { - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Resource - private FacadePointBuilder facadePointBuilder; + @Resource + private FacadePointBuilder facadePointBuilder; - @Override - public FacadePointBO selectById(Long id) { - PointBO managerBO = pointService.selectById(id); - return Objects.isNull(managerBO) ? null : facadePointBuilder.toFacadeBO(managerBO); - } + @Override + public FacadePointBO selectById(Long id) { + PointBO managerBO = pointService.selectById(id); + return Objects.isNull(managerBO) ? null : facadePointBuilder.toFacadeBO(managerBO); + } - @Override - public FacadePage selectByPage(FacadePointQuery query) { - PointQuery managerQuery = facadePointBuilder.toManagerQuery(query); - Page page = pointService.selectByPage(managerQuery); - if (Objects.isNull(page)) { - return FacadePage.empty(); - } + @Override + public FacadePage selectByPage(FacadePointQuery query) { + PointQuery managerQuery = facadePointBuilder.toManagerQuery(query); + Page page = pointService.selectByPage(managerQuery); + if (Objects.isNull(page)) { + return FacadePage.empty(); + } - List records = page.getRecords().stream().map(facadePointBuilder::toFacadeBO).toList(); - return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); - } + List records = page.getRecords().stream().map(facadePointBuilder::toFacadeBO).toList(); + return new FacadePage<>(page.getCurrent(), page.getSize(), page.getTotal(), page.getPages(), records); + } } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDeviceBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDeviceBuilder.java index ea125b35f..09fcca2d3 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDeviceBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDeviceBuilder.java @@ -31,11 +31,11 @@ import org.mapstruct.Mapper; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadeDeviceBuilder { - DeviceQuery toManagerQuery(FacadeDeviceQuery facadeQuery); + DeviceQuery toManagerQuery(FacadeDeviceQuery facadeQuery); - FacadeDeviceBO toFacadeBO(DeviceBO managerBO); + FacadeDeviceBO toFacadeBO(DeviceBO managerBO); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDriverBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDriverBuilder.java index 8be48a298..202b68a8b 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDriverBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadeDriverBuilder.java @@ -30,11 +30,11 @@ import org.mapstruct.Mapper; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadeDriverBuilder { - DriverQuery toManagerQuery(FacadeDriverQuery facadeQuery); + DriverQuery toManagerQuery(FacadeDriverQuery facadeQuery); - FacadeDriverBO toFacadeBO(DriverBO managerBO); + FacadeDriverBO toFacadeBO(DriverBO managerBO); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointBuilder.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointBuilder.java index f9ba8e9a6..1463d5d62 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointBuilder.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/builder/FacadePointBuilder.java @@ -30,11 +30,11 @@ import org.mapstruct.Mapper; * @author pnoker * @since 2026.5.5 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface FacadePointBuilder { - PointQuery toManagerQuery(FacadePointQuery facadeQuery); + PointQuery toManagerQuery(FacadePointQuery facadeQuery); - FacadePointBO toFacadeBO(PointBO managerBO); + FacadePointBO toFacadeBO(PointBO managerBO); } diff --git a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeManagerAutoConfiguration.java b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeManagerAutoConfiguration.java index 562e5acee..dd5e18756 100644 --- a/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeManagerAutoConfiguration.java +++ b/dc3-common/dc3-common-facade/dc3-common-facade-local-manager/src/main/java/io/github/pnoker/common/facade/local/config/LocalFacadeManagerAutoConfiguration.java @@ -40,18 +40,18 @@ import org.springframework.context.annotation.FilterType; @AutoConfiguration @ConditionalOnProperty(name = "dc3.facade.mode", havingValue = "local") @ComponentScan(basePackages = "io.github.pnoker.common.facade.local", useDefaultFilters = false, - includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, - classes = { io.github.pnoker.common.facade.local.DeviceLocalFacade.class, - io.github.pnoker.common.facade.local.DriverLocalFacade.class, - io.github.pnoker.common.facade.local.PointLocalFacade.class, FacadeDeviceBuilder.class, - FacadeDriverBuilder.class, FacadePointBuilder.class, })) + includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, + classes = {io.github.pnoker.common.facade.local.DeviceLocalFacade.class, + io.github.pnoker.common.facade.local.DriverLocalFacade.class, + io.github.pnoker.common.facade.local.PointLocalFacade.class, FacadeDeviceBuilder.class, + FacadeDriverBuilder.class, FacadePointBuilder.class,})) public class LocalFacadeManagerAutoConfiguration { - /** - * Referenced only to ensure the {@link DeviceLocalFacade} symbol is linked against - * this module's compiled classes at AutoConfiguration load time. - */ - @SuppressWarnings("unused") - private static final Class CANARY = DeviceLocalFacade.class; + /** + * Referenced only to ensure the {@link DeviceLocalFacade} symbol is linked against + * this module's compiled classes at AutoConfiguration load time. + */ + @SuppressWarnings("unused") + private static final Class CANARY = DeviceLocalFacade.class; } diff --git a/dc3-common/dc3-common-gateway/README.md b/dc3-common/dc3-common-gateway/README.md index 6e67c4525..3f0e83009 100644 --- a/dc3-common/dc3-common-gateway/README.md +++ b/dc3-common/dc3-common-gateway/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-gateway` is the shared gateway module of the IoT DC3 platform. It provides the `Authentic` gateway filter factory and supporting services that validate tokens with the +`dc3-common-gateway` is the shared gateway module of the IoT DC3 platform. It provides the `Authentic` gateway filter +factory and supporting services that validate tokens with the Auth Center before forwarding requests in the `dc3-gateway`. ## Module Information diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/config/ActiveGatewayProfileConfig.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/config/ActiveGatewayProfileConfig.java index 948886c00..450d01ec9 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/config/ActiveGatewayProfileConfig.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/config/ActiveGatewayProfileConfig.java @@ -37,11 +37,11 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveGatewayProfileConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - // Add gateway profile to active profiles - // This will enable gateway-specific configurations when the application starts - environment.addActiveProfile("gateway"); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + // Add gateway profile to active profiles + // This will enable gateway-specific configurations when the application starts + environment.addActiveProfile("gateway"); + } } diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilter.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilter.java index 3f72f5b72..2c8641298 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilter.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilter.java @@ -49,43 +49,41 @@ import reactor.core.publisher.Mono; @Component public class AuthenticGatewayFilter implements GatewayFilter { - private final FilterService filterService; + private final FilterService filterService; - public AuthenticGatewayFilter(FilterService filterService) { - this.filterService = filterService; - } + public AuthenticGatewayFilter(FilterService filterService) { + this.filterService = filterService; + } - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - ServerHttpRequest request = exchange.getRequest(); + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); - try { - FacadeTenantBO tenant = filterService.getTenant(request); - FacadeUserLoginBO userLogin = filterService.getUserLogin(request); - filterService.checkValid(request, tenant, userLogin); + try { + FacadeTenantBO tenant = filterService.getTenant(request); + FacadeUserLoginBO userLogin = filterService.getUserLogin(request); + filterService.checkValid(request, tenant, userLogin); - RequestHeader.UserHeader userHeader = filterService.getUser(userLogin, tenant); - ServerHttpRequest build = request.mutate() - .headers(headers -> headers.set(RequestConstant.Header.X_AUTH_USER, JsonUtil.toJsonString(userHeader))) - .build(); - return chain.filter(exchange.mutate().request(build).build()); - } - catch (UnAuthorizedException e) { - log.warn("AuthenticGatewayFilter unauthorized: {}, Url: {}", e.getMessage(), request.getURI()); - return writeErrorResponse(exchange, HttpStatus.UNAUTHORIZED, e.getMessage()); - } - catch (Exception e) { - log.error("AuthenticGatewayFilter unexpected error, Url: {}", request.getURI(), e); - return writeErrorResponse(exchange, HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error"); - } - } + RequestHeader.UserHeader userHeader = filterService.getUser(userLogin, tenant); + ServerHttpRequest build = request.mutate() + .headers(headers -> headers.set(RequestConstant.Header.X_AUTH_USER, JsonUtil.toJsonString(userHeader))) + .build(); + return chain.filter(exchange.mutate().request(build).build()); + } catch (UnAuthorizedException e) { + log.warn("AuthenticGatewayFilter unauthorized: {}, Url: {}", e.getMessage(), request.getURI()); + return writeErrorResponse(exchange, HttpStatus.UNAUTHORIZED, e.getMessage()); + } catch (Exception e) { + log.error("AuthenticGatewayFilter unexpected error, Url: {}", request.getURI(), e); + return writeErrorResponse(exchange, HttpStatus.INTERNAL_SERVER_ERROR, "Internal Server Error"); + } + } - private Mono writeErrorResponse(ServerWebExchange exchange, HttpStatus status, String message) { - ServerHttpResponse response = exchange.getResponse(); - response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); - response.setStatusCode(status); - DataBuffer dataBuffer = response.bufferFactory().wrap(JsonUtil.toJsonBytes(R.fail(message))); - return response.writeWith(Mono.just(dataBuffer)); - } + private Mono writeErrorResponse(ServerWebExchange exchange, HttpStatus status, String message) { + ServerHttpResponse response = exchange.getResponse(); + response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); + response.setStatusCode(status); + DataBuffer dataBuffer = response.bufferFactory().wrap(JsonUtil.toJsonBytes(R.fail(message))); + return response.writeWith(Mono.just(dataBuffer)); + } } diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilterFactory.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilterFactory.java index ba411eb9b..025a9f92f 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilterFactory.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/filter/AuthenticGatewayFilterFactory.java @@ -33,15 +33,15 @@ import org.springframework.stereotype.Component; @Component public class AuthenticGatewayFilterFactory extends AbstractGatewayFilterFactory { - private final AuthenticGatewayFilter authenticGatewayFilter; + private final AuthenticGatewayFilter authenticGatewayFilter; - public AuthenticGatewayFilterFactory(AuthenticGatewayFilter authenticGatewayFilter) { - this.authenticGatewayFilter = authenticGatewayFilter; - } + public AuthenticGatewayFilterFactory(AuthenticGatewayFilter authenticGatewayFilter) { + this.authenticGatewayFilter = authenticGatewayFilter; + } - @Override - public GatewayFilter apply(Object config) { - return authenticGatewayFilter; - } + @Override + public GatewayFilter apply(Object config) { + return authenticGatewayFilter; + } } diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/FilterService.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/FilterService.java index a58808c3f..8b99843a4 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/FilterService.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/FilterService.java @@ -29,12 +29,12 @@ import org.springframework.http.server.reactive.ServerHttpRequest; */ public interface FilterService { - FacadeTenantBO getTenant(ServerHttpRequest request); + FacadeTenantBO getTenant(ServerHttpRequest request); - FacadeUserLoginBO getUserLogin(ServerHttpRequest request); + FacadeUserLoginBO getUserLogin(ServerHttpRequest request); - RequestHeader.UserHeader getUser(FacadeUserLoginBO userLogin, FacadeTenantBO tenant); + RequestHeader.UserHeader getUser(FacadeUserLoginBO userLogin, FacadeTenantBO tenant); - void checkValid(ServerHttpRequest request, FacadeTenantBO tenant, FacadeUserLoginBO userLogin); + void checkValid(ServerHttpRequest request, FacadeTenantBO tenant, FacadeUserLoginBO userLogin); } diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/impl/FilterServiceImpl.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/impl/FilterServiceImpl.java index dfc0ad1c3..fd107926a 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/impl/FilterServiceImpl.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/gateway/service/impl/FilterServiceImpl.java @@ -48,82 +48,81 @@ import java.util.Objects; @Service public class FilterServiceImpl implements FilterService { - @Resource - private TenantFacade tenantFacade; + @Resource + private TenantFacade tenantFacade; - @Resource - private UserLoginFacade userLoginFacade; + @Resource + private UserLoginFacade userLoginFacade; - @Resource - private UserFacade userFacade; + @Resource + private UserFacade userFacade; - @Resource - private TokenFacade tokenFacade; + @Resource + private TokenFacade tokenFacade; - @Override - public FacadeTenantBO getTenant(ServerHttpRequest request) { - String code = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_TENANT); - if (StringUtils.isEmpty(code)) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } + @Override + public FacadeTenantBO getTenant(ServerHttpRequest request) { + String code = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_TENANT); + if (StringUtils.isEmpty(code)) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } - FacadeTenantBO tenant = tenantFacade.selectByCode(code); - if (Objects.isNull(tenant) || tenant.getEnableFlag() != EnableFlagEnum.ENABLE) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } - return tenant; - } + FacadeTenantBO tenant = tenantFacade.selectByCode(code); + if (Objects.isNull(tenant) || tenant.getEnableFlag() != EnableFlagEnum.ENABLE) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } + return tenant; + } - @Override - public FacadeUserLoginBO getUserLogin(ServerHttpRequest request) { - String name = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_LOGIN); - if (StringUtils.isEmpty(name)) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } + @Override + public FacadeUserLoginBO getUserLogin(ServerHttpRequest request) { + String name = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_LOGIN); + if (StringUtils.isEmpty(name)) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } - FacadeUserLoginBO userLogin = userLoginFacade.selectByName(name); - if (Objects.isNull(userLogin) || userLogin.getEnableFlag() != EnableFlagEnum.ENABLE) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } - return userLogin; - } + FacadeUserLoginBO userLogin = userLoginFacade.selectByName(name); + if (Objects.isNull(userLogin) || userLogin.getEnableFlag() != EnableFlagEnum.ENABLE) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } + return userLogin; + } - @Override - public RequestHeader.UserHeader getUser(FacadeUserLoginBO userLogin, FacadeTenantBO tenant) { - // Preserves the existing (surprising) behavior: lookup UserApi by UserLogin.id, - // not UserLogin.userId. Changing that belongs in a separate bug-fix PR. - FacadeUserBO user = userFacade.selectById(userLogin.getId()); - if (Objects.isNull(user)) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } + @Override + public RequestHeader.UserHeader getUser(FacadeUserLoginBO userLogin, FacadeTenantBO tenant) { + // Preserves the existing (surprising) behavior: lookup UserApi by UserLogin.id, + // not UserLogin.userId. Changing that belongs in a separate bug-fix PR. + FacadeUserBO user = userFacade.selectById(userLogin.getId()); + if (Objects.isNull(user)) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } - RequestHeader.UserHeader header = new RequestHeader.UserHeader(); - header.setUserId(user.getId()); - header.setNickName(user.getNickName()); - header.setUserName(user.getUserName()); - header.setTenantId(tenant.getId()); - return header; - } + RequestHeader.UserHeader header = new RequestHeader.UserHeader(); + header.setUserId(user.getId()); + header.setNickName(user.getNickName()); + header.setUserName(user.getUserName()); + header.setTenantId(tenant.getId()); + return header; + } - @Override - public void checkValid(ServerHttpRequest request, FacadeTenantBO tenant, FacadeUserLoginBO userLogin) { - String token = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_TOKEN); - RequestHeader.TokenHeader header; - try { - header = JsonUtil.parseObject(token, RequestHeader.TokenHeader.class); - } - catch (Exception e) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } - if (Objects.isNull(header) || StringUtils.isAnyEmpty(header.getSalt(), header.getToken())) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } + @Override + public void checkValid(ServerHttpRequest request, FacadeTenantBO tenant, FacadeUserLoginBO userLogin) { + String token = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_TOKEN); + RequestHeader.TokenHeader header; + try { + header = JsonUtil.parseObject(token, RequestHeader.TokenHeader.class); + } catch (Exception e) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } + if (Objects.isNull(header) || StringUtils.isAnyEmpty(header.getSalt(), header.getToken())) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } - boolean valid = tokenFacade.checkValid(tenant.getTenantCode(), userLogin.getLoginName(), header.getSalt(), - header.getToken()); - if (!valid) { - throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); - } - } + boolean valid = tokenFacade.checkValid(tenant.getTenantCode(), userLogin.getLoginName(), header.getSalt(), + header.getToken()); + if (!valid) { + throw new UnAuthorizedException(RequestConstant.Message.INVALID_REQUEST); + } + } } diff --git a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/init/GatewayInitRunner.java b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/init/GatewayInitRunner.java index cbfce8e8c..a8c3ebbd2 100644 --- a/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/init/GatewayInitRunner.java +++ b/dc3-common/dc3-common-gateway/src/main/java/io/github/pnoker/common/init/GatewayInitRunner.java @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.gateway" }) +@ComponentScan(basePackages = {"io.github.pnoker.common.gateway"}) public class GatewayInitRunner { } diff --git a/dc3-common/dc3-common-log/README.md b/dc3-common/dc3-common-log/README.md index 620261097..33a5cecf3 100644 --- a/dc3-common/dc3-common-log/README.md +++ b/dc3-common/dc3-common-log/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-log` is the shared logging aspect module of the IoT DC3 platform. It provides a custom AOP-based `@Logs` annotation for declarative method-level logging across all +`dc3-common-log` is the shared logging aspect module of the IoT DC3 platform. It provides a custom AOP-based `@Logs` +annotation for declarative method-level logging across all services. ## Module Information diff --git a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/Logs.java b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/Logs.java index e89a59aa7..8e649bf0b 100644 --- a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/Logs.java +++ b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/Logs.java @@ -17,12 +17,7 @@ package io.github.pnoker.common.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Custom annotation for logging method execution in DC3 IoT Platform. This annotation can @@ -39,28 +34,32 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) public @interface Logs { - /** - * The log message to be recorded - * @return The log message string - */ - String value() default ""; + /** + * The log message to be recorded + * + * @return The log message string + */ + String value() default ""; - /** - * The type/level of the log entry - * @return The LogsType enum value - */ - LogsType type() default LogsType.INFO; + /** + * The type/level of the log entry + * + * @return The LogsType enum value + */ + LogsType type() default LogsType.INFO; - /** - * Custom tag for categorizing or filtering logs - * @return The tag string - */ - String tag() default ""; + /** + * Custom tag for categorizing or filtering logs + * + * @return The tag string + */ + String tag() default ""; - /** - * Whether to persist the log entry to storage - * @return True if the log should be saved, false otherwise - */ - boolean save() default false; + /** + * Whether to persist the log entry to storage + * + * @return True if the log should be saved, false otherwise + */ + boolean save() default false; } diff --git a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java index 371a25fa2..936a7085d 100644 --- a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java +++ b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsAspect.java @@ -40,42 +40,42 @@ import java.util.UUID; @Configuration public class LogsAspect { - /** - * Pointcut definition targeting methods annotated with @Logs annotation. This - * pointcut will be used to intercept and log method executions. - */ - @Pointcut("@annotation(io.github.pnoker.common.annotation.Logs)") - public void logsCut() { - // nothing to do - } + /** + * Pointcut definition targeting methods annotated with @Logs annotation. This + * pointcut will be used to intercept and log method executions. + */ + @Pointcut("@annotation(io.github.pnoker.common.annotation.Logs)") + public void logsCut() { + // nothing to do + } - /** - * Around advice that handles the logging of method execution. Generates a unique UUID - * for each execution, logs the start and end of method calls, tracks execution time, - * and handles any exceptions that occur during execution. - * @param proceedingJoinPoint The joinpoint representing the intercepted method - * @param logs The Logs annotation instance containing the log message - * @return The result of the method execution - * @throws Throwable If any error occurs during method execution - */ - @Around("logsCut() && @annotation(logs)") - public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Logs logs) throws Throwable { - String uuid = UUID.randomUUID().toString(); - String className = proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName(); - String methodName = proceedingJoinPoint.getSignature().getName(); - long startTime = System.currentTimeMillis(); - log.info("Start => [{}].[{}.{}]: {}", uuid, className, methodName, logs.value()); - try { - Object proceed = proceedingJoinPoint.proceed(); - log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, - System.currentTimeMillis() - startTime, logs.value()); - return proceed; - } - catch (Throwable throwable) { - log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, - System.currentTimeMillis() - startTime, logs.value()); - throw throwable; - } - } + /** + * Around advice that handles the logging of method execution. Generates a unique UUID + * for each execution, logs the start and end of method calls, tracks execution time, + * and handles any exceptions that occur during execution. + * + * @param proceedingJoinPoint The joinpoint representing the intercepted method + * @param logs The Logs annotation instance containing the log message + * @return The result of the method execution + * @throws Throwable If any error occurs during method execution + */ + @Around("logsCut() && @annotation(logs)") + public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Logs logs) throws Throwable { + String uuid = UUID.randomUUID().toString(); + String className = proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName(); + String methodName = proceedingJoinPoint.getSignature().getName(); + long startTime = System.currentTimeMillis(); + log.info("Start => [{}].[{}.{}]: {}", uuid, className, methodName, logs.value()); + try { + Object proceed = proceedingJoinPoint.proceed(); + log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, + System.currentTimeMillis() - startTime, logs.value()); + return proceed; + } catch (Throwable throwable) { + log.info("End <= [{}].[{}.{}].[{}ms]: {}", uuid, className, methodName, + System.currentTimeMillis() - startTime, logs.value()); + throw throwable; + } + } } diff --git a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsType.java b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsType.java index 762e5f9a3..d3d049d68 100644 --- a/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsType.java +++ b/dc3-common/dc3-common-log/src/main/java/io/github/pnoker/common/annotation/LogsType.java @@ -30,6 +30,6 @@ package io.github.pnoker.common.annotation; */ public enum LogsType { - INFO, WARN, DEBUG, ERROR + INFO, WARN, DEBUG, ERROR } diff --git a/dc3-common/dc3-common-manager/README.md b/dc3-common/dc3-common-manager/README.md index 30e51a812..0b8730270 100644 --- a/dc3-common/dc3-common-manager/README.md +++ b/dc3-common/dc3-common-manager/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-manager` is the shared Device Management business module of the IoT DC3 platform. It contains all controllers, service implementations, gRPC servers, DAL managers, +`dc3-common-manager` is the shared Device Management business module of the IoT DC3 platform. It contains all +controllers, service implementations, gRPC servers, DAL managers, mappers, and event handling logic for the Manager Center. It is wired into `dc3-center-manager`. ## Module Information diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/config/ActiveManagerProfileConfig.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/config/ActiveManagerProfileConfig.java index b1961564e..146c4c83c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/config/ActiveManagerProfileConfig.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/config/ActiveManagerProfileConfig.java @@ -37,9 +37,9 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveManagerProfileConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("manager"); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("manager"); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/init/ManagerInitRunner.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/init/ManagerInitRunner.java index b6e03145e..62b4dc2a8 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/init/ManagerInitRunner.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/init/ManagerInitRunner.java @@ -34,31 +34,33 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.manager" }) -@MapperScan(basePackages = { "io.github.pnoker.common.manager.mapper" }) +@ComponentScan(basePackages = {"io.github.pnoker.common.manager"}) +@MapperScan(basePackages = {"io.github.pnoker.common.manager.mapper"}) public class ManagerInitRunner implements ApplicationRunner { - private final ScheduleForManagerService scheduleForManagerService; + private final ScheduleForManagerService scheduleForManagerService; - /** - * Constructs a new ManagerInitRunner with the required service dependency. - * @param scheduleForManagerService The service responsible for manager scheduling - * operations - */ - public ManagerInitRunner(ScheduleForManagerService scheduleForManagerService) { - this.scheduleForManagerService = scheduleForManagerService; - } + /** + * Constructs a new ManagerInitRunner with the required service dependency. + * + * @param scheduleForManagerService The service responsible for manager scheduling + * operations + */ + public ManagerInitRunner(ScheduleForManagerService scheduleForManagerService) { + this.scheduleForManagerService = scheduleForManagerService; + } - /** - * Executes the initialization process when the application starts. This method - * initializes the schedule manager service to set up necessary scheduling - * configurations and tasks. - * @param args Application arguments passed during startup - * @throws Exception If an error occurs during initialization - */ - @Override - public void run(ApplicationArguments args) throws Exception { - scheduleForManagerService.initial(); - } + /** + * Executes the initialization process when the application starts. This method + * initializes the schedule manager service to set up necessary scheduling + * configurations and tasks. + * + * @param args Application arguments passed during startup + * @throws Exception If an error occurs during initialization + */ + @Override + public void run(ApplicationArguments args) throws Exception { + scheduleForManagerService.initial(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DictionaryForManagerService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DictionaryForManagerService.java index 0ef05d2d5..b2a79d12a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DictionaryForManagerService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DictionaryForManagerService.java @@ -30,46 +30,52 @@ import io.github.pnoker.common.manager.entity.query.DictionaryQuery; */ public interface DictionaryForManagerService { - /** - * Get driver dictionary list with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page driverDictionary(DictionaryQuery entityQuery); + /** + * Get driver dictionary list with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page driverDictionary(DictionaryQuery entityQuery); - /** - * Get profile dictionary list with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page profileDictionary(DictionaryQuery entityQuery); + /** + * Get profile dictionary list with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page profileDictionary(DictionaryQuery entityQuery); - /** - * Get point dictionary under profile with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page pointDictionaryForProfile(DictionaryQuery entityQuery); + /** + * Get point dictionary under profile with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page pointDictionaryForProfile(DictionaryQuery entityQuery); - /** - * Get point dictionary under device with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page pointDictionaryForDevice(DictionaryQuery entityQuery); + /** + * Get point dictionary under device with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page pointDictionaryForDevice(DictionaryQuery entityQuery); - /** - * Get device dictionary list with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page deviceDictionary(DictionaryQuery entityQuery); + /** + * Get device dictionary list with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page deviceDictionary(DictionaryQuery entityQuery); - /** - * Get device dictionary under driver with pagination - * @param entityQuery {@link DictionaryQuery} - * @return DictionaryBO Page - */ - Page deviceDictionaryForDriver(DictionaryQuery entityQuery); + /** + * Get device dictionary under driver with pagination + * + * @param entityQuery {@link DictionaryQuery} + * @return DictionaryBO Page + */ + Page deviceDictionaryForDriver(DictionaryQuery entityQuery); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DriverRegisterService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DriverRegisterService.java index e838ab25f..b665510f9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DriverRegisterService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/DriverRegisterService.java @@ -33,24 +33,27 @@ import java.util.List; */ public interface DriverRegisterService { - /** - * Register driver - * @param entityGrpc GrpcDriverRegisterDTO - */ - DriverBO registerDriver(GrpcDriverRegisterDTO entityGrpc); + /** + * Register driver + * + * @param entityGrpc GrpcDriverRegisterDTO + */ + DriverBO registerDriver(GrpcDriverRegisterDTO entityGrpc); - /** - * Register driver attributes - * @param entityGrpc GrpcDriverRegisterDTO - * @param entityBO DriverBO - */ - List registerDriverAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO); + /** + * Register driver attributes + * + * @param entityGrpc GrpcDriverRegisterDTO + * @param entityBO DriverBO + */ + List registerDriverAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO); - /** - * Register point attributes - * @param entityGrpc GrpcDriverRegisterDTO - * @param entityBO DriverBO - */ - List registerPointAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO); + /** + * Register point attributes + * + * @param entityGrpc GrpcDriverRegisterDTO + * @param entityBO DriverBO + */ + List registerPointAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ImportDeviceService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ImportDeviceService.java index 59796bbd5..68543336e 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ImportDeviceService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ImportDeviceService.java @@ -34,16 +34,17 @@ import java.util.List; */ public interface ImportDeviceService { - /** - * Import device - * @param deviceBO Device - * @param pointBOList Point list - * @param driverAttributeBOList Driver attribute config list - * @param pointAttributeBOList Point attribute config list - * @param sheet Sheet - * @param row Row Index - */ - DeviceBO importDevice(DeviceBO deviceBO, List pointBOList, List driverAttributeBOList, - List pointAttributeBOList, Sheet sheet, int row); + /** + * Import device + * + * @param deviceBO Device + * @param pointBOList Point list + * @param driverAttributeBOList Driver attribute config list + * @param pointAttributeBOList Point attribute config list + * @param sheet Sheet + * @param row Row Index + */ + DeviceBO importDevice(DeviceBO deviceBO, List pointBOList, List driverAttributeBOList, + List pointAttributeBOList, Sheet sheet, int row); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ScheduleForManagerService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ScheduleForManagerService.java index 03bbd9de6..1d3ebdf4d 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ScheduleForManagerService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/ScheduleForManagerService.java @@ -24,9 +24,9 @@ package io.github.pnoker.common.manager.biz; */ public interface ScheduleForManagerService { - /** - * Initialize the scheduling task for manager - */ - void initial(); + /** + * Initialize the scheduling task for manager + */ + void initial(); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DictionaryForManagerServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DictionaryForManagerServiceImpl.java index 8dc9d147a..fb9f9348a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DictionaryForManagerServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DictionaryForManagerServiceImpl.java @@ -46,112 +46,112 @@ import java.util.Objects; @Service public class DictionaryForManagerServiceImpl implements DictionaryForManagerService { - @Resource - private DictionaryForManagerBuilder dictionaryBuilder; + @Resource + private DictionaryForManagerBuilder dictionaryBuilder; - @Resource - private DriverService driverService; + @Resource + private DriverService driverService; - @Resource - private ProfileService profileService; + @Resource + private ProfileService profileService; - @Resource - private DeviceService deviceService; + @Resource + private DeviceService deviceService; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Override - public Page driverDictionary(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page driverDictionary(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - DriverQuery driverQuery = DriverQuery.builder() - .page(entityQuery.getPage()) - .driverName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page driverPageBO = driverService.selectByPage(driverQuery); - return dictionaryBuilder.buildVOPageByDriverBOPage(driverPageBO); - } + DriverQuery driverQuery = DriverQuery.builder() + .page(entityQuery.getPage()) + .driverName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page driverPageBO = driverService.selectByPage(driverQuery); + return dictionaryBuilder.buildVOPageByDriverBOPage(driverPageBO); + } - @Override - public Page profileDictionary(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page profileDictionary(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - ProfileQuery profileQuery = ProfileQuery.builder() - .page(entityQuery.getPage()) - .profileName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page profilePageBO = profileService.selectByPage(profileQuery); - return dictionaryBuilder.buildVOPageByProfileBOPage(profilePageBO); - } + ProfileQuery profileQuery = ProfileQuery.builder() + .page(entityQuery.getPage()) + .profileName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page profilePageBO = profileService.selectByPage(profileQuery); + return dictionaryBuilder.buildVOPageByProfileBOPage(profilePageBO); + } - @Override - public Page pointDictionaryForProfile(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page pointDictionaryForProfile(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - PointQuery pointQuery = PointQuery.builder() - .page(entityQuery.getPage()) - .profileId(entityQuery.getParentId()) - .pointName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page pointPageBO = pointService.selectByPage(pointQuery); - return dictionaryBuilder.buildVOPageByPointBOPage(pointPageBO); - } + PointQuery pointQuery = PointQuery.builder() + .page(entityQuery.getPage()) + .profileId(entityQuery.getParentId()) + .pointName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page pointPageBO = pointService.selectByPage(pointQuery); + return dictionaryBuilder.buildVOPageByPointBOPage(pointPageBO); + } - @Override - public Page pointDictionaryForDevice(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page pointDictionaryForDevice(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - PointQuery pointQuery = PointQuery.builder() - .page(entityQuery.getPage()) - .deviceId(entityQuery.getParentId()) - .pointName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page pointPageBO = pointService.selectByPage(pointQuery); - return dictionaryBuilder.buildVOPageByPointBOPage(pointPageBO); - } + PointQuery pointQuery = PointQuery.builder() + .page(entityQuery.getPage()) + .deviceId(entityQuery.getParentId()) + .pointName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page pointPageBO = pointService.selectByPage(pointQuery); + return dictionaryBuilder.buildVOPageByPointBOPage(pointPageBO); + } - @Override - public Page deviceDictionary(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page deviceDictionary(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - DeviceQuery deviceQuery = DeviceQuery.builder() - .page(entityQuery.getPage()) - .deviceName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page devicePageBO = deviceService.selectByPage(deviceQuery); - return dictionaryBuilder.buildVOPageByDeviceBOPage(devicePageBO); - } + DeviceQuery deviceQuery = DeviceQuery.builder() + .page(entityQuery.getPage()) + .deviceName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page devicePageBO = deviceService.selectByPage(deviceQuery); + return dictionaryBuilder.buildVOPageByDeviceBOPage(devicePageBO); + } - @Override - public Page deviceDictionaryForDriver(DictionaryQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } + @Override + public Page deviceDictionaryForDriver(DictionaryQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } - DeviceQuery deviceQuery = DeviceQuery.builder() - .page(entityQuery.getPage()) - .driverId(entityQuery.getParentId()) - .deviceName(entityQuery.getLabel()) - .tenantId(entityQuery.getTenantId()) - .build(); - Page devicePageBO = deviceService.selectByPage(deviceQuery); - return dictionaryBuilder.buildVOPageByDeviceBOPage(devicePageBO); - } + DeviceQuery deviceQuery = DeviceQuery.builder() + .page(entityQuery.getPage()) + .driverId(entityQuery.getParentId()) + .deviceName(entityQuery.getLabel()) + .tenantId(entityQuery.getTenantId()) + .build(); + Page devicePageBO = deviceService.selectByPage(deviceQuery); + return dictionaryBuilder.buildVOPageByDeviceBOPage(devicePageBO); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DriverRegisterServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DriverRegisterServiceImpl.java index 235fd9b42..cbc35aecb 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DriverRegisterServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/DriverRegisterServiceImpl.java @@ -54,132 +54,129 @@ import java.util.stream.Collectors; @Service public class DriverRegisterServiceImpl implements DriverRegisterService { - private final GrpcDriverBuilder grpcDriverBuilder; + private final GrpcDriverBuilder grpcDriverBuilder; - private final GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; + private final GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; - private final GrpcPointAttributeBuilder grpcPointAttributeBuilder; + private final GrpcPointAttributeBuilder grpcPointAttributeBuilder; - private final DriverService driverService; + private final DriverService driverService; - private final DriverAttributeService driverAttributeService; + private final DriverAttributeService driverAttributeService; - private final PointAttributeService pointAttributeService; + private final PointAttributeService pointAttributeService; - private final TenantFacade tenantFacade; + private final TenantFacade tenantFacade; - public DriverRegisterServiceImpl(GrpcDriverBuilder grpcDriverBuilder, - GrpcDriverAttributeBuilder grpcDriverAttributeBuilder, GrpcPointAttributeBuilder grpcPointAttributeBuilder, - DriverService driverService, DriverAttributeService driverAttributeService, - PointAttributeService pointAttributeService, TenantFacade tenantFacade) { - this.grpcDriverBuilder = grpcDriverBuilder; - this.grpcDriverAttributeBuilder = grpcDriverAttributeBuilder; - this.grpcPointAttributeBuilder = grpcPointAttributeBuilder; - this.driverService = driverService; - this.driverAttributeService = driverAttributeService; - this.pointAttributeService = pointAttributeService; - this.tenantFacade = tenantFacade; - } + public DriverRegisterServiceImpl(GrpcDriverBuilder grpcDriverBuilder, + GrpcDriverAttributeBuilder grpcDriverAttributeBuilder, GrpcPointAttributeBuilder grpcPointAttributeBuilder, + DriverService driverService, DriverAttributeService driverAttributeService, + PointAttributeService pointAttributeService, TenantFacade tenantFacade) { + this.grpcDriverBuilder = grpcDriverBuilder; + this.grpcDriverAttributeBuilder = grpcDriverAttributeBuilder; + this.grpcPointAttributeBuilder = grpcPointAttributeBuilder; + this.driverService = driverService; + this.driverAttributeService = driverAttributeService; + this.pointAttributeService = pointAttributeService; + this.tenantFacade = tenantFacade; + } - @Override - public DriverBO registerDriver(GrpcDriverRegisterDTO entityGrpc) { - FacadeTenantBO tenant = tenantFacade.selectByCode(entityGrpc.getTenant()); - if (Objects.isNull(tenant)) { - throw new ServiceException("Tenant[{}] information is invalid", entityGrpc.getTenant()); - } + @Override + public DriverBO registerDriver(GrpcDriverRegisterDTO entityGrpc) { + FacadeTenantBO tenant = tenantFacade.selectByCode(entityGrpc.getTenant()); + if (Objects.isNull(tenant)) { + throw new ServiceException("Tenant[{}] information is invalid", entityGrpc.getTenant()); + } - DriverBO driverBO = grpcDriverBuilder.buildBOByGrpcDTO(entityGrpc.getDriver()); - Objects.requireNonNull(driverBO).setTenantId(tenant.getId()); - DriverBO entityBO = driverService.selectByServiceName(driverBO.getServiceName(), driverBO.getTenantId()); - if (Objects.nonNull(entityBO)) { - log.info("The driver has been registered, perform update: {}", JsonUtil.toJsonString(driverBO)); - driverBO.setId(entityBO.getId()); - driverService.update(driverBO); - } - else { - log.info("The driver is not registered, perform new addition: {}", JsonUtil.toJsonString(driverBO)); - driverService.save(driverBO); - } + DriverBO driverBO = grpcDriverBuilder.buildBOByGrpcDTO(entityGrpc.getDriver()); + Objects.requireNonNull(driverBO).setTenantId(tenant.getId()); + DriverBO entityBO = driverService.selectByServiceName(driverBO.getServiceName(), driverBO.getTenantId()); + if (Objects.nonNull(entityBO)) { + log.info("The driver has been registered, perform update: {}", JsonUtil.toJsonString(driverBO)); + driverBO.setId(entityBO.getId()); + driverService.update(driverBO); + } else { + log.info("The driver is not registered, perform new addition: {}", JsonUtil.toJsonString(driverBO)); + driverService.save(driverBO); + } - return driverService.selectByServiceName(driverBO.getServiceName(), driverBO.getTenantId()); - } + return driverService.selectByServiceName(driverBO.getServiceName(), driverBO.getTenantId()); + } - @Override - public List registerDriverAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO) { - Map newDriverAttributeMap = entityGrpc.getDriverAttributesList() - .stream() - .collect(Collectors.toMap(GrpcDriverAttributeDTO::getAttributeCode, - grpcDriverAttributeBuilder::buildBOByGrpcDTO)); + @Override + public List registerDriverAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO) { + Map newDriverAttributeMap = entityGrpc.getDriverAttributesList() + .stream() + .collect(Collectors.toMap(GrpcDriverAttributeDTO::getAttributeCode, + grpcDriverAttributeBuilder::buildBOByGrpcDTO)); - Map oldDriverAttributeMap = driverAttributeService.selectByDriverId(entityBO.getId()) - .stream() - .collect(Collectors.toMap(DriverAttributeBO::getAttributeCode, Function.identity())); + Map oldDriverAttributeMap = driverAttributeService.selectByDriverId(entityBO.getId()) + .stream() + .collect(Collectors.toMap(DriverAttributeBO::getAttributeCode, Function.identity())); - for (Map.Entry entry : newDriverAttributeMap.entrySet()) { - String name = entry.getKey(); - DriverAttributeBO attribute = newDriverAttributeMap.get(name); - attribute.setDriverId(entityBO.getId()); - if (oldDriverAttributeMap.containsKey(name)) { - log.debug("The driver attributes have been registered, update is performed: {}", - JsonUtil.toJsonString(attribute)); - attribute.setId(oldDriverAttributeMap.get(name).getId()); - driverAttributeService.update(attribute); - } - else { - log.debug("The driver attributes are not registered, perform new addition: {}", - JsonUtil.toJsonString(attribute)); - driverAttributeService.save(attribute); - } - } + for (Map.Entry entry : newDriverAttributeMap.entrySet()) { + String name = entry.getKey(); + DriverAttributeBO attribute = newDriverAttributeMap.get(name); + attribute.setDriverId(entityBO.getId()); + if (oldDriverAttributeMap.containsKey(name)) { + log.debug("The driver attributes have been registered, update is performed: {}", + JsonUtil.toJsonString(attribute)); + attribute.setId(oldDriverAttributeMap.get(name).getId()); + driverAttributeService.update(attribute); + } else { + log.debug("The driver attributes are not registered, perform new addition: {}", + JsonUtil.toJsonString(attribute)); + driverAttributeService.save(attribute); + } + } - for (Map.Entry entry : oldDriverAttributeMap.entrySet()) { - String name = entry.getKey(); - if (!newDriverAttributeMap.containsKey(name)) { - log.debug("Driver attribute is redundant, deleting: {}", oldDriverAttributeMap.get(name)); - driverAttributeService.remove(oldDriverAttributeMap.get(name).getId()); - } - } + for (Map.Entry entry : oldDriverAttributeMap.entrySet()) { + String name = entry.getKey(); + if (!newDriverAttributeMap.containsKey(name)) { + log.debug("Driver attribute is redundant, deleting: {}", oldDriverAttributeMap.get(name)); + driverAttributeService.remove(oldDriverAttributeMap.get(name).getId()); + } + } - return driverAttributeService.selectByDriverId(entityBO.getId()); - } + return driverAttributeService.selectByDriverId(entityBO.getId()); + } - @Override - public List registerPointAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO) { - Map newPointAttributeMap = entityGrpc.getPointAttributesList() - .stream() - .collect(Collectors.toMap(GrpcPointAttributeDTO::getAttributeCode, - grpcPointAttributeBuilder::buildBOByGrpcDTO)); + @Override + public List registerPointAttribute(GrpcDriverRegisterDTO entityGrpc, DriverBO entityBO) { + Map newPointAttributeMap = entityGrpc.getPointAttributesList() + .stream() + .collect(Collectors.toMap(GrpcPointAttributeDTO::getAttributeCode, + grpcPointAttributeBuilder::buildBOByGrpcDTO)); - Map oldPointAttributeMap = pointAttributeService.selectByDriverId(entityBO.getId()) - .stream() - .collect(Collectors.toMap(PointAttributeBO::getAttributeCode, Function.identity())); + Map oldPointAttributeMap = pointAttributeService.selectByDriverId(entityBO.getId()) + .stream() + .collect(Collectors.toMap(PointAttributeBO::getAttributeCode, Function.identity())); - for (Map.Entry entry : newPointAttributeMap.entrySet()) { - String name = entry.getKey(); - PointAttributeBO attribute = newPointAttributeMap.get(name); - attribute.setDriverId(entityBO.getId()); - if (oldPointAttributeMap.containsKey(name)) { - log.debug("The point attribute has been registered, update is performed: {}", - JsonUtil.toJsonString(attribute)); - attribute.setId(oldPointAttributeMap.get(name).getId()); - pointAttributeService.update(attribute); - } - else { - log.debug("The point attribute is not registered, perform update: {}", - JsonUtil.toJsonString(attribute)); - pointAttributeService.save(attribute); - } - } + for (Map.Entry entry : newPointAttributeMap.entrySet()) { + String name = entry.getKey(); + PointAttributeBO attribute = newPointAttributeMap.get(name); + attribute.setDriverId(entityBO.getId()); + if (oldPointAttributeMap.containsKey(name)) { + log.debug("The point attribute has been registered, update is performed: {}", + JsonUtil.toJsonString(attribute)); + attribute.setId(oldPointAttributeMap.get(name).getId()); + pointAttributeService.update(attribute); + } else { + log.debug("The point attribute is not registered, perform update: {}", + JsonUtil.toJsonString(attribute)); + pointAttributeService.save(attribute); + } + } - for (Map.Entry entry : oldPointAttributeMap.entrySet()) { - String name = entry.getKey(); - if (!newPointAttributeMap.containsKey(name)) { - log.debug("Point attribute is redundant, deleting: {}", oldPointAttributeMap.get(name)); - pointAttributeService.remove(oldPointAttributeMap.get(name).getId()); - } - } + for (Map.Entry entry : oldPointAttributeMap.entrySet()) { + String name = entry.getKey(); + if (!newPointAttributeMap.containsKey(name)) { + log.debug("Point attribute is redundant, deleting: {}", oldPointAttributeMap.get(name)); + pointAttributeService.remove(oldPointAttributeMap.get(name).getId()); + } + } - return pointAttributeService.selectByDriverId(entityBO.getId()); - } + return pointAttributeService.selectByDriverId(entityBO.getId()); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ImportDeviceServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ImportDeviceServiceImpl.java index 10c1d6827..76a676aa3 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ImportDeviceServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ImportDeviceServiceImpl.java @@ -49,130 +49,132 @@ import java.util.List; @Service public class ImportDeviceServiceImpl implements ImportDeviceService { - @Resource - private DeviceBuilder deviceBuilder; + @Resource + private DeviceBuilder deviceBuilder; - @Resource - private DeviceManager deviceManager; + @Resource + private DeviceManager deviceManager; - @Resource - private ProfileBindService profileBindService; + @Resource + private ProfileBindService profileBindService; - @Resource - private DriverAttributeConfigService driverAttributeConfigService; + @Resource + private DriverAttributeConfigService driverAttributeConfigService; - @Resource - private PointAttributeConfigService pointAttributeConfigService; + @Resource + private PointAttributeConfigService pointAttributeConfigService; - @Override - @Transactional - public DeviceBO importDevice(DeviceBO deviceBO, List pointBOList, - List driverAttributeBOList, List pointAttributeBOList, Sheet sheet, - int row) { - String deviceName = PoiUtil.getCellStringValue(sheet, row, 0); - if (StringUtils.isEmpty(deviceName)) { - throw new ImportException("The device name in line {} of the import file is empty", row + 1); - } + @Override + @Transactional + public DeviceBO importDevice(DeviceBO deviceBO, List pointBOList, + List driverAttributeBOList, List pointAttributeBOList, Sheet sheet, + int row) { + String deviceName = PoiUtil.getCellStringValue(sheet, row, 0); + if (StringUtils.isEmpty(deviceName)) { + throw new ImportException("The device name in line {} of the import file is empty", row + 1); + } - DeviceDO entityDO = new DeviceDO(); - entityDO.setDeviceName(deviceName); - entityDO.setDriverId(deviceBO.getDriverId()); - String deviceRemark = PoiUtil.getCellStringValue(sheet, row, 1); - entityDO.setDeviceExt(new JsonExt()); - entityDO.setRemark(deviceRemark); - entityDO.setTenantId(deviceBO.getTenantId()); + DeviceDO entityDO = new DeviceDO(); + entityDO.setDeviceName(deviceName); + entityDO.setDriverId(deviceBO.getDriverId()); + String deviceRemark = PoiUtil.getCellStringValue(sheet, row, 1); + entityDO.setDeviceExt(new JsonExt()); + entityDO.setRemark(deviceRemark); + entityDO.setTenantId(deviceBO.getTenantId()); - // Import device - entityDO = deviceManager.innerSave(entityDO); - DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); + // Import device + entityDO = deviceManager.innerSave(entityDO); + DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); - // Import device profile binding configuration - importProfileBind(entityBO, deviceBO.getProfileIds()); + // Import device profile binding configuration + importProfileBind(entityBO, deviceBO.getProfileIds()); - // Import driver attribute configuration - importDriverAttributeConfig(entityBO, driverAttributeBOList, sheet, row); + // Import driver attribute configuration + importDriverAttributeConfig(entityBO, driverAttributeBOList, sheet, row); - // Import point attribute configuration - importPointAttributeConfig(entityBO, pointBOList, driverAttributeBOList, pointAttributeBOList, sheet, row); + // Import point attribute configuration + importPointAttributeConfig(entityBO, pointBOList, driverAttributeBOList, pointAttributeBOList, sheet, row); - return entityBO; - } + return entityBO; + } - /** - * Import device profile binding configuration - * @param deviceBO Device - * @param profileIds Profile ID list - */ - private void importProfileBind(DeviceBO deviceBO, List profileIds) { - if (CollectionUtils.isEmpty(profileIds)) { - return; - } + /** + * Import device profile binding configuration + * + * @param deviceBO Device + * @param profileIds Profile ID list + */ + private void importProfileBind(DeviceBO deviceBO, List profileIds) { + if (CollectionUtils.isEmpty(profileIds)) { + return; + } - profileIds.forEach(profileId -> { - try { - ProfileBindBO entityBO = new ProfileBindBO(); - entityBO.setProfileId(profileId); - entityBO.setDeviceId(deviceBO.getId()); - entityBO.setTenantId(deviceBO.getTenantId()); - profileBindService.save(entityBO); - } - catch (Exception ignored) { - // nothing to do - } - }); + profileIds.forEach(profileId -> { + try { + ProfileBindBO entityBO = new ProfileBindBO(); + entityBO.setProfileId(profileId); + entityBO.setDeviceId(deviceBO.getId()); + entityBO.setTenantId(deviceBO.getTenantId()); + profileBindService.save(entityBO); + } catch (Exception ignored) { + // nothing to do + } + }); - } + } - /** - * Import driver attribute configuration - * @param deviceBO Device - * @param driverAttributeBOList DriverAttributeBO Array - * @param sheet Sheet - * @param row Row Index - */ - private void importDriverAttributeConfig(DeviceBO deviceBO, List driverAttributeBOList, - Sheet sheet, int row) { - for (int j = 0; j < driverAttributeBOList.size(); j++) { - DriverAttributeConfigBO entityBO = new DriverAttributeConfigBO(); - DriverAttributeBO driverAttributeBO = driverAttributeBOList.get(j); - entityBO.setAttributeId(driverAttributeBO.getId()); - entityBO.setDeviceId(deviceBO.getId()); - String attributeValue = PoiUtil.getCellStringValue(sheet, row, 2 + j); - entityBO.setConfigValue(attributeValue); - entityBO.setRemark(deviceBO.getRemark()); - entityBO.setTenantId(deviceBO.getTenantId()); - driverAttributeConfigService.innerSave(entityBO); - } - } + /** + * Import driver attribute configuration + * + * @param deviceBO Device + * @param driverAttributeBOList DriverAttributeBO Array + * @param sheet Sheet + * @param row Row Index + */ + private void importDriverAttributeConfig(DeviceBO deviceBO, List driverAttributeBOList, + Sheet sheet, int row) { + for (int j = 0; j < driverAttributeBOList.size(); j++) { + DriverAttributeConfigBO entityBO = new DriverAttributeConfigBO(); + DriverAttributeBO driverAttributeBO = driverAttributeBOList.get(j); + entityBO.setAttributeId(driverAttributeBO.getId()); + entityBO.setDeviceId(deviceBO.getId()); + String attributeValue = PoiUtil.getCellStringValue(sheet, row, 2 + j); + entityBO.setConfigValue(attributeValue); + entityBO.setRemark(deviceBO.getRemark()); + entityBO.setTenantId(deviceBO.getTenantId()); + driverAttributeConfigService.innerSave(entityBO); + } + } - /** - * Import point attribute configuration - * @param deviceBO Device - * @param driverAttributeBOList DriverAttributeBO Array - * @param pointAttributeBOList PointAttributeBO Array - * @param pointBOList PointBO Array - * @param sheet Sheet - * @param row Row Index - */ - private void importPointAttributeConfig(DeviceBO deviceBO, List pointBOList, - List driverAttributeBOList, List pointAttributeBOList, Sheet sheet, - int row) { - for (int j = 0; j < pointBOList.size(); j++) { - for (int k = 0; k < pointAttributeBOList.size(); k++) { - PointAttributeConfigBO entityBO = new PointAttributeConfigBO(); - PointBO pointBO = pointBOList.get(j); - PointAttributeBO pointAttributeBO = pointAttributeBOList.get(k); - entityBO.setAttributeId(pointAttributeBO.getId()); - entityBO.setDeviceId(deviceBO.getId()); - entityBO.setPointId(pointBO.getId()); - String attributeValue = PoiUtil.getCellStringValue(sheet, row, - 2 + driverAttributeBOList.size() + k * pointAttributeBOList.size() + j); - entityBO.setConfigValue(attributeValue); - entityBO.setRemark(deviceBO.getRemark()); - entityBO.setTenantId(deviceBO.getTenantId()); - pointAttributeConfigService.innerSave(entityBO); - } - } - } + /** + * Import point attribute configuration + * + * @param deviceBO Device + * @param driverAttributeBOList DriverAttributeBO Array + * @param pointAttributeBOList PointAttributeBO Array + * @param pointBOList PointBO Array + * @param sheet Sheet + * @param row Row Index + */ + private void importPointAttributeConfig(DeviceBO deviceBO, List pointBOList, + List driverAttributeBOList, List pointAttributeBOList, Sheet sheet, + int row) { + for (int j = 0; j < pointBOList.size(); j++) { + for (int k = 0; k < pointAttributeBOList.size(); k++) { + PointAttributeConfigBO entityBO = new PointAttributeConfigBO(); + PointBO pointBO = pointBOList.get(j); + PointAttributeBO pointAttributeBO = pointAttributeBOList.get(k); + entityBO.setAttributeId(pointAttributeBO.getId()); + entityBO.setDeviceId(deviceBO.getId()); + entityBO.setPointId(pointBO.getId()); + String attributeValue = PoiUtil.getCellStringValue(sheet, row, + 2 + driverAttributeBOList.size() + k * pointAttributeBOList.size() + j); + entityBO.setConfigValue(attributeValue); + entityBO.setRemark(deviceBO.getRemark()); + entityBO.setTenantId(deviceBO.getTenantId()); + pointAttributeConfigService.innerSave(entityBO); + } + } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ScheduleForManagerServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ScheduleForManagerServiceImpl.java index 3ed34b323..a2551dee4 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ScheduleForManagerServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/biz/impl/ScheduleForManagerServiceImpl.java @@ -35,21 +35,20 @@ import org.springframework.stereotype.Service; @Service public class ScheduleForManagerServiceImpl implements ScheduleForManagerService { - @Resource - private QuartzService quartzService; + @Resource + private QuartzService quartzService; - @Override - public void initial() { - try { - // Custom schedule - quartzService.createJobWithCron(ScheduleConstant.MANAGER_SCHEDULE_GROUP, "hourly-job", "0 0 0/1 * * ?", - HourlyJobForManager.class); + @Override + public void initial() { + try { + // Custom schedule + quartzService.createJobWithCron(ScheduleConstant.MANAGER_SCHEDULE_GROUP, "hourly-job", "0 0 0/1 * * ?", + HourlyJobForManager.class); - quartzService.startScheduler(); - } - catch (SchedulerException e) { - log.error(e.getMessage(), e); - } - } + quartzService.startScheduler(); + } catch (SchedulerException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/constant/TopologyLimits.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/constant/TopologyLimits.java index f20655508..9489aff27 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/constant/TopologyLimits.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/constant/TopologyLimits.java @@ -28,53 +28,53 @@ package io.github.pnoker.common.manager.constant; */ public final class TopologyLimits { - public static final int TOP_DRIVERS = 10; + public static final int TOP_DRIVERS = 10; - // ===== Top-N caps ============================================== - // Orders of magnitude: worst-case nodes ≈ - // TOP_DRIVERS + TOP_DEVICES + |bound profiles| + - // (TOP_POINTS_PER_PROFILE × |bound profiles|) + Others - // ≈ 10 + 20 + ~30 + 15×30 + ~20 ≈ 530 (G2 sankey comfortable). - public static final int TOP_DEVICES = 20; + // ===== Top-N caps ============================================== + // Orders of magnitude: worst-case nodes ≈ + // TOP_DRIVERS + TOP_DEVICES + |bound profiles| + + // (TOP_POINTS_PER_PROFILE × |bound profiles|) + Others + // ≈ 10 + 20 + ~30 + 15×30 + ~20 ≈ 530 (G2 sankey comfortable). + public static final int TOP_DEVICES = 20; - public static final int TOP_POINTS_PER_PROFILE = 15; + public static final int TOP_POINTS_PER_PROFILE = 15; - public static final String MODE_VOLUME = "volume"; + public static final String MODE_VOLUME = "volume"; - // ===== Modes ================================================== - public static final String MODE_CARDINALITY = "cardinality"; + // ===== Modes ================================================== + public static final String MODE_CARDINALITY = "cardinality"; - public static final String RANGE_TODAY = "today"; + public static final String RANGE_TODAY = "today"; - // ===== Range keys ============================================= - public static final String RANGE_24H = "24h"; + // ===== Range keys ============================================= + public static final String RANGE_24H = "24h"; - public static final String RANGE_7D = "7d"; + public static final String RANGE_7D = "7d"; - public static final String RANGE_30D = "30d"; + public static final String RANGE_30D = "30d"; - public static final String RANGE_DEFAULT = RANGE_7D; + public static final String RANGE_DEFAULT = RANGE_7D; - /** - * Short TTL — wide enough to coalesce refresh bursts, narrow enough that metadata - * edits surface on the next natural poll. - */ - public static final int CACHE_TTL_SECONDS = 60; + /** + * Short TTL — wide enough to coalesce refresh bursts, narrow enough that metadata + * edits surface on the next natural poll. + */ + public static final int CACHE_TTL_SECONDS = 60; - // ===== Cache config =========================================== - /** - * Cap on cache entries = (tenant × mode × rangeKey) triples held. - */ - public static final int CACHE_MAX_SIZE = 200; + // ===== Cache config =========================================== + /** + * Cap on cache entries = (tenant × mode × rangeKey) triples held. + */ + public static final int CACHE_MAX_SIZE = 200; - // ===== Fallback bucket keys ================================== - // Returned when an enum lookup fails (EnableFlagEnum.ofIndex(null) → null, - // or unknown driver_type_flag int). Frontend matches this on a localised - // label lookup — it's a stable dictionary token, not user-visible copy. - public static final String UNKNOWN_BUCKET = "UNKNOWN"; + // ===== Fallback bucket keys ================================== + // Returned when an enum lookup fails (EnableFlagEnum.ofIndex(null) → null, + // or unknown driver_type_flag int). Frontend matches this on a localised + // label lookup — it's a stable dictionary token, not user-visible copy. + public static final String UNKNOWN_BUCKET = "UNKNOWN"; - private TopologyLimits() { - // utility class — never instantiated - } + private TopologyLimits() { + // utility class — never instantiated + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DashboardController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DashboardController.java index 278f435d7..53aff60c5 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DashboardController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DashboardController.java @@ -49,80 +49,76 @@ import reactor.core.publisher.Mono; @RequestMapping(ManagerConstant.DASHBOARD_URL_PREFIX) public class DashboardController implements BaseController { - private final DashboardService dashboardService; + private final DashboardService dashboardService; - public DashboardController(DashboardService dashboardService) { - this.dashboardService = dashboardService; - } + public DashboardController(DashboardService dashboardService) { + this.dashboardService = dashboardService; + } - @GetMapping("/driver/stats") - public Mono> driverStats() { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.driverStats(tenantId))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/driver/stats") + public Mono> driverStats() { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.driverStats(tenantId))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - @GetMapping("/device/stats") - public Mono> deviceStats(@RequestParam(value = "topN", defaultValue = "10") int topN) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.deviceStats(tenantId, topN))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + @GetMapping("/device/stats") + public Mono> deviceStats(@RequestParam(value = "topN", defaultValue = "10") int topN) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.deviceStats(tenantId, topN))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Daily new-row counts for driver / device / point / profile tables over the last - * {@code days} days. Backs the stat-card sparklines. Returns fixed-length zero-padded - * arrays so the frontend never has to reason about missing days. - */ - @GetMapping("/growth") - public Mono> dailyGrowth(@RequestParam(value = "days", defaultValue = "7") int days) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.dailyGrowth(tenantId, days))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Daily new-row counts for driver / device / point / profile tables over the last + * {@code days} days. Backs the stat-card sparklines. Returns fixed-length zero-padded + * arrays so the frontend never has to reason about missing days. + */ + @GetMapping("/growth") + public Mono> dailyGrowth(@RequestParam(value = "days", defaultValue = "7") int days) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.dailyGrowth(tenantId, days))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Four-column Sankey topology (Driver → Device → Profile → Point). - * {@code mode=cardinality} is the Phase 0 default and counts relationships along each - * edge; future {@code mode=volume} will weight edges by point_value sample counts - * over {@code rangeKey}. - * - *

- * Top-N cropping is server-side — each cropped slice becomes an {@code others:*} - * pseudo-node with a {@code hiddenChildren} payload the frontend pops in a drill-in - * dialog. - *

- */ - @GetMapping("/topology") - public Mono> topology(@RequestParam(value = "mode", defaultValue = "cardinality") String mode, - @RequestParam(value = "rangeKey", required = false) String rangeKey) { - return getTenantId().flatMap(tenantId -> { - try { - return Mono.just(R.ok(dashboardService.topology(tenantId, mode, rangeKey))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Four-column Sankey topology (Driver → Device → Profile → Point). + * {@code mode=cardinality} is the Phase 0 default and counts relationships along each + * edge; future {@code mode=volume} will weight edges by point_value sample counts + * over {@code rangeKey}. + * + *

+ * Top-N cropping is server-side — each cropped slice becomes an {@code others:*} + * pseudo-node with a {@code hiddenChildren} payload the frontend pops in a drill-in + * dialog. + *

+ */ + @GetMapping("/topology") + public Mono> topology(@RequestParam(value = "mode", defaultValue = "cardinality") String mode, + @RequestParam(value = "rangeKey", required = false) String rangeKey) { + return getTenantId().flatMap(tenantId -> { + try { + return Mono.just(R.ok(dashboardService.topology(tenantId, mode, rangeKey))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DeviceController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DeviceController.java index 1ff859e06..805113228 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DeviceController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DeviceController.java @@ -60,184 +60,181 @@ import java.util.stream.Collectors; @RequestMapping(ManagerConstant.DEVICE_URL_PREFIX) public class DeviceController implements BaseController { - private final DeviceBuilder deviceBuilder; + private final DeviceBuilder deviceBuilder; - private final DeviceService deviceService; + private final DeviceService deviceService; - public DeviceController(DeviceBuilder deviceBuilder, DeviceService deviceService) { - this.deviceBuilder = deviceBuilder; - this.deviceService = deviceService; - } + public DeviceController(DeviceBuilder deviceBuilder, DeviceService deviceService) { + this.deviceBuilder = deviceBuilder; + this.deviceService = deviceService; + } - /** - * @param entityVO {@link DeviceVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody DeviceVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - deviceService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link DeviceVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody DeviceVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + deviceService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - deviceService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + deviceService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param entityVO {@link DeviceVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody DeviceVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - deviceService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link DeviceVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody DeviceVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + deviceService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Device - * @param id ID - * @return DeviceVO {@link DeviceVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - DeviceBO entityBO = deviceService.selectById(id); - DeviceVO entityVO = deviceBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Device + * + * @param id ID + * @return DeviceVO {@link DeviceVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + DeviceBO entityBO = deviceService.selectById(id); + DeviceVO entityVO = deviceBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Device - * @param deviceIds Device ID - * @return Map(ID, DeviceVO) - */ - @PostMapping("/ids") - public Mono>> selectByIds(@RequestBody List deviceIds) { - try { - List entityBOList = deviceService.selectByIds(deviceIds); - Map deviceMap = entityBOList.stream() - .collect(Collectors.toMap(DeviceBO::getId, entityBO -> deviceBuilder.buildVOByBO(entityBO))); - return Mono.just(R.ok(deviceMap)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Device + * + * @param deviceIds Device ID + * @return Map(ID, DeviceVO) + */ + @PostMapping("/ids") + public Mono>> selectByIds(@RequestBody List deviceIds) { + try { + List entityBOList = deviceService.selectByIds(deviceIds); + Map deviceMap = entityBOList.stream() + .collect(Collectors.toMap(DeviceBO::getId, entityBO -> deviceBuilder.buildVOByBO(entityBO))); + return Mono.just(R.ok(deviceMap)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device - * @param entityQuery - * @return R Of DeviceVO Page - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) DeviceQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DeviceQuery query = Objects.isNull(entityQuery) ? new DeviceQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = deviceService.selectByPage(query); - Page entityPageVO = deviceBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Device + * + * @param entityQuery + * @return R Of DeviceVO Page + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) DeviceQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DeviceQuery query = Objects.isNull(entityQuery) ? new DeviceQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = deviceService.selectByPage(query); + Page entityPageVO = deviceBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Device - * @param entityVO {@link DeviceVO} - * @return R of String - */ - @PostMapping("/import") - public Mono> importDevice(@Validated(Upload.class) DeviceVO entityVO, - @RequestPart("file") Mono filePart) { - return getTenantId().flatMap(tenantId -> { - try { - DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - return filePart.flatMap(part -> { - String filePath = FileUtil.getTempPath() + FileUtil.getRandomXlsxName(); - File file = new File(filePath); - return part.transferTo(file).then(Mono.defer(() -> { - deviceService.importDevice(entityBO, file); - return Mono.just(R.ok()); - })); - }); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Device + * + * @param entityVO {@link DeviceVO} + * @return R of String + */ + @PostMapping("/import") + public Mono> importDevice(@Validated(Upload.class) DeviceVO entityVO, + @RequestPart("file") Mono filePart) { + return getTenantId().flatMap(tenantId -> { + try { + DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + return filePart.flatMap(part -> { + String filePath = FileUtil.getTempPath() + FileUtil.getRandomXlsxName(); + File file = new File(filePath); + return part.transferTo(file).then(Mono.defer(() -> { + deviceService.importDevice(entityBO, file); + return Mono.just(R.ok()); + })); + }); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param entityVO {@link DeviceVO} - * @return - */ - @PostMapping("/export/import_template") - public ResponseEntity importTemplate(@Validated(Upload.class) @RequestBody DeviceVO entityVO) { - DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); - Path filePath = deviceService.generateImportTemplate(entityBO); - return ResponseUtil.responseFile(filePath); - } + /** + * @param entityVO {@link DeviceVO} + * @return + */ + @PostMapping("/export/import_template") + public ResponseEntity importTemplate(@Validated(Upload.class) @RequestBody DeviceVO entityVO) { + DeviceBO entityBO = deviceBuilder.buildBOByVO(entityVO); + Path filePath = deviceService.generateImportTemplate(entityBO); + return ResponseUtil.responseFile(filePath); + } - /** - * @param driverId - * @return - */ - @GetMapping("/getDeviceByDriverId/{driverId}") - public Mono> getDeviceByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - List deviceBOList = deviceService.selectByDriverId(driverId); - return Mono.just(R.ok(String.valueOf(deviceBOList.size()))); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param driverId + * @return + */ + @GetMapping("/getDeviceByDriverId/{driverId}") + public Mono> getDeviceByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + List deviceBOList = deviceService.selectByDriverId(driverId); + return Mono.just(R.ok(String.valueOf(deviceBOList.size()))); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DictionaryForManagerController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DictionaryForManagerController.java index 1cc61ecbf..ab088e045 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DictionaryForManagerController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DictionaryForManagerController.java @@ -49,148 +49,148 @@ import java.util.Objects; @RequestMapping(ManagerConstant.DICTIONARY_URL_PREFIX) public class DictionaryForManagerController implements BaseController { - private final DictionaryForManagerBuilder dictionaryForManagerBuilder; + private final DictionaryForManagerBuilder dictionaryForManagerBuilder; - private final DictionaryForManagerService dictionaryForManagerService; + private final DictionaryForManagerService dictionaryForManagerService; - public DictionaryForManagerController(DictionaryForManagerBuilder dictionaryForManagerBuilder, - DictionaryForManagerService dictionaryForManagerService) { - this.dictionaryForManagerBuilder = dictionaryForManagerBuilder; - this.dictionaryForManagerService = dictionaryForManagerService; - } + public DictionaryForManagerController(DictionaryForManagerBuilder dictionaryForManagerBuilder, + DictionaryForManagerService dictionaryForManagerService) { + this.dictionaryForManagerBuilder = dictionaryForManagerBuilder; + this.dictionaryForManagerService = dictionaryForManagerService; + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/driver") - public Mono>> driverDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.driverDictionary(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/driver") + public Mono>> driverDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.driverDictionary(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/profile") - public Mono>> profileDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.profileDictionary(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/profile") + public Mono>> profileDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.profileDictionary(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/profile_point") - public Mono>> pointDictionaryForProfile( - @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.pointDictionaryForProfile(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/profile_point") + public Mono>> pointDictionaryForProfile( + @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.pointDictionaryForProfile(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/device_point") - public Mono>> pointDictionaryForDevice( - @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.pointDictionaryForDevice(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/device_point") + public Mono>> pointDictionaryForDevice( + @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.pointDictionaryForDevice(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/device") - public Mono>> deviceDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.deviceDictionary(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/device") + public Mono>> deviceDictionary(@RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.deviceDictionary(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Dictionary - * @param entityQuery {@link DictionaryQuery} - * @return R Of DictionaryVO Page - */ - @PostMapping("/driver_device") - public Mono>> deviceDictionaryForDriver( - @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = dictionaryForManagerService.deviceDictionaryForDriver(query); - Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Dictionary + * + * @param entityQuery {@link DictionaryQuery} + * @return R Of DictionaryVO Page + */ + @PostMapping("/driver_device") + public Mono>> deviceDictionaryForDriver( + @Validated(Parent.class) @RequestBody(required = false) DictionaryQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DictionaryQuery query = Objects.isNull(entityQuery) ? new DictionaryQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = dictionaryForManagerService.deviceDictionaryForDriver(query); + Page entityPageVO = dictionaryForManagerBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeConfigController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeConfigController.java index ff24f7304..b4a43d0b5 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeConfigController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeConfigController.java @@ -50,157 +50,157 @@ import java.util.Objects; @RequestMapping(ManagerConstant.DRIVER_ATTRIBUTE_CONFIG_URL_PREFIX) public class DriverAttributeConfigController implements BaseController { - private final DriverAttributeConfigBuilder driverAttributeConfigBuilder; + private final DriverAttributeConfigBuilder driverAttributeConfigBuilder; - private final DriverAttributeConfigService driverAttributeConfigService; + private final DriverAttributeConfigService driverAttributeConfigService; - public DriverAttributeConfigController(DriverAttributeConfigBuilder driverAttributeConfigBuilder, - DriverAttributeConfigService driverAttributeConfigService) { - this.driverAttributeConfigBuilder = driverAttributeConfigBuilder; - this.driverAttributeConfigService = driverAttributeConfigService; - } + public DriverAttributeConfigController(DriverAttributeConfigBuilder driverAttributeConfigBuilder, + DriverAttributeConfigService driverAttributeConfigService) { + this.driverAttributeConfigBuilder = driverAttributeConfigBuilder; + this.driverAttributeConfigService = driverAttributeConfigService; + } - /** - * DriverConfig - * @param entityVO {@link DriverAttributeConfigVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody DriverAttributeConfigVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeConfigBO entityBO = driverAttributeConfigBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverAttributeConfigService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverConfig + * + * @param entityVO {@link DriverAttributeConfigVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody DriverAttributeConfigVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeConfigBO entityBO = driverAttributeConfigBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverAttributeConfigService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID DriverConfig - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - driverAttributeConfigService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID DriverConfig + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + driverAttributeConfigService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * DriverConfig - * @param entityVO {@link DriverAttributeConfigVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody DriverAttributeConfigVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeConfigBO entityBO = driverAttributeConfigBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverAttributeConfigService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverConfig + * + * @param entityVO {@link DriverAttributeConfigVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody DriverAttributeConfigVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeConfigBO entityBO = driverAttributeConfigBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverAttributeConfigService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID DriverConfig - * @param id ID - * @return DriverAttributeConfigVO {@link DriverAttributeConfigVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - DriverAttributeConfigBO entityBO = driverAttributeConfigService.selectById(id); - DriverAttributeConfigVO entityVO = driverAttributeConfigBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID DriverConfig + * + * @param id ID + * @return DriverAttributeConfigVO {@link DriverAttributeConfigVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + DriverAttributeConfigBO entityBO = driverAttributeConfigService.selectById(id); + DriverAttributeConfigVO entityVO = driverAttributeConfigBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Device ID DriverConfig - * @param attributeId Attribute ID - * @param deviceId Device ID - * @return DriverConfig - */ - @GetMapping("/device_id/{deviceId}/attribute_id/{attributeId}") - public Mono> selectByDeviceIdAndAttributeId( - @NotNull @PathVariable(value = "deviceId") Long deviceId, - @NotNull @PathVariable(value = "attributeId") Long attributeId) { - try { - DriverAttributeConfigBO entityBO = driverAttributeConfigService.selectByAttributeIdAndDeviceId(deviceId, - attributeId); - DriverAttributeConfigVO entityVO = driverAttributeConfigBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Device ID DriverConfig + * + * @param attributeId Attribute ID + * @param deviceId Device ID + * @return DriverConfig + */ + @GetMapping("/device_id/{deviceId}/attribute_id/{attributeId}") + public Mono> selectByDeviceIdAndAttributeId( + @NotNull @PathVariable(value = "deviceId") Long deviceId, + @NotNull @PathVariable(value = "attributeId") Long attributeId) { + try { + DriverAttributeConfigBO entityBO = driverAttributeConfigService.selectByAttributeIdAndDeviceId(deviceId, + attributeId); + DriverAttributeConfigVO entityVO = driverAttributeConfigBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device ID DriverConfig - * @param deviceId Device ID - * @return DriverConfig - */ - @GetMapping("/device_id/{deviceId}") - public Mono>> selectByDeviceId( - @NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - List entityBOList = driverAttributeConfigService.selectByDeviceId(deviceId); - List entityVOList = driverAttributeConfigBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Device ID DriverConfig + * + * @param deviceId Device ID + * @return DriverConfig + */ + @GetMapping("/device_id/{deviceId}") + public Mono>> selectByDeviceId( + @NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + List entityBOList = driverAttributeConfigService.selectByDeviceId(deviceId); + List entityVOList = driverAttributeConfigBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * DriverConfig - * @param entityQuery DriverConfig Dto - * @return Page Of DriverConfig - */ - @PostMapping("/list") - public Mono>> list( - @RequestBody(required = false) DriverAttributeConfigQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeConfigQuery query = Objects.isNull(entityQuery) ? new DriverAttributeConfigQuery() - : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = driverAttributeConfigService.selectByPage(query); - Page entityPageVO = driverAttributeConfigBuilder - .buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverConfig + * + * @param entityQuery DriverConfig Dto + * @return Page Of DriverConfig + */ + @PostMapping("/list") + public Mono>> list( + @RequestBody(required = false) DriverAttributeConfigQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeConfigQuery query = Objects.isNull(entityQuery) ? new DriverAttributeConfigQuery() + : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = driverAttributeConfigService.selectByPage(query); + Page entityPageVO = driverAttributeConfigBuilder + .buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeController.java index b4bacae35..44186f7af 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverAttributeController.java @@ -52,134 +52,133 @@ import java.util.Objects; @RequestMapping(ManagerConstant.DRIVER_ATTRIBUTE_URL_PREFIX) public class DriverAttributeController implements BaseController { - private final DriverAttributeBuilder driverAttributeBuilder; + private final DriverAttributeBuilder driverAttributeBuilder; - private final DriverAttributeService driverAttributeService; + private final DriverAttributeService driverAttributeService; - public DriverAttributeController(DriverAttributeBuilder driverAttributeBuilder, - DriverAttributeService driverAttributeService) { - this.driverAttributeBuilder = driverAttributeBuilder; - this.driverAttributeService = driverAttributeService; - } + public DriverAttributeController(DriverAttributeBuilder driverAttributeBuilder, + DriverAttributeService driverAttributeService) { + this.driverAttributeBuilder = driverAttributeBuilder; + this.driverAttributeService = driverAttributeService; + } - /** - * DriverAttribute - * @param entityVO {@link DriverAttributeVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody DriverAttributeVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeBO entityBO = driverAttributeBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverAttributeService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverAttribute + * + * @param entityVO {@link DriverAttributeVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody DriverAttributeVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeBO entityBO = driverAttributeBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverAttributeService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID DriverAttribute - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - driverAttributeService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID DriverAttribute + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + driverAttributeService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * DriverAttribute - * @param entityVO {@link DriverAttributeVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody DriverAttributeVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeBO entityBO = driverAttributeBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverAttributeService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverAttribute + * + * @param entityVO {@link DriverAttributeVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody DriverAttributeVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeBO entityBO = driverAttributeBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverAttributeService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID DriverAttribute - * @param id ID - * @return DriverAttributeVO {@link DriverAttributeVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - DriverAttributeBO entityBO = driverAttributeService.selectById(id); - DriverAttributeVO entityVO = driverAttributeBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID DriverAttribute + * + * @param id ID + * @return DriverAttributeVO {@link DriverAttributeVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + DriverAttributeBO entityBO = driverAttributeService.selectById(id); + DriverAttributeVO entityVO = driverAttributeBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Driver ID DriverAttribute - * @param id ID - * @return DriverAttribute - */ - @GetMapping("/driver_id/{id}") - public Mono>> selectByDriverId(@NotNull @PathVariable(value = "id") Long id) { - try { - List entityBOList = driverAttributeService.selectByDriverId(id); - List entityVO = driverAttributeBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVO)); - } - catch (NotFoundException ne) { - return Mono.just(R.ok(Collections.emptyList())); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Driver ID DriverAttribute + * + * @param id ID + * @return DriverAttribute + */ + @GetMapping("/driver_id/{id}") + public Mono>> selectByDriverId(@NotNull @PathVariable(value = "id") Long id) { + try { + List entityBOList = driverAttributeService.selectByDriverId(id); + List entityVO = driverAttributeBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVO)); + } catch (NotFoundException ne) { + return Mono.just(R.ok(Collections.emptyList())); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * DriverAttribute - * @param entityQuery Dto - * @return Page Of DriverAttribute - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) DriverAttributeQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DriverAttributeQuery query = Objects.isNull(entityQuery) ? new DriverAttributeQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = driverAttributeService.selectByPage(query); - Page entityPageVO = driverAttributeBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * DriverAttribute + * + * @param entityQuery Dto + * @return Page Of DriverAttribute + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) DriverAttributeQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DriverAttributeQuery query = Objects.isNull(entityQuery) ? new DriverAttributeQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = driverAttributeService.selectByPage(query); + Page entityPageVO = driverAttributeBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverController.java index 33fe1f73f..da67989bc 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/DriverController.java @@ -53,151 +53,151 @@ import java.util.stream.Collectors; @RequestMapping(ManagerConstant.DRIVER_URL_PREFIX) public class DriverController implements BaseController { - private final DriverBuilder driverBuilder; + private final DriverBuilder driverBuilder; - private final DriverService driverService; + private final DriverService driverService; - public DriverController(DriverBuilder driverBuilder, DriverService driverService) { - this.driverBuilder = driverBuilder; - this.driverService = driverService; - } + public DriverController(DriverBuilder driverBuilder, DriverService driverService) { + this.driverBuilder = driverBuilder; + this.driverService = driverService; + } - /** - * Driver - * @param entityVO {@link DriverVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody DriverVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverBO entityBO = driverBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Driver + * + * @param entityVO {@link DriverVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody DriverVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverBO entityBO = driverBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Driver - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - driverService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Driver + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + driverService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Driver - * @param entityVO {@link DriverVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody DriverVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - DriverBO entityBO = driverBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - driverService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Driver + * + * @param entityVO {@link DriverVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody DriverVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + DriverBO entityBO = driverBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + driverService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Driver - * @param id ID - * @return DriverVO {@link DriverVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - DriverBO entityBO = driverService.selectById(id); - DriverVO entityVO = driverBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Driver + * + * @param id ID + * @return DriverVO {@link DriverVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + DriverBO entityBO = driverService.selectById(id); + DriverVO entityVO = driverBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Driver - * @param driverIds Driver ID - * @return Map(ID, DriverVO) - */ - @PostMapping("/ids") - public Mono>> selectByIds(@RequestBody Set driverIds) { - try { - List entityBOList = driverService.selectByIds(driverIds); - Map driverMap = entityBOList.stream() - .collect(Collectors.toMap(DriverBO::getId, entityBO -> driverBuilder.buildVOByBO(entityBO))); - return Mono.just(R.ok(driverMap)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Driver + * + * @param driverIds Driver ID + * @return Map(ID, DriverVO) + */ + @PostMapping("/ids") + public Mono>> selectByIds(@RequestBody Set driverIds) { + try { + List entityBOList = driverService.selectByIds(driverIds); + Map driverMap = entityBOList.stream() + .collect(Collectors.toMap(DriverBO::getId, entityBO -> driverBuilder.buildVOByBO(entityBO))); + return Mono.just(R.ok(driverMap)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * SERVICENAME Driver - * @param serviceName Driver service name - * @return Driver - */ - @GetMapping("/service/{serviceName}") - public Mono> selectByServiceName(@NotNull @PathVariable(value = "serviceName") String serviceName) { - return getTenantId().flatMap(tenantId -> { - try { - DriverBO entityBO = driverService.selectByServiceName(serviceName, tenantId); - DriverVO entityVO = driverBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * SERVICENAME Driver + * + * @param serviceName Driver service name + * @return Driver + */ + @GetMapping("/service/{serviceName}") + public Mono> selectByServiceName(@NotNull @PathVariable(value = "serviceName") String serviceName) { + return getTenantId().flatMap(tenantId -> { + try { + DriverBO entityBO = driverService.selectByServiceName(serviceName, tenantId); + DriverVO entityVO = driverBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * Driver - * @param entityQuery Driver Dto - * @return Page Of Driver - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) DriverQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - DriverQuery query = Objects.isNull(entityQuery) ? new DriverQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = driverService.selectByPage(query); - Page entityPageVO = driverBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Driver + * + * @param entityQuery Driver Dto + * @return Page Of Driver + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) DriverQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + DriverQuery query = Objects.isNull(entityQuery) ? new DriverQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = driverService.selectByPage(query); + Page entityPageVO = driverBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/GroupController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/GroupController.java index 00d2c640c..f8f1d6cc0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/GroupController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/GroupController.java @@ -49,107 +49,102 @@ import java.util.Objects; @RequestMapping(ManagerConstant.GROUP_URL_PREFIX) public class GroupController implements BaseController { - private final GroupBuilder groupBuilder; + private final GroupBuilder groupBuilder; - private final GroupService groupService; + private final GroupService groupService; - public GroupController(GroupBuilder groupBuilder, GroupService groupService) { - this.groupBuilder = groupBuilder; - this.groupService = groupService; - } + public GroupController(GroupBuilder groupBuilder, GroupService groupService) { + this.groupBuilder = groupBuilder; + this.groupService = groupService; + } - /** - * @param entityVO {@link GroupVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody GroupVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - GroupBO entityBO = groupBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - groupService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link GroupVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody GroupVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + GroupBO entityBO = groupBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + groupService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - groupService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + groupService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param entityVO {@link GroupVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody GroupVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - GroupBO entityBO = groupBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - groupService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link GroupVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody GroupVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + GroupBO entityBO = groupBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + groupService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param id ID - * @return GroupVO {@link GroupVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - GroupBO entityBO = groupService.selectById(id); - GroupVO entityVO = groupBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param id ID + * @return GroupVO {@link GroupVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + GroupBO entityBO = groupService.selectById(id); + GroupVO entityVO = groupBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param entityQuery {@link GroupQuery} - * @return R Of GroupVO Page - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) GroupQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - GroupQuery query = Objects.isNull(entityQuery) ? new GroupQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = groupService.selectByPage(query); - Page entityPageVO = groupBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityQuery {@link GroupQuery} + * @return R Of GroupVO Page + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) GroupQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + GroupQuery query = Objects.isNull(entityQuery) ? new GroupQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = groupService.selectByPage(query); + Page entityPageVO = groupBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/LabelController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/LabelController.java index b1d0943b6..424c36c80 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/LabelController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/LabelController.java @@ -49,107 +49,102 @@ import java.util.Objects; @RequestMapping(ManagerConstant.LABEL_URL_PREFIX) public class LabelController implements BaseController { - private final LabelBuilder labelBuilder; + private final LabelBuilder labelBuilder; - private final LabelService labelService; + private final LabelService labelService; - public LabelController(LabelBuilder labelBuilder, LabelService labelService) { - this.labelBuilder = labelBuilder; - this.labelService = labelService; - } + public LabelController(LabelBuilder labelBuilder, LabelService labelService) { + this.labelBuilder = labelBuilder; + this.labelService = labelService; + } - /** - * @param entityVO {@link LabelVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody LabelVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - LabelBO entityBO = labelBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - labelService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link LabelVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody LabelVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + LabelBO entityBO = labelBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + labelService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - labelService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + labelService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param entityVO {@link LabelVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody LabelVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - LabelBO entityBO = labelBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - labelService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityVO {@link LabelVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody LabelVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + LabelBO entityBO = labelBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + labelService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param id ID - * @return LabelVO {@link LabelVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - LabelBO entityBO = labelService.selectById(id); - LabelVO entityVO = labelBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param id ID + * @return LabelVO {@link LabelVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + LabelBO entityBO = labelService.selectById(id); + LabelVO entityVO = labelBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param entityQuery {@link LabelQuery} - * @return R Of LabelVO Page - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) LabelQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - LabelQuery query = Objects.isNull(entityQuery) ? new LabelQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = labelService.selectByPage(query); - Page entityPageVO = labelBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * @param entityQuery {@link LabelQuery} + * @return R Of LabelVO Page + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) LabelQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + LabelQuery query = Objects.isNull(entityQuery) ? new LabelQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = labelService.selectByPage(query); + Page entityPageVO = labelBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeConfigController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeConfigController.java index 03ba8867b..bdee69b46 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeConfigController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeConfigController.java @@ -50,179 +50,179 @@ import java.util.Objects; @RequestMapping(ManagerConstant.POINT_ATTRIBUTE_CONFIG_URL_PREFIX) public class PointAttributeConfigController implements BaseController { - private final PointAttributeConfigBuilder pointAttributeConfigBuilder; + private final PointAttributeConfigBuilder pointAttributeConfigBuilder; - private final PointAttributeConfigService pointAttributeConfigService; + private final PointAttributeConfigService pointAttributeConfigService; - public PointAttributeConfigController(PointAttributeConfigBuilder pointAttributeConfigBuilder, - PointAttributeConfigService pointAttributeConfigService) { - this.pointAttributeConfigBuilder = pointAttributeConfigBuilder; - this.pointAttributeConfigService = pointAttributeConfigService; - } + public PointAttributeConfigController(PointAttributeConfigBuilder pointAttributeConfigBuilder, + PointAttributeConfigService pointAttributeConfigService) { + this.pointAttributeConfigBuilder = pointAttributeConfigBuilder; + this.pointAttributeConfigService = pointAttributeConfigService; + } - /** - * PointConfig - * @param entityVO {@link PointAttributeConfigVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody PointAttributeConfigVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeConfigBO entityBO = pointAttributeConfigBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointAttributeConfigService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointConfig + * + * @param entityVO {@link PointAttributeConfigVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody PointAttributeConfigVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeConfigBO entityBO = pointAttributeConfigBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointAttributeConfigService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID PointConfig - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - pointAttributeConfigService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID PointConfig + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + pointAttributeConfigService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * PointConfig - * @param entityVO {@link PointAttributeConfigVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody PointAttributeConfigVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeConfigBO entityBO = pointAttributeConfigBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointAttributeConfigService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointConfig + * + * @param entityVO {@link PointAttributeConfigVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody PointAttributeConfigVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeConfigBO entityBO = pointAttributeConfigBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointAttributeConfigService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID PointConfig - * @param id ID - * @return PointAttributeConfigVO {@link PointAttributeConfigVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - PointAttributeConfigBO entityBO = pointAttributeConfigService.selectById(id); - PointAttributeConfigVO entityVO = pointAttributeConfigBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID PointConfig + * + * @param id ID + * @return PointAttributeConfigVO {@link PointAttributeConfigVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + PointAttributeConfigBO entityBO = pointAttributeConfigService.selectById(id); + PointAttributeConfigVO entityVO = pointAttributeConfigBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID, Device ID Point ID PointConfig - * @param attributeId Attribute ID - * @param deviceId Device ID - * @param pointId Point ID - * @return PointConfig - */ - @GetMapping("/attribute_id/{attributeId}/device_id/{deviceId}/point_id/{pointId}") - public Mono> selectByAttributeIdAndDeviceIdAndPointId( - @NotNull @PathVariable(value = "attributeId") Long attributeId, - @NotNull @PathVariable(value = "deviceId") Long deviceId, - @NotNull @PathVariable(value = "pointId") Long pointId) { - try { - PointAttributeConfigBO entityBO = pointAttributeConfigService - .selectByAttributeIdAndDeviceIdAndPointId(attributeId, deviceId, pointId); - PointAttributeConfigVO entityVO = pointAttributeConfigBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID, Device ID Point ID PointConfig + * + * @param attributeId Attribute ID + * @param deviceId Device ID + * @param pointId Point ID + * @return PointConfig + */ + @GetMapping("/attribute_id/{attributeId}/device_id/{deviceId}/point_id/{pointId}") + public Mono> selectByAttributeIdAndDeviceIdAndPointId( + @NotNull @PathVariable(value = "attributeId") Long attributeId, + @NotNull @PathVariable(value = "deviceId") Long deviceId, + @NotNull @PathVariable(value = "pointId") Long pointId) { + try { + PointAttributeConfigBO entityBO = pointAttributeConfigService + .selectByAttributeIdAndDeviceIdAndPointId(attributeId, deviceId, pointId); + PointAttributeConfigVO entityVO = pointAttributeConfigBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device ID Point ID PointConfig - * @param deviceId Device ID - * @param pointId Point ID - * @return PointConfig - */ - @GetMapping("/device_id/{deviceId}/point_id/{pointId}") - public Mono>> selectByDeviceIdAndPointId( - @NotNull @PathVariable(value = "deviceId") Long deviceId, - @NotNull @PathVariable(value = "pointId") Long pointId) { - try { - List entityBOList = pointAttributeConfigService.selectByDeviceIdAndPointId(deviceId, - pointId); - List entityVOList = pointAttributeConfigBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Device ID Point ID PointConfig + * + * @param deviceId Device ID + * @param pointId Point ID + * @return PointConfig + */ + @GetMapping("/device_id/{deviceId}/point_id/{pointId}") + public Mono>> selectByDeviceIdAndPointId( + @NotNull @PathVariable(value = "deviceId") Long deviceId, + @NotNull @PathVariable(value = "pointId") Long pointId) { + try { + List entityBOList = pointAttributeConfigService.selectByDeviceIdAndPointId(deviceId, + pointId); + List entityVOList = pointAttributeConfigBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device ID PointConfig - * @param deviceId Device ID - * @return PointConfig - */ - @GetMapping("/device_id/{deviceId}") - public Mono>> selectByDeviceId( - @NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - List entityBOList = pointAttributeConfigService.selectByDeviceId(deviceId); - List entityVOList = pointAttributeConfigBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Device ID PointConfig + * + * @param deviceId Device ID + * @return PointConfig + */ + @GetMapping("/device_id/{deviceId}") + public Mono>> selectByDeviceId( + @NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + List entityBOList = pointAttributeConfigService.selectByDeviceId(deviceId); + List entityVOList = pointAttributeConfigBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * PointConfig - * @param entityQuery PointConfig Dto - * @return Page Of PointConfig - */ - @PostMapping("/list") - public Mono>> list( - @RequestBody(required = false) PointAttributeConfigQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeConfigQuery query = Objects.isNull(entityQuery) ? new PointAttributeConfigQuery() - : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = pointAttributeConfigService.selectByPage(query); - Page entityPageVO = pointAttributeConfigBuilder - .buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointConfig + * + * @param entityQuery PointConfig Dto + * @return Page Of PointConfig + */ + @PostMapping("/list") + public Mono>> list( + @RequestBody(required = false) PointAttributeConfigQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeConfigQuery query = Objects.isNull(entityQuery) ? new PointAttributeConfigQuery() + : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = pointAttributeConfigService.selectByPage(query); + Page entityPageVO = pointAttributeConfigBuilder + .buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeController.java index 1f0ae074b..225ba98fb 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointAttributeController.java @@ -52,134 +52,133 @@ import java.util.Objects; @RequestMapping(ManagerConstant.POINT_ATTRIBUTE_URL_PREFIX) public class PointAttributeController implements BaseController { - private final PointAttributeBuilder pointAttributeBuilder; + private final PointAttributeBuilder pointAttributeBuilder; - private final PointAttributeService pointAttributeService; + private final PointAttributeService pointAttributeService; - public PointAttributeController(PointAttributeBuilder pointAttributeBuilder, - PointAttributeService pointAttributeService) { - this.pointAttributeBuilder = pointAttributeBuilder; - this.pointAttributeService = pointAttributeService; - } + public PointAttributeController(PointAttributeBuilder pointAttributeBuilder, + PointAttributeService pointAttributeService) { + this.pointAttributeBuilder = pointAttributeBuilder; + this.pointAttributeService = pointAttributeService; + } - /** - * PointAttribute - * @param entityVO {@link PointAttributeVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody PointAttributeVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeBO entityBO = pointAttributeBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointAttributeService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointAttribute + * + * @param entityVO {@link PointAttributeVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody PointAttributeVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeBO entityBO = pointAttributeBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointAttributeService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID PointAttribute - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - pointAttributeService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID PointAttribute + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + pointAttributeService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * PointAttribute - * @param entityVO {@link PointAttributeVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody PointAttributeVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeBO entityBO = pointAttributeBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointAttributeService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointAttribute + * + * @param entityVO {@link PointAttributeVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody PointAttributeVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeBO entityBO = pointAttributeBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointAttributeService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID PointAttribute - * @param id ID - * @return PointAttributeVO {@link PointAttributeVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - PointAttributeBO entityBO = pointAttributeService.selectById(id); - PointAttributeVO entityVO = pointAttributeBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID PointAttribute + * + * @param id ID + * @return PointAttributeVO {@link PointAttributeVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + PointAttributeBO entityBO = pointAttributeService.selectById(id); + PointAttributeVO entityVO = pointAttributeBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Driver ID PointAttribute - * @param id ID - * @return Array - */ - @GetMapping("/driver_id/{id}") - public Mono>> selectByDriverId(@NotNull @PathVariable(value = "id") Long id) { - try { - List entityBOList = pointAttributeService.selectByDriverId(id); - List entityVO = pointAttributeBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVO)); - } - catch (NotFoundException ne) { - return Mono.just(R.ok(Collections.emptyList())); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Driver ID PointAttribute + * + * @param id ID + * @return Array + */ + @GetMapping("/driver_id/{id}") + public Mono>> selectByDriverId(@NotNull @PathVariable(value = "id") Long id) { + try { + List entityBOList = pointAttributeService.selectByDriverId(id); + List entityVO = pointAttributeBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVO)); + } catch (NotFoundException ne) { + return Mono.just(R.ok(Collections.emptyList())); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * PointAttribute - * @param entityQuery - * @return Page Of PointAttribute - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) PointAttributeQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - PointAttributeQuery query = Objects.isNull(entityQuery) ? new PointAttributeQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = pointAttributeService.selectByPage(query); - Page entityPageVO = pointAttributeBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * PointAttribute + * + * @param entityQuery + * @return Page Of PointAttribute + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) PointAttributeQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + PointAttributeQuery query = Objects.isNull(entityQuery) ? new PointAttributeQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = pointAttributeService.selectByPage(query); + Page entityPageVO = pointAttributeBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointController.java index 331b779ac..11e6847cb 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/PointController.java @@ -55,352 +55,344 @@ import java.util.stream.Collectors; @RequestMapping(ManagerConstant.POINT_URL_PREFIX) public class PointController implements BaseController { - private final PointBuilder pointBuilder; + private final PointBuilder pointBuilder; - private final PointService pointService; + private final PointService pointService; - private final DeviceBuilder deviceBuilder; + private final DeviceBuilder deviceBuilder; - public PointController(PointBuilder pointBuilder, PointService pointService, DeviceBuilder deviceBuilder) { - this.pointBuilder = pointBuilder; - this.pointService = pointService; - this.deviceBuilder = deviceBuilder; - } + public PointController(PointBuilder pointBuilder, PointService pointService, DeviceBuilder deviceBuilder) { + this.pointBuilder = pointBuilder; + this.pointService = pointService; + this.deviceBuilder = deviceBuilder; + } - /** - * Point - * @param entityVO {@link PointVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody PointVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointBO entityBO = pointBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Point + * + * @param entityVO {@link PointVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody PointVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointBO entityBO = pointBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Point - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - pointService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Point + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + pointService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Point - * @param entityVO {@link PointVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody PointVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - PointBO entityBO = pointBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - pointService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Point + * + * @param entityVO {@link PointVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody PointVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + PointBO entityBO = pointBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + pointService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Point - * @param id ID - * @return PointVO {@link PointVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - PointBO entityBO = pointService.selectById(id); - PointVO entityVO = pointBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Point + * + * @param id ID + * @return PointVO {@link PointVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + PointBO entityBO = pointService.selectById(id); + PointVO entityVO = pointBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Point - * @param pointIds Point ID - * @return Map(ID, PointVO) - */ - @PostMapping("/ids") - public Mono>> selectByIds(@RequestBody Set pointIds) { - try { - List entityBOList = pointService.selectByIds(pointIds); - Map deviceMap = entityBOList.stream() - .collect(Collectors.toMap(PointBO::getId, entityBO -> pointBuilder.buildVOByBO(entityBO))); - return Mono.just(R.ok(deviceMap)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Point + * + * @param pointIds Point ID + * @return Map(ID, PointVO) + */ + @PostMapping("/ids") + public Mono>> selectByIds(@RequestBody Set pointIds) { + try { + List entityBOList = pointService.selectByIds(pointIds); + Map deviceMap = entityBOList.stream() + .collect(Collectors.toMap(PointBO::getId, entityBO -> pointBuilder.buildVOByBO(entityBO))); + return Mono.just(R.ok(deviceMap)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Point - * @param profileId Point ID - * @return Point - */ - @GetMapping("/profile_id/{profileId}") - public Mono>> selectByProfileId(@NotNull @PathVariable(value = "profileId") Long profileId) { - try { - List entityBOList = pointService.selectByProfileId(profileId); - List entityVOList = pointBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Point + * + * @param profileId Point ID + * @return Point + */ + @GetMapping("/profile_id/{profileId}") + public Mono>> selectByProfileId(@NotNull @PathVariable(value = "profileId") Long profileId) { + try { + List entityBOList = pointService.selectByProfileId(profileId); + List entityVOList = pointBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device ID Point - * @param deviceId Device ID - * @return Point Array - */ - @GetMapping("/device_id/{deviceId}") - public Mono>> selectByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - List entityBOList = pointService.selectByDeviceId(deviceId); - List entityVOList = pointBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Device ID Point + * + * @param deviceId Device ID + * @return Point Array + */ + @GetMapping("/device_id/{deviceId}") + public Mono>> selectByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + List entityBOList = pointService.selectByDeviceId(deviceId); + List entityVOList = pointBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Point - * @param entityQuery Point Dto - * @return Page Of Point - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) PointQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - PointQuery query = Objects.isNull(entityQuery) ? new PointQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = pointService.selectByPage(query); - Page entityPageVO = pointBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Point + * + * @param entityQuery Point Dto + * @return Page Of Point + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) PointQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + PointQuery query = Objects.isNull(entityQuery) ? new PointQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = pointService.selectByPage(query); + Page entityPageVO = pointBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * @param pointIds Point ID - * @return Map String:String - */ - @PostMapping("/unit") - public Mono>> unit(@RequestBody Set pointIds) { - try { - Map units = pointService.unit(pointIds); - if (Objects.nonNull(units)) { - Map unitCodeMap = units.entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - return Mono.just(R.ok(unitCodeMap)); - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - return Mono.just(R.fail()); - } + /** + * @param pointIds Point ID + * @return Map String:String + */ + @PostMapping("/unit") + public Mono>> unit(@RequestBody Set pointIds) { + try { + Map units = pointService.unit(pointIds); + if (Objects.nonNull(units)) { + Map unitCodeMap = units.entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return Mono.just(R.ok(unitCodeMap)); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + return Mono.just(R.fail()); + } - /** - * @param pointId id - * @return {@link R}<{@link Set}<{@link Long}>> - */ - @GetMapping("/selectPointStatisticsWithDevice/{pointId}") - public Mono> selectPointStatisticsWithDevice( - @NotNull @PathVariable(value = "pointId") Long pointId) { - try { - DeviceByPointBO deviceByPointBO = pointService.selectPointStatisticsWithDevice(pointId); - DeviceByPointVO deviceByPointVO = deviceBuilder.buildVOPointByBO(deviceByPointBO); - return Mono.just(R.ok(deviceByPointVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param pointId id + * @return {@link R}<{@link Set}<{@link Long}>> + */ + @GetMapping("/selectPointStatisticsWithDevice/{pointId}") + public Mono> selectPointStatisticsWithDevice( + @NotNull @PathVariable(value = "pointId") Long pointId) { + try { + DeviceByPointBO deviceByPointBO = pointService.selectPointStatisticsWithDevice(pointId); + DeviceByPointVO deviceByPointVO = deviceBuilder.buildVOPointByBO(deviceByPointBO); + return Mono.just(R.ok(deviceByPointVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * - * id - * @param pointId id - * @param deviceIds id - * @return {@link R}<{@link Map}<{@link Long}, {@link String}>> - */ - @PostMapping("/selectPointStatisticsByDeviceId/{pointId}") - public Mono>> selectPointStatisticsByDeviceId( - @NotNull @PathVariable(value = "pointId") Long pointId, @NotNull @RequestBody Set deviceIds) { - try { - List list = pointService.selectPointStatisticsByDeviceId(pointId, deviceIds); - List pointDataVolumeRunVO = pointBuilder.buildVOPointDataByBO(list); - return Mono.just(R.ok(pointDataVolumeRunVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * + * id + * + * @param pointId id + * @param deviceIds id + * @return {@link R}<{@link Map}<{@link Long}, {@link String}>> + */ + @PostMapping("/selectPointStatisticsByDeviceId/{pointId}") + public Mono>> selectPointStatisticsByDeviceId( + @NotNull @PathVariable(value = "pointId") Long pointId, @NotNull @RequestBody Set deviceIds) { + try { + List list = pointService.selectPointStatisticsByDeviceId(pointId, deviceIds); + List pointDataVolumeRunVO = pointBuilder.buildVOPointDataByBO(list); + return Mono.just(R.ok(pointDataVolumeRunVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * - * id - * @param pointId id - * @return {@link R}<{@link Map}<{@link Long}, {@link String}>> - */ - @GetMapping("/selectPointStatisticsByPointId/{pointId}") - public Mono> selectPointStatisticsByPointId(@NotNull @PathVariable(value = "pointId") Long pointId) { - try { - PointDataVolumeRunDO pointDataVolumeRunDO = pointService.selectPointStatisticsByPointId(pointId); - return Mono - .just(R.ok(Objects.isNull(pointDataVolumeRunDO.getTotal()) ? 0 : pointDataVolumeRunDO.getTotal())); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * + * id + * + * @param pointId id + * @return {@link R}<{@link Map}<{@link Long}, {@link String}>> + */ + @GetMapping("/selectPointStatisticsByPointId/{pointId}") + public Mono> selectPointStatisticsByPointId(@NotNull @PathVariable(value = "pointId") Long pointId) { + try { + PointDataVolumeRunDO pointDataVolumeRunDO = pointService.selectPointStatisticsByPointId(pointId); + return Mono + .just(R.ok(Objects.isNull(pointDataVolumeRunDO.getTotal()) ? 0 : pointDataVolumeRunDO.getTotal())); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param deviceId - * @return - */ - @GetMapping("/selectPointByDeviceId/{deviceId}") - public Mono> selectPointByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - Long count = pointService.selectPointByDeviceId(deviceId); - return Mono.just(R.ok(count)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param deviceId + * @return + */ + @GetMapping("/selectPointByDeviceId/{deviceId}") + public Mono> selectPointByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + Long count = pointService.selectPointByDeviceId(deviceId); + return Mono.just(R.ok(count)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param deviceId - * @return - */ - @GetMapping("/selectPointConfigByDeviceId/{deviceId}") - public Mono> selectPointConfigByDeviceId( - @NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - PointConfigByDeviceBO pointConfigByDeviceBO = pointService.selectPointConfigByDeviceId(deviceId); - PointConfigByDeviceVO pointConfigByDeviceVO = pointBuilder.buildVODeviceByBO(pointConfigByDeviceBO); - return Mono.just(R.ok(pointConfigByDeviceVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param deviceId + * @return + */ + @GetMapping("/selectPointConfigByDeviceId/{deviceId}") + public Mono> selectPointConfigByDeviceId( + @NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + PointConfigByDeviceBO pointConfigByDeviceBO = pointService.selectPointConfigByDeviceId(deviceId); + PointConfigByDeviceVO pointConfigByDeviceVO = pointBuilder.buildVODeviceByBO(pointConfigByDeviceBO); + return Mono.just(R.ok(pointConfigByDeviceVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param deviceId - * @param pointIds - * @return - */ - @PostMapping("/selectDeviceStatisticsByPointId/{deviceId}") - public Mono>> selectDeviceStatisticsByPointId( - @NotNull @PathVariable(value = "deviceId") Long deviceId, @NotNull @RequestBody Set pointIds) { - try { - List list = pointService.selectDeviceStatisticsByPointId(deviceId, pointIds); - List deviceDataVolumeRunVOList = pointBuilder.buildVODeviceDataByBO(list); - return Mono.just(R.ok(deviceDataVolumeRunVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param deviceId + * @param pointIds + * @return + */ + @PostMapping("/selectDeviceStatisticsByPointId/{deviceId}") + public Mono>> selectDeviceStatisticsByPointId( + @NotNull @PathVariable(value = "deviceId") Long deviceId, @NotNull @RequestBody Set pointIds) { + try { + List list = pointService.selectDeviceStatisticsByPointId(deviceId, pointIds); + List deviceDataVolumeRunVOList = pointBuilder.buildVODeviceDataByBO(list); + return Mono.just(R.ok(deviceDataVolumeRunVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param driverId - * @return - */ - @GetMapping("/selectPointDataByDriverId/{driverId}") - public Mono> selectPointDataByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - PointDataVolumeRunDO pointDataVolumeRunDO = pointService.selectPointDataByDriverId(driverId); - return Mono - .just(R.ok(Objects.isNull(pointDataVolumeRunDO.getTotal()) ? 0 : pointDataVolumeRunDO.getTotal())); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param driverId + * @return + */ + @GetMapping("/selectPointDataByDriverId/{driverId}") + public Mono> selectPointDataByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + PointDataVolumeRunDO pointDataVolumeRunDO = pointService.selectPointDataByDriverId(driverId); + return Mono + .just(R.ok(Objects.isNull(pointDataVolumeRunDO.getTotal()) ? 0 : pointDataVolumeRunDO.getTotal())); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * @param driverId - * @return - */ - @GetMapping("/selectPointByDriverId/{driverId}") - public Mono> selectPointByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { - try { - Long result = pointService.selectPointByDriverId(driverId); - return Mono.just(R.ok(result)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * @param driverId + * @return + */ + @GetMapping("/selectPointByDriverId/{driverId}") + public Mono> selectPointByDriverId(@NotNull @PathVariable(value = "driverId") Long driverId) { + try { + Long result = pointService.selectPointByDriverId(driverId); + return Mono.just(R.ok(result)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - @GetMapping("/selectPointDataStatisticsByDriverId/{driverId}") - public Mono> selectPointDataStatisticsByDriverId( - @NotNull @PathVariable(value = "driverId") Long driverId) { - try { - PointDataStatisticsByDriverIdBO pointDataStatisticsByDriverIdBOList = pointService - .selectPointDataStatisticsByDriverId(driverId); - PointDataStatisticsByDriverIdVO pointDataStatisticsByDriverIdVOList = pointBuilder - .buildVOPointDataDriverByBO(pointDataStatisticsByDriverIdBOList); - return Mono.just(R.ok(pointDataStatisticsByDriverIdVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @GetMapping("/selectPointDataStatisticsByDriverId/{driverId}") + public Mono> selectPointDataStatisticsByDriverId( + @NotNull @PathVariable(value = "driverId") Long driverId) { + try { + PointDataStatisticsByDriverIdBO pointDataStatisticsByDriverIdBOList = pointService + .selectPointDataStatisticsByDriverId(driverId); + PointDataStatisticsByDriverIdVO pointDataStatisticsByDriverIdVOList = pointBuilder + .buildVOPointDataDriverByBO(pointDataStatisticsByDriverIdBOList); + return Mono.just(R.ok(pointDataStatisticsByDriverIdVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/ProfileController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/ProfileController.java index 76d0036e6..c010e0c16 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/ProfileController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/ProfileController.java @@ -53,148 +53,148 @@ import java.util.stream.Collectors; @RequestMapping(ManagerConstant.PROFILE_URL_PREFIX) public class ProfileController implements BaseController { - private final ProfileBuilder profileBuilder; + private final ProfileBuilder profileBuilder; - private final ProfileService profileService; + private final ProfileService profileService; - public ProfileController(ProfileBuilder profileBuilder, ProfileService profileService) { - this.profileBuilder = profileBuilder; - this.profileService = profileService; - } + public ProfileController(ProfileBuilder profileBuilder, ProfileService profileService) { + this.profileBuilder = profileBuilder; + this.profileService = profileService; + } - /** - * Profile - * @param entityVO {@link ProfileVO} - * @return R of String - */ - @PostMapping("/add") - public Mono> add(@Validated(Add.class) @RequestBody ProfileVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - ProfileBO entityBO = profileBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - profileService.save(entityBO); - return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Profile + * + * @param entityVO {@link ProfileVO} + * @return R of String + */ + @PostMapping("/add") + public Mono> add(@Validated(Add.class) @RequestBody ProfileVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + ProfileBO entityBO = profileBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + profileService.save(entityBO); + return Mono.just(R.ok(ResponseEnum.ADD_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Profile - * @param id ID - * @return R of String - */ - @PostMapping("/delete/{id}") - public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { - try { - profileService.remove(id); - return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Profile + * + * @param id ID + * @return R of String + */ + @PostMapping("/delete/{id}") + public Mono> delete(@NotNull @PathVariable(value = "id") Long id) { + try { + profileService.remove(id); + return Mono.just(R.ok(ResponseEnum.DELETE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Profile - * @param entityVO {@link ProfileVO} - * @return R of String - */ - @PostMapping("/update") - public Mono> update(@Validated(Update.class) @RequestBody ProfileVO entityVO) { - return getTenantId().flatMap(tenantId -> { - try { - ProfileBO entityBO = profileBuilder.buildBOByVO(entityVO); - entityBO.setTenantId(tenantId); - profileService.update(entityBO); - return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Profile + * + * @param entityVO {@link ProfileVO} + * @return R of String + */ + @PostMapping("/update") + public Mono> update(@Validated(Update.class) @RequestBody ProfileVO entityVO) { + return getTenantId().flatMap(tenantId -> { + try { + ProfileBO entityBO = profileBuilder.buildBOByVO(entityVO); + entityBO.setTenantId(tenantId); + profileService.update(entityBO); + return Mono.just(R.ok(ResponseEnum.UPDATE_SUCCESS)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + }); + } - /** - * ID Profile - * @param id ID - * @return ProfileVO {@link ProfileVO} - */ - @GetMapping("/id/{id}") - public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { - try { - ProfileBO entityBO = profileService.selectById(id); - ProfileVO entityVO = profileBuilder.buildVOByBO(entityBO); - return Mono.just(R.ok(entityVO)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Profile + * + * @param id ID + * @return ProfileVO {@link ProfileVO} + */ + @GetMapping("/id/{id}") + public Mono> selectById(@NotNull @PathVariable(value = "id") Long id) { + try { + ProfileBO entityBO = profileService.selectById(id); + ProfileVO entityVO = profileBuilder.buildVOByBO(entityBO); + return Mono.just(R.ok(entityVO)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * ID Profile - * @param profileIds ID - * @return Map(ID, ProfileVO) - */ - @PostMapping("/ids") - public Mono>> selectByIds(@RequestBody Set profileIds) { - try { - List entityBOList = profileService.selectByIds(profileIds); - Map deviceMap = entityBOList.stream() - .collect(Collectors.toMap(ProfileBO::getId, entityBO -> profileBuilder.buildVOByBO(entityBO))); - return Mono.just(R.ok(deviceMap)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * ID Profile + * + * @param profileIds ID + * @return Map(ID, ProfileVO) + */ + @PostMapping("/ids") + public Mono>> selectByIds(@RequestBody Set profileIds) { + try { + List entityBOList = profileService.selectByIds(profileIds); + Map deviceMap = entityBOList.stream() + .collect(Collectors.toMap(ProfileBO::getId, entityBO -> profileBuilder.buildVOByBO(entityBO))); + return Mono.just(R.ok(deviceMap)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Device ID Profile - * @param deviceId Device ID - * @return Profile - */ - @GetMapping("/device_id/{deviceId}") - public Mono>> selectByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { - try { - List entityBOList = profileService.selectByDeviceId(deviceId); - List entityVOList = profileBuilder.buildVOListByBOList(entityBOList); - return Mono.just(R.ok(entityVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + /** + * Device ID Profile + * + * @param deviceId Device ID + * @return Profile + */ + @GetMapping("/device_id/{deviceId}") + public Mono>> selectByDeviceId(@NotNull @PathVariable(value = "deviceId") Long deviceId) { + try { + List entityBOList = profileService.selectByDeviceId(deviceId); + List entityVOList = profileBuilder.buildVOListByBOList(entityBOList); + return Mono.just(R.ok(entityVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } - /** - * Profile - * @param entityQuery Profile Dto - * @return Page Of Profile - */ - @PostMapping("/list") - public Mono>> list(@RequestBody(required = false) ProfileQuery entityQuery) { - return getTenantId().flatMap(tenantId -> { - try { - ProfileQuery query = Objects.isNull(entityQuery) ? new ProfileQuery() : entityQuery; - query.setTenantId(tenantId); - Page entityPageBO = profileService.selectByPage(query); - Page entityPageVO = profileBuilder.buildVOPageByBOPage(entityPageBO); - return Mono.just(R.ok(entityPageVO)); - } - catch (Exception e) { - return Mono.just(R.fail(e.getMessage())); - } - }); - } + /** + * Profile + * + * @param entityQuery Profile Dto + * @return Page Of Profile + */ + @PostMapping("/list") + public Mono>> list(@RequestBody(required = false) ProfileQuery entityQuery) { + return getTenantId().flatMap(tenantId -> { + try { + ProfileQuery query = Objects.isNull(entityQuery) ? new ProfileQuery() : entityQuery; + query.setTenantId(tenantId); + Page entityPageBO = profileService.selectByPage(query); + Page entityPageVO = profileBuilder.buildVOPageByBOPage(entityPageBO); + return Mono.just(R.ok(entityPageVO)); + } catch (Exception e) { + return Mono.just(R.fail(e.getMessage())); + } + }); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/TopicController.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/TopicController.java index 3535aae14..c1e1572bd 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/TopicController.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/controller/TopicController.java @@ -46,22 +46,21 @@ import java.util.List; @RequestMapping(ManagerConstant.TOPIC_URL_PREFIX) public class TopicController implements BaseController { - private final TopicService topicService; + private final TopicService topicService; - public TopicController(TopicService topicService) { - this.topicService = topicService; - } + public TopicController(TopicService topicService) { + this.topicService = topicService; + } - @PostMapping("/list") - public Mono>>> query(@RequestBody(required = false) TopicQuery topicQuery) { - try { - Page> topicVOList = topicService.query(topicQuery); - return Mono.just(R.ok(topicVOList)); - } - catch (Exception e) { - log.error(e.getMessage(), e); - return Mono.just(R.fail(e.getMessage())); - } - } + @PostMapping("/list") + public Mono>>> query(@RequestBody(required = false) TopicQuery topicQuery) { + try { + Page> topicVOList = topicService.query(topicQuery); + return Mono.just(R.ok(topicVOList)); + } catch (Exception e) { + log.error(e.getMessage(), e); + return Mono.just(R.fail(e.getMessage())); + } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/DeviceManager.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/DeviceManager.java index 36969584a..2778ef4f2 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/DeviceManager.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/DeviceManager.java @@ -32,17 +32,17 @@ import io.github.pnoker.common.manager.entity.model.DeviceDO; */ public interface DeviceManager extends IService { - /** - * @param entityDO {@link DeviceDO} - * @param isUpdate - * @return - */ - boolean checkDuplicate(DeviceDO entityDO, boolean isUpdate); + /** + * @param entityDO {@link DeviceDO} + * @param isUpdate + * @return + */ + boolean checkDuplicate(DeviceDO entityDO, boolean isUpdate); - /** - * @param entityDO {@link DeviceBO} - * @return {@link DeviceDO} - */ - DeviceDO innerSave(DeviceDO entityDO); + /** + * @param entityDO {@link DeviceBO} + * @return {@link DeviceDO} + */ + DeviceDO innerSave(DeviceDO entityDO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DeviceManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DeviceManagerImpl.java index c76ad3663..3e1cd833a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DeviceManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DeviceManagerImpl.java @@ -43,31 +43,31 @@ import java.util.Objects; @Service public class DeviceManagerImpl extends ServiceImpl implements DeviceManager { - @Override - public boolean checkDuplicate(DeviceDO entityDO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DeviceDO::getDeviceName, entityDO.getDeviceName()); - wrapper.eq(StringUtils.isNotEmpty(entityDO.getDeviceCode()), DeviceDO::getDeviceCode, entityDO.getDeviceCode()); - wrapper.eq(DeviceDO::getTenantId, entityDO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DeviceDO one = getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityDO.getId()); - } + @Override + public boolean checkDuplicate(DeviceDO entityDO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DeviceDO::getDeviceName, entityDO.getDeviceName()); + wrapper.eq(StringUtils.isNotEmpty(entityDO.getDeviceCode()), DeviceDO::getDeviceCode, entityDO.getDeviceCode()); + wrapper.eq(DeviceDO::getTenantId, entityDO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DeviceDO one = getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityDO.getId()); + } - @Override - public DeviceDO innerSave(DeviceDO entityDO) { - boolean duplicate = checkDuplicate(entityDO, false); - if (duplicate) { - throw new DuplicateException("Failed to create device: device has been duplicated"); - } + @Override + public DeviceDO innerSave(DeviceDO entityDO) { + boolean duplicate = checkDuplicate(entityDO, false); + if (duplicate) { + throw new DuplicateException("Failed to create device: device has been duplicated"); + } - if (!save(entityDO)) { - throw new AddException("Failed to create device"); - } - return entityDO; - } + if (!save(entityDO)) { + throw new AddException("Failed to create device"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeConfigManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeConfigManagerImpl.java index eede5349e..380c5f686 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeConfigManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeConfigManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class DriverAttributeConfigManagerImpl extends ServiceImpl - implements DriverAttributeConfigManager { + implements DriverAttributeConfigManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeManagerImpl.java index 75d44a43b..520abead4 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/DriverAttributeManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class DriverAttributeManagerImpl extends ServiceImpl - implements DriverAttributeManager { + implements DriverAttributeManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeConfigManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeConfigManagerImpl.java index 42826fd32..2daf472da 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeConfigManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeConfigManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointAttributeConfigManagerImpl extends ServiceImpl - implements PointAttributeConfigManager { + implements PointAttributeConfigManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeManagerImpl.java index 03587a79b..2ff0084b8 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointAttributeManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointAttributeManagerImpl extends ServiceImpl - implements PointAttributeManager { + implements PointAttributeManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeHistoryManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeHistoryManagerImpl.java index 1cb33cd37..4e38e1d4d 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeHistoryManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeHistoryManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointDataVolumeHistoryManagerImpl extends - ServiceImpl implements PointDataVolumeHistoryManager { + ServiceImpl implements PointDataVolumeHistoryManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeRunManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeRunManagerImpl.java index c54cc8247..b9948d37c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeRunManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/PointDataVolumeRunManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class PointDataVolumeRunManagerImpl extends ServiceImpl - implements PointDataVolumeRunManager { + implements PointDataVolumeRunManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/ProfileBindManagerImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/ProfileBindManagerImpl.java index 979524b40..f57f034b9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/ProfileBindManagerImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/dal/impl/ProfileBindManagerImpl.java @@ -34,6 +34,6 @@ import org.springframework.stereotype.Service; */ @Service public class ProfileBindManagerImpl extends ServiceImpl - implements ProfileBindManager { + implements ProfileBindManager { } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceBO.java index 84c6f783d..6ddc45fe0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceBO.java @@ -38,51 +38,51 @@ import java.util.List; @ToString(callSuper = true) public class DeviceBO extends BaseBO { - /** - * Device Name - */ - private String deviceName; + /** + * Device Name + */ + private String deviceName; - /** - * Device ID - */ - private String deviceCode; + /** + * Device ID + */ + private String deviceCode; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * - */ - private DeviceExt deviceExt; + /** + * + */ + private DeviceExt deviceExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // + // - /** - * ID - */ - private List profileIds; + /** + * ID + */ + private List profileIds; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceByPointBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceByPointBO.java index b18f2c5db..edbb3922e 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceByPointBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceByPointBO.java @@ -37,14 +37,14 @@ import java.util.List; @AllArgsConstructor public class DeviceByPointBO { - /** - * - */ - private Long count; + /** + * + */ + private Long count; - /** - * - */ - private List devices; + /** + * + */ + private List devices; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceDataVolumeRunBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceDataVolumeRunBO.java index e4b63c354..f2dec6aa2 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceDataVolumeRunBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DeviceDataVolumeRunBO.java @@ -36,14 +36,14 @@ import java.util.List; @AllArgsConstructor public class DeviceDataVolumeRunBO { - /** - * Name - */ - private String pointName; + /** + * Name + */ + private String pointName; - /** - * 7 days - */ - private List total; + /** + * 7 days + */ + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeBO.java index 5d468cac4..0e142c65b 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeBO.java @@ -37,54 +37,54 @@ import lombok.*; @ToString(callSuper = true) public class DriverAttributeBO extends BaseBO { - /** - * Name - */ - private String attributeName; + /** + * Name + */ + private String attributeName; - /** - * Code - */ - private String attributeCode; + /** + * Code + */ + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * - */ - private String defaultValue; + /** + * + */ + private String defaultValue; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * - */ - private DriverAttributeExt attributeExt; + /** + * + */ + private DriverAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeConfigBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeConfigBO.java index 533c43f19..f2269da6e 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeConfigBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverAttributeConfigBO.java @@ -36,44 +36,44 @@ import lombok.*; @ToString(callSuper = true) public class DriverAttributeConfigBO extends BaseBO { - /** - * ID - */ - private Long attributeId; + /** + * ID + */ + private Long attributeId; - /** - * - */ - private String configValue; + /** + * + */ + private String configValue; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * - */ - private JsonExt configExt; + /** + * + */ + private JsonExt configExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverBO.java index e6ee872db..091083506 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/DriverBO.java @@ -37,54 +37,54 @@ import lombok.*; @ToString(callSuper = true) public class DriverBO extends BaseBO { - /** - * Name - */ - private String driverName; + /** + * Name + */ + private String driverName; - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * Driver service name - */ - private String serviceName; + /** + * Driver service name + */ + private String serviceName; - /** - * - */ - private String serviceHost; + /** + * + */ + private String serviceHost; - /** - * Type - */ - private DriverTypeFlagEnum driverTypeFlag; + /** + * Type + */ + private DriverTypeFlagEnum driverTypeFlag; - /** - * - */ - private DriverExt driverExt; + /** + * + */ + private DriverExt driverExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeBO.java index 5f291ad68..a0cedac56 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeBO.java @@ -37,54 +37,54 @@ import lombok.*; @ToString(callSuper = true) public class PointAttributeBO extends BaseBO { - /** - * Name - */ - private String attributeName; + /** + * Name + */ + private String attributeName; - /** - * Code - */ - private String attributeCode; + /** + * Code + */ + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * - */ - private String defaultValue; + /** + * + */ + private String defaultValue; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * - */ - private PointAttributeExt attributeExt; + /** + * + */ + private PointAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeConfigBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeConfigBO.java index f7a7d5898..30f6779b3 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeConfigBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointAttributeConfigBO.java @@ -36,49 +36,49 @@ import lombok.*; @ToString(callSuper = true) public class PointAttributeConfigBO extends BaseBO { - /** - * ID - */ - private Long attributeId; + /** + * ID + */ + private Long attributeId; - /** - * - */ - private String configValue; + /** + * + */ + private String configValue; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * - */ - private JsonExt configExt; + /** + * + */ + private JsonExt configExt; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointBO.java index c8253db55..c18c1a181 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointBO.java @@ -40,86 +40,86 @@ import java.math.BigDecimal; @ToString(callSuper = true) public class PointBO extends BaseBO { - /** - * Name - */ - private String pointName; + /** + * Name + */ + private String pointName; - /** - * Code - */ - private String pointCode; + /** + * Code + */ + private String pointCode; - /** - * Type - */ - private PointTypeFlagEnum pointTypeFlag; + /** + * Type + */ + private PointTypeFlagEnum pointTypeFlag; - /** - * - */ - private RwFlagEnum rwFlag; + /** + * + */ + private RwFlagEnum rwFlag; - /** - * - */ - private BigDecimal baseValue; + /** + * + */ + private BigDecimal baseValue; - /** - * - */ - private BigDecimal multiple; + /** + * + */ + private BigDecimal multiple; - /** - * - */ - private Byte valueDecimal; + /** + * + */ + private Byte valueDecimal; - /** - * - */ - private String unit; + /** + * + */ + private String unit; - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; - /** - * - */ - private PointExt pointExt; + /** + * + */ + private PointExt pointExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - /** - * - */ - public void setByDefault() { - this.pointTypeFlag = PointTypeFlagEnum.STRING; - this.rwFlag = RwFlagEnum.R; - this.baseValue = BigDecimal.valueOf(0); - this.multiple = BigDecimal.valueOf(1); - this.valueDecimal = 6; - this.unit = ""; - } + /** + * + */ + public void setByDefault() { + this.pointTypeFlag = PointTypeFlagEnum.STRING; + this.rwFlag = RwFlagEnum.R; + this.baseValue = BigDecimal.valueOf(0); + this.multiple = BigDecimal.valueOf(1); + this.valueDecimal = 6; + this.unit = ""; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointConfigByDeviceBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointConfigByDeviceBO.java index daacf62c2..63576ca7d 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointConfigByDeviceBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointConfigByDeviceBO.java @@ -37,19 +37,19 @@ import java.util.List; @AllArgsConstructor public class PointConfigByDeviceBO { - /** - * - */ - private Long configCount; + /** + * + */ + private Long configCount; - /** - * - */ - private Long unConfigCount; + /** + * + */ + private Long unConfigCount; - /** - * - */ - private List points; + /** + * + */ + private List points; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataStatisticsByDriverIdBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataStatisticsByDriverIdBO.java index 37efba683..31ec5eee5 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataStatisticsByDriverIdBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataStatisticsByDriverIdBO.java @@ -36,14 +36,14 @@ import java.util.List; @AllArgsConstructor public class PointDataStatisticsByDriverIdBO { - /** - * Name - */ - private String driverName; + /** + * Name + */ + private String driverName; - /** - * 7 days - */ - private List total; + /** + * 7 days + */ + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataVolumeRunBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataVolumeRunBO.java index 34aad76e4..2b1ea40f3 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataVolumeRunBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/PointDataVolumeRunBO.java @@ -36,14 +36,14 @@ import java.util.List; @AllArgsConstructor public class PointDataVolumeRunBO { - /** - * Device Name - */ - private String deviceName; + /** + * Device Name + */ + private String deviceName; - /** - * 7 days - */ - private List total; + /** + * 7 days + */ + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBO.java index 234ea6501..7c97917ce 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBO.java @@ -38,49 +38,49 @@ import lombok.*; @ToString(callSuper = true) public class ProfileBO extends BaseBO { - /** - * Name - */ - private String profileName; + /** + * Name + */ + private String profileName; - /** - * Code - */ - private String profileCode; + /** + * Code + */ + private String profileCode; - /** - * Type - */ - private ProfileShareFlagEnum profileShareFlag; + /** + * Type + */ + private ProfileShareFlagEnum profileShareFlag; - /** - * Type - */ - private ProfileTypeFlagEnum profileTypeFlag; + /** + * Type + */ + private ProfileTypeFlagEnum profileTypeFlag; - /** - * - */ - private ProfileExt profileExt; + /** + * + */ + private ProfileExt profileExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBindBO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBindBO.java index 22093069d..fa826616a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBindBO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/ProfileBindBO.java @@ -34,19 +34,19 @@ import lombok.*; @ToString(callSuper = true) public class ProfileBindBO extends BaseBO { - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/BucketRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/BucketRow.java index ff66705d6..c59526396 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/BucketRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/BucketRow.java @@ -39,13 +39,13 @@ import lombok.ToString; @ToString public class BucketRow { - /** - * Group column value. Typed {@code Object} because different queries GROUP BY columns - * of different JDBC types (SMALLINT enable_flag, VARCHAR service_name, BIGINT - * driver_id). Service-side formatters narrow it per call-site. - */ - private Object key; + /** + * Group column value. Typed {@code Object} because different queries GROUP BY columns + * of different JDBC types (SMALLINT enable_flag, VARCHAR service_name, BIGINT + * driver_id). Service-side formatters narrow it per call-site. + */ + private Object key; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/DailyGrowthRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/DailyGrowthRow.java index 1892175ab..5e1d90fc0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/DailyGrowthRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/DailyGrowthRow.java @@ -31,8 +31,8 @@ import java.time.LocalDate; @ToString public class DailyGrowthRow { - private LocalDate day; + private LocalDate day; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/PointVolumeRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/PointVolumeRow.java index 63cd41f61..5bdc9b762 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/PointVolumeRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/PointVolumeRow.java @@ -30,10 +30,10 @@ import lombok.ToString; @ToString public class PointVolumeRow { - private long deviceId; + private long deviceId; - private long pointId; + private long pointId; - private long cnt; + private long cnt; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/ProfileBindingRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/ProfileBindingRow.java index a223d1c8e..7e0ab799a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/ProfileBindingRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/ProfileBindingRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class ProfileBindingRow { - private long profileId; + private long profileId; - private long deviceId; + private long deviceId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDeviceRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDeviceRow.java index f59c38957..95edd0e28 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDeviceRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDeviceRow.java @@ -30,12 +30,12 @@ import lombok.ToString; @ToString public class TopologyDeviceRow { - private long id; + private long id; - private String deviceName; + private String deviceName; - private long driverId; + private long driverId; - private long profileCount; + private long profileCount; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDriverRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDriverRow.java index e3fb6c898..ce0e36a8d 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDriverRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyDriverRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class TopologyDriverRow { - private long id; + private long id; - private String driverName; + private String driverName; - private long deviceCount; + private long deviceCount; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyPointRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyPointRow.java index f70a1a7aa..5bd9ddc6c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyPointRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyPointRow.java @@ -29,10 +29,10 @@ import lombok.ToString; @ToString public class TopologyPointRow { - private long id; + private long id; - private String pointName; + private String pointName; - private long profileId; + private long profileId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyProfileRow.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyProfileRow.java index a85b9ed79..18d76d1b8 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyProfileRow.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/bo/dashboard/TopologyProfileRow.java @@ -29,8 +29,8 @@ import lombok.ToString; @ToString public class TopologyProfileRow { - private long id; + private long id; - private String profileName; + private String profileName; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DeviceBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DeviceBuilder.java index 8b0c6d7d1..4c6fc4f2c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DeviceBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DeviceBuilder.java @@ -46,139 +46,149 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DeviceBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - DeviceBO buildBOByVO(DeviceVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + DeviceBO buildBOByVO(DeviceVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deviceExt", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - DeviceDO buildDOByBO(DeviceBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deviceExt", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + DeviceDO buildDOByBO(DeviceBO entityBO); - @AfterMapping - default void afterProcess(DeviceBO entityBO, @MappingTarget DeviceDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getDeviceCode())) { - entityDO.setDeviceCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(DeviceBO entityBO, @MappingTarget DeviceDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getDeviceCode())) { + entityDO.setDeviceCode(CodeUtil.getCode()); + } - // Json Ext - DeviceExt entityExt = entityBO.getDeviceExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setDeviceExt(ext); + // Json Ext + DeviceExt entityExt = entityBO.getDeviceExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setDeviceExt(ext); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "deviceExt", ignore = true) - @Mapping(target = "profileIds", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DeviceBO buildBOByDO(DeviceDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "deviceExt", ignore = true) + @Mapping(target = "profileIds", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DeviceBO buildBOByDO(DeviceDO entityDO); - @AfterMapping - default void afterProcess(DeviceDO entityDO, @MappingTarget DeviceBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getDeviceExt(); - if (Objects.nonNull(entityExt)) { - DeviceExt ext = new DeviceExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DeviceExt.Content.class)); - entityBO.setDeviceExt(ext); - } + @AfterMapping + default void afterProcess(DeviceDO entityDO, @MappingTarget DeviceBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getDeviceExt(); + if (Objects.nonNull(entityExt)) { + DeviceExt ext = new DeviceExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DeviceExt.Content.class)); + entityBO.setDeviceExt(ext); + } - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - DeviceVO buildVOByBO(DeviceBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + DeviceVO buildVOByBO(DeviceBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - DeviceByPointVO buildVOPointByBO(DeviceByPointBO deviceByPointBO); + DeviceByPointVO buildVOPointByBO(DeviceByPointBO deviceByPointBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DictionaryForManagerBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DictionaryForManagerBuilder.java index 3bc3cfcc5..b4d3e8a19 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DictionaryForManagerBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DictionaryForManagerBuilder.java @@ -35,103 +35,111 @@ import org.mapstruct.Mapping; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DictionaryForManagerBuilder extends DictionaryBuilder { - // + // - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByDriverBO(DriverBO entityBO) { - return DictionaryBO.builder().label(entityBO.getDriverName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByDriverBO(DriverBO entityBO) { + return DictionaryBO.builder().label(entityBO.getDriverName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByDriverBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByDriverBOPage(Page entityPageBO); - // + // - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByProfileBO(ProfileBO entityBO) { - return DictionaryBO.builder().label(entityBO.getProfileName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByProfileBO(ProfileBO entityBO) { + return DictionaryBO.builder().label(entityBO.getProfileName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByProfileBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByProfileBOPage(Page entityPageBO); - // + // - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByPointBO(PointBO entityBO) { - return DictionaryBO.builder().label(entityBO.getPointName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByPointBO(PointBO entityBO) { + return DictionaryBO.builder().label(entityBO.getPointName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByPointBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByPointBOPage(Page entityPageBO); - // + // - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - default DictionaryBO buildVOByDeviceBO(DeviceBO entityBO) { - return DictionaryBO.builder().label(entityBO.getDeviceName()).value(entityBO.getId().toString()).build(); - } + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + default DictionaryBO buildVOByDeviceBO(DeviceBO entityBO) { + return DictionaryBO.builder().label(entityBO.getDeviceName()).value(entityBO.getId().toString()).build(); + } - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByDeviceBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByDeviceBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeBuilder.java index 1cfb5ac2a..c454ee180 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeBuilder.java @@ -43,141 +43,151 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DriverAttributeBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - DriverAttributeBO buildBOByVO(DriverAttributeVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + DriverAttributeBO buildBOByVO(DriverAttributeVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - DriverAttributeDO buildDOByBO(DriverAttributeBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + DriverAttributeDO buildDOByBO(DriverAttributeBO entityBO); - @AfterMapping - default void afterProcess(DriverAttributeBO entityBO, @MappingTarget DriverAttributeDO entityDO) { - // Json Ext - DriverAttributeExt entityExt = entityBO.getAttributeExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setAttributeExt(ext); + @AfterMapping + default void afterProcess(DriverAttributeBO entityBO, @MappingTarget DriverAttributeDO entityDO) { + // Json Ext + DriverAttributeExt entityExt = entityBO.getAttributeExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setAttributeExt(ext); - // AttributeType Flag - AttributeTypeFlagEnum attributeTypeFlag = entityBO.getAttributeTypeFlag(); - Optional.ofNullable(attributeTypeFlag).ifPresent(value -> entityDO.setAttributeTypeFlag(value.getIndex())); + // AttributeType Flag + AttributeTypeFlagEnum attributeTypeFlag = entityBO.getAttributeTypeFlag(); + Optional.ofNullable(attributeTypeFlag).ifPresent(value -> entityDO.setAttributeTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverAttributeBO buildBOByDO(DriverAttributeDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverAttributeBO buildBOByDO(DriverAttributeDO entityDO); - @AfterMapping - default void afterProcess(DriverAttributeDO entityDO, @MappingTarget DriverAttributeBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getAttributeExt(); - if (Objects.nonNull(entityExt)) { - DriverAttributeExt ext = new DriverAttributeExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DriverAttributeExt.Content.class)); - entityBO.setAttributeExt(ext); - } + @AfterMapping + default void afterProcess(DriverAttributeDO entityDO, @MappingTarget DriverAttributeBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getAttributeExt(); + if (Objects.nonNull(entityExt)) { + DriverAttributeExt ext = new DriverAttributeExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DriverAttributeExt.Content.class)); + entityBO.setAttributeExt(ext); + } - // AttributeType Flag - Byte attributeTypeFlag = entityDO.getAttributeTypeFlag(); - entityBO.setAttributeTypeFlag(AttributeTypeFlagEnum.ofIndex(attributeTypeFlag)); + // AttributeType Flag + Byte attributeTypeFlag = entityDO.getAttributeTypeFlag(); + entityBO.setAttributeTypeFlag(AttributeTypeFlagEnum.ofIndex(attributeTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - DriverAttributeVO buildVOByBO(DriverAttributeBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + DriverAttributeVO buildVOByBO(DriverAttributeBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeConfigBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeConfigBuilder.java index dd4c84f0f..7738832bc 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverAttributeConfigBuilder.java @@ -38,107 +38,117 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DriverAttributeConfigBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - DriverAttributeConfigBO buildBOByVO(DriverAttributeConfigVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + DriverAttributeConfigBO buildBOByVO(DriverAttributeConfigVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - DriverAttributeConfigDO buildDOByBO(DriverAttributeConfigBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + DriverAttributeConfigDO buildDOByBO(DriverAttributeConfigBO entityBO); - @AfterMapping - default void afterProcess(DriverAttributeConfigBO entityBO, @MappingTarget DriverAttributeConfigDO entityDO) { - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + @AfterMapping + default void afterProcess(DriverAttributeConfigBO entityBO, @MappingTarget DriverAttributeConfigDO entityDO) { + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "enableFlag", ignore = true) - DriverAttributeConfigBO buildBOByDO(DriverAttributeConfigDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "enableFlag", ignore = true) + DriverAttributeConfigBO buildBOByDO(DriverAttributeConfigDO entityDO); - @AfterMapping - default void afterProcess(DriverAttributeConfigDO entityDO, @MappingTarget DriverAttributeConfigBO entityBO) { - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + @AfterMapping + default void afterProcess(DriverAttributeConfigDO entityDO, @MappingTarget DriverAttributeConfigBO entityBO) { + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - DriverAttributeConfigVO buildVOByBO(DriverAttributeConfigBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + DriverAttributeConfigVO buildVOByBO(DriverAttributeConfigBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverBuilder.java index e0875820d..1f2cce7a7 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/DriverBuilder.java @@ -45,146 +45,156 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface DriverBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - DriverBO buildBOByVO(DriverVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + DriverBO buildBOByVO(DriverVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - DriverDO buildDOByBO(DriverBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + DriverDO buildDOByBO(DriverBO entityBO); - @AfterMapping - default void afterProcess(DriverBO entityBO, @MappingTarget DriverDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getDriverCode())) { - entityDO.setDriverCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(DriverBO entityBO, @MappingTarget DriverDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getDriverCode())) { + entityDO.setDriverCode(CodeUtil.getCode()); + } - // Json Ext - DriverExt entityExt = entityBO.getDriverExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setDriverExt(ext); + // Json Ext + DriverExt entityExt = entityBO.getDriverExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setDriverExt(ext); - // DriverType Flag - DriverTypeFlagEnum driverTypeFlag = entityBO.getDriverTypeFlag(); - Optional.ofNullable(driverTypeFlag).ifPresent(value -> entityDO.setDriverTypeFlag(value.getIndex())); + // DriverType Flag + DriverTypeFlagEnum driverTypeFlag = entityBO.getDriverTypeFlag(); + Optional.ofNullable(driverTypeFlag).ifPresent(value -> entityDO.setDriverTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverBO buildBOByDO(DriverDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverBO buildBOByDO(DriverDO entityDO); - @AfterMapping - default void afterProcess(DriverDO entityDO, @MappingTarget DriverBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getDriverExt(); - if (Objects.nonNull(entityExt)) { - DriverExt ext = new DriverExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DriverExt.Content.class)); - entityBO.setDriverExt(ext); - } + @AfterMapping + default void afterProcess(DriverDO entityDO, @MappingTarget DriverBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getDriverExt(); + if (Objects.nonNull(entityExt)) { + DriverExt ext = new DriverExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), DriverExt.Content.class)); + entityBO.setDriverExt(ext); + } - // DriverType Flag - Byte driverTypeFlag = entityDO.getDriverTypeFlag(); - entityBO.setDriverTypeFlag(DriverTypeFlagEnum.ofIndex(driverTypeFlag)); + // DriverType Flag + Byte driverTypeFlag = entityDO.getDriverTypeFlag(); + entityBO.setDriverTypeFlag(DriverTypeFlagEnum.ofIndex(driverTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - DriverVO buildVOByBO(DriverBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + DriverVO buildVOByBO(DriverBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeBuilder.java index 763b01d6e..c13a7c2ba 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeBuilder.java @@ -43,141 +43,151 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface PointAttributeBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - PointAttributeBO buildBOByVO(PointAttributeVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + PointAttributeBO buildBOByVO(PointAttributeVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - PointAttributeDO buildDOByBO(PointAttributeBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + PointAttributeDO buildDOByBO(PointAttributeBO entityBO); - @AfterMapping - default void afterProcess(PointAttributeBO entityBO, @MappingTarget PointAttributeDO entityDO) { - // Json Ext - PointAttributeExt entityExt = entityBO.getAttributeExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setAttributeExt(ext); + @AfterMapping + default void afterProcess(PointAttributeBO entityBO, @MappingTarget PointAttributeDO entityDO) { + // Json Ext + PointAttributeExt entityExt = entityBO.getAttributeExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setAttributeExt(ext); - // AttributeType Flag - AttributeTypeFlagEnum attributeTypeFlag = entityBO.getAttributeTypeFlag(); - Optional.ofNullable(attributeTypeFlag).ifPresent(value -> entityDO.setAttributeTypeFlag(value.getIndex())); + // AttributeType Flag + AttributeTypeFlagEnum attributeTypeFlag = entityBO.getAttributeTypeFlag(); + Optional.ofNullable(attributeTypeFlag).ifPresent(value -> entityDO.setAttributeTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointAttributeBO buildBOByDO(PointAttributeDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointAttributeBO buildBOByDO(PointAttributeDO entityDO); - @AfterMapping - default void afterProcess(PointAttributeDO entityDO, @MappingTarget PointAttributeBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getAttributeExt(); - if (Objects.nonNull(entityExt)) { - PointAttributeExt ext = new PointAttributeExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), PointAttributeExt.Content.class)); - entityBO.setAttributeExt(ext); - } + @AfterMapping + default void afterProcess(PointAttributeDO entityDO, @MappingTarget PointAttributeBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getAttributeExt(); + if (Objects.nonNull(entityExt)) { + PointAttributeExt ext = new PointAttributeExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), PointAttributeExt.Content.class)); + entityBO.setAttributeExt(ext); + } - // AttributeType Flag - Byte attributeTypeFlag = entityDO.getAttributeTypeFlag(); - entityBO.setAttributeTypeFlag(AttributeTypeFlagEnum.ofIndex(attributeTypeFlag)); + // AttributeType Flag + Byte attributeTypeFlag = entityDO.getAttributeTypeFlag(); + entityBO.setAttributeTypeFlag(AttributeTypeFlagEnum.ofIndex(attributeTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - PointAttributeVO buildVOByBO(PointAttributeBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + PointAttributeVO buildVOByBO(PointAttributeBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeConfigBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeConfigBuilder.java index 95c15065b..b1badbcd2 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointAttributeConfigBuilder.java @@ -38,107 +38,117 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface PointAttributeConfigBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - PointAttributeConfigBO buildBOByVO(PointAttributeConfigVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + PointAttributeConfigBO buildBOByVO(PointAttributeConfigVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - PointAttributeConfigDO buildDOByBO(PointAttributeConfigBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + PointAttributeConfigDO buildDOByBO(PointAttributeConfigBO entityBO); - @AfterMapping - default void afterProcess(PointAttributeConfigBO entityBO, @MappingTarget PointAttributeConfigDO entityDO) { - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + @AfterMapping + default void afterProcess(PointAttributeConfigBO entityBO, @MappingTarget PointAttributeConfigDO entityDO) { + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "enableFlag", ignore = true) - PointAttributeConfigBO buildBOByDO(PointAttributeConfigDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "enableFlag", ignore = true) + PointAttributeConfigBO buildBOByDO(PointAttributeConfigDO entityDO); - @AfterMapping - default void afterProcess(PointAttributeConfigDO entityDO, @MappingTarget PointAttributeConfigBO entityBO) { - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + @AfterMapping + default void afterProcess(PointAttributeConfigDO entityDO, @MappingTarget PointAttributeConfigBO entityBO) { + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - PointAttributeConfigVO buildVOByBO(PointAttributeConfigBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + PointAttributeConfigVO buildVOByBO(PointAttributeConfigBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointBuilder.java index 3d89b01d5..23bd02229 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/PointBuilder.java @@ -46,165 +46,175 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface PointBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - PointBO buildBOByVO(PointVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + PointBO buildBOByVO(PointVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "pointExt", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - PointDO buildDOByBO(PointBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "pointExt", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + PointDO buildDOByBO(PointBO entityBO); - @AfterMapping - default void afterProcess(PointBO entityBO, @MappingTarget PointDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getPointCode())) { - entityDO.setPointCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(PointBO entityBO, @MappingTarget PointDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getPointCode())) { + entityDO.setPointCode(CodeUtil.getCode()); + } - // Json Ext - PointExt entityExt = entityBO.getPointExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setPointExt(ext); + // Json Ext + PointExt entityExt = entityBO.getPointExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setPointExt(ext); - // PointType Flag - PointTypeFlagEnum pointTypeFlag = entityBO.getPointTypeFlag(); - Optional.ofNullable(pointTypeFlag).ifPresent(value -> entityDO.setPointTypeFlag(value.getIndex())); + // PointType Flag + PointTypeFlagEnum pointTypeFlag = entityBO.getPointTypeFlag(); + Optional.ofNullable(pointTypeFlag).ifPresent(value -> entityDO.setPointTypeFlag(value.getIndex())); - // Rw Flag - RwFlagEnum rwFlag = entityBO.getRwFlag(); - Optional.ofNullable(rwFlag).ifPresent(value -> entityDO.setRwFlag(value.getIndex())); + // Rw Flag + RwFlagEnum rwFlag = entityBO.getRwFlag(); + Optional.ofNullable(rwFlag).ifPresent(value -> entityDO.setRwFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "pointExt", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointBO buildBOByDO(PointDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "pointExt", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointBO buildBOByDO(PointDO entityDO); - @AfterMapping - default void afterProcess(PointDO entityDO, @MappingTarget PointBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getPointExt(); - if (Objects.nonNull(entityExt)) { - PointExt ext = new PointExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), PointExt.Content.class)); - entityBO.setPointExt(ext); - } + @AfterMapping + default void afterProcess(PointDO entityDO, @MappingTarget PointBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getPointExt(); + if (Objects.nonNull(entityExt)) { + PointExt ext = new PointExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), PointExt.Content.class)); + entityBO.setPointExt(ext); + } - // PointType Flag - Byte pointTypeFlag = entityDO.getPointTypeFlag(); - entityBO.setPointTypeFlag(PointTypeFlagEnum.ofIndex(pointTypeFlag)); + // PointType Flag + Byte pointTypeFlag = entityDO.getPointTypeFlag(); + entityBO.setPointTypeFlag(PointTypeFlagEnum.ofIndex(pointTypeFlag)); - // Rw Flag - Byte rwFlag = entityDO.getRwFlag(); - entityBO.setRwFlag(RwFlagEnum.ofIndex(rwFlag)); + // Rw Flag + Byte rwFlag = entityDO.getRwFlag(); + entityBO.setRwFlag(RwFlagEnum.ofIndex(rwFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - PointVO buildVOByBO(PointBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + PointVO buildVOByBO(PointBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); - List buildVOPointDataByBO(List list); + List buildVOPointDataByBO(List list); - PointConfigByDeviceVO buildVODeviceByBO(PointConfigByDeviceBO pointConfigByDeviceBO); + PointConfigByDeviceVO buildVODeviceByBO(PointConfigByDeviceBO pointConfigByDeviceBO); - List buildVODeviceDataByBO(List list); + List buildVODeviceDataByBO(List list); - PointDataStatisticsByDriverIdVO buildVOPointDataDriverByBO( - PointDataStatisticsByDriverIdBO pointDataStatisticsByDriverIdBOList); + PointDataStatisticsByDriverIdVO buildVOPointDataDriverByBO( + PointDataStatisticsByDriverIdBO pointDataStatisticsByDriverIdBOList); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBindBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBindBuilder.java index 9e16a00ec..ea8da11db 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBindBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBindBuilder.java @@ -34,91 +34,101 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface ProfileBindBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - ProfileBindBO buildBOByVO(ProfileBindVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + ProfileBindBO buildBOByVO(ProfileBindVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "deleted", ignore = true) - ProfileBindDO buildDOByBO(ProfileBindBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "deleted", ignore = true) + ProfileBindDO buildDOByBO(ProfileBindBO entityBO); - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - ProfileBindBO buildBOByDO(ProfileBindDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + ProfileBindBO buildBOByDO(ProfileBindDO entityDO); - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - ProfileBindVO buildVOByBO(ProfileBindBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + ProfileBindVO buildVOByBO(ProfileBindBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBuilder.java index c1d30ea64..d65e993ae 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/builder/ProfileBuilder.java @@ -46,156 +46,166 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface ProfileBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - @Mapping(target = "tenantId", ignore = true) - ProfileBO buildBOByVO(ProfileVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + @Mapping(target = "tenantId", ignore = true) + ProfileBO buildBOByVO(ProfileVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO Array - * @return EntityBO Array - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO Array + * @return EntityBO Array + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to DO - * @param entityBO EntityBO - * @return EntityDO - */ - @Mapping(target = "profileExt", ignore = true) - @Mapping(target = "profileShareFlag", ignore = true) - @Mapping(target = "profileTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deleted", ignore = true) - ProfileDO buildDOByBO(ProfileBO entityBO); + /** + * BO to DO + * + * @param entityBO EntityBO + * @return EntityDO + */ + @Mapping(target = "profileExt", ignore = true) + @Mapping(target = "profileShareFlag", ignore = true) + @Mapping(target = "profileTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deleted", ignore = true) + ProfileDO buildDOByBO(ProfileBO entityBO); - @AfterMapping - default void afterProcess(ProfileBO entityBO, @MappingTarget ProfileDO entityDO) { - // Code - if (StringUtils.isEmpty(entityBO.getProfileCode())) { - entityDO.setProfileCode(CodeUtil.getCode()); - } + @AfterMapping + default void afterProcess(ProfileBO entityBO, @MappingTarget ProfileDO entityDO) { + // Code + if (StringUtils.isEmpty(entityBO.getProfileCode())) { + entityDO.setProfileCode(CodeUtil.getCode()); + } - // Json Ext - ProfileExt entityExt = entityBO.getProfileExt(); - JsonExt ext = new JsonExt(); - if (Objects.nonNull(entityExt)) { - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); - } - entityDO.setProfileExt(ext); + // Json Ext + ProfileExt entityExt = entityBO.getProfileExt(); + JsonExt ext = new JsonExt(); + if (Objects.nonNull(entityExt)) { + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.toJsonString(entityExt.getContent())); + } + entityDO.setProfileExt(ext); - // ProfileShare Flag - ProfileShareFlagEnum profileShareFlag = entityBO.getProfileShareFlag(); - Optional.ofNullable(profileShareFlag).ifPresent(value -> entityDO.setProfileShareFlag(value.getIndex())); + // ProfileShare Flag + ProfileShareFlagEnum profileShareFlag = entityBO.getProfileShareFlag(); + Optional.ofNullable(profileShareFlag).ifPresent(value -> entityDO.setProfileShareFlag(value.getIndex())); - // ProfileType Flag - ProfileTypeFlagEnum profileTypeFlag = entityBO.getProfileTypeFlag(); - Optional.ofNullable(profileTypeFlag).ifPresent(value -> entityDO.setProfileTypeFlag(value.getIndex())); + // ProfileType Flag + ProfileTypeFlagEnum profileTypeFlag = entityBO.getProfileTypeFlag(); + Optional.ofNullable(profileTypeFlag).ifPresent(value -> entityDO.setProfileTypeFlag(value.getIndex())); - // Enable Flag - EnableFlagEnum enableFlag = entityBO.getEnableFlag(); - Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); - } + // Enable Flag + EnableFlagEnum enableFlag = entityBO.getEnableFlag(); + Optional.ofNullable(enableFlag).ifPresent(value -> entityDO.setEnableFlag(value.getIndex())); + } - /** - * BOList to DOList - * @param entityBOList EntityBO Array - * @return EntityDO Array - */ - List buildDOListByBOList(List entityBOList); + /** + * BOList to DOList + * + * @param entityBOList EntityBO Array + * @return EntityDO Array + */ + List buildDOListByBOList(List entityBOList); - /** - * DO to BO - * @param entityDO EntityDO - * @return EntityBO - */ - @Mapping(target = "profileExt", ignore = true) - @Mapping(target = "profileShareFlag", ignore = true) - @Mapping(target = "profileTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - ProfileBO buildBOByDO(ProfileDO entityDO); + /** + * DO to BO + * + * @param entityDO EntityDO + * @return EntityBO + */ + @Mapping(target = "profileExt", ignore = true) + @Mapping(target = "profileShareFlag", ignore = true) + @Mapping(target = "profileTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + ProfileBO buildBOByDO(ProfileDO entityDO); - @AfterMapping - default void afterProcess(ProfileDO entityDO, @MappingTarget ProfileBO entityBO) { - // Json Ext - JsonExt entityExt = entityDO.getProfileExt(); - if (Objects.nonNull(entityExt)) { - ProfileExt ext = new ProfileExt(); - ext.setType(entityExt.getType()); - ext.setVersion(entityExt.getVersion()); - ext.setRemark(entityExt.getRemark()); - ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ProfileExt.Content.class)); - entityBO.setProfileExt(ext); - } + @AfterMapping + default void afterProcess(ProfileDO entityDO, @MappingTarget ProfileBO entityBO) { + // Json Ext + JsonExt entityExt = entityDO.getProfileExt(); + if (Objects.nonNull(entityExt)) { + ProfileExt ext = new ProfileExt(); + ext.setType(entityExt.getType()); + ext.setVersion(entityExt.getVersion()); + ext.setRemark(entityExt.getRemark()); + ext.setContent(JsonUtil.parseObject(entityExt.getContent(), ProfileExt.Content.class)); + entityBO.setProfileExt(ext); + } - // ProfileShare Flag - Byte profileShareFlag = entityDO.getProfileShareFlag(); - entityBO.setProfileShareFlag(ProfileShareFlagEnum.ofIndex(profileShareFlag)); + // ProfileShare Flag + Byte profileShareFlag = entityDO.getProfileShareFlag(); + entityBO.setProfileShareFlag(ProfileShareFlagEnum.ofIndex(profileShareFlag)); - // ProfileType Flag - Byte profileTypeFlag = entityDO.getProfileTypeFlag(); - entityBO.setProfileTypeFlag(ProfileTypeFlagEnum.ofIndex(profileTypeFlag)); + // ProfileType Flag + Byte profileTypeFlag = entityDO.getProfileTypeFlag(); + entityBO.setProfileTypeFlag(ProfileTypeFlagEnum.ofIndex(profileTypeFlag)); - // Enable Flag - Byte enableFlag = entityDO.getEnableFlag(); - entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); - } + // Enable Flag + Byte enableFlag = entityDO.getEnableFlag(); + entityBO.setEnableFlag(EnableFlagEnum.ofIndex(enableFlag)); + } - /** - * DOList to BOList - * @param entityDOList EntityDO Array - * @return EntityBO Array - */ - List buildBOListByDOList(List entityDOList); + /** + * DOList to BOList + * + * @param entityDOList EntityDO Array + * @return EntityBO Array + */ + List buildBOListByDOList(List entityDOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - ProfileVO buildVOByBO(ProfileBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + ProfileVO buildVOByBO(ProfileBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO Array - * @return EntityVO Array - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO Array + * @return EntityVO Array + */ + List buildVOListByBOList(List entityBOList); - /** - * DOPage to BOPage - * @param entityPageDO EntityDO Page - * @return EntityBO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildBOPageByDOPage(Page entityPageDO); + /** + * DOPage to BOPage + * + * @param entityPageDO EntityDO Page + * @return EntityBO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildBOPageByDOPage(Page entityPageDO); - /** - * BOPage to VOPage - * @param entityPageBO EntityBO Page - * @return EntityVO Page - */ - @Mapping(target = "orders", ignore = true) - @Mapping(target = "countId", ignore = true) - @Mapping(target = "maxLimit", ignore = true) - @Mapping(target = "searchCount", ignore = true) - @Mapping(target = "optimizeCountSql", ignore = true) - @Mapping(target = "optimizeJoinOfCountSql", ignore = true) - Page buildVOPageByBOPage(Page entityPageBO); + /** + * BOPage to VOPage + * + * @param entityPageBO EntityBO Page + * @return EntityVO Page + */ + @Mapping(target = "orders", ignore = true) + @Mapping(target = "countId", ignore = true) + @Mapping(target = "maxLimit", ignore = true) + @Mapping(target = "searchCount", ignore = true) + @Mapping(target = "optimizeCountSql", ignore = true) + @Mapping(target = "optimizeJoinOfCountSql", ignore = true) + Page buildVOPageByBOPage(Page entityPageBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DeviceDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DeviceDO.java index bf7394feb..251e47b74 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DeviceDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DeviceDO.java @@ -43,110 +43,110 @@ import java.time.LocalDateTime; @TableName(value = "dc3_device", autoResultMap = true) public class DeviceDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Device Name - */ - @TableField("device_name") - private String deviceName; + /** + * Device Name + */ + @TableField("device_name") + private String deviceName; - /** - * Device ID - */ - @TableField("device_code") - private String deviceCode; + /** + * Device ID + */ + @TableField("device_code") + private String deviceCode; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * - */ - @TableField(value = "device_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt deviceExt; + /** + * + */ + @TableField(value = "device_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt deviceExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeConfigDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeConfigDO.java index 3ef776260..f87cd392f 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeConfigDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeConfigDO.java @@ -43,110 +43,110 @@ import java.time.LocalDateTime; @TableName(value = "dc3_driver_attribute_config", autoResultMap = true) public class DriverAttributeConfigDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("attribute_id") - private Long attributeId; + /** + * ID + */ + @TableField("attribute_id") + private Long attributeId; - /** - * - */ - @TableField("config_value") - private String configValue; + /** + * + */ + @TableField("config_value") + private String configValue; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * - */ - @TableField(value = "config_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt configExt; + /** + * + */ + @TableField(value = "config_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt configExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeDO.java index 74429349d..3084ebfb7 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverAttributeDO.java @@ -43,122 +43,122 @@ import java.time.LocalDateTime; @TableName(value = "dc3_driver_attribute", autoResultMap = true) public class DriverAttributeDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("attribute_name") - private String attributeName; + /** + * Name + */ + @TableField("attribute_name") + private String attributeName; - /** - * Code - */ - @TableField("attribute_code") - private String attributeCode; + /** + * Code + */ + @TableField("attribute_code") + private String attributeCode; - /** - * Type - */ - @TableField("attribute_type_flag") - private Byte attributeTypeFlag; + /** + * Type + */ + @TableField("attribute_type_flag") + private Byte attributeTypeFlag; - /** - * - */ - @TableField("default_value") - private String defaultValue; + /** + * + */ + @TableField("default_value") + private String defaultValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * - */ - @TableField(value = "attribute_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt attributeExt; + /** + * + */ + @TableField(value = "attribute_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt attributeExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverDO.java index c2b3497bd..2ec6b5ad3 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/DriverDO.java @@ -43,122 +43,122 @@ import java.time.LocalDateTime; @TableName(value = "dc3_driver", autoResultMap = true) public class DriverDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("driver_name") - private String driverName; + /** + * Name + */ + @TableField("driver_name") + private String driverName; - /** - * Driver ID - */ - @TableField("driver_code") - private String driverCode; + /** + * Driver ID + */ + @TableField("driver_code") + private String driverCode; - /** - * Name - */ - @TableField("service_name") - private String serviceName; + /** + * Name + */ + @TableField("service_name") + private String serviceName; - /** - * - */ - @TableField("service_host") - private String serviceHost; + /** + * + */ + @TableField("service_host") + private String serviceHost; - /** - * Type - */ - @TableField("driver_type_flag") - private Byte driverTypeFlag; + /** + * Type + */ + @TableField("driver_type_flag") + private Byte driverTypeFlag; - /** - * - */ - @TableField(value = "driver_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt driverExt; + /** + * + */ + @TableField(value = "driver_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt driverExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeConfigDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeConfigDO.java index 8d112ed6c..2376ba042 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeConfigDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeConfigDO.java @@ -43,116 +43,116 @@ import java.time.LocalDateTime; @TableName(value = "dc3_point_attribute_config", autoResultMap = true) public class PointAttributeConfigDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("attribute_id") - private Long attributeId; + /** + * ID + */ + @TableField("attribute_id") + private Long attributeId; - /** - * - */ - @TableField("config_value") - private String configValue; + /** + * + */ + @TableField("config_value") + private String configValue; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * - */ - @TableField(value = "config_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt configExt; + /** + * + */ + @TableField(value = "config_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt configExt; - /** - * Point ID - */ - @TableField("point_id") - private Long pointId; + /** + * Point ID + */ + @TableField("point_id") + private Long pointId; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeDO.java index 5ff0ea9c3..81f9969b6 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointAttributeDO.java @@ -43,122 +43,122 @@ import java.time.LocalDateTime; @TableName(value = "dc3_point_attribute", autoResultMap = true) public class PointAttributeDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("attribute_name") - private String attributeName; + /** + * Name + */ + @TableField("attribute_name") + private String attributeName; - /** - * Code - */ - @TableField("attribute_code") - private String attributeCode; + /** + * Code + */ + @TableField("attribute_code") + private String attributeCode; - /** - * Type - */ - @TableField("attribute_type_flag") - private Byte attributeTypeFlag; + /** + * Type + */ + @TableField("attribute_type_flag") + private Byte attributeTypeFlag; - /** - * - */ - @TableField("default_value") - private String defaultValue; + /** + * + */ + @TableField("default_value") + private String defaultValue; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * - */ - @TableField(value = "attribute_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt attributeExt; + /** + * + */ + @TableField(value = "attribute_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt attributeExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDO.java index 53a5d2a8b..28e8d0bf1 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDO.java @@ -43,146 +43,146 @@ import java.time.LocalDateTime; @TableName(value = "dc3_point", autoResultMap = true) public class PointDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("point_name") - private String pointName; + /** + * Name + */ + @TableField("point_name") + private String pointName; - /** - * Code - */ - @TableField("point_code") - private String pointCode; + /** + * Code + */ + @TableField("point_code") + private String pointCode; - /** - * Type - */ - @TableField("point_type_flag") - private Byte pointTypeFlag; + /** + * Type + */ + @TableField("point_type_flag") + private Byte pointTypeFlag; - /** - * - */ - @TableField("rw_flag") - private Byte rwFlag; + /** + * + */ + @TableField("rw_flag") + private Byte rwFlag; - /** - * - */ - @TableField("base_value") - private Double baseValue; + /** + * + */ + @TableField("base_value") + private Double baseValue; - /** - * - */ - @TableField("multiple") - private Double multiple; + /** + * + */ + @TableField("multiple") + private Double multiple; - /** - * - */ - @TableField("value_decimal") - private Byte valueDecimal; + /** + * + */ + @TableField("value_decimal") + private Byte valueDecimal; - /** - * - */ - @TableField("unit") - private String unit; + /** + * + */ + @TableField("unit") + private String unit; - /** - * ID - */ - @TableField("profile_id") - private Long profileId; + /** + * ID + */ + @TableField("profile_id") + private Long profileId; - /** - * - */ - @TableField(value = "point_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt pointExt; + /** + * + */ + @TableField(value = "point_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt pointExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeHistoryDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeHistoryDO.java index 2b5f7bd3f..53e8759ea 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeHistoryDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeHistoryDO.java @@ -41,98 +41,98 @@ import java.time.LocalDateTime; @TableName("dc3_point_data_volume_history") public class PointDataVolumeHistoryDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Code - */ - @TableField("point_id") - private Long pointId; + /** + * Code + */ + @TableField("point_id") + private Long pointId; - /** - * Name - */ - @TableField("point_name") - private String pointName; + /** + * Name + */ + @TableField("point_name") + private String pointName; - /** - * - */ - @TableField("total") - private Long total; + /** + * + */ + @TableField("total") + private Long total; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableField("deleted") - @TableLogic - private Integer deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableField("deleted") + @TableLogic + private Integer deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeRunDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeRunDO.java index 397cf2419..4e2280784 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeRunDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/PointDataVolumeRunDO.java @@ -41,98 +41,98 @@ import java.time.LocalDateTime; @TableName("dc3_point_data_volume_run") public class PointDataVolumeRunDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Driver ID - */ - @TableField("driver_id") - private Long driverId; + /** + * Driver ID + */ + @TableField("driver_id") + private Long driverId; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Code - */ - @TableField("point_id") - private Long pointId; + /** + * Code + */ + @TableField("point_id") + private Long pointId; - /** - * Name - */ - @TableField("point_name") - private String pointName; + /** + * Name + */ + @TableField("point_name") + private String pointName; - /** - * - */ - @TableField("total") - private Long total; + /** + * + */ + @TableField("total") + private Long total; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableField("deleted") - @TableLogic - private Integer deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableField("deleted") + @TableLogic + private Integer deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileBindDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileBindDO.java index cb0e302e1..7093849ca 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileBindDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileBindDO.java @@ -41,80 +41,80 @@ import java.time.LocalDateTime; @TableName("dc3_profile_bind") public class ProfileBindDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * ID - */ - @TableField("profile_id") - private Long profileId; + /** + * ID + */ + @TableField("profile_id") + private Long profileId; - /** - * Device ID - */ - @TableField("device_id") - private Long deviceId; + /** + * Device ID + */ + @TableField("device_id") + private Long deviceId; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileDO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileDO.java index e39d957c1..365ec5e70 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileDO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/model/ProfileDO.java @@ -43,116 +43,116 @@ import java.time.LocalDateTime; @TableName(value = "dc3_profile", autoResultMap = true) public class ProfileDO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @TableId(value = "id", type = IdType.ASSIGN_ID) - private Long id; + /** + * Primary key ID + */ + @TableId(value = "id", type = IdType.ASSIGN_ID) + private Long id; - /** - * Name - */ - @TableField("profile_name") - private String profileName; + /** + * Name + */ + @TableField("profile_name") + private String profileName; - /** - * Code - */ - @TableField("profile_code") - private String profileCode; + /** + * Code + */ + @TableField("profile_code") + private String profileCode; - /** - * Type - */ - @TableField("profile_share_flag") - private Byte profileShareFlag; + /** + * Type + */ + @TableField("profile_share_flag") + private Byte profileShareFlag; - /** - * Type - */ - @TableField("profile_type_flag") - private Byte profileTypeFlag; + /** + * Type + */ + @TableField("profile_type_flag") + private Byte profileTypeFlag; - /** - * - */ - @TableField(value = "profile_ext", typeHandler = JacksonTypeHandler.class) - private JsonExt profileExt; + /** + * + */ + @TableField(value = "profile_ext", typeHandler = JacksonTypeHandler.class) + private JsonExt profileExt; - /** - * Enable flag, 0:, 1:Disable - */ - @TableField("enable_flag") - private Byte enableFlag; + /** + * Enable flag, 0:, 1:Disable + */ + @TableField("enable_flag") + private Byte enableFlag; - /** - * Tenant ID - */ - @TableField("tenant_id") - private Long tenantId; + /** + * Tenant ID + */ + @TableField("tenant_id") + private Long tenantId; - /** - * Description - */ - @TableField("remark") - private String remark; + /** + * Description + */ + @TableField("remark") + private String remark; - /** - * - */ - @TableField("signature") - private String signature; + /** + * + */ + @TableField("signature") + private String signature; - /** - * - */ - @TableField("version") - private Integer version; + /** + * + */ + @TableField("version") + private Integer version; - /** - * Creator ID - */ - @TableField("creator_id") - private Long creatorId; + /** + * Creator ID + */ + @TableField("creator_id") + private Long creatorId; - /** - * Creator Name - */ - @TableField("creator_name") - private String creatorName; + /** + * Creator Name + */ + @TableField("creator_name") + private String creatorName; - /** - * Create Time - */ - @TableField("create_time") - private LocalDateTime createTime; + /** + * Create Time + */ + @TableField("create_time") + private LocalDateTime createTime; - /** - * Operator ID - */ - @TableField("operator_id") - private Long operatorId; + /** + * Operator ID + */ + @TableField("operator_id") + private Long operatorId; - /** - * Operator Name - */ - @TableField("operator_name") - private String operatorName; + /** + * Operator Name + */ + @TableField("operator_name") + private String operatorName; - /** - * Operate Time - */ - @TableField("operate_time") - private LocalDateTime operateTime; + /** + * Operate Time + */ + @TableField("operate_time") + private LocalDateTime operateTime; - /** - * Logical delete flag, 0:not deleted, 1:deleted - */ - @TableLogic - @TableField("deleted") - private Byte deleted; + /** + * Logical delete flag, 0:not deleted, 1:deleted + */ + @TableLogic + @TableField("deleted") + private Byte deleted; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DeviceQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DeviceQuery.java index 7bb4b3598..209ba2cbb 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DeviceQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DeviceQuery.java @@ -39,48 +39,48 @@ import java.io.Serializable; @AllArgsConstructor public class DeviceQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Device Name - */ - private String deviceName; + /** + * Device Name + */ + private String deviceName; - /** - * Device ID - */ - private String deviceCode; + /** + * Device ID + */ + private String deviceCode; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // + // - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DictionaryQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DictionaryQuery.java index 3f01af689..6e75e7d2f 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DictionaryQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DictionaryQuery.java @@ -36,20 +36,20 @@ import java.io.Serializable; @AllArgsConstructor public class DictionaryQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - private String label; + private String label; - private Long parentId; + private Long parentId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeConfigQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeConfigQuery.java index 33849fa84..b7a8561a4 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeConfigQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeConfigQuery.java @@ -39,36 +39,36 @@ import java.io.Serializable; @AllArgsConstructor public class DriverAttributeConfigQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * ID - */ - private Long attributeId; + /** + * ID + */ + private Long attributeId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeQuery.java index 0c482ed66..405fb7797 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverAttributeQuery.java @@ -40,46 +40,46 @@ import java.io.Serializable; @AllArgsConstructor public class DriverAttributeQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String attributeName; + /** + * Name + */ + private String attributeName; - /** - * Code - */ - private String attributeCode; + /** + * Code + */ + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverQuery.java index fb51e5247..b80862fa1 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/DriverQuery.java @@ -40,51 +40,51 @@ import java.io.Serializable; @AllArgsConstructor public class DriverQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String driverName; + /** + * Name + */ + private String driverName; - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * Driver service name - */ - private String serviceName; + /** + * Driver service name + */ + private String serviceName; - /** - * - */ - private String serviceHost; + /** + * + */ + private String serviceHost; - /** - * Type - */ - private DriverTypeFlagEnum driverTypeFlag; + /** + * Type + */ + private DriverTypeFlagEnum driverTypeFlag; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeConfigQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeConfigQuery.java index 1012c65cd..70426f5f4 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeConfigQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeConfigQuery.java @@ -39,41 +39,41 @@ import java.io.Serializable; @AllArgsConstructor public class PointAttributeConfigQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * ID - */ - private Long attributeId; + /** + * ID + */ + private Long attributeId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeQuery.java index 604a04c10..009cf5e98 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointAttributeQuery.java @@ -40,46 +40,46 @@ import java.io.Serializable; @AllArgsConstructor public class PointAttributeQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String attributeName; + /** + * Name + */ + private String attributeName; - /** - * Code - */ - private String attributeCode; + /** + * Code + */ + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointQuery.java index 68dbcb8e6..1891f435e 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/PointQuery.java @@ -41,58 +41,58 @@ import java.io.Serializable; @AllArgsConstructor public class PointQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String pointName; + /** + * Name + */ + private String pointName; - /** - * Code - */ - private String pointCode; + /** + * Code + */ + private String pointCode; - /** - * Type - */ - private PointTypeFlagEnum pointTypeFlag; + /** + * Type + */ + private PointTypeFlagEnum pointTypeFlag; - /** - * - */ - private RwFlagEnum rwFlag; + /** + * + */ + private RwFlagEnum rwFlag; - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // + // - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileBindQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileBindQuery.java index 7feecbc6f..d0ca7af45 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileBindQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileBindQuery.java @@ -38,26 +38,26 @@ import java.io.Serializable; @AllArgsConstructor public class ProfileBindQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * ID - */ - private Long profileId; + /** + * ID + */ + private Long profileId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileQuery.java index 0c6c84eb6..ee5673281 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/ProfileQuery.java @@ -41,53 +41,53 @@ import java.io.Serializable; @AllArgsConstructor public class ProfileQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID - */ - private Long tenantId; + /** + * Tenant ID + */ + private Long tenantId; - // + // - /** - * Name - */ - private String profileName; + /** + * Name + */ + private String profileName; - /** - * Code - */ - private String profileCode; + /** + * Code + */ + private String profileCode; - /** - * Type - */ - private ProfileShareFlagEnum profileShareFlag; + /** + * Type + */ + private ProfileShareFlagEnum profileShareFlag; - /** - * Type - */ - private ProfileTypeFlagEnum profileTypeFlag; + /** + * Type + */ + private ProfileTypeFlagEnum profileTypeFlag; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // + // - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/TopicQuery.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/TopicQuery.java index b5830937e..c788cb0d3 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/TopicQuery.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/query/TopicQuery.java @@ -38,21 +38,21 @@ import java.io.Serializable; @AllArgsConstructor public class TopicQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * - */ + /** + * + */ - private String topic; + private String topic; - /** - * Device Name - */ + /** + * Device Name + */ - private String deviceName; + private String deviceName; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceByPointVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceByPointVO.java index e197578f4..c0d889863 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceByPointVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceByPointVO.java @@ -39,14 +39,14 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DeviceByPointVO { - /** - * - */ - private Long count; + /** + * + */ + private Long count; - /** - * - */ - private List devices; + /** + * + */ + private List devices; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceDataVolumeRunVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceDataVolumeRunVO.java index 3a44c29db..21d99e586 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceDataVolumeRunVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceDataVolumeRunVO.java @@ -38,8 +38,8 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DeviceDataVolumeRunVO { - private String pointName; + private String pointName; - private List total; + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceVO.java index a04267746..b5b2482aa 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DeviceVO.java @@ -46,47 +46,47 @@ import java.util.Set; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DeviceVO extends BaseVO { - /** - * Device Name - */ - @NotBlank(message = "设备名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "设备名称格式无效", - groups = { Add.class, Update.class }) - private String deviceName; + /** + * Device Name + */ + @NotBlank(message = "设备名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "设备名称格式无效", + groups = {Add.class, Update.class}) + private String deviceName; - /** - * Device ID - */ - private String deviceCode; + /** + * Device ID + */ + private String deviceCode; - /** - * Driver ID - */ - @NotNull(message = "驱动ID不能为空", groups = { Add.class, Update.class, Upload.class }) - private Long driverId; + /** + * Driver ID + */ + @NotNull(message = "驱动ID不能为空", groups = {Add.class, Update.class, Upload.class}) + private Long driverId; - /** - * - */ - private DeviceExt deviceExt; + /** + * + */ + private DeviceExt deviceExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; - // - @NotNull(message = "ID", groups = { Upload.class }) - private Set profileIds; + // + @NotNull(message = "ID", groups = {Upload.class}) + private Set profileIds; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeConfigVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeConfigVO.java index a78af8c02..4e7b869ee 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeConfigVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeConfigVO.java @@ -41,42 +41,42 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DriverAttributeConfigVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "驱动属性ID不能为空", groups = { Add.class, Update.class }) - private Long attributeId; + /** + * ID + */ + @NotNull(message = "驱动属性ID不能为空", groups = {Add.class, Update.class}) + private Long attributeId; - /** - * - */ - @NotNull(message = "驱动属性配置值不能为空") - private String configValue; + /** + * + */ + @NotNull(message = "驱动属性配置值不能为空") + private String configValue; - /** - * Device ID - */ - @NotNull(message = "设备ID不能为空", groups = { Add.class, Update.class }) - private Long deviceId; + /** + * Device ID + */ + @NotNull(message = "设备ID不能为空", groups = {Add.class, Update.class}) + private Long deviceId; - /** - * - */ - private JsonExt configExt; + /** + * + */ + private JsonExt configExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeVO.java index 8b61a3a86..2febed5ae 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverAttributeVO.java @@ -44,56 +44,56 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DriverAttributeVO extends BaseVO { - /** - * Name - */ - @NotBlank(message = "属性名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "属性名称格式无效", - groups = { Add.class, Update.class }) - private String attributeName; + /** + * Name + */ + @NotBlank(message = "属性名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "属性名称格式无效", + groups = {Add.class, Update.class}) + private String attributeName; - /** - * Code - */ - @NotBlank(message = "属性编号不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "属性编号格式无效", - groups = { Add.class, Update.class }) - private String attributeCode; + /** + * Code + */ + @NotBlank(message = "属性编号不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "属性编号格式无效", + groups = {Add.class, Update.class}) + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * - */ - private String defaultValue; + /** + * + */ + private String defaultValue; - /** - * Driver ID - */ - @NotNull(message = "驱动ID不能为空", groups = { Add.class, Update.class }) - private Long driverId; + /** + * Driver ID + */ + @NotNull(message = "驱动ID不能为空", groups = {Add.class, Update.class}) + private Long driverId; - /** - * - */ - private DriverAttributeExt attributeExt; + /** + * + */ + private DriverAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverVO.java index 9be743350..4fe2fb4e1 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/DriverVO.java @@ -43,58 +43,58 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class DriverVO extends BaseVO { - /** - * Name - */ - @NotBlank(message = "驱动名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "驱动名称格式无效", - groups = { Add.class, Update.class }) - private String driverName; + /** + * Name + */ + @NotBlank(message = "驱动名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "驱动名称格式无效", + groups = {Add.class, Update.class}) + private String driverName; - /** - * Driver ID - */ - private String driverCode; + /** + * Driver ID + */ + private String driverCode; - /** - * Driver service name - */ - @NotBlank(message = "服务名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9\\-_#@/.|]{1,31}$", message = "服务名称格式无效", - groups = { Add.class, Update.class }) - private String serviceName; + /** + * Driver service name + */ + @NotBlank(message = "服务名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9\\-_#@/.|]{1,31}$", message = "服务名称格式无效", + groups = {Add.class, Update.class}) + private String serviceName; - /** - * - */ - @NotBlank(message = "服务主机不能为空", groups = { Add.class }) - @Pattern(regexp = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$", - message = "服务主机格式无效", groups = { Add.class, Update.class }) - private String serviceHost; + /** + * + */ + @NotBlank(message = "服务主机不能为空", groups = {Add.class}) + @Pattern(regexp = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$", + message = "服务主机格式无效", groups = {Add.class, Update.class}) + private String serviceHost; - /** - * Type - */ - private DriverTypeFlagEnum driverTypeFlag; + /** + * Type + */ + private DriverTypeFlagEnum driverTypeFlag; - /** - * - */ - private DriverExt driverExt; + /** + * + */ + private DriverExt driverExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeConfigVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeConfigVO.java index 14b3deb47..3d09242c4 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeConfigVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeConfigVO.java @@ -41,48 +41,48 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointAttributeConfigVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "位号属性ID不能为空", groups = { Add.class, Update.class }) - private Long attributeId; + /** + * ID + */ + @NotNull(message = "位号属性ID不能为空", groups = {Add.class, Update.class}) + private Long attributeId; - /** - * - */ - @NotNull(message = "位号属性配置值不能为空") - private String configValue; + /** + * + */ + @NotNull(message = "位号属性配置值不能为空") + private String configValue; - /** - * Device ID - */ - @NotNull(message = "设备ID不能为空", groups = { Add.class, Update.class }) - private Long deviceId; + /** + * Device ID + */ + @NotNull(message = "设备ID不能为空", groups = {Add.class, Update.class}) + private Long deviceId; - /** - * - */ - private JsonExt configExt; + /** + * + */ + private JsonExt configExt; - /** - * Point ID - */ - @NotNull(message = "位号ID不能为空", groups = { Add.class, Update.class }) - private Long pointId; + /** + * Point ID + */ + @NotNull(message = "位号ID不能为空", groups = {Add.class, Update.class}) + private Long pointId; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeVO.java index 561d25d03..52ddf60a6 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointAttributeVO.java @@ -44,56 +44,56 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointAttributeVO extends BaseVO { - /** - * Name - */ - @NotBlank(message = "属性名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "属性名称格式无效", - groups = { Add.class, Update.class }) - private String attributeName; + /** + * Name + */ + @NotBlank(message = "属性名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "属性名称格式无效", + groups = {Add.class, Update.class}) + private String attributeName; - /** - * Code - */ - @NotBlank(message = "属性编号不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "属性编号格式无效", - groups = { Add.class, Update.class }) - private String attributeCode; + /** + * Code + */ + @NotBlank(message = "属性编号不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9][A-Za-z0-9-_#@/.|]{1,31}$", message = "属性编号格式无效", + groups = {Add.class, Update.class}) + private String attributeCode; - /** - * Type - */ - private AttributeTypeFlagEnum attributeTypeFlag; + /** + * Type + */ + private AttributeTypeFlagEnum attributeTypeFlag; - /** - * - */ - private String defaultValue; + /** + * + */ + private String defaultValue; - /** - * Driver ID - */ - @NotNull(message = "驱动ID不能为空", groups = { Add.class, Update.class }) - private Long driverId; + /** + * Driver ID + */ + @NotNull(message = "驱动ID不能为空", groups = {Add.class, Update.class}) + private Long driverId; - /** - * - */ - private PointAttributeExt attributeExt; + /** + * + */ + private PointAttributeExt attributeExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointConfigByDeviceVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointConfigByDeviceVO.java index 2eb76b4bf..e80569cb9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointConfigByDeviceVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointConfigByDeviceVO.java @@ -39,19 +39,19 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointConfigByDeviceVO { - /** - * - */ - private Long unConfigCount; + /** + * + */ + private Long unConfigCount; - /** - * - */ - private Long configCount; + /** + * + */ + private Long configCount; - /** - * - */ - private List points; + /** + * + */ + private List points; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataStatisticsByDriverIdVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataStatisticsByDriverIdVO.java index b6c39f9ed..8fd680af8 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataStatisticsByDriverIdVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataStatisticsByDriverIdVO.java @@ -38,8 +38,8 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointDataStatisticsByDriverIdVO { - private String driverName; + private String driverName; - private List total; + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataVolumeRunVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataVolumeRunVO.java index 79f9f5a0d..a1b8ab14c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataVolumeRunVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointDataVolumeRunVO.java @@ -38,8 +38,8 @@ import java.util.List; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointDataVolumeRunVO { - private String deviceName; + private String deviceName; - private List total; + private List total; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointVO.java index a71e53f5f..e73b9b4d0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/PointVO.java @@ -47,73 +47,73 @@ import java.math.BigDecimal; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class PointVO extends BaseVO { - /** - * Name - */ - @NotBlank(message = "位号名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "位号名称格式无效", - groups = { Add.class, Update.class }) - private String pointName; + /** + * Name + */ + @NotBlank(message = "位号名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "位号名称格式无效", + groups = {Add.class, Update.class}) + private String pointName; - /** - * Code - */ - private String pointCode; + /** + * Code + */ + private String pointCode; - /** - * Type - */ - private PointTypeFlagEnum pointTypeFlag; + /** + * Type + */ + private PointTypeFlagEnum pointTypeFlag; - /** - * - */ - private RwFlagEnum rwFlag; + /** + * + */ + private RwFlagEnum rwFlag; - /** - * - */ - private BigDecimal baseValue; + /** + * + */ + private BigDecimal baseValue; - /** - * - */ - private BigDecimal multiple; + /** + * + */ + private BigDecimal multiple; - /** - * - */ - private Byte valueDecimal; + /** + * + */ + private Byte valueDecimal; - /** - * - */ - private String unit; + /** + * + */ + private String unit; - /** - * ID - */ - @NotNull(message = "模版ID不能为空", groups = { Add.class, Update.class }) - private Long profileId; + /** + * ID + */ + @NotNull(message = "模版ID不能为空", groups = {Add.class, Update.class}) + private Long profileId; - /** - * - */ - private PointExt pointExt; + /** + * + */ + private PointExt pointExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileBindVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileBindVO.java index 8eb2f3030..be4e16b51 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileBindVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileBindVO.java @@ -39,16 +39,16 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ProfileBindVO extends BaseVO { - /** - * ID - */ - @NotNull(message = "模版ID不能为空", groups = { Add.class, Update.class }) - private Long profileId; + /** + * ID + */ + @NotNull(message = "模版ID不能为空", groups = {Add.class, Update.class}) + private Long profileId; - /** - * Device ID - */ - @NotNull(message = "设备ID不能为空", groups = { Add.class, Update.class }) - private Long deviceId; + /** + * Device ID + */ + @NotNull(message = "设备ID不能为空", groups = {Add.class, Update.class}) + private Long deviceId; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileVO.java index 16d8aa050..3a86d1ea0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/ProfileVO.java @@ -44,47 +44,47 @@ import lombok.*; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class ProfileVO extends BaseVO { - /** - * Name - */ - @NotBlank(message = "模版名称不能为空", groups = { Add.class }) - @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "模版名称格式无效", - groups = { Add.class, Update.class }) - private String profileName; + /** + * Name + */ + @NotBlank(message = "模版名称不能为空", groups = {Add.class}) + @Pattern(regexp = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$", message = "模版名称格式无效", + groups = {Add.class, Update.class}) + private String profileName; - /** - * Code - */ - private String profileCode; + /** + * Code + */ + private String profileCode; - /** - * Type - */ - private ProfileShareFlagEnum profileShareFlag; + /** + * Type + */ + private ProfileShareFlagEnum profileShareFlag; - /** - * Type - */ - private ProfileTypeFlagEnum profileTypeFlag; + /** + * Type + */ + private ProfileTypeFlagEnum profileTypeFlag; - /** - * - */ - private ProfileExt profileExt; + /** + * + */ + private ProfileExt profileExt; - /** - * Enable flag - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag + */ + private EnableFlagEnum enableFlag; - /** - * - */ - private String signature; + /** + * + */ + private String signature; - /** - * - */ - private Integer version; + /** + * + */ + private Integer version; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/TopicVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/TopicVO.java index f0d8fcb99..39d849885 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/TopicVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/TopicVO.java @@ -30,10 +30,10 @@ import lombok.Data; @Data public class TopicVO { - private String topic; + private String topic; - private String deviceName; + private String deviceName; - private String pointName; + private String pointName; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/BucketVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/BucketVO.java index 4c3a2de10..bd4997a94 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/BucketVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/BucketVO.java @@ -39,15 +39,15 @@ import java.io.Serializable; @AllArgsConstructor public class BucketVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Human-readable bucket key (e.g. "ENABLE", "DISABLE", "GATEWAY", or an entity id - * rendered as string). - */ - private String key; + /** + * Human-readable bucket key (e.g. "ENABLE", "DISABLE", "GATEWAY", or an entity id + * rendered as string). + */ + private String key; - private long count; + private long count; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DeviceStatsVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DeviceStatsVO.java index 4d437d387..496c337b7 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DeviceStatsVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DeviceStatsVO.java @@ -37,25 +37,25 @@ import java.util.List; @ToString public class DeviceStatsVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long total; + private long total; - /** - * Counts by enable flag. - */ - private List byEnable = new ArrayList<>(); + /** + * Counts by enable flag. + */ + private List byEnable = new ArrayList<>(); - /** - * Top-N devices grouped by driver_id — key is stringified driver id. - */ - private List byDriver = new ArrayList<>(); + /** + * Top-N devices grouped by driver_id — key is stringified driver id. + */ + private List byDriver = new ArrayList<>(); - /** - * Top-N profile bindings — key is stringified profile id. Note that one device may - * bind to multiple profiles, so these counts are bindings, not unique devices. - */ - private List byProfile = new ArrayList<>(); + /** + * Top-N profile bindings — key is stringified profile id. Note that one device may + * bind to multiple profiles, so these counts are bindings, not unique devices. + */ + private List byProfile = new ArrayList<>(); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DriverStatsVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DriverStatsVO.java index 170ca8bbf..46c703ac2 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DriverStatsVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/DriverStatsVO.java @@ -37,28 +37,28 @@ import java.util.List; @ToString public class DriverStatsVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long total; + private long total; - /** - * Counts by enable flag. {@link BucketVO#getKey()} is "ENABLE" or "DISABLE". - */ - private List byEnable = new ArrayList<>(); + /** + * Counts by enable flag. {@link BucketVO#getKey()} is "ENABLE" or "DISABLE". + */ + private List byEnable = new ArrayList<>(); - /** - * Counts by driver_type_flag. Key is the enum name (DRIVER_CLIENT, DRIVER_SERVER, - * GATEWAY, CONNECT). - */ - private List byType = new ArrayList<>(); + /** + * Counts by driver_type_flag. Key is the enum name (DRIVER_CLIENT, DRIVER_SERVER, + * GATEWAY, CONNECT). + */ + private List byType = new ArrayList<>(); - /** - * Counts by service_name — the real "protocol breakdown" the home dashboard exposes. - * Key is the raw service name (e.g. {@code dc3-driver-modbus-tcp}, - * {@code dc3-driver-mqtt}); the frontend strips the {@code dc3-driver-} prefix before - * rendering. - */ - private List byService = new ArrayList<>(); + /** + * Counts by service_name — the real "protocol breakdown" the home dashboard exposes. + * Key is the raw service name (e.g. {@code dc3-driver-modbus-tcp}, + * {@code dc3-driver-mqtt}); the frontend strips the {@code dc3-driver-} prefix before + * rendering. + */ + private List byService = new ArrayList<>(); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/GrowthVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/GrowthVO.java index 1ce11bd19..73fe4d4c9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/GrowthVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/GrowthVO.java @@ -39,15 +39,15 @@ import java.util.List; @NoArgsConstructor public class GrowthVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private List driver; + private List driver; - private List device; + private List device; - private List point; + private List point; - private List profile; + private List profile; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyHiddenChildVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyHiddenChildVO.java index 184c539e2..673fb1580 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyHiddenChildVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyHiddenChildVO.java @@ -36,20 +36,20 @@ import java.io.Serializable; @ToString public class TopologyHiddenChildVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Prefixed id, same scheme as {@link TopologyNodeVO#getId()} — {@code driver:{n}} / - * {@code device:{n}} / {@code point:{n}}. - */ - private String id; + /** + * Prefixed id, same scheme as {@link TopologyNodeVO#getId()} — {@code driver:{n}} / + * {@code device:{n}} / {@code point:{n}}. + */ + private String id; - private String name; + private String name; - /** - * {@code driver | device | point}. Profile layer does not get collapsed. - */ - private String type; + /** + * {@code driver | device | point}. Profile layer does not get collapsed. + */ + private String type; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyLinkVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyLinkVO.java index 08122c77d..48d406414 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyLinkVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyLinkVO.java @@ -39,13 +39,13 @@ import java.io.Serializable; @ToString public class TopologyLinkVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String source; + private String source; - private String target; + private String target; - private long value; + private long value; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyNodeVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyNodeVO.java index 5aaff3ee0..0afb12c4b 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyNodeVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyNodeVO.java @@ -38,37 +38,37 @@ import java.util.List; @ToString public class TopologyNodeVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Prefixed id — one of {@code driver:{n}}, {@code device:{n}}, {@code profile:{n}}, - * {@code point:{n}}, {@code others:{layer}:{parentId}}. - */ - private String id; + /** + * Prefixed id — one of {@code driver:{n}}, {@code device:{n}}, {@code profile:{n}}, + * {@code point:{n}}, {@code others:{layer}:{parentId}}. + */ + private String id; - /** - * Human-readable label. For {@code others:*} nodes, {@code "Others (N)"} where N is - * the count of hidden children. - */ - private String name; + /** + * Human-readable label. For {@code others:*} nodes, {@code "Others (N)"} where N is + * the count of hidden children. + */ + private String name; - /** - * 1 = driver, 2 = device, 3 = profile, 4 = point. Frontend fixes column x-position - * from this. - */ - private int layer; + /** + * 1 = driver, 2 = device, 3 = profile, 4 = point. Frontend fixes column x-position + * from this. + */ + private int layer; - /** - * {@code driver | device | profile | point | others}. Drives node colour + click - * routing. - */ - private String type; + /** + * {@code driver | device | profile | point | others}. Drives node colour + click + * routing. + */ + private String type; - /** - * Only populated on {@code others:*} nodes. List of the actual entities collapsed - * here — frontend shows these in a drill-in dialog. - */ - private List hiddenChildren; + /** + * Only populated on {@code others:*} nodes. List of the actual entities collapsed + * here — frontend shows these in a drill-in dialog. + */ + private List hiddenChildren; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyStatsVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyStatsVO.java index dc4ae0fa5..f8cfc1f54 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyStatsVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyStatsVO.java @@ -37,22 +37,22 @@ import java.io.Serializable; @ToString public class TopologyStatsVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long driverCount; + private long driverCount; - private long deviceCount; + private long deviceCount; - private long profileCount; + private long profileCount; - private long pointCount; + private long pointCount; - /** - * Short human-readable range label ("24h" / "7d" / ...) — present only when the - * server computed volumes over a time window (volume mode). null for cardinality mode - * so the frontend footer can skip it. - */ - private String rangeLabel; + /** + * Short human-readable range label ("24h" / "7d" / ...) — present only when the + * server computed volumes over a time window (volume mode). null for cardinality mode + * so the frontend footer can skip it. + */ + private String rangeLabel; } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyVO.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyVO.java index 0be2c9841..bd0a2500c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyVO.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/entity/vo/dashboard/TopologyVO.java @@ -45,13 +45,13 @@ import java.util.List; @ToString public class TopologyVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private List nodes = new ArrayList<>(); + private List nodes = new ArrayList<>(); - private List links = new ArrayList<>(); + private List links = new ArrayList<>(); - private TopologyStatsVO stats = new TopologyStatsVO(); + private TopologyStatsVO stats = new TopologyStatsVO(); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventListener.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventListener.java index 1b960847b..86db6bf23 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventListener.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventListener.java @@ -44,42 +44,40 @@ import java.util.List; @Component public class MetadataEventListener implements ApplicationListener { - @Resource - private DriverService driverService; + @Resource + private DriverService driverService; - @Resource - private RabbitTemplate rabbitTemplate; + @Resource + private RabbitTemplate rabbitTemplate; - @Async - @Override - public void onApplicationEvent(MetadataEvent metadataEvent) { - log.info("Metadata event listener received: {}", JsonUtil.toJsonString(metadataEvent)); - try { - Long id = metadataEvent.getId(); - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataEventDTO entityDTO = new MetadataEventDTO(id, metadataType, metadataEvent.getOperateType()); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - DriverBO entityBO = driverService.selectByDeviceId(id); - notifyDriver(entityBO.getServiceName(), entityDTO); - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - List entityBOList = driverService.selectByPointId(id); - entityBOList.forEach(entityBO -> notifyDriver(entityBO.getServiceName(), entityDTO)); - } - } - catch (Exception e) { - log.error("Metadata event listener error: {}", e.getMessage(), e); - } - } + @Async + @Override + public void onApplicationEvent(MetadataEvent metadataEvent) { + log.info("Metadata event listener received: {}", JsonUtil.toJsonString(metadataEvent)); + try { + Long id = metadataEvent.getId(); + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataEventDTO entityDTO = new MetadataEventDTO(id, metadataType, metadataEvent.getOperateType()); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + DriverBO entityBO = driverService.selectByDeviceId(id); + notifyDriver(entityBO.getServiceName(), entityDTO); + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + List entityBOList = driverService.selectByPointId(id); + entityBOList.forEach(entityBO -> notifyDriver(entityBO.getServiceName(), entityDTO)); + } + } catch (Exception e) { + log.error("Metadata event listener error: {}", e.getMessage(), e); + } + } - /** - * @param service - * @param entityDTO DriverTransferMetadataDTO - */ - private void notifyDriver(String service, MetadataEventDTO entityDTO) { - log.info("Notify driver[{}]: {}", service, JsonUtil.toJsonString(entityDTO)); - rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_METADATA, - RabbitConstant.ROUTING_DRIVER_METADATA_PREFIX + service, entityDTO); - } + /** + * @param service + * @param entityDTO DriverTransferMetadataDTO + */ + private void notifyDriver(String service, MetadataEventDTO entityDTO) { + log.info("Notify driver[{}]: {}", service, JsonUtil.toJsonString(entityDTO)); + rabbitTemplate.convertAndSend(RabbitConstant.TOPIC_EXCHANGE_METADATA, + RabbitConstant.ROUTING_DRIVER_METADATA_PREFIX + service, entityDTO); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventPublisher.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventPublisher.java index 9904a6292..18be45045 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventPublisher.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/event/metadata/MetadataEventPublisher.java @@ -36,18 +36,18 @@ import org.springframework.stereotype.Component; @EnableAsync public class MetadataEventPublisher { - private final ApplicationEventPublisher applicationEventPublisher; + private final ApplicationEventPublisher applicationEventPublisher; - public MetadataEventPublisher(ApplicationEventPublisher applicationEventPublisher) { - this.applicationEventPublisher = applicationEventPublisher; - } + public MetadataEventPublisher(ApplicationEventPublisher applicationEventPublisher) { + this.applicationEventPublisher = applicationEventPublisher; + } - /** - * @param metadataEvent MetadataEvent - */ - public void publishEvent(MetadataEvent metadataEvent) { - log.info("Metadata event publisher publishEvent: {}", JsonUtil.toJsonString(metadataEvent)); - applicationEventPublisher.publishEvent(metadataEvent); - } + /** + * @param metadataEvent MetadataEvent + */ + public void publishEvent(MetadataEvent metadataEvent) { + log.info("Metadata event publisher publishEvent: {}", JsonUtil.toJsonString(metadataEvent)); + applicationEventPublisher.publishEvent(metadataEvent); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/generator/MybatisGenerator.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/generator/MybatisGenerator.java index 53e296caa..cfeee6559 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/generator/MybatisGenerator.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/generator/MybatisGenerator.java @@ -35,29 +35,29 @@ import io.github.pnoker.common.utils.MybatisUtil; */ public class MybatisGenerator { - public static void main(String[] args) { - generator(); - } + public static void main(String[] args) { + generator(); + } - public static void generator() { - String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-manager/src/main"; - MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_manager", "dc3", "dc3dc3dc3") - .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) - .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) - .packageConfig(builder -> builder.parent("io.github.pnoker.common.manager") - .entity("entity.model") - .service("dal") - .serviceImpl("dal.impl") - .mapper("mapper") - .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/manager/dal", - OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/manager/dal/impl", OutputFile.xml, - path + "/resources/mapping"))) - .templateEngine(new FreemarkerTemplateEngine()) - .strategyConfig(MybatisUtil::defaultStrategyConfig) - .strategyConfig(builder -> builder.addInclude("dc3_device", "dc3_driver", "dc3_driver_attribute", - "dc3_driver_attribute_config", "dc3_point", "dc3_point_attribute", "dc3_point_attribute_config", - "dc3_profile", "dc3_profile_bind")) - .execute(); - } + public static void generator() { + String path = System.getProperty("user.dir") + "/dc3-common/dc3-common-manager/src/main"; + MybatisUtil.defaultGenerator("dc3-postgres", "35432", "dc3", "dc3_manager", "dc3", "dc3dc3dc3") + .globalConfig(builder -> MybatisUtil.defaultGlobalConfig(builder, path)) + .dataSourceConfig(MybatisUtil::defaultDataSourceConfig) + .packageConfig(builder -> builder.parent("io.github.pnoker.common.manager") + .entity("entity.model") + .service("dal") + .serviceImpl("dal.impl") + .mapper("mapper") + .pathInfo(ImmutableMap.of(OutputFile.service, path + "/java/io/github/pnoker/common/manager/dal", + OutputFile.serviceImpl, path + "/java/io/github/pnoker/common/manager/dal/impl", OutputFile.xml, + path + "/resources/mapping"))) + .templateEngine(new FreemarkerTemplateEngine()) + .strategyConfig(MybatisUtil::defaultStrategyConfig) + .strategyConfig(builder -> builder.addInclude("dc3_device", "dc3_driver", "dc3_driver_attribute", + "dc3_driver_attribute_config", "dc3_point", "dc3_point_attribute", "dc3_point_attribute_config", + "dc3_profile", "dc3_profile_bind")) + .execute(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDeviceBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDeviceBuilder.java index bc61026ef..4d6c5abbf 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDeviceBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDeviceBuilder.java @@ -43,80 +43,83 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDeviceBuilder { - /** - * Grpc Query to Query - * @param entityQuery GrpcPageDeviceQuery - * @return DeviceQuery - */ - @Mapping(target = "page", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DeviceQuery buildQueryByGrpcQuery(GrpcPageDeviceQuery entityQuery); + /** + * Grpc Query to Query + * + * @param entityQuery GrpcPageDeviceQuery + * @return DeviceQuery + */ + @Mapping(target = "page", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DeviceQuery buildQueryByGrpcQuery(GrpcPageDeviceQuery entityQuery); - @AfterMapping - default void afterProcess(GrpcPageDeviceQuery entityGrpc, - @MappingTarget DeviceQuery.DeviceQueryBuilder entityQuery) { - Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); - entityQuery.page(pages); + @AfterMapping + default void afterProcess(GrpcPageDeviceQuery entityGrpc, + @MappingTarget DeviceQuery.DeviceQueryBuilder entityQuery) { + Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); + entityQuery.page(pages); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); - } + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); + } - /** - * Grpc Query to Query - * @param entityQuery GrpcPageDeviceQuery - * @return DeviceQuery - */ - @Mapping(target = "page", ignore = true) - @Mapping(target = "deviceName", ignore = true) - @Mapping(target = "deviceCode", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "version", ignore = true) - @Mapping(target = "profileId", ignore = true) - DeviceQuery buildQueryByGrpcQuery(io.github.pnoker.api.common.driver.GrpcPageDeviceQuery entityQuery); + /** + * Grpc Query to Query + * + * @param entityQuery GrpcPageDeviceQuery + * @return DeviceQuery + */ + @Mapping(target = "page", ignore = true) + @Mapping(target = "deviceName", ignore = true) + @Mapping(target = "deviceCode", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "version", ignore = true) + @Mapping(target = "profileId", ignore = true) + DeviceQuery buildQueryByGrpcQuery(io.github.pnoker.api.common.driver.GrpcPageDeviceQuery entityQuery); - @AfterMapping - default void afterProcess(io.github.pnoker.api.common.driver.GrpcPageDeviceQuery entityGrpc, - @MappingTarget DeviceQuery.DeviceQueryBuilder entityQuery) { - Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); - entityQuery.page(pages); - } + @AfterMapping + default void afterProcess(io.github.pnoker.api.common.driver.GrpcPageDeviceQuery entityGrpc, + @MappingTarget DeviceQuery.DeviceQueryBuilder entityQuery) { + Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); + entityQuery.page(pages); + } - /** - * BO to Grpc DTO - * @param entityBO DeviceBO - * @return GrpcDeviceDTO - */ - @Mapping(target = "deviceExt", ignore = true) - @Mapping(target = "profileIdsList", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "deviceNameBytes", ignore = true) - @Mapping(target = "deviceCodeBytes", ignore = true) - @Mapping(target = "deviceExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDeviceDTO buildGrpcDTOByBO(DeviceBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO DeviceBO + * @return GrpcDeviceDTO + */ + @Mapping(target = "deviceExt", ignore = true) + @Mapping(target = "profileIdsList", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "deviceNameBytes", ignore = true) + @Mapping(target = "deviceCodeBytes", ignore = true) + @Mapping(target = "deviceExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDeviceDTO buildGrpcDTOByBO(DeviceBO entityBO); - @AfterMapping - default void afterProcess(DeviceBO entityBO, @MappingTarget GrpcDeviceDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DeviceBO entityBO, @MappingTarget GrpcDeviceDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - CollectionOptional.ofNullable(entityBO.getProfileIds()).ifPresent(entityGrpc::addAllProfileIds); - Optional.ofNullable(entityBO.getDeviceExt()) - .ifPresent(value -> entityGrpc.setDeviceExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + CollectionOptional.ofNullable(entityBO.getProfileIds()).ifPresent(entityGrpc::addAllProfileIds); + Optional.ofNullable(entityBO.getDeviceExt()) + .ifPresent(value -> entityGrpc.setDeviceExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeBuilder.java index d114c0d32..38fa573e6 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeBuilder.java @@ -42,74 +42,76 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDriverAttributeBuilder { - /** - * Grpc DTO to BO - * @param entityGrpc GrpcDriverAttributeDTO - * @return DriverAttributeBO - */ - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverAttributeBO buildBOByGrpcDTO(GrpcDriverAttributeDTO entityGrpc); + /** + * Grpc DTO to BO + * + * @param entityGrpc GrpcDriverAttributeDTO + * @return DriverAttributeBO + */ + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverAttributeBO buildBOByGrpcDTO(GrpcDriverAttributeDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDriverAttributeDTO entityGrpc, @MappingTarget DriverAttributeBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcDriverAttributeDTO entityGrpc, @MappingTarget DriverAttributeBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - JsonOptional.ofNullable(entityGrpc.getAttributeExt()) - .ifPresent(value -> entityBO.setAttributeExt(JsonUtil.parseObject(value, DriverAttributeExt.class))); - Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) - .ifPresent(entityBO::setAttributeTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getAttributeExt()) + .ifPresent(value -> entityBO.setAttributeExt(JsonUtil.parseObject(value, DriverAttributeExt.class))); + Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) + .ifPresent(entityBO::setAttributeTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } - /** - * BO to Grpc DTO - * @param entityBO DriverAttributeBO - * @return GrpcDriverAttributeDTO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "attributeNameBytes", ignore = true) - @Mapping(target = "attributeCodeBytes", ignore = true) - @Mapping(target = "defaultValueBytes", ignore = true) - @Mapping(target = "attributeExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDriverAttributeDTO buildGrpcDTOByBO(DriverAttributeBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO DriverAttributeBO + * @return GrpcDriverAttributeDTO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "attributeNameBytes", ignore = true) + @Mapping(target = "attributeCodeBytes", ignore = true) + @Mapping(target = "defaultValueBytes", ignore = true) + @Mapping(target = "attributeExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDriverAttributeDTO buildGrpcDTOByBO(DriverAttributeBO entityBO); - @AfterMapping - default void afterProcess(DriverAttributeBO entityBO, @MappingTarget GrpcDriverAttributeDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DriverAttributeBO entityBO, @MappingTarget GrpcDriverAttributeDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getAttributeExt()) - .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getAttributeTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), - () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getAttributeExt()) + .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getAttributeTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), + () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeConfigBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeConfigBuilder.java index bb537b4be..924df38e5 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverAttributeConfigBuilder.java @@ -37,36 +37,37 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDriverAttributeConfigBuilder { - /** - * BO to Grpc DTO - * @param entityBO DriverAttributeConfigBO - * @return GrpcDriverAttributeConfigDTO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "configValueBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDriverAttributeConfigDTO buildGrpcDTOByBO(DriverAttributeConfigBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO DriverAttributeConfigBO + * @return GrpcDriverAttributeConfigDTO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "configValueBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDriverAttributeConfigDTO buildGrpcDTOByBO(DriverAttributeConfigBO entityBO); - @AfterMapping - default void afterProcess(DriverAttributeConfigBO entityBO, - @MappingTarget GrpcDriverAttributeConfigDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DriverAttributeConfigBO entityBO, + @MappingTarget GrpcDriverAttributeConfigDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverBuilder.java index c7226a02a..97a9d92ed 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcDriverBuilder.java @@ -45,96 +45,99 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcDriverBuilder { - /** - * Grpc Query to Query - * @param entityQuery GrpcPageDriverQuery - * @return DriverQuery - */ - @Mapping(target = "page", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverQuery buildQueryByGrpcQuery(GrpcPageDriverQuery entityQuery); + /** + * Grpc Query to Query + * + * @param entityQuery GrpcPageDriverQuery + * @return DriverQuery + */ + @Mapping(target = "page", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverQuery buildQueryByGrpcQuery(GrpcPageDriverQuery entityQuery); - @AfterMapping - default void afterProcess(GrpcPageDriverQuery entityGrpc, - @MappingTarget DriverQuery.DriverQueryBuilder entityQuery) { - Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); - entityQuery.page(pages); + @AfterMapping + default void afterProcess(GrpcPageDriverQuery entityGrpc, + @MappingTarget DriverQuery.DriverQueryBuilder entityQuery) { + Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); + entityQuery.page(pages); - Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) - .ifPresent(entityQuery::driverTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); - } + Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) + .ifPresent(entityQuery::driverTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); + } - /** - * BO to Grpc DTO - * @param entityBO DriverBO - * @return GrpcDriverDTO - */ - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "driverNameBytes", ignore = true) - @Mapping(target = "driverCodeBytes", ignore = true) - @Mapping(target = "serviceNameBytes", ignore = true) - @Mapping(target = "serviceHostBytes", ignore = true) - @Mapping(target = "driverExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcDriverDTO buildGrpcDTOByBO(DriverBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO DriverBO + * @return GrpcDriverDTO + */ + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "driverNameBytes", ignore = true) + @Mapping(target = "driverCodeBytes", ignore = true) + @Mapping(target = "serviceNameBytes", ignore = true) + @Mapping(target = "serviceHostBytes", ignore = true) + @Mapping(target = "driverExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcDriverDTO buildGrpcDTOByBO(DriverBO entityBO); - @AfterMapping - default void afterProcess(DriverBO entityBO, @MappingTarget GrpcDriverDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(DriverBO entityBO, @MappingTarget GrpcDriverDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getDriverExt()) - .ifPresent(value -> entityGrpc.setDriverExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getDriverTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setDriverTypeFlag(value.getIndex()), - () -> entityGrpc.setDriverTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getDriverExt()) + .ifPresent(value -> entityGrpc.setDriverExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getDriverTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setDriverTypeFlag(value.getIndex()), + () -> entityGrpc.setDriverTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } - /** - * Grpc DTO to BO - * @param entityGrpc GrpcDriverDTO - * @return DriverBO - */ - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "driverExt", ignore = true) - @Mapping(target = "driverTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - DriverBO buildBOByGrpcDTO(GrpcDriverDTO entityGrpc); + /** + * Grpc DTO to BO + * + * @param entityGrpc GrpcDriverDTO + * @return DriverBO + */ + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "driverExt", ignore = true) + @Mapping(target = "driverTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + DriverBO buildBOByGrpcDTO(GrpcDriverDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcDriverDTO entityGrpc, @MappingTarget DriverBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcDriverDTO entityGrpc, @MappingTarget DriverBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - JsonOptional.ofNullable(entityGrpc.getDriverExt()) - .ifPresent(value -> entityBO.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); - Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) - .ifPresent(entityBO::setDriverTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getDriverExt()) + .ifPresent(value -> entityBO.setDriverExt(JsonUtil.parseObject(value, DriverExt.class))); + Optional.ofNullable(DriverTypeFlagEnum.ofIndex((byte) entityGrpc.getDriverTypeFlag())) + .ifPresent(entityBO::setDriverTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeBuilder.java index bf82e09ac..ed6d81d71 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeBuilder.java @@ -42,74 +42,76 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcPointAttributeBuilder { - /** - * Grpc DTO to BO - * @param entityGrpc GrpcPointAttributeDTO - * @return PointAttributeBO - */ - @Mapping(target = "id", ignore = true) - @Mapping(target = "remark", ignore = true) - @Mapping(target = "creatorId", ignore = true) - @Mapping(target = "creatorName", ignore = true) - @Mapping(target = "createTime", ignore = true) - @Mapping(target = "operatorId", ignore = true) - @Mapping(target = "operatorName", ignore = true) - @Mapping(target = "operateTime", ignore = true) - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointAttributeBO buildBOByGrpcDTO(GrpcPointAttributeDTO entityGrpc); + /** + * Grpc DTO to BO + * + * @param entityGrpc GrpcPointAttributeDTO + * @return PointAttributeBO + */ + @Mapping(target = "id", ignore = true) + @Mapping(target = "remark", ignore = true) + @Mapping(target = "creatorId", ignore = true) + @Mapping(target = "creatorName", ignore = true) + @Mapping(target = "createTime", ignore = true) + @Mapping(target = "operatorId", ignore = true) + @Mapping(target = "operatorName", ignore = true) + @Mapping(target = "operateTime", ignore = true) + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointAttributeBO buildBOByGrpcDTO(GrpcPointAttributeDTO entityGrpc); - @AfterMapping - default void afterProcess(GrpcPointAttributeDTO entityGrpc, @MappingTarget PointAttributeBO entityBO) { - GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); + @AfterMapping + default void afterProcess(GrpcPointAttributeDTO entityGrpc, @MappingTarget PointAttributeBO entityBO) { + GrpcBuilderUtil.buildBaseBOByGrpcBase(entityGrpc.getBase(), entityBO); - JsonOptional.ofNullable(entityGrpc.getAttributeExt()) - .ifPresent(value -> entityBO.setAttributeExt(JsonUtil.parseObject(value, PointAttributeExt.class))); - Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) - .ifPresent(entityBO::setAttributeTypeFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); - } + JsonOptional.ofNullable(entityGrpc.getAttributeExt()) + .ifPresent(value -> entityBO.setAttributeExt(JsonUtil.parseObject(value, PointAttributeExt.class))); + Optional.ofNullable(AttributeTypeFlagEnum.ofIndex((byte) entityGrpc.getAttributeTypeFlag())) + .ifPresent(entityBO::setAttributeTypeFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityBO::setEnableFlag); + } - /** - * BO to Grpc DTO - * @param entityBO PointAttributeBO - * @return GrpcPointAttributeDTO - */ - @Mapping(target = "attributeExt", ignore = true) - @Mapping(target = "attributeTypeFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "attributeNameBytes", ignore = true) - @Mapping(target = "attributeCodeBytes", ignore = true) - @Mapping(target = "defaultValueBytes", ignore = true) - @Mapping(target = "attributeExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcPointAttributeDTO buildGrpcDTOByBO(PointAttributeBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO PointAttributeBO + * @return GrpcPointAttributeDTO + */ + @Mapping(target = "attributeExt", ignore = true) + @Mapping(target = "attributeTypeFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "attributeNameBytes", ignore = true) + @Mapping(target = "attributeCodeBytes", ignore = true) + @Mapping(target = "defaultValueBytes", ignore = true) + @Mapping(target = "attributeExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcPointAttributeDTO buildGrpcDTOByBO(PointAttributeBO entityBO); - @AfterMapping - default void afterProcess(PointAttributeBO entityBO, @MappingTarget GrpcPointAttributeDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(PointAttributeBO entityBO, @MappingTarget GrpcPointAttributeDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getAttributeExt()) - .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getAttributeTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), - () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getAttributeExt()) + .ifPresent(value -> entityGrpc.setAttributeExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getAttributeTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setAttributeTypeFlag(value.getIndex()), + () -> entityGrpc.setAttributeTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeConfigBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeConfigBuilder.java index f8c38c243..97c93c0bd 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeConfigBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointAttributeConfigBuilder.java @@ -37,36 +37,37 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcPointAttributeConfigBuilder { - /** - * BO to Grpc DTO - * @param entityBO PointAttributeConfigBO - * @return GrpcPointAttributeConfigDTO - */ - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "configValueBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcPointAttributeConfigDTO buildGrpcDTOByBO(PointAttributeConfigBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO PointAttributeConfigBO + * @return GrpcPointAttributeConfigDTO + */ + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "configValueBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcPointAttributeConfigDTO buildGrpcDTOByBO(PointAttributeConfigBO entityBO); - @AfterMapping - default void afterProcess(PointAttributeConfigBO entityBO, - @MappingTarget GrpcPointAttributeConfigDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(PointAttributeConfigBO entityBO, + @MappingTarget GrpcPointAttributeConfigDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointBuilder.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointBuilder.java index 7b1f9d515..0b5337292 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointBuilder.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/builder/GrpcPointBuilder.java @@ -44,88 +44,90 @@ import java.util.Optional; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface GrpcPointBuilder { - /** - * Grpc Query to Query - * @param entityQuery GrpcPagePointQuery - * @return PointQuery - */ - @Mapping(target = "page", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointQuery buildQueryByGrpcQuery(GrpcPagePointQuery entityQuery); + /** + * Grpc Query to Query + * + * @param entityQuery GrpcPagePointQuery + * @return PointQuery + */ + @Mapping(target = "page", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointQuery buildQueryByGrpcQuery(GrpcPagePointQuery entityQuery); - @AfterMapping - default void afterProcess(GrpcPagePointQuery entityGrpc, @MappingTarget PointQuery.PointQueryBuilder entityQuery) { - Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); - entityQuery.page(pages); + @AfterMapping + default void afterProcess(GrpcPagePointQuery entityGrpc, @MappingTarget PointQuery.PointQueryBuilder entityQuery) { + Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); + entityQuery.page(pages); - Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) entityGrpc.getPointTypeFlag())) - .ifPresent(entityQuery::pointTypeFlag); - Optional.ofNullable(RwFlagEnum.ofIndex((byte) entityGrpc.getRwFlag())).ifPresent(entityQuery::rwFlag); - EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); - } + Optional.ofNullable(PointTypeFlagEnum.ofIndex((byte) entityGrpc.getPointTypeFlag())) + .ifPresent(entityQuery::pointTypeFlag); + Optional.ofNullable(RwFlagEnum.ofIndex((byte) entityGrpc.getRwFlag())).ifPresent(entityQuery::rwFlag); + EnableOptional.ofNullable(entityGrpc.getEnableFlag()).ifPresent(entityQuery::enableFlag); + } - @Mapping(target = "page", ignore = true) - @Mapping(target = "pointName", ignore = true) - @Mapping(target = "pointCode", ignore = true) - @Mapping(target = "version", ignore = true) - @Mapping(target = "profileId", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - PointQuery buildQueryByGrpcQuery(io.github.pnoker.api.common.driver.GrpcPagePointQuery entityQuery); + @Mapping(target = "page", ignore = true) + @Mapping(target = "pointName", ignore = true) + @Mapping(target = "pointCode", ignore = true) + @Mapping(target = "version", ignore = true) + @Mapping(target = "profileId", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + PointQuery buildQueryByGrpcQuery(io.github.pnoker.api.common.driver.GrpcPagePointQuery entityQuery); - @AfterMapping - default void afterProcess(io.github.pnoker.api.common.driver.GrpcPagePointQuery entityGrpc, - @MappingTarget PointQuery.PointQueryBuilder entityQuery) { - Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); - entityQuery.page(pages); - } + @AfterMapping + default void afterProcess(io.github.pnoker.api.common.driver.GrpcPagePointQuery entityGrpc, + @MappingTarget PointQuery.PointQueryBuilder entityQuery) { + Pages pages = GrpcBuilderUtil.buildPagesByGrpcPage(entityGrpc.getPage()); + entityQuery.page(pages); + } - /** - * BO to Grpc DTO - * @param entityBO PointBO - * @return GrpcPointDTO - */ - @Mapping(target = "pointExt", ignore = true) - @Mapping(target = "pointTypeFlag", ignore = true) - @Mapping(target = "rwFlag", ignore = true) - @Mapping(target = "enableFlag", ignore = true) - @Mapping(target = "pointNameBytes", ignore = true) - @Mapping(target = "pointCodeBytes", ignore = true) - @Mapping(target = "unitBytes", ignore = true) - @Mapping(target = "pointExtBytes", ignore = true) - @Mapping(target = "signatureBytes", ignore = true) - @Mapping(target = "mergeFrom", ignore = true) - @Mapping(target = "clearField", ignore = true) - @Mapping(target = "clearOneof", ignore = true) - @Mapping(target = "base", ignore = true) - @Mapping(target = "mergeBase", ignore = true) - @Mapping(target = "unknownFields", ignore = true) - @Mapping(target = "mergeUnknownFields", ignore = true) - @Mapping(target = "allFields", ignore = true) - GrpcPointDTO buildGrpcDTOByBO(PointBO entityBO); + /** + * BO to Grpc DTO + * + * @param entityBO PointBO + * @return GrpcPointDTO + */ + @Mapping(target = "pointExt", ignore = true) + @Mapping(target = "pointTypeFlag", ignore = true) + @Mapping(target = "rwFlag", ignore = true) + @Mapping(target = "enableFlag", ignore = true) + @Mapping(target = "pointNameBytes", ignore = true) + @Mapping(target = "pointCodeBytes", ignore = true) + @Mapping(target = "unitBytes", ignore = true) + @Mapping(target = "pointExtBytes", ignore = true) + @Mapping(target = "signatureBytes", ignore = true) + @Mapping(target = "mergeFrom", ignore = true) + @Mapping(target = "clearField", ignore = true) + @Mapping(target = "clearOneof", ignore = true) + @Mapping(target = "base", ignore = true) + @Mapping(target = "mergeBase", ignore = true) + @Mapping(target = "unknownFields", ignore = true) + @Mapping(target = "mergeUnknownFields", ignore = true) + @Mapping(target = "allFields", ignore = true) + GrpcPointDTO buildGrpcDTOByBO(PointBO entityBO); - @AfterMapping - default void afterProcess(PointBO entityBO, @MappingTarget GrpcPointDTO.Builder entityGrpc) { - GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); - entityGrpc.setBase(grpcBase); + @AfterMapping + default void afterProcess(PointBO entityBO, @MappingTarget GrpcPointDTO.Builder entityGrpc) { + GrpcBase grpcBase = GrpcBuilderUtil.buildGrpcBaseByBO(entityBO); + entityGrpc.setBase(grpcBase); - Optional.ofNullable(entityBO.getPointExt()) - .ifPresent(value -> entityGrpc.setPointExt(JsonUtil.toJsonString(value))); - Optional.ofNullable(entityBO.getPointTypeFlag()) - .ifPresentOrElse(value -> entityGrpc.setPointTypeFlag(value.getIndex()), - () -> entityGrpc.setPointTypeFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getRwFlag()) - .ifPresentOrElse(value -> entityGrpc.setRwFlag(value.getIndex()), - () -> entityGrpc.setRwFlag(DefaultConstant.NULL_INT)); - Optional.ofNullable(entityBO.getEnableFlag()) - .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), - () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); - } + Optional.ofNullable(entityBO.getPointExt()) + .ifPresent(value -> entityGrpc.setPointExt(JsonUtil.toJsonString(value))); + Optional.ofNullable(entityBO.getPointTypeFlag()) + .ifPresentOrElse(value -> entityGrpc.setPointTypeFlag(value.getIndex()), + () -> entityGrpc.setPointTypeFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getRwFlag()) + .ifPresentOrElse(value -> entityGrpc.setRwFlag(value.getIndex()), + () -> entityGrpc.setRwFlag(DefaultConstant.NULL_INT)); + Optional.ofNullable(entityBO.getEnableFlag()) + .ifPresentOrElse(value -> entityGrpc.setEnableFlag(value.getIndex()), + () -> entityGrpc.setEnableFlag(DefaultConstant.DEFAULT_INT)); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDeviceServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDeviceServer.java index 3868b10a5..c08463dc7 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDeviceServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDeviceServer.java @@ -55,113 +55,111 @@ import java.util.Objects; @Service public class DriverDeviceServer extends DeviceApiGrpc.DeviceApiImplBase { - @Resource - private GrpcDeviceBuilder grpcDeviceBuilder; + @Resource + private GrpcDeviceBuilder grpcDeviceBuilder; - @Resource - private GrpcDriverAttributeConfigBuilder grpcDriverAttributeConfigBuilder; + @Resource + private GrpcDriverAttributeConfigBuilder grpcDriverAttributeConfigBuilder; - @Resource - private GrpcPointAttributeConfigBuilder grpcPointAttributeConfigBuilder; + @Resource + private GrpcPointAttributeConfigBuilder grpcPointAttributeConfigBuilder; - @Resource - private DeviceService deviceService; + @Resource + private DeviceService deviceService; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Resource - private DriverAttributeConfigService driverAttributeConfigService; + @Resource + private DriverAttributeConfigService driverAttributeConfigService; - @Resource - private PointAttributeConfigService pointAttributeConfigService; + @Resource + private PointAttributeConfigService pointAttributeConfigService; - @Override - public void selectByPage(GrpcPageDeviceQuery request, StreamObserver responseObserver) { - GrpcRPageDeviceDTO.Builder builder = GrpcRPageDeviceDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByPage(GrpcPageDeviceQuery request, StreamObserver responseObserver) { + GrpcRPageDeviceDTO.Builder builder = GrpcRPageDeviceDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DeviceQuery query = grpcDeviceBuilder.buildQueryByGrpcQuery(request); + DeviceQuery query = grpcDeviceBuilder.buildQueryByGrpcQuery(request); - Page entityPage = deviceService.selectByPage(query); - if (Objects.isNull(entityPage)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + Page entityPage = deviceService.selectByPage(query); + if (Objects.isNull(entityPage)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - GrpcPageDeviceDTO.Builder pageBuilder = GrpcPageDeviceDTO.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(entityPage.getCurrent()); - page.setSize(entityPage.getSize()); - page.setPages(entityPage.getPages()); - page.setTotal(entityPage.getTotal()); - pageBuilder.setPage(page); + GrpcPageDeviceDTO.Builder pageBuilder = GrpcPageDeviceDTO.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(entityPage.getCurrent()); + page.setSize(entityPage.getSize()); + page.setPages(entityPage.getPages()); + page.setTotal(entityPage.getTotal()); + pageBuilder.setPage(page); - List entityGrpcDTOList = entityPage.getRecords() - .stream() - .map(entityBO -> getDeviceAttachDTO(entityBO).build()) - .toList(); - pageBuilder.addAllData(entityGrpcDTOList); + List entityGrpcDTOList = entityPage.getRecords() + .stream() + .map(entityBO -> getDeviceAttachDTO(entityBO).build()) + .toList(); + pageBuilder.addAllData(entityGrpcDTOList); - builder.setData(pageBuilder); - } + builder.setData(pageBuilder); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectById(GrpcDeviceQuery request, StreamObserver responseObserver) { - GrpcRDeviceDTO.Builder builder = GrpcRDeviceDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectById(GrpcDeviceQuery request, StreamObserver responseObserver) { + GrpcRDeviceDTO.Builder builder = GrpcRDeviceDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DeviceBO entityBO = deviceService.selectById(request.getDeviceId()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + DeviceBO entityBO = deviceService.selectById(request.getDeviceId()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(getDeviceAttachDTO(entityBO)); - } + builder.setData(getDeviceAttachDTO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - private GrpcRDeviceAttachDTO.Builder getDeviceAttachDTO(DeviceBO entityBO) { - GrpcRDeviceAttachDTO.Builder builder = GrpcRDeviceAttachDTO.newBuilder(); - GrpcDeviceDTO entityGrpcDTO = grpcDeviceBuilder.buildGrpcDTOByBO(entityBO); - builder.setDevice(entityGrpcDTO); + private GrpcRDeviceAttachDTO.Builder getDeviceAttachDTO(DeviceBO entityBO) { + GrpcRDeviceAttachDTO.Builder builder = GrpcRDeviceAttachDTO.newBuilder(); + GrpcDeviceDTO entityGrpcDTO = grpcDeviceBuilder.buildGrpcDTOByBO(entityBO); + builder.setDevice(entityGrpcDTO); - // - List pointBOList = pointService.selectByDeviceId(entityBO.getId()); - CollectionOptional.ofNullable(pointBOList) - .ifPresent(value -> builder.addAllPointIds(value.stream().map(PointBO::getId).toList())); + // + List pointBOList = pointService.selectByDeviceId(entityBO.getId()); + CollectionOptional.ofNullable(pointBOList) + .ifPresent(value -> builder.addAllPointIds(value.stream().map(PointBO::getId).toList())); - List driverAttributeConfigBOList = driverAttributeConfigService - .selectByDeviceId(entityBO.getId()); - CollectionOptional.ofNullable(driverAttributeConfigBOList) - .ifPresent(value -> builder - .addAllDriverConfigs(value.stream().map(grpcDriverAttributeConfigBuilder::buildGrpcDTOByBO).toList())); + List driverAttributeConfigBOList = driverAttributeConfigService + .selectByDeviceId(entityBO.getId()); + CollectionOptional.ofNullable(driverAttributeConfigBOList) + .ifPresent(value -> builder + .addAllDriverConfigs(value.stream().map(grpcDriverAttributeConfigBuilder::buildGrpcDTOByBO).toList())); - List pointAttributeConfigBOList = pointAttributeConfigService - .selectByDeviceId(entityBO.getId()); - CollectionOptional.ofNullable(pointAttributeConfigBOList) - .ifPresent(value -> builder - .addAllPointConfigs(value.stream().map(grpcPointAttributeConfigBuilder::buildGrpcDTOByBO).toList())); - return builder; - } + List pointAttributeConfigBOList = pointAttributeConfigService + .selectByDeviceId(entityBO.getId()); + CollectionOptional.ofNullable(pointAttributeConfigBOList) + .ifPresent(value -> builder + .addAllPointConfigs(value.stream().map(grpcPointAttributeConfigBuilder::buildGrpcDTOByBO).toList())); + return builder; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDriverServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDriverServer.java index a9187abea..837d7b3a1 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDriverServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverDriverServer.java @@ -51,67 +51,66 @@ import java.util.List; @Service public class DriverDriverServer extends DriverApiGrpc.DriverApiImplBase { - @Resource - private GrpcDriverBuilder grpcDriverBuilder; + @Resource + private GrpcDriverBuilder grpcDriverBuilder; - @Resource - private GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; + @Resource + private GrpcDriverAttributeBuilder grpcDriverAttributeBuilder; - @Resource - private GrpcPointAttributeBuilder grpcPointAttributeBuilder; + @Resource + private GrpcPointAttributeBuilder grpcPointAttributeBuilder; - @Resource - private DriverRegisterService driverRegisterService; + @Resource + private DriverRegisterService driverRegisterService; - @Resource - private DeviceService deviceService; + @Resource + private DeviceService deviceService; - @Override - public void driverRegister(GrpcDriverRegisterDTO request, StreamObserver responseObserver) { - GrpcRDriverRegisterDTO.Builder builder = GrpcRDriverRegisterDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void driverRegister(GrpcDriverRegisterDTO request, StreamObserver responseObserver) { + GrpcRDriverRegisterDTO.Builder builder = GrpcRDriverRegisterDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - try { - // - DriverBO entityBO = driverRegisterService.registerDriver(request); - GrpcDriverDTO entityGrpcDTO = grpcDriverBuilder.buildGrpcDTOByBO(entityBO); - builder.setDriver(entityGrpcDTO); + try { + // + DriverBO entityBO = driverRegisterService.registerDriver(request); + GrpcDriverDTO entityGrpcDTO = grpcDriverBuilder.buildGrpcDTOByBO(entityBO); + builder.setDriver(entityGrpcDTO); - // - List driverAttributeBOList = driverRegisterService.registerDriverAttribute(request, - entityBO); - List grpcDriverAttributeDTOList = driverAttributeBOList.stream() - .map(grpcDriverAttributeBuilder::buildGrpcDTOByBO) - .toList(); - builder.addAllDriverAttributes(grpcDriverAttributeDTOList); + // + List driverAttributeBOList = driverRegisterService.registerDriverAttribute(request, + entityBO); + List grpcDriverAttributeDTOList = driverAttributeBOList.stream() + .map(grpcDriverAttributeBuilder::buildGrpcDTOByBO) + .toList(); + builder.addAllDriverAttributes(grpcDriverAttributeDTOList); - // - List pointAttributeBOList = driverRegisterService.registerPointAttribute(request, - entityBO); - List grpcPointAttributeDTOList = pointAttributeBOList.stream() - .map(grpcPointAttributeBuilder::buildGrpcDTOByBO) - .toList(); - builder.addAllPointAttributes(grpcPointAttributeDTOList); + // + List pointAttributeBOList = driverRegisterService.registerPointAttribute(request, + entityBO); + List grpcPointAttributeDTOList = pointAttributeBOList.stream() + .map(grpcPointAttributeBuilder::buildGrpcDTOByBO) + .toList(); + builder.addAllPointAttributes(grpcPointAttributeDTOList); - // - List idList = deviceService.selectIdsByDriverId(entityBO.getId()); - builder.addAllDeviceIds(idList); + // + List idList = deviceService.selectIdsByDriverId(entityBO.getId()); + builder.addAllDeviceIds(idList); - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); - } - catch (Exception e) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.FAILURE.getCode()); - rBuilder.setMessage(e.getMessage()); + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); + } catch (Exception e) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.FAILURE.getCode()); + rBuilder.setMessage(e.getMessage()); - log.error(e.getMessage(), e); - } + log.error(e.getMessage(), e); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverPointServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverPointServer.java index f80faaf87..da76e4772 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverPointServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/driver/DriverPointServer.java @@ -46,74 +46,72 @@ import java.util.Objects; @Service public class DriverPointServer extends PointApiGrpc.PointApiImplBase { - @Resource - private GrpcPointBuilder grpcPointBuilder; + @Resource + private GrpcPointBuilder grpcPointBuilder; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Override - public void selectByPage(GrpcPagePointQuery request, StreamObserver responseObserver) { - GrpcRPagePointDTO.Builder builder = GrpcRPagePointDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByPage(GrpcPagePointQuery request, StreamObserver responseObserver) { + GrpcRPagePointDTO.Builder builder = GrpcRPagePointDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - PointQuery query = grpcPointBuilder.buildQueryByGrpcQuery(request); + PointQuery query = grpcPointBuilder.buildQueryByGrpcQuery(request); - Page entityPage = pointService.selectByPage(query); - if (Objects.isNull(entityPage)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + Page entityPage = pointService.selectByPage(query); + if (Objects.isNull(entityPage)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - GrpcPagePointDTO.Builder pageBuilder = GrpcPagePointDTO.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(entityPage.getCurrent()); - page.setSize(entityPage.getSize()); - page.setPages(entityPage.getPages()); - page.setTotal(entityPage.getTotal()); - pageBuilder.setPage(page); + GrpcPagePointDTO.Builder pageBuilder = GrpcPagePointDTO.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(entityPage.getCurrent()); + page.setSize(entityPage.getSize()); + page.setPages(entityPage.getPages()); + page.setTotal(entityPage.getTotal()); + pageBuilder.setPage(page); - List entityGrpcDTOList = entityPage.getRecords() - .stream() - .map(grpcPointBuilder::buildGrpcDTOByBO) - .toList(); - pageBuilder.addAllData(entityGrpcDTOList); + List entityGrpcDTOList = entityPage.getRecords() + .stream() + .map(grpcPointBuilder::buildGrpcDTOByBO) + .toList(); + pageBuilder.addAllData(entityGrpcDTOList); - builder.setData(pageBuilder); - } + builder.setData(pageBuilder); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectById(GrpcPointQuery request, StreamObserver responseObserver) { - GrpcRPointDTO.Builder builder = GrpcRPointDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectById(GrpcPointQuery request, StreamObserver responseObserver) { + GrpcRPointDTO.Builder builder = GrpcRPointDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - PointBO entityBO = pointService.selectById(request.getPointId()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + PointBO entityBO = pointService.selectById(request.getPointId()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcPointBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcPointBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDeviceServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDeviceServer.java index c3e9340dc..1ddd518e1 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDeviceServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDeviceServer.java @@ -47,130 +47,126 @@ import java.util.Objects; @Service public class ManagerDeviceServer extends DeviceApiGrpc.DeviceApiImplBase { - @Resource - private GrpcDeviceBuilder grpcDeviceBuilder; + @Resource + private GrpcDeviceBuilder grpcDeviceBuilder; - @Resource - private DeviceService deviceService; + @Resource + private DeviceService deviceService; - @Override - public void selectByPage(GrpcPageDeviceQuery request, StreamObserver responseObserver) { - GrpcRPageDeviceDTO.Builder builder = GrpcRPageDeviceDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByPage(GrpcPageDeviceQuery request, StreamObserver responseObserver) { + GrpcRPageDeviceDTO.Builder builder = GrpcRPageDeviceDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DeviceQuery query = grpcDeviceBuilder.buildQueryByGrpcQuery(request); + DeviceQuery query = grpcDeviceBuilder.buildQueryByGrpcQuery(request); - Page entityPage = deviceService.selectByPage(query); - if (Objects.isNull(entityPage)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + Page entityPage = deviceService.selectByPage(query); + if (Objects.isNull(entityPage)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - GrpcPageDeviceDTO.Builder pageBuilder = GrpcPageDeviceDTO.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(entityPage.getCurrent()); - page.setSize(entityPage.getSize()); - page.setPages(entityPage.getPages()); - page.setTotal(entityPage.getTotal()); - pageBuilder.setPage(page); + GrpcPageDeviceDTO.Builder pageBuilder = GrpcPageDeviceDTO.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(entityPage.getCurrent()); + page.setSize(entityPage.getSize()); + page.setPages(entityPage.getPages()); + page.setTotal(entityPage.getTotal()); + pageBuilder.setPage(page); - List entityGrpcDTOList = entityPage.getRecords() - .stream() - .map(grpcDeviceBuilder::buildGrpcDTOByBO) - .toList(); - pageBuilder.addAllData(entityGrpcDTOList); + List entityGrpcDTOList = entityPage.getRecords() + .stream() + .map(grpcDeviceBuilder::buildGrpcDTOByBO) + .toList(); + pageBuilder.addAllData(entityGrpcDTOList); - builder.setData(pageBuilder); - } + builder.setData(pageBuilder); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectByDriverId(GrpcDriverQuery driver, StreamObserver responseObserver) { - GrpcRDeviceListDTO.Builder builder = GrpcRDeviceListDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByDriverId(GrpcDriverQuery driver, StreamObserver responseObserver) { + GrpcRDeviceListDTO.Builder builder = GrpcRDeviceListDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - List entityBOList = deviceService.selectByDriverId(driver.getDriverId()); - if (CollectionUtils.isEmpty(entityBOList)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + List entityBOList = deviceService.selectByDriverId(driver.getDriverId()); + if (CollectionUtils.isEmpty(entityBOList)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - List entityGrpcDTOList = entityBOList.stream() - .map(grpcDeviceBuilder::buildGrpcDTOByBO) - .toList(); + List entityGrpcDTOList = entityBOList.stream() + .map(grpcDeviceBuilder::buildGrpcDTOByBO) + .toList(); - builder.addAllData(entityGrpcDTOList); - } + builder.addAllData(entityGrpcDTOList); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectByProfileId(GrpcProfileQuery request, StreamObserver responseObserver) { - GrpcRDeviceListDTO.Builder builder = GrpcRDeviceListDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByProfileId(GrpcProfileQuery request, StreamObserver responseObserver) { + GrpcRDeviceListDTO.Builder builder = GrpcRDeviceListDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - List entityBOList = deviceService.selectByProfileId(request.getProfileId()); - if (CollectionUtils.isEmpty(entityBOList)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + List entityBOList = deviceService.selectByProfileId(request.getProfileId()); + if (CollectionUtils.isEmpty(entityBOList)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - List entityGrpcDTOList = entityBOList.stream() - .map(grpcDeviceBuilder::buildGrpcDTOByBO) - .toList(); + List entityGrpcDTOList = entityBOList.stream() + .map(grpcDeviceBuilder::buildGrpcDTOByBO) + .toList(); - builder.addAllData(entityGrpcDTOList); - } + builder.addAllData(entityGrpcDTOList); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectByDeviceId(GrpcDeviceQuery request, StreamObserver responseObserver) { - GrpcRDeviceDTO.Builder builder = GrpcRDeviceDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByDeviceId(GrpcDeviceQuery request, StreamObserver responseObserver) { + GrpcRDeviceDTO.Builder builder = GrpcRDeviceDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DeviceBO entityBO = deviceService.selectById(request.getDeviceId()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + DeviceBO entityBO = deviceService.selectById(request.getDeviceId()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcDeviceBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcDeviceBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDriverServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDriverServer.java index eb3504215..8379d40d0 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDriverServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerDriverServer.java @@ -46,98 +46,95 @@ import java.util.Objects; @Service public class ManagerDriverServer extends DriverApiGrpc.DriverApiImplBase { - @Resource - private GrpcDriverBuilder grpcDriverBuilder; + @Resource + private GrpcDriverBuilder grpcDriverBuilder; - @Resource - private DriverService driverService; + @Resource + private DriverService driverService; - @Override - public void selectByPage(GrpcPageDriverQuery request, StreamObserver responseObserver) { - GrpcRPageDriverDTO.Builder builder = GrpcRPageDriverDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByPage(GrpcPageDriverQuery request, StreamObserver responseObserver) { + GrpcRPageDriverDTO.Builder builder = GrpcRPageDriverDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DriverQuery query = grpcDriverBuilder.buildQueryByGrpcQuery(request); + DriverQuery query = grpcDriverBuilder.buildQueryByGrpcQuery(request); - Page entityPage = driverService.selectByPage(query); - if (Objects.isNull(entityPage)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + Page entityPage = driverService.selectByPage(query); + if (Objects.isNull(entityPage)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - GrpcPageDriverDTO.Builder pageBuilder = GrpcPageDriverDTO.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(entityPage.getCurrent()); - page.setSize(entityPage.getSize()); - page.setPages(entityPage.getPages()); - page.setTotal(entityPage.getTotal()); - pageBuilder.setPage(page); + GrpcPageDriverDTO.Builder pageBuilder = GrpcPageDriverDTO.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(entityPage.getCurrent()); + page.setSize(entityPage.getSize()); + page.setPages(entityPage.getPages()); + page.setTotal(entityPage.getTotal()); + pageBuilder.setPage(page); - List entityGrpcDTOList = entityPage.getRecords() - .stream() - .map(grpcDriverBuilder::buildGrpcDTOByBO) - .toList(); - pageBuilder.addAllData(entityGrpcDTOList); + List entityGrpcDTOList = entityPage.getRecords() + .stream() + .map(grpcDriverBuilder::buildGrpcDTOByBO) + .toList(); + pageBuilder.addAllData(entityGrpcDTOList); - builder.setData(pageBuilder); - } + builder.setData(pageBuilder); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectByDeviceId(GrpcDeviceQuery request, StreamObserver responseObserver) { - GrpcRDriverDTO.Builder builder = GrpcRDriverDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByDeviceId(GrpcDeviceQuery request, StreamObserver responseObserver) { + GrpcRDriverDTO.Builder builder = GrpcRDriverDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DriverBO entityDO = driverService.selectByDeviceId(request.getDeviceId()); - if (Objects.isNull(entityDO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + DriverBO entityDO = driverService.selectByDeviceId(request.getDeviceId()); + if (Objects.isNull(entityDO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcDriverBuilder.buildGrpcDTOByBO(entityDO)); - } + builder.setData(grpcDriverBuilder.buildGrpcDTOByBO(entityDO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectByDriverId(GrpcDriverQuery request, StreamObserver responseObserver) { - GrpcRDriverDTO.Builder builder = GrpcRDriverDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByDriverId(GrpcDriverQuery request, StreamObserver responseObserver) { + GrpcRDriverDTO.Builder builder = GrpcRDriverDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - DriverBO driverBO = driverService.selectById(request.getDriverId()); - if (Objects.isNull(driverBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + DriverBO driverBO = driverService.selectById(request.getDriverId()); + if (Objects.isNull(driverBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcDriverBuilder.buildGrpcDTOByBO(driverBO)); - } + builder.setData(grpcDriverBuilder.buildGrpcDTOByBO(driverBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerPointServer.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerPointServer.java index 15473a5c3..b6d11214a 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerPointServer.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/grpc/server/manager/ManagerPointServer.java @@ -46,74 +46,72 @@ import java.util.Objects; @Service public class ManagerPointServer extends PointApiGrpc.PointApiImplBase { - @Resource - private GrpcPointBuilder grpcPointBuilder; + @Resource + private GrpcPointBuilder grpcPointBuilder; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Override - public void selectByPage(GrpcPagePointQuery request, StreamObserver responseObserver) { - GrpcRPagePointDTO.Builder builder = GrpcRPagePointDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectByPage(GrpcPagePointQuery request, StreamObserver responseObserver) { + GrpcRPagePointDTO.Builder builder = GrpcRPagePointDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - PointQuery query = grpcPointBuilder.buildQueryByGrpcQuery(request); + PointQuery query = grpcPointBuilder.buildQueryByGrpcQuery(request); - Page entityPage = pointService.selectByPage(query); - if (Objects.isNull(entityPage)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + Page entityPage = pointService.selectByPage(query); + if (Objects.isNull(entityPage)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - GrpcPagePointDTO.Builder pagePointBuilder = GrpcPagePointDTO.newBuilder(); - GrpcPage.Builder page = GrpcPage.newBuilder(); - page.setCurrent(entityPage.getCurrent()); - page.setSize(entityPage.getSize()); - page.setPages(entityPage.getPages()); - page.setTotal(entityPage.getTotal()); - pagePointBuilder.setPage(page); + GrpcPagePointDTO.Builder pagePointBuilder = GrpcPagePointDTO.newBuilder(); + GrpcPage.Builder page = GrpcPage.newBuilder(); + page.setCurrent(entityPage.getCurrent()); + page.setSize(entityPage.getSize()); + page.setPages(entityPage.getPages()); + page.setTotal(entityPage.getTotal()); + pagePointBuilder.setPage(page); - List entityGrpcDTOList = entityPage.getRecords() - .stream() - .map(grpcPointBuilder::buildGrpcDTOByBO) - .toList(); - pagePointBuilder.addAllData(entityGrpcDTOList); + List entityGrpcDTOList = entityPage.getRecords() + .stream() + .map(grpcPointBuilder::buildGrpcDTOByBO) + .toList(); + pagePointBuilder.addAllData(entityGrpcDTOList); - builder.setData(pagePointBuilder); - } + builder.setData(pagePointBuilder); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } - @Override - public void selectById(GrpcPointQuery request, StreamObserver responseObserver) { - GrpcRPointDTO.Builder builder = GrpcRPointDTO.newBuilder(); - GrpcR.Builder rBuilder = GrpcR.newBuilder(); + @Override + public void selectById(GrpcPointQuery request, StreamObserver responseObserver) { + GrpcRPointDTO.Builder builder = GrpcRPointDTO.newBuilder(); + GrpcR.Builder rBuilder = GrpcR.newBuilder(); - PointBO entityBO = pointService.selectById(request.getPointId()); - if (Objects.isNull(entityBO)) { - rBuilder.setOk(false); - rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); - rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); - } - else { - rBuilder.setOk(true); - rBuilder.setCode(ResponseEnum.OK.getCode()); - rBuilder.setMessage(ResponseEnum.OK.getText()); + PointBO entityBO = pointService.selectById(request.getPointId()); + if (Objects.isNull(entityBO)) { + rBuilder.setOk(false); + rBuilder.setCode(ResponseEnum.NO_RESOURCE.getCode()); + rBuilder.setMessage(ResponseEnum.NO_RESOURCE.getText()); + } else { + rBuilder.setOk(true); + rBuilder.setCode(ResponseEnum.OK.getCode()); + rBuilder.setMessage(ResponseEnum.OK.getText()); - builder.setData(grpcPointBuilder.buildGrpcDTOByBO(entityBO)); - } + builder.setData(grpcPointBuilder.buildGrpcDTOByBO(entityBO)); + } - builder.setResult(rBuilder); - responseObserver.onNext(builder.build()); - responseObserver.onCompleted(); - } + builder.setResult(rBuilder); + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/job/HourlyJobForManager.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/job/HourlyJobForManager.java index b50025ed2..cc6a3bd51 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/job/HourlyJobForManager.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/job/HourlyJobForManager.java @@ -35,17 +35,18 @@ import org.springframework.stereotype.Component; @Component public class HourlyJobForManager extends QuartzJobBean { - /** - * - * * - *

- * * biz service - * @param context JobExecutionContext - * @throws JobExecutionException JobExecutionException - */ - @Override - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - log.info("hourlyJobHandler: {}", LocalDateTimeUtil.now()); - } + /** + * + * * + *

+ * * biz service + * + * @param context JobExecutionContext + * @throws JobExecutionException JobExecutionException + */ + @Override + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + log.info("hourlyJobHandler: {}", LocalDateTimeUtil.now()); + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DashboardMapper.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DashboardMapper.java index 3a86859e5..0432a8338 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DashboardMapper.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DashboardMapper.java @@ -43,65 +43,65 @@ import java.util.List; @Mapper public interface DashboardMapper { - /** - * Driver counts grouped by {@code enable_flag} (aliased to {@code key}). - */ - List countDriverByEnable(@Param("tenantId") Long tenantId); + /** + * Driver counts grouped by {@code enable_flag} (aliased to {@code key}). + */ + List countDriverByEnable(@Param("tenantId") Long tenantId); - /** - * Driver counts grouped by {@code driver_type_flag} (aliased to {@code key}). - */ - List countDriverByType(@Param("tenantId") Long tenantId); + /** + * Driver counts grouped by {@code driver_type_flag} (aliased to {@code key}). + */ + List countDriverByType(@Param("tenantId") Long tenantId); - /** - * Driver counts grouped by {@code service_name} (aliased to {@code key}). - */ - List countDriverByService(@Param("tenantId") Long tenantId); + /** + * Driver counts grouped by {@code service_name} (aliased to {@code key}). + */ + List countDriverByService(@Param("tenantId") Long tenantId); - /** - * Device counts grouped by {@code enable_flag} (aliased to {@code key}). - */ - List countDeviceByEnable(@Param("tenantId") Long tenantId); + /** + * Device counts grouped by {@code enable_flag} (aliased to {@code key}). + */ + List countDeviceByEnable(@Param("tenantId") Long tenantId); - /** - * Device counts grouped by {@code driver_id} (aliased to {@code key}). Top-N. - */ - List countDeviceByDriver(@Param("tenantId") Long tenantId, @Param("limit") int limit); + /** + * Device counts grouped by {@code driver_id} (aliased to {@code key}). Top-N. + */ + List countDeviceByDriver(@Param("tenantId") Long tenantId, @Param("limit") int limit); - /** - * Device counts grouped by {@code profile_id} (aliased to {@code key}). Top-N. - */ - List countDeviceByProfile(@Param("tenantId") Long tenantId, @Param("limit") int limit); + /** + * Device counts grouped by {@code profile_id} (aliased to {@code key}). Top-N. + */ + List countDeviceByProfile(@Param("tenantId") Long tenantId, @Param("limit") int limit); - /** - * Daily new-row count for the given entity table. {@code table} is interpolated - * (service layer whitelists it). Missing days are padded with zero service-side so - * the frontend always gets a fixed-length array. - */ - List dailyGrowth(@Param("tenantId") Long tenantId, @Param("table") String table, - @Param("from") LocalDateTime from, @Param("to") LocalDateTime to); + /** + * Daily new-row count for the given entity table. {@code table} is interpolated + * (service layer whitelists it). Missing days are padded with zero service-side so + * the frontend always gets a fixed-length array. + */ + List dailyGrowth(@Param("tenantId") Long tenantId, @Param("table") String table, + @Param("from") LocalDateTime from, @Param("to") LocalDateTime to); - // ---- Topology (GET /dashboard/topology) ---------------------------- + // ---- Topology (GET /dashboard/topology) ---------------------------- - List topologyDrivers(@Param("tenantId") Long tenantId); + List topologyDrivers(@Param("tenantId") Long tenantId); - List topologyDevicesByDrivers(@Param("tenantId") Long tenantId, - @Param("driverIds") Collection driverIds); + List topologyDevicesByDrivers(@Param("tenantId") Long tenantId, + @Param("driverIds") Collection driverIds); - List topologyProfileBindings(@Param("tenantId") Long tenantId, - @Param("deviceIds") Collection deviceIds); + List topologyProfileBindings(@Param("tenantId") Long tenantId, + @Param("deviceIds") Collection deviceIds); - List topologyProfilesByIds(@Param("tenantId") Long tenantId, - @Param("profileIds") Collection profileIds); + List topologyProfilesByIds(@Param("tenantId") Long tenantId, + @Param("profileIds") Collection profileIds); - List topologyPointsByProfiles(@Param("tenantId") Long tenantId, - @Param("profileIds") Collection profileIds); + List topologyPointsByProfiles(@Param("tenantId") Long tenantId, + @Param("profileIds") Collection profileIds); - /** - * Volume rollup for the topology's "volume" mode — counts point_value rows per - * {@code (device_id, point_id)} over the selected time window, queried against - * {@code dc3_history.v_dc3_point_value_all} (cross-schema). - */ - List topologyPointVolumes(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); + /** + * Volume rollup for the topology's "volume" mode — counts point_value rows per + * {@code (device_id, point_id)} over the selected time window, queried against + * {@code dc3_history.v_dc3_point_value_all} (cross-schema). + */ + List topologyPointVolumes(@Param("tenantId") Long tenantId, @Param("from") LocalDateTime from); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DeviceMapper.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DeviceMapper.java index fcb7c2021..72b9afb2c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DeviceMapper.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/DeviceMapper.java @@ -35,7 +35,7 @@ import org.apache.ibatis.annotations.Param; */ public interface DeviceMapper extends BaseMapper { - Page selectPageWithProfile(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, - @Param("profileId") Long profileId); + Page selectPageWithProfile(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, + @Param("profileId") Long profileId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/PointMapper.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/PointMapper.java index b28574eee..833dfeab8 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/PointMapper.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/PointMapper.java @@ -35,7 +35,7 @@ import org.apache.ibatis.annotations.Param; */ public interface PointMapper extends BaseMapper { - Page selectPageWithDevice(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, - @Param("deviceId") Long deviceId); + Page selectPageWithDevice(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, + @Param("deviceId") Long deviceId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/ProfileMapper.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/ProfileMapper.java index e8610c4dd..8a5adc38d 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/ProfileMapper.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/mapper/ProfileMapper.java @@ -35,7 +35,7 @@ import org.apache.ibatis.annotations.Param; */ public interface ProfileMapper extends BaseMapper { - Page selectPageWithDevice(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, - @Param("deviceId") Long deviceId); + Page selectPageWithDevice(Page page, @Param(Constants.WRAPPER) Wrapper wrapper, + @Param("deviceId") Long deviceId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DashboardService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DashboardService.java index cf09e0a7a..5a5f31c62 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DashboardService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DashboardService.java @@ -31,39 +31,40 @@ import io.github.pnoker.common.manager.entity.vo.dashboard.TopologyVO; */ public interface DashboardService { - DriverStatsVO driverStats(Long tenantId); + DriverStatsVO driverStats(Long tenantId); - DeviceStatsVO deviceStats(Long tenantId, int topN); + DeviceStatsVO deviceStats(Long tenantId, int topN); - /** - * Daily new-row counts for driver / device / point / profile tables over the last - * {@code days} days. Used to back the stat-card sparklines on the home page. Arrays - * are fixed length = {@code days} with zero-padded missing days, oldest first. - */ - GrowthVO dailyGrowth(Long tenantId, int days); + /** + * Daily new-row counts for driver / device / point / profile tables over the last + * {@code days} days. Used to back the stat-card sparklines on the home page. Arrays + * are fixed length = {@code days} with zero-padded missing days, oldest first. + */ + GrowthVO dailyGrowth(Long tenantId, int days); - /** - * Four-column topology Sankey (Driver → Device → Profile → Point) used by the home - * page. Top-N cropped server-side; overflow rolls into {@code others:*} nodes whose - * {@code hiddenChildren} carry the collapsed list for drill-in. - * - *

- * {@code mode="cardinality"} weights edges by the number of relationships (1 per - * device / binding / point). {@code mode="volume"} weights edges by the number of - * point_value samples each carried over the {@code rangeKey} window (today / 24h / 7d - * / 30d); entity Top-N cropping at each layer also sorts by those volumes. - *

- * - *

- * Results are cached for 60s keyed by {@code tenant:mode:rangeKey} — the graph - * changes slowly and the volume-mode aggregate touches the Timescale hypertable view, - * so repeated refreshes stay cheap. - *

- * @param tenantId caller's tenant id - * @param mode {@code "cardinality"} | {@code "volume"} - * @param rangeKey time window key for volume mode; ignored for cardinality. Defaults - * to {@code "7d"} when blank. - */ - TopologyVO topology(Long tenantId, String mode, String rangeKey); + /** + * Four-column topology Sankey (Driver → Device → Profile → Point) used by the home + * page. Top-N cropped server-side; overflow rolls into {@code others:*} nodes whose + * {@code hiddenChildren} carry the collapsed list for drill-in. + * + *

+ * {@code mode="cardinality"} weights edges by the number of relationships (1 per + * device / binding / point). {@code mode="volume"} weights edges by the number of + * point_value samples each carried over the {@code rangeKey} window (today / 24h / 7d + * / 30d); entity Top-N cropping at each layer also sorts by those volumes. + *

+ * + *

+ * Results are cached for 60s keyed by {@code tenant:mode:rangeKey} — the graph + * changes slowly and the volume-mode aggregate touches the Timescale hypertable view, + * so repeated refreshes stay cheap. + *

+ * + * @param tenantId caller's tenant id + * @param mode {@code "cardinality"} | {@code "volume"} + * @param rangeKey time window key for volume mode; ignored for cardinality. Defaults + * to {@code "7d"} when blank. + */ + TopologyVO topology(Long tenantId, String mode, String rangeKey); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DeviceService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DeviceService.java index 592901a67..cbfa0eccb 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DeviceService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DeviceService.java @@ -34,60 +34,66 @@ import java.util.List; */ public interface DeviceService extends BaseService { - /** - * Name TenantId - * @param name Device Name - * @param tenantId Tenant ID - * @return {@link DeviceBO} - */ - DeviceBO selectByName(String name, Long tenantId); + /** + * Name TenantId + * + * @param name Device Name + * @param tenantId Tenant ID + * @return {@link DeviceBO} + */ + DeviceBO selectByName(String name, Long tenantId); - /** - * Name TenantId - * @param code Device ID - * @param tenantId Tenant ID - * @return {@link DeviceBO} - */ - DeviceBO selectByCode(String code, Long tenantId); + /** + * Name TenantId + * + * @param code Device ID + * @param tenantId Tenant ID + * @return {@link DeviceBO} + */ + DeviceBO selectByCode(String code, Long tenantId); - /** - * Driver ID - * @param driverId Driver ID - * @return {@link DeviceBO} - */ - List selectByDriverId(Long driverId); + /** + * Driver ID + * + * @param driverId Driver ID + * @return {@link DeviceBO} + */ + List selectByDriverId(Long driverId); - /** - * Driver ID Device ID - * @param driverId Driver ID - * @return {@link DeviceBO} - */ - List selectIdsByDriverId(Long driverId); + /** + * Driver ID Device ID + * + * @param driverId Driver ID + * @return {@link DeviceBO} + */ + List selectIdsByDriverId(Long driverId); - /** - * ID - * @param profileId ID - * @return {@link DeviceBO} - */ - List selectByProfileId(Long profileId); + /** + * ID + * + * @param profileId ID + * @return {@link DeviceBO} + */ + List selectByProfileId(Long profileId); - /** - * Device ID - * @param ids Device ID - * @return {@link DeviceBO} - */ - List selectByIds(List ids); + /** + * Device ID + * + * @param ids Device ID + * @return {@link DeviceBO} + */ + List selectByIds(List ids); - /** - * @param entityBO {@link DeviceBO} - * @param multipartFile {@link File} - */ - void importDevice(DeviceBO entityBO, File multipartFile); + /** + * @param entityBO {@link DeviceBO} + * @param multipartFile {@link File} + */ + void importDevice(DeviceBO entityBO, File multipartFile); - /** - * @param entityBO {@link DeviceBO} - * @return File Path - */ - Path generateImportTemplate(DeviceBO entityBO); + /** + * @param entityBO {@link DeviceBO} + * @return File Path + */ + Path generateImportTemplate(DeviceBO entityBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeConfigService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeConfigService.java index ca0e89259..7759ca29f 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeConfigService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeConfigService.java @@ -33,32 +33,35 @@ import java.util.List; */ public interface DriverAttributeConfigService extends BaseService { - /** - * Device ID - * @param deviceId Device ID - * @return DriverConfig - */ - List selectByDeviceId(Long deviceId); + /** + * Device ID + * + * @param deviceId Device ID + * @return DriverConfig + */ + List selectByDeviceId(Long deviceId); - /** - * ID - * @param attributeId ID - * @return DriverConfig - */ - List selectByAttributeId(Long attributeId); + /** + * ID + * + * @param attributeId ID + * @return DriverConfig + */ + List selectByAttributeId(Long attributeId); - /** - * ID Device ID - * @param deviceId Device ID - * @param attributeId ID - * @return DriverConfig - */ - DriverAttributeConfigBO selectByAttributeIdAndDeviceId(Long deviceId, Long attributeId); + /** + * ID Device ID + * + * @param deviceId Device ID + * @param attributeId ID + * @return DriverConfig + */ + DriverAttributeConfigBO selectByAttributeIdAndDeviceId(Long deviceId, Long attributeId); - /** - * @param entityBO {@link DriverAttributeConfigBO} - * @return {@link DeviceBO} - */ - DriverAttributeConfigBO innerSave(DriverAttributeConfigBO entityBO); + /** + * @param entityBO {@link DriverAttributeConfigBO} + * @return {@link DeviceBO} + */ + DriverAttributeConfigBO innerSave(DriverAttributeConfigBO entityBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeService.java index 9f78b52cc..de84a1203 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverAttributeService.java @@ -32,19 +32,21 @@ import java.util.List; */ public interface DriverAttributeService extends BaseService { - /** - * Driver ID - * @param driverId Driver ID - * @return Array - */ - List selectByDriverId(Long driverId); + /** + * Driver ID + * + * @param driverId Driver ID + * @return Array + */ + List selectByDriverId(Long driverId); - /** - * Code Driver ID - * @param name Code - * @param driverId Driver ID - * @return DriverAttribute - */ - DriverAttributeBO selectByNameAndDriverId(String name, Long driverId); + /** + * Code Driver ID + * + * @param name Code + * @param driverId Driver ID + * @return DriverAttribute + */ + DriverAttributeBO selectByNameAndDriverId(String name, Long driverId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverService.java index 21a591033..30336435f 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/DriverService.java @@ -33,40 +33,45 @@ import java.util.Set; */ public interface DriverService extends BaseService { - /** - * ServiceName - * @param serviceName Driver service name - * @param tenantId Tenant ID - * @return Driver - */ - DriverBO selectByServiceName(String serviceName, Long tenantId); + /** + * ServiceName + * + * @param serviceName Driver service name + * @param tenantId Tenant ID + * @return Driver + */ + DriverBO selectByServiceName(String serviceName, Long tenantId); - /** - * ID - * @param profileId ID - * @return Driver - */ - List selectByProfileId(Long profileId); + /** + * ID + * + * @param profileId ID + * @return Driver + */ + List selectByProfileId(Long profileId); - /** - * Point ID - * @param pointId Point ID - * @return Driver - */ - List selectByPointId(Long pointId); + /** + * Point ID + * + * @param pointId Point ID + * @return Driver + */ + List selectByPointId(Long pointId); - /** - * Driver ID - * @param deviceId Device ID - * @return Driver - */ - DriverBO selectByDeviceId(Long deviceId); + /** + * Driver ID + * + * @param deviceId Device ID + * @return Driver + */ + DriverBO selectByDeviceId(Long deviceId); - /** - * Driver ID - * @param ids Driver ID - * @return Driver - */ - List selectByIds(Set ids); + /** + * Driver ID + * + * @param ids Driver ID + * @return Driver + */ + List selectByIds(Set ids); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeConfigService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeConfigService.java index 26f0e79bc..99dc89e25 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeConfigService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeConfigService.java @@ -33,41 +33,45 @@ import java.util.List; */ public interface PointAttributeConfigService extends BaseService { - /** - * Device ID - * @param deviceId Device ID - * @return PointConfig - */ - List selectByDeviceId(Long deviceId); + /** + * Device ID + * + * @param deviceId Device ID + * @return PointConfig + */ + List selectByDeviceId(Long deviceId); - /** - * ID - * @param attributeId ID - * @return PointConfig - */ - List selectByAttributeId(Long attributeId); + /** + * ID + * + * @param attributeId ID + * @return PointConfig + */ + List selectByAttributeId(Long attributeId); - /** - * Device ID Point ID - * @param deviceId Device ID - * @param pointId Point ID - * @return PointConfig - */ - List selectByDeviceIdAndPointId(Long deviceId, Long pointId); + /** + * Device ID Point ID + * + * @param deviceId Device ID + * @param pointId Point ID + * @return PointConfig + */ + List selectByDeviceIdAndPointId(Long deviceId, Long pointId); - /** - * ID Device ID Point ID - * @param attributeId ID - * @param deviceId Device ID - * @param pointId Point ID - * @return PointConfig - */ - PointAttributeConfigBO selectByAttributeIdAndDeviceIdAndPointId(Long attributeId, Long deviceId, Long pointId); + /** + * ID Device ID Point ID + * + * @param attributeId ID + * @param deviceId Device ID + * @param pointId Point ID + * @return PointConfig + */ + PointAttributeConfigBO selectByAttributeIdAndDeviceIdAndPointId(Long attributeId, Long deviceId, Long pointId); - /** - * @param entityBO {@link PointAttributeConfigBO} - * @return {@link DeviceBO} - */ - PointAttributeConfigBO innerSave(PointAttributeConfigBO entityBO); + /** + * @param entityBO {@link PointAttributeConfigBO} + * @return {@link DeviceBO} + */ + PointAttributeConfigBO innerSave(PointAttributeConfigBO entityBO); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeService.java index 3930cc62a..b1df2fe15 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointAttributeService.java @@ -32,19 +32,21 @@ import java.util.List; */ public interface PointAttributeService extends BaseService { - /** - * Code Driver ID - * @param name Code - * @param driverId Driver ID - * @return PointAttribute - */ - PointAttributeBO selectByNameAndDriverId(String name, Long driverId); + /** + * Code Driver ID + * + * @param name Code + * @param driverId Driver ID + * @return PointAttribute + */ + PointAttributeBO selectByNameAndDriverId(String name, Long driverId); - /** - * Driver ID - * @param driverId Driver ID - * @return Array - */ - List selectByDriverId(Long driverId); + /** + * Driver ID + * + * @param driverId Driver ID + * @return Array + */ + List selectByDriverId(Long driverId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointService.java index 18af8d703..d7bd10a96 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/PointService.java @@ -35,99 +35,106 @@ import java.util.Set; */ public interface PointService extends BaseService { - /** - * ID - * @param profileId Point ID - * @return Point - */ - List selectByProfileId(Long profileId); + /** + * ID + * + * @param profileId Point ID + * @return Point + */ + List selectByProfileId(Long profileId); - /** - * Device ID - * @param deviceId Device ID - * @return Point - */ - List selectByDeviceId(Long deviceId); + /** + * Device ID + * + * @param deviceId Device ID + * @return Point + */ + List selectByDeviceId(Long deviceId); - /** - * ID - * @param profileIds ID - * @return Point - */ - List selectByProfileIds(List profileIds); + /** + * ID + * + * @param profileIds ID + * @return Point + */ + List selectByProfileIds(List profileIds); - /** - * Device ID - * @param ids Point ID - * @return Point - */ - List selectByIds(Set ids); + /** + * Device ID + * + * @param ids Point ID + * @return Point + */ + List selectByIds(Set ids); - /** - * @param pointIds Point ID - * @return Map Long:Unit String - */ - Map unit(Set pointIds); + /** + * @param pointIds Point ID + * @return Map Long:Unit String + */ + Map unit(Set pointIds); - /** - * @param pointId id - * @return {@link Set}<{@link Long}> - */ - DeviceByPointBO selectPointStatisticsWithDevice(Long pointId); + /** + * @param pointId id + * @return {@link Set}<{@link Long}> + */ + DeviceByPointBO selectPointStatisticsWithDevice(Long pointId); - /** - * - * id - * @param pointId id - * @param deviceIds id - * @return {@link List}<{@link List}<{@link PointDataVolumeRunDO}>> - */ - List selectPointStatisticsByDeviceId(Long pointId, Set deviceIds); + /** + * + * id + * + * @param pointId id + * @param deviceIds id + * @return {@link List}<{@link List}<{@link PointDataVolumeRunDO}>> + */ + List selectPointStatisticsByDeviceId(Long pointId, Set deviceIds); - /** - * - * id - * @param pointId id - * @return {@link List}<{@link List}<{@link PointDataVolumeRunDO}>> - */ - PointDataVolumeRunDO selectPointStatisticsByPointId(Long pointId); + /** + * + * id + * + * @param pointId id + * @return {@link List}<{@link List}<{@link PointDataVolumeRunDO}>> + */ + PointDataVolumeRunDO selectPointStatisticsByPointId(Long pointId); - /** - * @param deviceId - * @return - */ - Long selectPointByDeviceId(Long deviceId); + /** + * @param deviceId + * @return + */ + Long selectPointByDeviceId(Long deviceId); - /** - * @param deviceId - * @return - */ - PointConfigByDeviceBO selectPointConfigByDeviceId(Long deviceId); + /** + * @param deviceId + * @return + */ + PointConfigByDeviceBO selectPointConfigByDeviceId(Long deviceId); - /** - * @param deviceId - * @param pointIds - * @return - */ - List selectDeviceStatisticsByPointId(Long deviceId, Set pointIds); + /** + * @param deviceId + * @param pointIds + * @return + */ + List selectDeviceStatisticsByPointId(Long deviceId, Set pointIds); - /** - * @param driverId - * @return - */ - PointDataVolumeRunDO selectPointDataByDriverId(Long driverId); + /** + * @param driverId + * @return + */ + PointDataVolumeRunDO selectPointDataByDriverId(Long driverId); - /** - * @param driverId - * @return - */ - Long selectPointByDriverId(Long driverId); + /** + * @param driverId + * @return + */ + Long selectPointByDriverId(Long driverId); - /** - * 7 days - * @param driverId - * @return - */ - PointDataStatisticsByDriverIdBO selectPointDataStatisticsByDriverId(Long driverId); + /** + * 7 days + * + * @param driverId + * @return + */ + PointDataStatisticsByDriverIdBO selectPointDataStatisticsByDriverId(Long driverId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileBindService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileBindService.java index 2c26f6305..0f9ae0edf 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileBindService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileBindService.java @@ -32,41 +32,46 @@ import java.util.List; */ public interface ProfileBindService extends BaseService { - /** - * Device ID - * @param deviceId Device ID - * @return - */ - Boolean removeByDeviceId(Long deviceId); + /** + * Device ID + * + * @param deviceId Device ID + * @return + */ + Boolean removeByDeviceId(Long deviceId); - /** - * Device ID ID - * @param deviceId Device ID - * @param profileId Point ID - * @return - */ - Boolean removeByDeviceIdAndProfileId(Long deviceId, Long profileId); + /** + * Device ID ID + * + * @param deviceId Device ID + * @param profileId Point ID + * @return + */ + Boolean removeByDeviceIdAndProfileId(Long deviceId, Long profileId); - /** - * Device ID ID - * @param deviceId Device ID - * @param profileId Point ID - * @return ProfileBind - */ - ProfileBindBO selectByDeviceIdAndProfileId(Long deviceId, Long profileId); + /** + * Device ID ID + * + * @param deviceId Device ID + * @param profileId Point ID + * @return ProfileBind + */ + ProfileBindBO selectByDeviceIdAndProfileId(Long deviceId, Long profileId); - /** - * ID Device ID - * @param profileId Point ID - * @return Device ID - */ - List selectDeviceIdsByProfileId(Long profileId); + /** + * ID Device ID + * + * @param profileId Point ID + * @return Device ID + */ + List selectDeviceIdsByProfileId(Long profileId); - /** - * Device ID ID - * @param deviceId Device ID - * @return ID - */ - List selectProfileIdsByDeviceId(Long deviceId); + /** + * Device ID ID + * + * @param deviceId Device ID + * @return ID + */ + List selectProfileIdsByDeviceId(Long deviceId); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileService.java index 68862c06b..8875199c9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/ProfileService.java @@ -34,27 +34,30 @@ import java.util.Set; */ public interface ProfileService extends BaseService { - /** - * Query profile by profile name and type - * @param tenantId Tenant ID - * @param name Profile name - * @param type Profile type {@link ProfileTypeFlagEnum} - * @return ProfileBO - */ - ProfileBO selectByNameAndType(Long tenantId, String name, ProfileTypeFlagEnum type); + /** + * Query profile by profile name and type + * + * @param tenantId Tenant ID + * @param name Profile name + * @param type Profile type {@link ProfileTypeFlagEnum} + * @return ProfileBO + */ + ProfileBO selectByNameAndType(Long tenantId, String name, ProfileTypeFlagEnum type); - /** - * Query profiles by device ID - * @param deviceId Device ID - * @return ProfileBO list - */ - List selectByDeviceId(Long deviceId); + /** + * Query profiles by device ID + * + * @param deviceId Device ID + * @return ProfileBO list + */ + List selectByDeviceId(Long deviceId); - /** - * Query profiles by a set of profile IDs - * @param ids Profile ID set - * @return ProfileBO list - */ - List selectByIds(Set ids); + /** + * Query profiles by a set of profile IDs + * + * @param ids Profile ID set + * @return ProfileBO list + */ + List selectByIds(Set ids); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/TopicService.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/TopicService.java index 843b31e4d..d5e2cd8fa 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/TopicService.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/TopicService.java @@ -35,6 +35,6 @@ import java.util.List; public interface TopicService extends IService { - Page> query(TopicQuery topicQuery); + Page> query(TopicQuery topicQuery); } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DashboardServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DashboardServiceImpl.java index 1fe69518a..9c12a6e7c 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DashboardServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DashboardServiceImpl.java @@ -44,567 +44,563 @@ import java.util.*; @Service public class DashboardServiceImpl implements DashboardService { - // Top-N caps, mode / range literals and cache sizing all live in - // {@link TopologyLimits} — tuning them is a single-line change there. + // Top-N caps, mode / range literals and cache sizing all live in + // {@link TopologyLimits} — tuning them is a single-line change there. - private final Cache topologyCache = Caffeine.newBuilder() - .expireAfterWrite(Duration.ofSeconds(TopologyLimits.CACHE_TTL_SECONDS)) - .maximumSize(TopologyLimits.CACHE_MAX_SIZE) - .build(); + private final Cache topologyCache = Caffeine.newBuilder() + .expireAfterWrite(Duration.ofSeconds(TopologyLimits.CACHE_TTL_SECONDS)) + .maximumSize(TopologyLimits.CACHE_MAX_SIZE) + .build(); - @Resource - private DashboardMapper dashboardMapper; + @Resource + private DashboardMapper dashboardMapper; - private static List buckets(List rows, KeyFormatter fmt) { - List out = new ArrayList<>(rows.size()); - for (BucketRow row : rows) { - BucketVO vo = new BucketVO(); - vo.setKey(fmt.format(row.getKey())); - vo.setCount(row.getCount()); - out.add(vo); - } - return out; - } + private static List buckets(List rows, KeyFormatter fmt) { + List out = new ArrayList<>(rows.size()); + for (BucketRow row : rows) { + BucketVO vo = new BucketVO(); + vo.setKey(fmt.format(row.getKey())); + vo.setCount(row.getCount()); + out.add(vo); + } + return out; + } - private static String enableKey(Object raw) { - if (raw == null) - return TopologyLimits.UNKNOWN_BUCKET; - Byte b = raw instanceof Number n ? n.byteValue() : Byte.parseByte(raw.toString()); - EnableFlagEnum e = EnableFlagEnum.ofIndex(b); - return e == null ? TopologyLimits.UNKNOWN_BUCKET : e.name(); - } + private static String enableKey(Object raw) { + if (raw == null) + return TopologyLimits.UNKNOWN_BUCKET; + Byte b = raw instanceof Number n ? n.byteValue() : Byte.parseByte(raw.toString()); + EnableFlagEnum e = EnableFlagEnum.ofIndex(b); + return e == null ? TopologyLimits.UNKNOWN_BUCKET : e.name(); + } - // ================================================================ - // Topology (GET /dashboard/topology) - // ================================================================ + // ================================================================ + // Topology (GET /dashboard/topology) + // ================================================================ - private static String driverTypeKey(Object raw) { - if (raw == null) - return TopologyLimits.UNKNOWN_BUCKET; - Byte b = raw instanceof Number n ? n.byteValue() : Byte.parseByte(raw.toString()); - DriverTypeFlagEnum e = DriverTypeFlagEnum.ofIndex(b); - return e == null ? TopologyLimits.UNKNOWN_BUCKET : e.name(); - } + private static String driverTypeKey(Object raw) { + if (raw == null) + return TopologyLimits.UNKNOWN_BUCKET; + Byte b = raw instanceof Number n ? n.byteValue() : Byte.parseByte(raw.toString()); + DriverTypeFlagEnum e = DriverTypeFlagEnum.ofIndex(b); + return e == null ? TopologyLimits.UNKNOWN_BUCKET : e.name(); + } - /** - * Pads a sparse (day, count) row set into a fixed-length series ending on - * {@code today}. - */ - private static List fillSeries(List rows, LocalDate today, int length) { - long[] series = new long[length]; - LocalDate anchor = today.minusDays(length - 1L); - for (DailyGrowthRow row : rows) { - LocalDate day = row.getDay(); - if (day == null) - continue; - int idx = (int) (day.toEpochDay() - anchor.toEpochDay()); - if (idx >= 0 && idx < length) { - series[idx] = row.getCount(); - } - } - List out = new ArrayList<>(length); - for (long v : series) - out.add(v); - return out; - } + /** + * Pads a sparse (day, count) row set into a fixed-length series ending on + * {@code today}. + */ + private static List fillSeries(List rows, LocalDate today, int length) { + long[] series = new long[length]; + LocalDate anchor = today.minusDays(length - 1L); + for (DailyGrowthRow row : rows) { + LocalDate day = row.getDay(); + if (day == null) + continue; + int idx = (int) (day.toEpochDay() - anchor.toEpochDay()); + if (idx >= 0 && idx < length) { + series[idx] = row.getCount(); + } + } + List out = new ArrayList<>(length); + for (long v : series) + out.add(v); + return out; + } - private static TopologyStatsVO emptyStats(String rangeKey, boolean volumeMode) { - TopologyStatsVO s = new TopologyStatsVO(); - s.setRangeLabel(volumeMode ? rangeLabel(rangeKey) : null); - return s; - } + private static TopologyStatsVO emptyStats(String rangeKey, boolean volumeMode) { + TopologyStatsVO s = new TopologyStatsVO(); + s.setRangeLabel(volumeMode ? rangeLabel(rangeKey) : null); + return s; + } - /** - * Primary sort = weight desc; tie-break = id asc (stable layout). - */ - private static Comparator cmpByMap(Map weights, java.util.function.ToLongFunction idOf) { - return (a, b) -> { - long wa = weights.getOrDefault(idOf.applyAsLong(a), 0L); - long wb = weights.getOrDefault(idOf.applyAsLong(b), 0L); - int cmp = Long.compare(wb, wa); - if (cmp != 0) - return cmp; - return Long.compare(idOf.applyAsLong(a), idOf.applyAsLong(b)); - }; - } + /** + * Primary sort = weight desc; tie-break = id asc (stable layout). + */ + private static Comparator cmpByMap(Map weights, java.util.function.ToLongFunction idOf) { + return (a, b) -> { + long wa = weights.getOrDefault(idOf.applyAsLong(a), 0L); + long wb = weights.getOrDefault(idOf.applyAsLong(b), 0L); + int cmp = Long.compare(wb, wa); + if (cmp != 0) + return cmp; + return Long.compare(idOf.applyAsLong(a), idOf.applyAsLong(b)); + }; + } - private static String normaliseRange(String rangeKey) { - if (rangeKey == null || rangeKey.isBlank()) - return TopologyLimits.RANGE_DEFAULT; - return switch (rangeKey) { - case TopologyLimits.RANGE_TODAY, TopologyLimits.RANGE_24H, TopologyLimits.RANGE_7D, - TopologyLimits.RANGE_30D -> - rangeKey; - default -> TopologyLimits.RANGE_DEFAULT; - }; - } + private static String normaliseRange(String rangeKey) { + if (rangeKey == null || rangeKey.isBlank()) + return TopologyLimits.RANGE_DEFAULT; + return switch (rangeKey) { + case TopologyLimits.RANGE_TODAY, TopologyLimits.RANGE_24H, TopologyLimits.RANGE_7D, + TopologyLimits.RANGE_30D -> rangeKey; + default -> TopologyLimits.RANGE_DEFAULT; + }; + } - private static LocalDateTime fromOfRange(String rangeKey) { - LocalDateTime now = LocalDateTime.now(); - return switch (rangeKey) { - case TopologyLimits.RANGE_TODAY -> now.toLocalDate().atStartOfDay(); - case TopologyLimits.RANGE_24H -> now.minusHours(24); - case TopologyLimits.RANGE_30D -> now.minusDays(30); - default -> now.minusDays(7); - }; - } + private static LocalDateTime fromOfRange(String rangeKey) { + LocalDateTime now = LocalDateTime.now(); + return switch (rangeKey) { + case TopologyLimits.RANGE_TODAY -> now.toLocalDate().atStartOfDay(); + case TopologyLimits.RANGE_24H -> now.minusHours(24); + case TopologyLimits.RANGE_30D -> now.minusDays(30); + default -> now.minusDays(7); + }; + } - private static String rangeLabel(String rangeKey) { - return switch (rangeKey) { - case TopologyLimits.RANGE_TODAY -> "Today"; - case TopologyLimits.RANGE_24H -> TopologyLimits.RANGE_24H; - case TopologyLimits.RANGE_30D -> TopologyLimits.RANGE_30D; - default -> TopologyLimits.RANGE_DEFAULT; - }; - } + private static String rangeLabel(String rangeKey) { + return switch (rangeKey) { + case TopologyLimits.RANGE_TODAY -> "Today"; + case TopologyLimits.RANGE_24H -> TopologyLimits.RANGE_24H; + case TopologyLimits.RANGE_30D -> TopologyLimits.RANGE_30D; + default -> TopologyLimits.RANGE_DEFAULT; + }; + } - private static long nullZero(Long v) { - return v == null ? 0L : v; - } + private static long nullZero(Long v) { + return v == null ? 0L : v; + } - private static TopologyNodeVO node(String id, String name, int layer, String type, - List hiddenChildren) { - TopologyNodeVO n = new TopologyNodeVO(); - n.setId(id); - n.setName(name); - n.setLayer(layer); - n.setType(type); - n.setHiddenChildren(hiddenChildren); - return n; - } + private static TopologyNodeVO node(String id, String name, int layer, String type, + List hiddenChildren) { + TopologyNodeVO n = new TopologyNodeVO(); + n.setId(id); + n.setName(name); + n.setLayer(layer); + n.setType(type); + n.setHiddenChildren(hiddenChildren); + return n; + } - private static TopologyLinkVO link(String source, String target, long value) { - TopologyLinkVO l = new TopologyLinkVO(); - l.setSource(source); - l.setTarget(target); - l.setValue(value); - return l; - } + private static TopologyLinkVO link(String source, String target, long value) { + TopologyLinkVO l = new TopologyLinkVO(); + l.setSource(source); + l.setTarget(target); + l.setValue(value); + return l; + } - @Override - public DriverStatsVO driverStats(Long tenantId) { - DriverStatsVO out = new DriverStatsVO(); + @Override + public DriverStatsVO driverStats(Long tenantId) { + DriverStatsVO out = new DriverStatsVO(); - List byEnable = buckets(dashboardMapper.countDriverByEnable(tenantId), - DashboardServiceImpl::enableKey); - List byType = buckets(dashboardMapper.countDriverByType(tenantId), - DashboardServiceImpl::driverTypeKey); - List byService = buckets(dashboardMapper.countDriverByService(tenantId), - v -> v == null ? SymbolConstant.HYPHEN : v.toString()); + List byEnable = buckets(dashboardMapper.countDriverByEnable(tenantId), + DashboardServiceImpl::enableKey); + List byType = buckets(dashboardMapper.countDriverByType(tenantId), + DashboardServiceImpl::driverTypeKey); + List byService = buckets(dashboardMapper.countDriverByService(tenantId), + v -> v == null ? SymbolConstant.HYPHEN : v.toString()); - out.setByEnable(byEnable); - out.setByType(byType); - out.setByService(byService); - out.setTotal(byEnable.stream().mapToLong(BucketVO::getCount).sum()); - return out; - } + out.setByEnable(byEnable); + out.setByType(byType); + out.setByService(byService); + out.setTotal(byEnable.stream().mapToLong(BucketVO::getCount).sum()); + return out; + } - @Override - public DeviceStatsVO deviceStats(Long tenantId, int topN) { - int clampedTopN = Math.clamp(topN, 1, 50); - DeviceStatsVO out = new DeviceStatsVO(); + @Override + public DeviceStatsVO deviceStats(Long tenantId, int topN) { + int clampedTopN = Math.clamp(topN, 1, 50); + DeviceStatsVO out = new DeviceStatsVO(); - List byEnable = buckets(dashboardMapper.countDeviceByEnable(tenantId), - DashboardServiceImpl::enableKey); - List byDriver = buckets(dashboardMapper.countDeviceByDriver(tenantId, clampedTopN), - v -> v == null ? SymbolConstant.HYPHEN : v.toString()); - List byProfile = buckets(dashboardMapper.countDeviceByProfile(tenantId, clampedTopN), - v -> v == null ? SymbolConstant.HYPHEN : v.toString()); + List byEnable = buckets(dashboardMapper.countDeviceByEnable(tenantId), + DashboardServiceImpl::enableKey); + List byDriver = buckets(dashboardMapper.countDeviceByDriver(tenantId, clampedTopN), + v -> v == null ? SymbolConstant.HYPHEN : v.toString()); + List byProfile = buckets(dashboardMapper.countDeviceByProfile(tenantId, clampedTopN), + v -> v == null ? SymbolConstant.HYPHEN : v.toString()); - out.setByEnable(byEnable); - out.setByDriver(byDriver); - out.setByProfile(byProfile); - out.setTotal(byEnable.stream().mapToLong(BucketVO::getCount).sum()); - return out; - } + out.setByEnable(byEnable); + out.setByDriver(byDriver); + out.setByProfile(byProfile); + out.setTotal(byEnable.stream().mapToLong(BucketVO::getCount).sum()); + return out; + } - @Override - public GrowthVO dailyGrowth(Long tenantId, int days) { - int clamped = Math.clamp(days, 1, 90); - LocalDate today = LocalDate.now(); - LocalDateTime from = today.minusDays(clamped - 1L).atStartOfDay(); - LocalDateTime to = today.plusDays(1).atStartOfDay(); + @Override + public GrowthVO dailyGrowth(Long tenantId, int days) { + int clamped = Math.clamp(days, 1, 90); + LocalDate today = LocalDate.now(); + LocalDateTime from = today.minusDays(clamped - 1L).atStartOfDay(); + LocalDateTime to = today.plusDays(1).atStartOfDay(); - GrowthVO out = new GrowthVO(); - out.setDriver(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_driver", from, to), today, clamped)); - out.setDevice(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_device", from, to), today, clamped)); - out.setPoint(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_point", from, to), today, clamped)); - out.setProfile(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_profile", from, to), today, clamped)); - return out; - } + GrowthVO out = new GrowthVO(); + out.setDriver(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_driver", from, to), today, clamped)); + out.setDevice(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_device", from, to), today, clamped)); + out.setPoint(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_point", from, to), today, clamped)); + out.setProfile(fillSeries(dashboardMapper.dailyGrowth(tenantId, "dc3_profile", from, to), today, clamped)); + return out; + } - @Override - public TopologyVO topology(Long tenantId, String mode, String rangeKey) { - String normMode = TopologyLimits.MODE_VOLUME.equalsIgnoreCase(mode) ? TopologyLimits.MODE_VOLUME - : TopologyLimits.MODE_CARDINALITY; - String normRange = normaliseRange(rangeKey); - String cacheKey = tenantId + ":" + normMode + ":" + normRange; - TopologyVO hit = topologyCache.getIfPresent(cacheKey); - if (hit != null) - return hit; + @Override + public TopologyVO topology(Long tenantId, String mode, String rangeKey) { + String normMode = TopologyLimits.MODE_VOLUME.equalsIgnoreCase(mode) ? TopologyLimits.MODE_VOLUME + : TopologyLimits.MODE_CARDINALITY; + String normRange = normaliseRange(rangeKey); + String cacheKey = tenantId + ":" + normMode + ":" + normRange; + TopologyVO hit = topologyCache.getIfPresent(cacheKey); + if (hit != null) + return hit; - TopologyVO out = computeTopology(tenantId, normMode, normRange); - topologyCache.put(cacheKey, out); - return out; - } + TopologyVO out = computeTopology(tenantId, normMode, normRange); + topologyCache.put(cacheKey, out); + return out; + } - private TopologyVO computeTopology(Long tenantId, String mode, String rangeKey) { - TopologyVO out = new TopologyVO(); - boolean volumeMode = TopologyLimits.MODE_VOLUME.equals(mode); + private TopologyVO computeTopology(Long tenantId, String mode, String rangeKey) { + TopologyVO out = new TopologyVO(); + boolean volumeMode = TopologyLimits.MODE_VOLUME.equals(mode); - // ---- Fetch metadata (tenant-wide) -------------------------------- - // Pull everything up-front — cardinality over metadata is small, and - // volume mode's Top-N sort needs per-entity weights anyway so a - // single-pass rollup is simpler than iterated filtered queries. + // ---- Fetch metadata (tenant-wide) -------------------------------- + // Pull everything up-front — cardinality over metadata is small, and + // volume mode's Top-N sort needs per-entity weights anyway so a + // single-pass rollup is simpler than iterated filtered queries. - List driverRows = dashboardMapper.topologyDrivers(tenantId); - long driverTotal = driverRows.size(); - if (driverRows.isEmpty()) { - out.setStats(emptyStats(rangeKey, volumeMode)); - return out; - } + List driverRows = dashboardMapper.topologyDrivers(tenantId); + long driverTotal = driverRows.size(); + if (driverRows.isEmpty()) { + out.setStats(emptyStats(rangeKey, volumeMode)); + return out; + } - Map driverNameById = new LinkedHashMap<>(); - for (TopologyDriverRow r : driverRows) { - driverNameById.put(r.getId(), r.getDriverName()); - } - // All driver ids are needed to fetch their devices; we crop AFTER - // computing volumes so the top-N drivers reflect real activity, not - // just the ones with the most devices listed. - List allDriverIds = new ArrayList<>(driverNameById.keySet()); + Map driverNameById = new LinkedHashMap<>(); + for (TopologyDriverRow r : driverRows) { + driverNameById.put(r.getId(), r.getDriverName()); + } + // All driver ids are needed to fetch their devices; we crop AFTER + // computing volumes so the top-N drivers reflect real activity, not + // just the ones with the most devices listed. + List allDriverIds = new ArrayList<>(driverNameById.keySet()); - List deviceRows = dashboardMapper.topologyDevicesByDrivers(tenantId, allDriverIds); - long deviceTotal = deviceRows.size(); - Map deviceToDriver = new HashMap<>(deviceRows.size() * 2); - Map deviceNameById = new LinkedHashMap<>(); - for (TopologyDeviceRow r : deviceRows) { - Long did = r.getId(); - deviceToDriver.put(did, r.getDriverId()); - deviceNameById.put(did, r.getDeviceName()); - } - List allDeviceIds = new ArrayList<>(deviceNameById.keySet()); + List deviceRows = dashboardMapper.topologyDevicesByDrivers(tenantId, allDriverIds); + long deviceTotal = deviceRows.size(); + Map deviceToDriver = new HashMap<>(deviceRows.size() * 2); + Map deviceNameById = new LinkedHashMap<>(); + for (TopologyDeviceRow r : deviceRows) { + Long did = r.getId(); + deviceToDriver.put(did, r.getDriverId()); + deviceNameById.put(did, r.getDeviceName()); + } + List allDeviceIds = new ArrayList<>(deviceNameById.keySet()); - List bindingRows = allDeviceIds.isEmpty() ? Collections.emptyList() - : dashboardMapper.topologyProfileBindings(tenantId, allDeviceIds); - // device → set and profile → set - Map> profilesByDevice = new HashMap<>(); - Map> devicesByProfile = new LinkedHashMap<>(); - for (ProfileBindingRow r : bindingRows) { - Long did = r.getDeviceId(); - Long pid = r.getProfileId(); - profilesByDevice.computeIfAbsent(did, k -> new HashSet<>()).add(pid); - devicesByProfile.computeIfAbsent(pid, k -> new LinkedHashSet<>()).add(did); - } + List bindingRows = allDeviceIds.isEmpty() ? Collections.emptyList() + : dashboardMapper.topologyProfileBindings(tenantId, allDeviceIds); + // device → set and profile → set + Map> profilesByDevice = new HashMap<>(); + Map> devicesByProfile = new LinkedHashMap<>(); + for (ProfileBindingRow r : bindingRows) { + Long did = r.getDeviceId(); + Long pid = r.getProfileId(); + profilesByDevice.computeIfAbsent(did, k -> new HashSet<>()).add(pid); + devicesByProfile.computeIfAbsent(pid, k -> new LinkedHashSet<>()).add(did); + } - Set allProfileIdSet = devicesByProfile.keySet(); - List profileRows = allProfileIdSet.isEmpty() ? Collections.emptyList() - : dashboardMapper.topologyProfilesByIds(tenantId, allProfileIdSet); - Map profileNameById = new LinkedHashMap<>(); - for (TopologyProfileRow r : profileRows) { - profileNameById.put(r.getId(), r.getProfileName()); - } + Set allProfileIdSet = devicesByProfile.keySet(); + List profileRows = allProfileIdSet.isEmpty() ? Collections.emptyList() + : dashboardMapper.topologyProfilesByIds(tenantId, allProfileIdSet); + Map profileNameById = new LinkedHashMap<>(); + for (TopologyProfileRow r : profileRows) { + profileNameById.put(r.getId(), r.getProfileName()); + } - List pointRows = allProfileIdSet.isEmpty() ? Collections.emptyList() - : dashboardMapper.topologyPointsByProfiles(tenantId, allProfileIdSet); - long pointTotal = pointRows.size(); - // profile → ordered list of points - Map> pointsByProfile = new LinkedHashMap<>(); - for (TopologyPointRow r : pointRows) { - pointsByProfile.computeIfAbsent(r.getProfileId(), k -> new ArrayList<>()).add(r); - } + List pointRows = allProfileIdSet.isEmpty() ? Collections.emptyList() + : dashboardMapper.topologyPointsByProfiles(tenantId, allProfileIdSet); + long pointTotal = pointRows.size(); + // profile → ordered list of points + Map> pointsByProfile = new LinkedHashMap<>(); + for (TopologyPointRow r : pointRows) { + pointsByProfile.computeIfAbsent(r.getProfileId(), k -> new ArrayList<>()).add(r); + } - // ---- Fetch volumes if needed ------------------------------------- - // Map<(deviceId, pointId), count>. Empty in cardinality mode. - Map> volumeByDevicePoint = new HashMap<>(); - if (volumeMode) { - LocalDateTime from = fromOfRange(rangeKey); - List volumeRows = dashboardMapper.topologyPointVolumes(tenantId, from); - for (PointVolumeRow r : volumeRows) { - Long did = r.getDeviceId(); - Long pid = r.getPointId(); - long cnt = r.getCnt(); - volumeByDevicePoint.computeIfAbsent(did, k -> new HashMap<>()).put(pid, cnt); - } - } + // ---- Fetch volumes if needed ------------------------------------- + // Map<(deviceId, pointId), count>. Empty in cardinality mode. + Map> volumeByDevicePoint = new HashMap<>(); + if (volumeMode) { + LocalDateTime from = fromOfRange(rangeKey); + List volumeRows = dashboardMapper.topologyPointVolumes(tenantId, from); + for (PointVolumeRow r : volumeRows) { + Long did = r.getDeviceId(); + Long pid = r.getPointId(); + long cnt = r.getCnt(); + volumeByDevicePoint.computeIfAbsent(did, k -> new HashMap<>()).put(pid, cnt); + } + } - // ---- Compute per-entity weights --------------------------------- - // In volume mode weights are pv counts; in cardinality mode they - // degenerate to the structural counts the earlier implementation - // used (devices per driver, profiles per device, 1 per point). + // ---- Compute per-entity weights --------------------------------- + // In volume mode weights are pv counts; in cardinality mode they + // degenerate to the structural counts the earlier implementation + // used (devices per driver, profiles per device, 1 per point). - // point weight = Σ volumes[(d, p)] over all d bound to p's profile - Map pointWeight = new HashMap<>(); - // device weight = Σ volumes[(d, p)] over all p in any profile bound - // to d (cardinality fallback = count of profile bindings) - Map deviceWeight = new HashMap<>(); - // driver weight = Σ device weights for d.driver_id = r (cardinality - // fallback = count of devices) - Map driverWeight = new HashMap<>(); + // point weight = Σ volumes[(d, p)] over all d bound to p's profile + Map pointWeight = new HashMap<>(); + // device weight = Σ volumes[(d, p)] over all p in any profile bound + // to d (cardinality fallback = count of profile bindings) + Map deviceWeight = new HashMap<>(); + // driver weight = Σ device weights for d.driver_id = r (cardinality + // fallback = count of devices) + Map driverWeight = new HashMap<>(); - if (volumeMode) { - for (Map.Entry> e : pointsByProfile.entrySet()) { - Long profileId = e.getKey(); - Set devs = devicesByProfile.getOrDefault(profileId, Collections.emptySet()); - for (TopologyPointRow r : e.getValue()) { - Long pid = r.getId(); - long sum = 0; - for (Long did : devs) { - Map vs = volumeByDevicePoint.get(did); - if (vs != null) - sum += vs.getOrDefault(pid, 0L); - } - pointWeight.put(pid, sum); - } - } - for (Map.Entry> e : volumeByDevicePoint.entrySet()) { - Long did = e.getKey(); - long sum = 0; - for (long v : e.getValue().values()) - sum += v; - deviceWeight.put(did, sum); - Long drvId = deviceToDriver.get(did); - if (drvId != null) - driverWeight.merge(drvId, sum, Long::sum); - } - } - else { - // Cardinality fallbacks mirror the original Top-N behaviour: - // driver weight = count of devices - // device weight = count of profile bindings - // point weight = 1 (stable tie-break on id desc later) - for (TopologyDriverRow r : driverRows) { - driverWeight.put(r.getId(), r.getDeviceCount()); - } - for (TopologyDeviceRow r : deviceRows) { - deviceWeight.put(r.getId(), r.getProfileCount()); - } - for (TopologyPointRow r : pointRows) { - pointWeight.put(r.getId(), 1L); - } - } + if (volumeMode) { + for (Map.Entry> e : pointsByProfile.entrySet()) { + Long profileId = e.getKey(); + Set devs = devicesByProfile.getOrDefault(profileId, Collections.emptySet()); + for (TopologyPointRow r : e.getValue()) { + Long pid = r.getId(); + long sum = 0; + for (Long did : devs) { + Map vs = volumeByDevicePoint.get(did); + if (vs != null) + sum += vs.getOrDefault(pid, 0L); + } + pointWeight.put(pid, sum); + } + } + for (Map.Entry> e : volumeByDevicePoint.entrySet()) { + Long did = e.getKey(); + long sum = 0; + for (long v : e.getValue().values()) + sum += v; + deviceWeight.put(did, sum); + Long drvId = deviceToDriver.get(did); + if (drvId != null) + driverWeight.merge(drvId, sum, Long::sum); + } + } else { + // Cardinality fallbacks mirror the original Top-N behaviour: + // driver weight = count of devices + // device weight = count of profile bindings + // point weight = 1 (stable tie-break on id desc later) + for (TopologyDriverRow r : driverRows) { + driverWeight.put(r.getId(), r.getDeviceCount()); + } + for (TopologyDeviceRow r : deviceRows) { + deviceWeight.put(r.getId(), r.getProfileCount()); + } + for (TopologyPointRow r : pointRows) { + pointWeight.put(r.getId(), 1L); + } + } - // ---- Volume-mode zero-weight filter ----------------------------- - // In volume mode the whole point of the chart is "where is data - // actually flowing". Entities with zero flow — brand-new drivers - // not yet registered, devices without a profile binding, points - // whose sensor hasn't reported in the selected window — just add - // visual noise (half-rendered columns with no bands). Drop them - // here BEFORE Top-N sort so the crop reflects real activity. - // - // Cardinality mode keeps everything so operators can still see - // "unconfigured" entities on the structural view. - List activeDrivers = volumeMode ? driverRows.stream() - .filter(r -> nullZero(driverWeight.get(r.getId())) > 0) - .collect(java.util.stream.Collectors.toList()) : new ArrayList<>(driverRows); + // ---- Volume-mode zero-weight filter ----------------------------- + // In volume mode the whole point of the chart is "where is data + // actually flowing". Entities with zero flow — brand-new drivers + // not yet registered, devices without a profile binding, points + // whose sensor hasn't reported in the selected window — just add + // visual noise (half-rendered columns with no bands). Drop them + // here BEFORE Top-N sort so the crop reflects real activity. + // + // Cardinality mode keeps everything so operators can still see + // "unconfigured" entities on the structural view. + List activeDrivers = volumeMode ? driverRows.stream() + .filter(r -> nullZero(driverWeight.get(r.getId())) > 0) + .collect(java.util.stream.Collectors.toList()) : new ArrayList<>(driverRows); - // ---- Crop Top-N drivers ---------------------------------------- - activeDrivers.sort(cmpByMap(driverWeight, v -> v.getId())); - List topDrivers = activeDrivers.size() > TopologyLimits.TOP_DRIVERS - ? activeDrivers.subList(0, TopologyLimits.TOP_DRIVERS) : activeDrivers; - Set topDriverIds = new LinkedHashSet<>(); - for (TopologyDriverRow r : topDrivers) - topDriverIds.add(r.getId()); + // ---- Crop Top-N drivers ---------------------------------------- + activeDrivers.sort(cmpByMap(driverWeight, v -> v.getId())); + List topDrivers = activeDrivers.size() > TopologyLimits.TOP_DRIVERS + ? activeDrivers.subList(0, TopologyLimits.TOP_DRIVERS) : activeDrivers; + Set topDriverIds = new LinkedHashSet<>(); + for (TopologyDriverRow r : topDrivers) + topDriverIds.add(r.getId()); - // ---- Crop Top-N devices (must belong to a kept driver) ---------- - List filteredDevices = new ArrayList<>(); - for (TopologyDeviceRow r : deviceRows) { - if (!topDriverIds.contains(r.getDriverId())) - continue; - if (volumeMode && nullZero(deviceWeight.get(r.getId())) == 0) - continue; - filteredDevices.add(r); - } - filteredDevices.sort(cmpByMap(deviceWeight, v -> v.getId())); - List topDevices = filteredDevices.size() > TopologyLimits.TOP_DEVICES - ? filteredDevices.subList(0, TopologyLimits.TOP_DEVICES) : filteredDevices; - Set topDeviceIdSet = new LinkedHashSet<>(); - for (TopologyDeviceRow r : topDevices) - topDeviceIdSet.add(r.getId()); + // ---- Crop Top-N devices (must belong to a kept driver) ---------- + List filteredDevices = new ArrayList<>(); + for (TopologyDeviceRow r : deviceRows) { + if (!topDriverIds.contains(r.getDriverId())) + continue; + if (volumeMode && nullZero(deviceWeight.get(r.getId())) == 0) + continue; + filteredDevices.add(r); + } + filteredDevices.sort(cmpByMap(deviceWeight, v -> v.getId())); + List topDevices = filteredDevices.size() > TopologyLimits.TOP_DEVICES + ? filteredDevices.subList(0, TopologyLimits.TOP_DEVICES) : filteredDevices; + Set topDeviceIdSet = new LinkedHashSet<>(); + for (TopologyDeviceRow r : topDevices) + topDeviceIdSet.add(r.getId()); - // Per-driver "others:device:{driverId}" buckets for cropped - // devices. In volume mode only devices that had activity but got - // cropped land here — zero-flow devices were filtered above, so - // Others never represents "nothing is happening". - Map> otherDevicesByDriver = new LinkedHashMap<>(); - for (TopologyDeviceRow r : filteredDevices) { - Long deviceId = r.getId(); - if (topDeviceIdSet.contains(deviceId)) - continue; - Long drvId = r.getDriverId(); - TopologyHiddenChildVO hidden = new TopologyHiddenChildVO(); - hidden.setId("device:" + deviceId); - hidden.setName(r.getDeviceName()); - hidden.setType("device"); - otherDevicesByDriver.computeIfAbsent(drvId, k -> new ArrayList<>()).add(hidden); - } + // Per-driver "others:device:{driverId}" buckets for cropped + // devices. In volume mode only devices that had activity but got + // cropped land here — zero-flow devices were filtered above, so + // Others never represents "nothing is happening". + Map> otherDevicesByDriver = new LinkedHashMap<>(); + for (TopologyDeviceRow r : filteredDevices) { + Long deviceId = r.getId(); + if (topDeviceIdSet.contains(deviceId)) + continue; + Long drvId = r.getDriverId(); + TopologyHiddenChildVO hidden = new TopologyHiddenChildVO(); + hidden.setId("device:" + deviceId); + hidden.setName(r.getDeviceName()); + hidden.setType("device"); + otherDevicesByDriver.computeIfAbsent(drvId, k -> new ArrayList<>()).add(hidden); + } - // ---- Profile set (bound to kept devices) ----------------------- - // In volume mode drop profiles whose points collectively got no - // samples — otherwise the profile column paints a tile with no - // outgoing band, exactly the "空模板" case the operator flagged. - Set keptProfileIds = new LinkedHashSet<>(); - for (Long did : topDeviceIdSet) { - Set pids = profilesByDevice.get(did); - if (pids != null) - keptProfileIds.addAll(pids); - } - if (volumeMode) { - Set active = new LinkedHashSet<>(); - for (Long pid : keptProfileIds) { - long sum = 0; - for (TopologyPointRow p : pointsByProfile.getOrDefault(pid, Collections.emptyList())) { - sum += nullZero(pointWeight.get(p.getId())); - if (sum > 0) - break; - } - if (sum > 0) - active.add(pid); - } - keptProfileIds = active; - } + // ---- Profile set (bound to kept devices) ----------------------- + // In volume mode drop profiles whose points collectively got no + // samples — otherwise the profile column paints a tile with no + // outgoing band, exactly the "空模板" case the operator flagged. + Set keptProfileIds = new LinkedHashSet<>(); + for (Long did : topDeviceIdSet) { + Set pids = profilesByDevice.get(did); + if (pids != null) + keptProfileIds.addAll(pids); + } + if (volumeMode) { + Set active = new LinkedHashSet<>(); + for (Long pid : keptProfileIds) { + long sum = 0; + for (TopologyPointRow p : pointsByProfile.getOrDefault(pid, Collections.emptyList())) { + sum += nullZero(pointWeight.get(p.getId())); + if (sum > 0) + break; + } + if (sum > 0) + active.add(pid); + } + keptProfileIds = active; + } - // ---- Compose nodes + links ------------------------------------- - List nodes = new ArrayList<>(); - List links = new ArrayList<>(); + // ---- Compose nodes + links ------------------------------------- + List nodes = new ArrayList<>(); + List links = new ArrayList<>(); - for (TopologyDriverRow r : topDrivers) { - Long id = r.getId(); - nodes.add(node("driver:" + id, driverNameById.get(id), 1, "driver", null)); - } + for (TopologyDriverRow r : topDrivers) { + Long id = r.getId(); + nodes.add(node("driver:" + id, driverNameById.get(id), 1, "driver", null)); + } - // Driver → Device links. Edge weight in cardinality mode = 1 (one - // relationship); in volume mode = that device's total pv count. - for (TopologyDeviceRow r : topDevices) { - Long id = r.getId(); - Long driverId = r.getDriverId(); - String name = r.getDeviceName(); - nodes.add(node("device:" + id, name, 2, "device", null)); - long w = volumeMode ? nullZero(deviceWeight.get(id)) : 1L; - links.add(link("driver:" + driverId, "device:" + id, Math.max(1L, w))); - } + // Driver → Device links. Edge weight in cardinality mode = 1 (one + // relationship); in volume mode = that device's total pv count. + for (TopologyDeviceRow r : topDevices) { + Long id = r.getId(); + Long driverId = r.getDriverId(); + String name = r.getDeviceName(); + nodes.add(node("device:" + id, name, 2, "device", null)); + long w = volumeMode ? nullZero(deviceWeight.get(id)) : 1L; + links.add(link("driver:" + driverId, "device:" + id, Math.max(1L, w))); + } - for (Map.Entry> e : otherDevicesByDriver.entrySet()) { - Long driverId = e.getKey(); - List children = e.getValue(); - long w; - if (volumeMode) { - long sum = 0; - for (TopologyHiddenChildVO c : children) { - long did = Long.parseLong(c.getId().substring("device:".length())); - sum += nullZero(deviceWeight.get(did)); - } - w = Math.max(1L, sum); - } - else { - w = children.size(); - } - String otherId = "others:device:" + driverId; - nodes.add(node(otherId, "Others (" + children.size() + ")", 2, "others", children)); - links.add(link("driver:" + driverId, otherId, w)); - } + for (Map.Entry> e : otherDevicesByDriver.entrySet()) { + Long driverId = e.getKey(); + List children = e.getValue(); + long w; + if (volumeMode) { + long sum = 0; + for (TopologyHiddenChildVO c : children) { + long did = Long.parseLong(c.getId().substring("device:".length())); + sum += nullZero(deviceWeight.get(did)); + } + w = Math.max(1L, sum); + } else { + w = children.size(); + } + String otherId = "others:device:" + driverId; + nodes.add(node(otherId, "Others (" + children.size() + ")", 2, "others", children)); + links.add(link("driver:" + driverId, otherId, w)); + } - // Profile nodes - for (Long profileId : keptProfileIds) { - String name = profileNameById.getOrDefault(profileId, String.valueOf(profileId)); - nodes.add(node("profile:" + profileId, name, 3, "profile", null)); - } + // Profile nodes + for (Long profileId : keptProfileIds) { + String name = profileNameById.getOrDefault(profileId, String.valueOf(profileId)); + nodes.add(node("profile:" + profileId, name, 3, "profile", null)); + } - // Device → Profile links — one per (device, profile) binding where - // the device was kept. Volume-mode weight = Σ pv over the points - // on that profile for that device. Skip the edge entirely when - // that sum is 0 so we don't draw a dangling minimum-width band - // for a device that never sent data through this profile — even - // if other devices on the same profile did. - for (ProfileBindingRow r : bindingRows) { - Long deviceId = r.getDeviceId(); - Long profileId = r.getProfileId(); - if (!topDeviceIdSet.contains(deviceId)) - continue; - if (!keptProfileIds.contains(profileId)) - continue; - long w = 1L; - if (volumeMode) { - long sum = 0; - Map devVols = volumeByDevicePoint.get(deviceId); - List pts = pointsByProfile.getOrDefault(profileId, Collections.emptyList()); - if (devVols != null) { - for (TopologyPointRow p : pts) { - sum += devVols.getOrDefault(p.getId(), 0L); - } - } - if (sum == 0) - continue; - w = sum; - } - links.add(link("device:" + deviceId, "profile:" + profileId, w)); - } + // Device → Profile links — one per (device, profile) binding where + // the device was kept. Volume-mode weight = Σ pv over the points + // on that profile for that device. Skip the edge entirely when + // that sum is 0 so we don't draw a dangling minimum-width band + // for a device that never sent data through this profile — even + // if other devices on the same profile did. + for (ProfileBindingRow r : bindingRows) { + Long deviceId = r.getDeviceId(); + Long profileId = r.getProfileId(); + if (!topDeviceIdSet.contains(deviceId)) + continue; + if (!keptProfileIds.contains(profileId)) + continue; + long w = 1L; + if (volumeMode) { + long sum = 0; + Map devVols = volumeByDevicePoint.get(deviceId); + List pts = pointsByProfile.getOrDefault(profileId, Collections.emptyList()); + if (devVols != null) { + for (TopologyPointRow p : pts) { + sum += devVols.getOrDefault(p.getId(), 0L); + } + } + if (sum == 0) + continue; + w = sum; + } + links.add(link("device:" + deviceId, "profile:" + profileId, w)); + } - // Profile → Point layer with per-profile Top-N and Others. In - // volume mode we drop points whose weight is 0 up front so the - // profile never renders a slim tile for "this point is declared - // but silent"; cardinality keeps everything for the structural - // view. - for (Long profileId : keptProfileIds) { - List allPoints = new ArrayList<>( - pointsByProfile.getOrDefault(profileId, Collections.emptyList())); - if (volumeMode) { - allPoints.removeIf(p -> nullZero(pointWeight.get(p.getId())) == 0); - allPoints.sort(cmpByMap(pointWeight, v -> v.getId())); - } - else { - allPoints.sort(Comparator.comparingLong((TopologyPointRow r) -> r.getId()).reversed()); - } + // Profile → Point layer with per-profile Top-N and Others. In + // volume mode we drop points whose weight is 0 up front so the + // profile never renders a slim tile for "this point is declared + // but silent"; cardinality keeps everything for the structural + // view. + for (Long profileId : keptProfileIds) { + List allPoints = new ArrayList<>( + pointsByProfile.getOrDefault(profileId, Collections.emptyList())); + if (volumeMode) { + allPoints.removeIf(p -> nullZero(pointWeight.get(p.getId())) == 0); + allPoints.sort(cmpByMap(pointWeight, v -> v.getId())); + } else { + allPoints.sort(Comparator.comparingLong((TopologyPointRow r) -> r.getId()).reversed()); + } - int keep = Math.min(TopologyLimits.TOP_POINTS_PER_PROFILE, allPoints.size()); - for (int i = 0; i < keep; i++) { - TopologyPointRow r = allPoints.get(i); - Long id = r.getId(); - String name = r.getPointName(); - nodes.add(node("point:" + id, name, 4, "point", null)); - long w = volumeMode ? nullZero(pointWeight.get(id)) : 1L; - links.add(link("profile:" + profileId, "point:" + id, Math.max(1L, w))); - } + int keep = Math.min(TopologyLimits.TOP_POINTS_PER_PROFILE, allPoints.size()); + for (int i = 0; i < keep; i++) { + TopologyPointRow r = allPoints.get(i); + Long id = r.getId(); + String name = r.getPointName(); + nodes.add(node("point:" + id, name, 4, "point", null)); + long w = volumeMode ? nullZero(pointWeight.get(id)) : 1L; + links.add(link("profile:" + profileId, "point:" + id, Math.max(1L, w))); + } - if (allPoints.size() > keep) { - List children = new ArrayList<>(allPoints.size() - keep); - long sumW = 0; - for (int i = keep; i < allPoints.size(); i++) { - TopologyPointRow r = allPoints.get(i); - Long id = r.getId(); - TopologyHiddenChildVO hidden = new TopologyHiddenChildVO(); - hidden.setId("point:" + id); - hidden.setName(r.getPointName()); - hidden.setType("point"); - children.add(hidden); - if (volumeMode) - sumW += nullZero(pointWeight.get(id)); - } - long w = volumeMode ? Math.max(1L, sumW) : children.size(); - String otherId = "others:point:" + profileId; - nodes.add(node(otherId, "Others (" + children.size() + ")", 4, "others", children)); - links.add(link("profile:" + profileId, otherId, w)); - } - } + if (allPoints.size() > keep) { + List children = new ArrayList<>(allPoints.size() - keep); + long sumW = 0; + for (int i = keep; i < allPoints.size(); i++) { + TopologyPointRow r = allPoints.get(i); + Long id = r.getId(); + TopologyHiddenChildVO hidden = new TopologyHiddenChildVO(); + hidden.setId("point:" + id); + hidden.setName(r.getPointName()); + hidden.setType("point"); + children.add(hidden); + if (volumeMode) + sumW += nullZero(pointWeight.get(id)); + } + long w = volumeMode ? Math.max(1L, sumW) : children.size(); + String otherId = "others:point:" + profileId; + nodes.add(node(otherId, "Others (" + children.size() + ")", 4, "others", children)); + links.add(link("profile:" + profileId, otherId, w)); + } + } - // ---- stats ---- - TopologyStatsVO stats = new TopologyStatsVO(); - stats.setDriverCount(driverTotal); - stats.setDeviceCount(deviceTotal); - stats.setProfileCount(allProfileIdSet.size()); - stats.setPointCount(pointTotal); - stats.setRangeLabel(volumeMode ? rangeLabel(rangeKey) : null); + // ---- stats ---- + TopologyStatsVO stats = new TopologyStatsVO(); + stats.setDriverCount(driverTotal); + stats.setDeviceCount(deviceTotal); + stats.setProfileCount(allProfileIdSet.size()); + stats.setPointCount(pointTotal); + stats.setRangeLabel(volumeMode ? rangeLabel(rangeKey) : null); - out.setNodes(nodes); - out.setLinks(links); - out.setStats(stats); - return out; - } + out.setNodes(nodes); + out.setLinks(links); + out.setStats(stats); + return out; + } - @FunctionalInterface - private interface KeyFormatter { + @FunctionalInterface + private interface KeyFormatter { - String format(Object raw); + String format(Object raw); - } + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DeviceServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DeviceServiceImpl.java index a4a31ce65..5dfbe86d9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DeviceServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DeviceServiceImpl.java @@ -77,476 +77,472 @@ import java.util.Objects; @Service public class DeviceServiceImpl implements DeviceService { - @Resource - private DeviceBuilder deviceBuilder; + @Resource + private DeviceBuilder deviceBuilder; - @Resource - private DeviceManager deviceManager; + @Resource + private DeviceManager deviceManager; - @Resource - private DeviceMapper deviceMapper; + @Resource + private DeviceMapper deviceMapper; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Resource - private ProfileBindService profileBindService; + @Resource + private ProfileBindService profileBindService; - @Resource - private DriverAttributeService driverAttributeService; + @Resource + private DriverAttributeService driverAttributeService; - @Resource - private PointAttributeService pointAttributeService; + @Resource + private PointAttributeService pointAttributeService; - @Resource - private ImportDeviceService importDeviceService; + @Resource + private ImportDeviceService importDeviceService; - @Resource - private MetadataEventPublisher metadataEventPublisher; + @Resource + private MetadataEventPublisher metadataEventPublisher; - @Override - public void save(DeviceBO entityBO) { - boolean duplicate = checkDuplicate(entityBO, false); - if (duplicate) { - throw new DuplicateException("Failed to create device: device has been duplicated"); - } + @Override + public void save(DeviceBO entityBO) { + boolean duplicate = checkDuplicate(entityBO, false); + if (duplicate) { + throw new DuplicateException("Failed to create device: device has been duplicated"); + } - DeviceDO entityDO = deviceBuilder.buildDOByBO(entityBO); - if (!deviceManager.save(entityDO)) { - throw new AddException("Failed to create device"); - } + DeviceDO entityDO = deviceBuilder.buildDOByBO(entityBO); + if (!deviceManager.save(entityDO)) { + throw new AddException("Failed to create device"); + } - addProfileBind(entityDO, entityBO.getProfileIds()); + addProfileBind(entityDO, entityBO.getProfileIds()); - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.ADD); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.ADD); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - @Transactional - public void remove(Long id) { - DeviceDO entityDO = getDOById(id, true); + @Override + @Transactional + public void remove(Long id) { + DeviceDO entityDO = getDOById(id, true); - // - if (!profileBindService.removeByDeviceId(id)) { - throw new DeleteException("Failed to remove profile bind"); - } + // + if (!profileBindService.removeByDeviceId(id)) { + throw new DeleteException("Failed to remove profile bind"); + } - if (!deviceManager.removeById(id)) { - throw new DeleteException("Failed to remove device"); - } + if (!deviceManager.removeById(id)) { + throw new DeleteException("Failed to remove device"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.DELETE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.DELETE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public void update(DeviceBO entityBO) { - DeviceDO entityDO = getDOById(entityBO.getId(), true); + @Override + public void update(DeviceBO entityBO) { + DeviceDO entityDO = getDOById(entityBO.getId(), true); - boolean duplicate = checkDuplicate(entityBO, true); - if (duplicate) { - throw new DuplicateException("Failed to update device: device has been duplicated"); - } + boolean duplicate = checkDuplicate(entityBO, true); + if (duplicate) { + throw new DuplicateException("Failed to update device: device has been duplicated"); + } - List newProfileIds = entityBO.getProfileIds(); - List oldProfileIds = profileBindService.selectProfileIdsByDeviceId(entityBO.getId()); + List newProfileIds = entityBO.getProfileIds(); + List oldProfileIds = profileBindService.selectProfileIdsByDeviceId(entityBO.getId()); - // - ArrayList addIds = new ArrayList<>(newProfileIds); - addIds.removeAll(oldProfileIds); - addProfileBind(entityDO, addIds); + // + ArrayList addIds = new ArrayList<>(newProfileIds); + addIds.removeAll(oldProfileIds); + addProfileBind(entityDO, addIds); - // - ArrayList deleteIds = new ArrayList<>(oldProfileIds); - deleteIds.removeAll(newProfileIds); - deleteIds.forEach(profileId -> profileBindService.removeByDeviceIdAndProfileId(entityBO.getId(), profileId)); + // + ArrayList deleteIds = new ArrayList<>(oldProfileIds); + deleteIds.removeAll(newProfileIds); + deleteIds.forEach(profileId -> profileBindService.removeByDeviceIdAndProfileId(entityBO.getId(), profileId)); - entityDO = deviceBuilder.buildDOByBO(entityBO); - entityBO.setOperateTime(null); - if (!deviceManager.updateById(entityDO)) { - throw new UpdateException("The device update failed"); - } + entityDO = deviceBuilder.buildDOByBO(entityBO); + entityBO.setOperateTime(null); + if (!deviceManager.updateById(entityDO)) { + throw new UpdateException("The device update failed"); + } - DeviceBO deviceBO = selectById(entityBO.getId()); - deviceBO.setProfileIds(CollectionUtils.isEmpty(newProfileIds) ? oldProfileIds : newProfileIds); - entityBO.setDeviceName(deviceBO.getDeviceName()); + DeviceBO deviceBO = selectById(entityBO.getId()); + deviceBO.setProfileIds(CollectionUtils.isEmpty(newProfileIds) ? oldProfileIds : newProfileIds); + entityBO.setDeviceName(deviceBO.getDeviceName()); - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public DeviceBO selectById(Long id) { - DeviceDO entityDO = getDOById(id, true); - DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); - entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(id)); - return entityBO; - } + @Override + public DeviceBO selectById(Long id) { + DeviceDO entityDO = getDOById(id, true); + DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); + entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(id)); + return entityBO; + } - @Override - public DeviceBO selectByName(String name, Long tenantId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DeviceDO::getDeviceName, name); - wrapper.eq(DeviceDO::getTenantId, tenantId); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DeviceDO entityDO = deviceManager.getOne(wrapper); - DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); - entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(entityDO.getId())); - return entityBO; - } + @Override + public DeviceBO selectByName(String name, Long tenantId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DeviceDO::getDeviceName, name); + wrapper.eq(DeviceDO::getTenantId, tenantId); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DeviceDO entityDO = deviceManager.getOne(wrapper); + DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); + entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(entityDO.getId())); + return entityBO; + } - @Override - public DeviceBO selectByCode(String code, Long tenantId) { - LambdaQueryChainWrapper wrapper = deviceManager.lambdaQuery() - .eq(DeviceDO::getDeviceCode, code) - .eq(DeviceDO::getTenantId, tenantId) - .last(QueryWrapperConstant.LIMIT_ONE); - DeviceDO entityDO = wrapper.one(); - DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); - entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(entityDO.getId())); - return entityBO; - } + @Override + public DeviceBO selectByCode(String code, Long tenantId) { + LambdaQueryChainWrapper wrapper = deviceManager.lambdaQuery() + .eq(DeviceDO::getDeviceCode, code) + .eq(DeviceDO::getTenantId, tenantId) + .last(QueryWrapperConstant.LIMIT_ONE); + DeviceDO entityDO = wrapper.one(); + DeviceBO entityBO = deviceBuilder.buildBOByDO(entityDO); + entityBO.setProfileIds(profileBindService.selectProfileIdsByDeviceId(entityDO.getId())); + return entityBO; + } - @Override - public List selectByDriverId(Long driverId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DeviceDO::getDriverId, driverId); - List entityDOList = deviceManager.list(wrapper); - List deviceBOList = deviceBuilder.buildBOListByDOList(entityDOList); - deviceBOList - .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); - return deviceBOList; - } + @Override + public List selectByDriverId(Long driverId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DeviceDO::getDriverId, driverId); + List entityDOList = deviceManager.list(wrapper); + List deviceBOList = deviceBuilder.buildBOListByDOList(entityDOList); + deviceBOList + .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); + return deviceBOList; + } - @Override - public List selectIdsByDriverId(Long driverId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DeviceDO::getDriverId, driverId).select(DeviceDO::getId); - return deviceManager.list(wrapper).stream().map(DeviceDO::getId).toList(); - } + @Override + public List selectIdsByDriverId(Long driverId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DeviceDO::getDriverId, driverId).select(DeviceDO::getId); + return deviceManager.list(wrapper).stream().map(DeviceDO::getId).toList(); + } - @Override - public List selectByProfileId(Long profileId) { - return selectByIds(profileBindService.selectDeviceIdsByProfileId(profileId)); - } + @Override + public List selectByProfileId(Long profileId) { + return selectByIds(profileBindService.selectDeviceIdsByProfileId(profileId)); + } - @Override - public List selectByIds(List ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyList(); - } - List entityDOList = deviceManager.listByIds(ids); - List deviceBOList = deviceBuilder.buildBOListByDOList(entityDOList); - deviceBOList - .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); - return deviceBOList; - } + @Override + public List selectByIds(List ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyList(); + } + List entityDOList = deviceManager.listByIds(ids); + List deviceBOList = deviceBuilder.buildBOListByDOList(entityDOList); + deviceBOList + .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); + return deviceBOList; + } - @Override - public Page selectByPage(DeviceQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = deviceMapper.selectPageWithProfile(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery), entityQuery.getProfileId()); - Page entityPageBO = deviceBuilder.buildBOPageByDOPage(entityPageDO); - entityPageBO.getRecords() - .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); - return entityPageBO; - } + @Override + public Page selectByPage(DeviceQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = deviceMapper.selectPageWithProfile(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery), entityQuery.getProfileId()); + Page entityPageBO = deviceBuilder.buildBOPageByDOPage(entityPageDO); + entityPageBO.getRecords() + .forEach(device -> device.setProfileIds(profileBindService.selectProfileIdsByDeviceId(device.getId()))); + return entityPageBO; + } - @Override - public void importDevice(DeviceBO entityBO, File file) { - List pointBOList = pointService.selectByProfileIds(entityBO.getProfileIds()); - List driverAttributeBOList = driverAttributeService.selectByDriverId(entityBO.getDriverId()); - List pointAttributeBOList = pointAttributeService.selectByDriverId(entityBO.getDriverId()); + @Override + public void importDevice(DeviceBO entityBO, File file) { + List pointBOList = pointService.selectByProfileIds(entityBO.getProfileIds()); + List driverAttributeBOList = driverAttributeService.selectByDriverId(entityBO.getDriverId()); + List pointAttributeBOList = pointAttributeService.selectByDriverId(entityBO.getDriverId()); - Workbook workbook; - try { - workbook = new XSSFWorkbook(file); - } - catch (Exception e) { - throw new ImportException("The import template file incorrectly: {}", e.getMessage()); - } + Workbook workbook; + try { + workbook = new XSSFWorkbook(file); + } catch (Exception e) { + throw new ImportException("The import template file incorrectly: {}", e.getMessage()); + } - if (!configIsEqual(workbook, driverAttributeBOList, pointAttributeBOList, pointBOList)) { - throw new ImportException("The import template is formatted incorrectly"); - } + if (!configIsEqual(workbook, driverAttributeBOList, pointAttributeBOList, pointBOList)) { + throw new ImportException("The import template is formatted incorrectly"); + } - Sheet sheet = workbook.getSheet(""); - for (int i = 4; i <= sheet.getLastRowNum(); i++) { - DeviceBO importDeviceBO; - try { - importDeviceBO = importDeviceService.importDevice(entityBO, pointBOList, driverAttributeBOList, - pointAttributeBOList, sheet, i); - log.info("Import device succeeded, row index: {}", i + 1); - } - catch (Exception e) { - log.info("Skip import device, row index: {}, {}", i + 1, e.getMessage(), e); - continue; - } + Sheet sheet = workbook.getSheet(""); + for (int i = 4; i <= sheet.getLastRowNum(); i++) { + DeviceBO importDeviceBO; + try { + importDeviceBO = importDeviceService.importDevice(entityBO, pointBOList, driverAttributeBOList, + pointAttributeBOList, sheet, i); + log.info("Import device succeeded, row index: {}", i + 1); + } catch (Exception e) { + log.info("Skip import device, row index: {}, {}", i + 1, e.getMessage(), e); + continue; + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, importDeviceBO.getId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.ADD); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, importDeviceBO.getId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.ADD); + metadataEventPublisher.publishEvent(metadataEvent); + } - // - try { - FileUtils.delete(file); - } - catch (IOException e) { - log.error(e.getMessage(), e); - } - } + // + try { + FileUtils.delete(file); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } - @Override - public Path generateImportTemplate(DeviceBO entityBO) { - List driverAttributeBOList = driverAttributeService.selectByDriverId(entityBO.getDriverId()); - List pointAttributeBOList = pointAttributeService.selectByDriverId(entityBO.getDriverId()); - List pointBOList = pointService.selectByProfileIds(entityBO.getProfileIds()); + @Override + public Path generateImportTemplate(DeviceBO entityBO) { + List driverAttributeBOList = driverAttributeService.selectByDriverId(entityBO.getDriverId()); + List pointAttributeBOList = pointAttributeService.selectByDriverId(entityBO.getDriverId()); + List pointBOList = pointService.selectByProfileIds(entityBO.getProfileIds()); - Workbook workbook = new XSSFWorkbook(); - CellStyle cellStyle = PoiUtil.getCenterCellStyle(workbook); + Workbook workbook = new XSSFWorkbook(); + CellStyle cellStyle = PoiUtil.getCenterCellStyle(workbook); - // - Sheet mainSheet = workbook.createSheet(""); - mainSheet.setDefaultColumnWidth(25); + // + Sheet mainSheet = workbook.createSheet(""); + mainSheet.setDefaultColumnWidth(25); - // - configConfigSheet(driverAttributeBOList, pointAttributeBOList, pointBOList, workbook); + // + configConfigSheet(driverAttributeBOList, pointAttributeBOList, pointBOList, workbook); - // - Row remarkRow = mainSheet.createRow(0); - PoiUtil.createCell(remarkRow, 0, ": 5"); - PoiUtil.mergedRegion(mainSheet, 0, 0, 0, - 2 + driverAttributeBOList.size() + pointAttributeBOList.size() * pointBOList.size() - 1); + // + Row remarkRow = mainSheet.createRow(0); + PoiUtil.createCell(remarkRow, 0, ": 5"); + PoiUtil.mergedRegion(mainSheet, 0, 0, 0, + 2 + driverAttributeBOList.size() + pointAttributeBOList.size() * pointBOList.size() - 1); - // - Row titleRow = mainSheet.createRow(1); - PoiUtil.createCellWithStyle(titleRow, 0, "Device Name", cellStyle); - PoiUtil.createCellWithStyle(titleRow, 1, "Description", cellStyle); - PoiUtil.mergedRegion(mainSheet, 1, 3, 0, 0); - PoiUtil.mergedRegion(mainSheet, 1, 3, 1, 1); + // + Row titleRow = mainSheet.createRow(1); + PoiUtil.createCellWithStyle(titleRow, 0, "Device Name", cellStyle); + PoiUtil.createCellWithStyle(titleRow, 1, "Description", cellStyle); + PoiUtil.mergedRegion(mainSheet, 1, 3, 0, 0); + PoiUtil.mergedRegion(mainSheet, 1, 3, 1, 1); - Row attributeRow = mainSheet.createRow(3); - // - configAttributeCell(driverAttributeBOList, mainSheet, titleRow, attributeRow, cellStyle); - // - configPointCell(driverAttributeBOList, pointAttributeBOList, pointBOList, mainSheet, titleRow, attributeRow, - cellStyle); + Row attributeRow = mainSheet.createRow(3); + // + configAttributeCell(driverAttributeBOList, mainSheet, titleRow, attributeRow, cellStyle); + // + configPointCell(driverAttributeBOList, pointAttributeBOList, pointBOList, mainSheet, titleRow, attributeRow, + cellStyle); - // - return generateTemplate(workbook); - } + // + return generateTemplate(workbook); + } - /** - * @param workbook Workbook - * @param driverAttributeBOList Array - * @param pointAttributeBOList Array - * @param pointBOList Point - */ - private boolean configIsEqual(Workbook workbook, List driverAttributeBOList, - List pointAttributeBOList, List pointBOList) { - Sheet configSheet = workbook.getSheet("()"); - String driverAttributesValueNew = JsonUtil.toJsonString(driverAttributeBOList); - String driverAttributesValueOld = PoiUtil.getCellStringValue(configSheet, 0, 0); - if (!driverAttributesValueNew.equals(driverAttributesValueOld)) { - return false; - } + /** + * @param workbook Workbook + * @param driverAttributeBOList Array + * @param pointAttributeBOList Array + * @param pointBOList Point + */ + private boolean configIsEqual(Workbook workbook, List driverAttributeBOList, + List pointAttributeBOList, List pointBOList) { + Sheet configSheet = workbook.getSheet("()"); + String driverAttributesValueNew = JsonUtil.toJsonString(driverAttributeBOList); + String driverAttributesValueOld = PoiUtil.getCellStringValue(configSheet, 0, 0); + if (!driverAttributesValueNew.equals(driverAttributesValueOld)) { + return false; + } - String newPointAttributesValue = JsonUtil.toJsonString(pointAttributeBOList); - String oldPointAttributesValue = PoiUtil.getCellStringValue(configSheet, 1, 0); - if (!newPointAttributesValue.equals(oldPointAttributesValue)) { - return false; - } + String newPointAttributesValue = JsonUtil.toJsonString(pointAttributeBOList); + String oldPointAttributesValue = PoiUtil.getCellStringValue(configSheet, 1, 0); + if (!newPointAttributesValue.equals(oldPointAttributesValue)) { + return false; + } - String pointsValueNew = JsonUtil.toJsonString(pointBOList); - String pointsValueOld = PoiUtil.getCellStringValue(configSheet, 2, 0); + String pointsValueNew = JsonUtil.toJsonString(pointBOList); + String pointsValueOld = PoiUtil.getCellStringValue(configSheet, 2, 0); - return pointsValueNew.equals(pointsValueOld); - } + return pointsValueNew.equals(pointsValueOld); + } - /** - * @param driverAttributeBOList Array - * @param mainSheet Main Sheet - * @param titleRow Title Row - * @param attributeRow Attribute Row - */ - private void configAttributeCell(List driverAttributeBOList, Sheet mainSheet, Row titleRow, - Row attributeRow, CellStyle cellStyle) { - if (driverAttributeBOList.isEmpty()) { - return; - } + /** + * @param driverAttributeBOList Array + * @param mainSheet Main Sheet + * @param titleRow Title Row + * @param attributeRow Attribute Row + */ + private void configAttributeCell(List driverAttributeBOList, Sheet mainSheet, Row titleRow, + Row attributeRow, CellStyle cellStyle) { + if (driverAttributeBOList.isEmpty()) { + return; + } - PoiUtil.createCellWithStyle(titleRow, 2, "", cellStyle); - PoiUtil.mergedRegion(mainSheet, 1, 2, 2, 2 + driverAttributeBOList.size() - 1); - for (int i = 0; i < driverAttributeBOList.size(); i++) { - PoiUtil.createCellWithStyle(attributeRow, 2 + i, driverAttributeBOList.get(i).getAttributeName(), - cellStyle); - } + PoiUtil.createCellWithStyle(titleRow, 2, "", cellStyle); + PoiUtil.mergedRegion(mainSheet, 1, 2, 2, 2 + driverAttributeBOList.size() - 1); + for (int i = 0; i < driverAttributeBOList.size(); i++) { + PoiUtil.createCellWithStyle(attributeRow, 2 + i, driverAttributeBOList.get(i).getAttributeName(), + cellStyle); + } - } + } - /** - * @param driverAttributeBOList Array - * @param pointAttributeBOList Array - * @param pointBOList Point Array - * @param workbook Workbook - */ - private void configConfigSheet(List driverAttributeBOList, - List pointAttributeBOList, List pointBOList, Workbook workbook) { - Sheet configSheet = workbook.createSheet("()"); - Row driverAttributesRow = configSheet.createRow(0); - Row pointAttributesRow = configSheet.createRow(1); - Row pointsRow = configSheet.createRow(2); - PoiUtil.createCell(driverAttributesRow, 0, JsonUtil.toJsonString(driverAttributeBOList)); - PoiUtil.createCell(pointAttributesRow, 0, JsonUtil.toJsonString(pointAttributeBOList)); - PoiUtil.createCell(pointsRow, 0, JsonUtil.toJsonString(pointBOList)); - } + /** + * @param driverAttributeBOList Array + * @param pointAttributeBOList Array + * @param pointBOList Point Array + * @param workbook Workbook + */ + private void configConfigSheet(List driverAttributeBOList, + List pointAttributeBOList, List pointBOList, Workbook workbook) { + Sheet configSheet = workbook.createSheet("()"); + Row driverAttributesRow = configSheet.createRow(0); + Row pointAttributesRow = configSheet.createRow(1); + Row pointsRow = configSheet.createRow(2); + PoiUtil.createCell(driverAttributesRow, 0, JsonUtil.toJsonString(driverAttributeBOList)); + PoiUtil.createCell(pointAttributesRow, 0, JsonUtil.toJsonString(pointAttributeBOList)); + PoiUtil.createCell(pointsRow, 0, JsonUtil.toJsonString(pointBOList)); + } - /** - * @param driverAttributeBOList Array - * @param pointAttributeBOList Array - * @param pointBOList Point Array - * @param mainSheet Main Sheet - * @param titleRow Title Row - * @param attributeRow Attribute Row - * @param cellStyle CellStyle - */ - private void configPointCell(List driverAttributeBOList, - List pointAttributeBOList, List pointBOList, Sheet mainSheet, Row titleRow, - Row attributeRow, CellStyle cellStyle) { - if (pointAttributeBOList.isEmpty()) { - return; - } + /** + * @param driverAttributeBOList Array + * @param pointAttributeBOList Array + * @param pointBOList Point Array + * @param mainSheet Main Sheet + * @param titleRow Title Row + * @param attributeRow Attribute Row + * @param cellStyle CellStyle + */ + private void configPointCell(List driverAttributeBOList, + List pointAttributeBOList, List pointBOList, Sheet mainSheet, Row titleRow, + Row attributeRow, CellStyle cellStyle) { + if (pointAttributeBOList.isEmpty()) { + return; + } - Row pointRow = mainSheet.createRow(2); - PoiUtil.createCellWithStyle(titleRow, 2 + driverAttributeBOList.size(), "", cellStyle); - PoiUtil.mergedRegion(mainSheet, 1, 1, 2 + driverAttributeBOList.size(), - 2 + driverAttributeBOList.size() + pointAttributeBOList.size() * pointBOList.size() - 1); - for (int i = 0; i < pointBOList.size(); i++) { - PoiUtil.createCellWithStyle(pointRow, 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size(), - pointBOList.get(i).getPointName(), cellStyle); - PoiUtil.mergedRegion(mainSheet, 2, 2, 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size(), 2 - + driverAttributeBOList.size() + i * pointAttributeBOList.size() + pointAttributeBOList.size() - 1); - for (int j = 0; j < pointAttributeBOList.size(); j++) { - PoiUtil.createCellWithStyle(attributeRow, - 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size() + j, - pointAttributeBOList.get(j).getAttributeName(), cellStyle); - } - } - } + Row pointRow = mainSheet.createRow(2); + PoiUtil.createCellWithStyle(titleRow, 2 + driverAttributeBOList.size(), "", cellStyle); + PoiUtil.mergedRegion(mainSheet, 1, 1, 2 + driverAttributeBOList.size(), + 2 + driverAttributeBOList.size() + pointAttributeBOList.size() * pointBOList.size() - 1); + for (int i = 0; i < pointBOList.size(); i++) { + PoiUtil.createCellWithStyle(pointRow, 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size(), + pointBOList.get(i).getPointName(), cellStyle); + PoiUtil.mergedRegion(mainSheet, 2, 2, 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size(), 2 + + driverAttributeBOList.size() + i * pointAttributeBOList.size() + pointAttributeBOList.size() - 1); + for (int j = 0; j < pointAttributeBOList.size(); j++) { + PoiUtil.createCellWithStyle(attributeRow, + 2 + driverAttributeBOList.size() + i * pointAttributeBOList.size() + j, + pointAttributeBOList.get(j).getAttributeName(), cellStyle); + } + } + } - /** - * @param workbook Workbook - * @return Path - */ - private Path generateTemplate(Workbook workbook) { - Path path; - try { - PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); - org.springframework.core.io.Resource resource = resolver.getResource("classpath:/"); - Path resourcePath = Paths.get(resource.getURI()); - String fileName = MessageFormat.format("dc3_device_import_template_{0}.xlsx", System.currentTimeMillis()); - path = resourcePath.resolve(fileName); - FileOutputStream outputStream = new FileOutputStream(path.toUri().getPath()); - workbook.write(outputStream); - workbook.close(); - outputStream.close(); - } - catch (IOException e) { - throw new ServiceException("Generate template error: {}", e.getMessage()); - } - return path; - } + /** + * @param workbook Workbook + * @return Path + */ + private Path generateTemplate(Workbook workbook) { + Path path; + try { + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + org.springframework.core.io.Resource resource = resolver.getResource("classpath:/"); + Path resourcePath = Paths.get(resource.getURI()); + String fileName = MessageFormat.format("dc3_device_import_template_{0}.xlsx", System.currentTimeMillis()); + path = resourcePath.resolve(fileName); + FileOutputStream outputStream = new FileOutputStream(path.toUri().getPath()); + workbook.write(outputStream); + workbook.close(); + outputStream.close(); + } catch (IOException e) { + throw new ServiceException("Generate template error: {}", e.getMessage()); + } + return path; + } - private void addProfileBind(DeviceDO entityDO, List profileIds) { - if (CollectionUtils.isEmpty(profileIds)) { - return; - } + private void addProfileBind(DeviceDO entityDO, List profileIds) { + if (CollectionUtils.isEmpty(profileIds)) { + return; + } - profileIds.forEach(profileId -> { - try { - ProfileBindBO entityBO = new ProfileBindBO(); - entityBO.setProfileId(profileId); - entityBO.setDeviceId(entityDO.getId()); - entityBO.setTenantId(entityDO.getTenantId()); - profileBindService.save(entityBO); - } - catch (Exception ignored) { - // nothing to do - } - }); + profileIds.forEach(profileId -> { + try { + ProfileBindBO entityBO = new ProfileBindBO(); + entityBO.setProfileId(profileId); + entityBO.setDeviceId(entityDO.getId()); + entityBO.setTenantId(entityDO.getTenantId()); + profileBindService.save(entityBO); + } catch (Exception ignored) { + // nothing to do + } + }); - } + } - /** - * @param id Device ID - * @return - */ - private boolean checkExist(Long id) { - DeviceDO entityDO = deviceManager.getById(id); - return Objects.nonNull(entityDO); - } + /** + * @param id Device ID + * @return + */ + private boolean checkExist(Long id) { + DeviceDO entityDO = deviceManager.getById(id); + return Objects.nonNull(entityDO); + } - /** - * @param entityQuery {@link DeviceQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(DeviceQuery entityQuery) { - QueryWrapper wrapper = Wrappers.query(); - wrapper.eq("dd.deleted", 0); - if (Objects.nonNull(entityQuery)) { - wrapper.like(StringUtils.isNotEmpty(entityQuery.getDeviceName()), "dd.device_name", - entityQuery.getDeviceName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getDeviceCode()), "dd.device_code", - entityQuery.getDeviceCode()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), "dd.driver_id", entityQuery.getDriverId()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dd.enable_flag", entityQuery.getEnableFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dd.tenant_id", entityQuery.getTenantId()); - } - return wrapper.lambda(); - } + /** + * @param entityQuery {@link DeviceQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(DeviceQuery entityQuery) { + QueryWrapper wrapper = Wrappers.query(); + wrapper.eq("dd.deleted", 0); + if (Objects.nonNull(entityQuery)) { + wrapper.like(StringUtils.isNotEmpty(entityQuery.getDeviceName()), "dd.device_name", + entityQuery.getDeviceName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getDeviceCode()), "dd.device_code", + entityQuery.getDeviceCode()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), "dd.driver_id", entityQuery.getDriverId()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dd.enable_flag", entityQuery.getEnableFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dd.tenant_id", entityQuery.getTenantId()); + } + return wrapper.lambda(); + } - /** - * @param entityBO {@link DeviceBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(DeviceBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DeviceDO::getDeviceName, entityBO.getDeviceName()); - wrapper.eq(StringUtils.isNotEmpty(entityBO.getDeviceCode()), DeviceDO::getDeviceCode, entityBO.getDeviceCode()); - wrapper.eq(DeviceDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DeviceDO one = deviceManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link DeviceBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(DeviceBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DeviceDO::getDeviceName, entityBO.getDeviceName()); + wrapper.eq(StringUtils.isNotEmpty(entityBO.getDeviceCode()), DeviceDO::getDeviceCode, entityBO.getDeviceCode()); + wrapper.eq(DeviceDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DeviceDO one = deviceManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link DeviceDO} - */ - private DeviceDO getDOById(Long id, boolean throwException) { - DeviceDO entityDO = deviceManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Device does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link DeviceDO} + */ + private DeviceDO getDOById(Long id, boolean throwException) { + DeviceDO entityDO = deviceManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Device does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeConfigServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeConfigServiceImpl.java index 2fd6fbd1d..db9635da9 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeConfigServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeConfigServiceImpl.java @@ -54,170 +54,171 @@ import java.util.Objects; @Service public class DriverAttributeConfigServiceImpl implements DriverAttributeConfigService { - @Resource - private DriverAttributeConfigBuilder driverAttributeConfigBuilder; + @Resource + private DriverAttributeConfigBuilder driverAttributeConfigBuilder; - @Resource - private DriverAttributeConfigManager driverAttributeConfigManager; + @Resource + private DriverAttributeConfigManager driverAttributeConfigManager; - @Resource - private MetadataEventPublisher metadataEventPublisher; + @Resource + private MetadataEventPublisher metadataEventPublisher; - @Override - public void save(DriverAttributeConfigBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException( - "Failed to create driver attribute config: driver attribute config has been duplicated"); - } + @Override + public void save(DriverAttributeConfigBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException( + "Failed to create driver attribute config: driver attribute config has been duplicated"); + } - DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); - if (!driverAttributeConfigManager.save(entityDO)) { - throw new AddException("Failed to create driver attribute config"); - } + DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); + if (!driverAttributeConfigManager.save(entityDO)) { + throw new AddException("Failed to create driver attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public DriverAttributeConfigBO innerSave(DriverAttributeConfigBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException( - "Failed to create driver attribute config: driver attribute config has been duplicated"); - } + @Override + public DriverAttributeConfigBO innerSave(DriverAttributeConfigBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException( + "Failed to create driver attribute config: driver attribute config has been duplicated"); + } - DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); - if (!driverAttributeConfigManager.save(entityDO)) { - throw new AddException("Failed to create driver attribute config"); - } + DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); + if (!driverAttributeConfigManager.save(entityDO)) { + throw new AddException("Failed to create driver attribute config"); + } - return driverAttributeConfigBuilder.buildBOByDO(entityDO); - } + return driverAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public void remove(Long id) { - DriverAttributeConfigDO entityDO = getDOById(id, true); + @Override + public void remove(Long id) { + DriverAttributeConfigDO entityDO = getDOById(id, true); - if (!driverAttributeConfigManager.removeById(id)) { - throw new DeleteException("Failed to remove driver attribute config"); - } + if (!driverAttributeConfigManager.removeById(id)) { + throw new DeleteException("Failed to remove driver attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public void update(DriverAttributeConfigBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(DriverAttributeConfigBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException( - "Failed to update driver attribute config: driver attribute config has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException( + "Failed to update driver attribute config: driver attribute config has been duplicated"); + } - DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); - entityBO.setOperateTime(null); - if (!driverAttributeConfigManager.updateById(entityDO)) { - throw new UpdateException("Failed to update driver attribute config"); - } + DriverAttributeConfigDO entityDO = driverAttributeConfigBuilder.buildDOByBO(entityBO); + entityBO.setOperateTime(null); + if (!driverAttributeConfigManager.updateById(entityDO)) { + throw new UpdateException("Failed to update driver attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public DriverAttributeConfigBO selectById(Long id) { - DriverAttributeConfigDO entityDO = getDOById(id, true); - return driverAttributeConfigBuilder.buildBOByDO(entityDO); - } + @Override + public DriverAttributeConfigBO selectById(Long id) { + DriverAttributeConfigDO entityDO = getDOById(id, true); + return driverAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public DriverAttributeConfigBO selectByAttributeIdAndDeviceId(Long deviceId, Long attributeId) { - LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() - .eq(DriverAttributeConfigDO::getAttributeId, attributeId) - .eq(DriverAttributeConfigDO::getDeviceId, deviceId) - .last(QueryWrapperConstant.LIMIT_ONE); - DriverAttributeConfigDO entityDO = wrapper.one(); - return driverAttributeConfigBuilder.buildBOByDO(entityDO); - } + @Override + public DriverAttributeConfigBO selectByAttributeIdAndDeviceId(Long deviceId, Long attributeId) { + LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() + .eq(DriverAttributeConfigDO::getAttributeId, attributeId) + .eq(DriverAttributeConfigDO::getDeviceId, deviceId) + .last(QueryWrapperConstant.LIMIT_ONE); + DriverAttributeConfigDO entityDO = wrapper.one(); + return driverAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByAttributeId(Long attributeId) { - LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() - .eq(DriverAttributeConfigDO::getAttributeId, attributeId); - List entityDO = wrapper.list(); - return driverAttributeConfigBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByAttributeId(Long attributeId) { + LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() + .eq(DriverAttributeConfigDO::getAttributeId, attributeId); + List entityDO = wrapper.list(); + return driverAttributeConfigBuilder.buildBOListByDOList(entityDO); + } - @Override - public List selectByDeviceId(Long deviceId) { - LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() - .eq(DriverAttributeConfigDO::getDeviceId, deviceId); - List entityDO = wrapper.list(); - return driverAttributeConfigBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByDeviceId(Long deviceId) { + LambdaQueryChainWrapper wrapper = driverAttributeConfigManager.lambdaQuery() + .eq(DriverAttributeConfigDO::getDeviceId, deviceId); + List entityDO = wrapper.list(); + return driverAttributeConfigBuilder.buildBOListByDOList(entityDO); + } - @Override - public Page selectByPage(DriverAttributeConfigQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = driverAttributeConfigManager - .page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return driverAttributeConfigBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(DriverAttributeConfigQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = driverAttributeConfigManager + .page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return driverAttributeConfigBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link DriverAttributeConfigQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(DriverAttributeConfigQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getAttributeId()), DriverAttributeConfigDO::getAttributeId, - entityQuery.getAttributeId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), DriverAttributeConfigDO::getDeviceId, - entityQuery.getDeviceId()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverAttributeConfigDO::getTenantId, - entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link DriverAttributeConfigQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(DriverAttributeConfigQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getAttributeId()), DriverAttributeConfigDO::getAttributeId, + entityQuery.getAttributeId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), DriverAttributeConfigDO::getDeviceId, + entityQuery.getDeviceId()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverAttributeConfigDO::getTenantId, + entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link DriverAttributeConfigBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(DriverAttributeConfigBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DriverAttributeConfigDO::getAttributeId, entityBO.getAttributeId()); - wrapper.eq(DriverAttributeConfigDO::getDeviceId, entityBO.getDeviceId()); - wrapper.eq(DriverAttributeConfigDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DriverAttributeConfigDO one = driverAttributeConfigManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link DriverAttributeConfigBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(DriverAttributeConfigBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DriverAttributeConfigDO::getAttributeId, entityBO.getAttributeId()); + wrapper.eq(DriverAttributeConfigDO::getDeviceId, entityBO.getDeviceId()); + wrapper.eq(DriverAttributeConfigDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DriverAttributeConfigDO one = driverAttributeConfigManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link DriverAttributeConfigDO} - */ - private DriverAttributeConfigDO getDOById(Long id, boolean throwException) { - DriverAttributeConfigDO entityDO = driverAttributeConfigManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Driver attribute does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link DriverAttributeConfigDO} + */ + private DriverAttributeConfigDO getDOById(Long id, boolean throwException) { + DriverAttributeConfigDO entityDO = driverAttributeConfigManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Driver attribute does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeServiceImpl.java index a8b1a6495..21c61a162 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverAttributeServiceImpl.java @@ -51,131 +51,132 @@ import java.util.Objects; @Service public class DriverAttributeServiceImpl implements DriverAttributeService { - @Resource - private DriverAttributeBuilder driverAttributeBuilder; + @Resource + private DriverAttributeBuilder driverAttributeBuilder; - @Resource - private DriverAttributeManager driverAttributeManager; + @Resource + private DriverAttributeManager driverAttributeManager; - @Override - public void save(DriverAttributeBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException("Failed to create driver attribute: driver attribute has been duplicated"); - } + @Override + public void save(DriverAttributeBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException("Failed to create driver attribute: driver attribute has been duplicated"); + } - DriverAttributeDO entityDO = driverAttributeBuilder.buildDOByBO(entityBO); - if (!driverAttributeManager.save(entityDO)) { - throw new AddException("Failed to create driver attribute"); - } - } + DriverAttributeDO entityDO = driverAttributeBuilder.buildDOByBO(entityBO); + if (!driverAttributeManager.save(entityDO)) { + throw new AddException("Failed to create driver attribute"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!driverAttributeManager.removeById(id)) { - throw new DeleteException("Failed to remove driver attribute"); - } - } + if (!driverAttributeManager.removeById(id)) { + throw new DeleteException("Failed to remove driver attribute"); + } + } - @Override - public void update(DriverAttributeBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(DriverAttributeBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException("Failed to update driver attribute: driver attribute has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException("Failed to update driver attribute: driver attribute has been duplicated"); + } - DriverAttributeDO entityDO = driverAttributeBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!driverAttributeManager.updateById(entityDO)) { - throw new UpdateException("Failed to update driver attribute"); - } - } + DriverAttributeDO entityDO = driverAttributeBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!driverAttributeManager.updateById(entityDO)) { + throw new UpdateException("Failed to update driver attribute"); + } + } - @Override - public DriverAttributeBO selectById(Long id) { - DriverAttributeDO entityDO = getDOById(id, true); - return driverAttributeBuilder.buildBOByDO(entityDO); - } + @Override + public DriverAttributeBO selectById(Long id) { + DriverAttributeDO entityDO = getDOById(id, true); + return driverAttributeBuilder.buildBOByDO(entityDO); + } - @Override - public DriverAttributeBO selectByNameAndDriverId(String name, Long driverId) { - LambdaQueryChainWrapper wrapper = driverAttributeManager.lambdaQuery() - .eq(DriverAttributeDO::getAttributeCode, name) - .eq(DriverAttributeDO::getDriverId, driverId) - .last(QueryWrapperConstant.LIMIT_ONE); - DriverAttributeDO entityDO = wrapper.one(); - return driverAttributeBuilder.buildBOByDO(entityDO); - } + @Override + public DriverAttributeBO selectByNameAndDriverId(String name, Long driverId) { + LambdaQueryChainWrapper wrapper = driverAttributeManager.lambdaQuery() + .eq(DriverAttributeDO::getAttributeCode, name) + .eq(DriverAttributeDO::getDriverId, driverId) + .last(QueryWrapperConstant.LIMIT_ONE); + DriverAttributeDO entityDO = wrapper.one(); + return driverAttributeBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByDriverId(Long driverId) { - LambdaQueryChainWrapper wrapper = driverAttributeManager.lambdaQuery() - .eq(DriverAttributeDO::getDriverId, driverId); - List entityDO = wrapper.list(); - return driverAttributeBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByDriverId(Long driverId) { + LambdaQueryChainWrapper wrapper = driverAttributeManager.lambdaQuery() + .eq(DriverAttributeDO::getDriverId, driverId); + List entityDO = wrapper.list(); + return driverAttributeBuilder.buildBOListByDOList(entityDO); + } - @Override - public Page selectByPage(DriverAttributeQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = driverAttributeManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return driverAttributeBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(DriverAttributeQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = driverAttributeManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return driverAttributeBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link DriverAttributeQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(DriverAttributeQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeCode()), DriverAttributeDO::getAttributeCode, - entityQuery.getAttributeCode()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeName()), DriverAttributeDO::getAttributeName, - entityQuery.getAttributeName()); - wrapper.eq(Objects.nonNull(entityQuery.getAttributeTypeFlag()), DriverAttributeDO::getAttributeTypeFlag, - entityQuery.getAttributeTypeFlag()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), DriverAttributeDO::getDriverId, - entityQuery.getDriverId()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverAttributeDO::getTenantId, - entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link DriverAttributeQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(DriverAttributeQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeCode()), DriverAttributeDO::getAttributeCode, + entityQuery.getAttributeCode()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeName()), DriverAttributeDO::getAttributeName, + entityQuery.getAttributeName()); + wrapper.eq(Objects.nonNull(entityQuery.getAttributeTypeFlag()), DriverAttributeDO::getAttributeTypeFlag, + entityQuery.getAttributeTypeFlag()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), DriverAttributeDO::getDriverId, + entityQuery.getDriverId()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverAttributeDO::getTenantId, + entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link DriverAttributeBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(DriverAttributeBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DriverAttributeDO::getAttributeCode, entityBO.getAttributeCode()); - wrapper.eq(DriverAttributeDO::getDriverId, entityBO.getDriverId()); - wrapper.eq(DriverAttributeDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DriverAttributeDO one = driverAttributeManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link DriverAttributeBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(DriverAttributeBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DriverAttributeDO::getAttributeCode, entityBO.getAttributeCode()); + wrapper.eq(DriverAttributeDO::getDriverId, entityBO.getDriverId()); + wrapper.eq(DriverAttributeDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DriverAttributeDO one = driverAttributeManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link DriverAttributeDO} - */ - private DriverAttributeDO getDOById(Long id, boolean throwException) { - DriverAttributeDO entityDO = driverAttributeManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Driver attribute does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link DriverAttributeDO} + */ + private DriverAttributeDO getDOById(Long id, boolean throwException) { + DriverAttributeDO entityDO = driverAttributeManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Driver attribute does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverServiceImpl.java index 4579dcf7b..592fb2ede 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/DriverServiceImpl.java @@ -59,172 +59,173 @@ import java.util.stream.Collectors; @Service public class DriverServiceImpl implements DriverService { - @Resource - private DriverBuilder driverBuilder; + @Resource + private DriverBuilder driverBuilder; - @Resource - private DriverManager driverManager; + @Resource + private DriverManager driverManager; - @Resource - private DeviceManager deviceManager; + @Resource + private DeviceManager deviceManager; - @Resource - private PointManager pointManager; + @Resource + private PointManager pointManager; - @Resource - private ProfileBindService profileBindService; + @Resource + private ProfileBindService profileBindService; - @Override - public void save(DriverBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(DriverBO entityBO) { + checkDuplicate(entityBO, false, true); - DriverDO entityDO = driverBuilder.buildDOByBO(entityBO); - if (!driverManager.save(entityDO)) { - throw new AddException("Failed to create driver"); - } - } + DriverDO entityDO = driverBuilder.buildDOByBO(entityBO); + if (!driverManager.save(entityDO)) { + throw new AddException("Failed to create driver"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!driverManager.removeById(id)) { - throw new DeleteException("Failed to remove driver"); - } - } + if (!driverManager.removeById(id)) { + throw new DeleteException("Failed to remove driver"); + } + } - @Override - public void update(DriverBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(DriverBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - DriverDO entityDO = driverBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!driverManager.updateById(entityDO)) { - throw new UpdateException("Failed to update point attribute config"); - } - } + DriverDO entityDO = driverBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!driverManager.updateById(entityDO)) { + throw new UpdateException("Failed to update point attribute config"); + } + } - @Override - public DriverBO selectById(Long id) { - DriverDO entityDO = getDOById(id, true); - return driverBuilder.buildBOByDO(entityDO); - } + @Override + public DriverBO selectById(Long id) { + DriverDO entityDO = getDOById(id, true); + return driverBuilder.buildBOByDO(entityDO); + } - @Override - public Page selectByPage(DriverQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = driverManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return driverBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(DriverQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = driverManager.page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return driverBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public List selectByIds(Set ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyList(); - } - List entityDOList = driverManager.listByIds(ids); - return driverBuilder.buildBOListByDOList(entityDOList); - } + @Override + public List selectByIds(Set ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyList(); + } + List entityDOList = driverManager.listByIds(ids); + return driverBuilder.buildBOListByDOList(entityDOList); + } - @Override - public DriverBO selectByServiceName(String serviceName, Long tenantId) { - LambdaQueryChainWrapper wrapper = driverManager.lambdaQuery() - .eq(DriverDO::getServiceName, serviceName) - .eq(DriverDO::getTenantId, tenantId) - .last(QueryWrapperConstant.LIMIT_ONE); - DriverDO entityDO = wrapper.one(); - return driverBuilder.buildBOByDO(entityDO); - } + @Override + public DriverBO selectByServiceName(String serviceName, Long tenantId) { + LambdaQueryChainWrapper wrapper = driverManager.lambdaQuery() + .eq(DriverDO::getServiceName, serviceName) + .eq(DriverDO::getTenantId, tenantId) + .last(QueryWrapperConstant.LIMIT_ONE); + DriverDO entityDO = wrapper.one(); + return driverBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByProfileId(Long profileId) { - List ids = profileBindService.selectDeviceIdsByProfileId(profileId); - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyList(); - } + @Override + public List selectByProfileId(Long profileId) { + List ids = profileBindService.selectDeviceIdsByProfileId(profileId); + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyList(); + } - List deviceDOList = deviceManager.listByIds(ids); - Set driverIds = deviceDOList.stream().map(DeviceDO::getDriverId).collect(Collectors.toSet()); - List entityDOList = selectByIds(driverIds); - if (CollectionUtils.isEmpty(entityDOList)) { - return Collections.emptyList(); - } + List deviceDOList = deviceManager.listByIds(ids); + Set driverIds = deviceDOList.stream().map(DeviceDO::getDriverId).collect(Collectors.toSet()); + List entityDOList = selectByIds(driverIds); + if (CollectionUtils.isEmpty(entityDOList)) { + return Collections.emptyList(); + } - return entityDOList; - } + return entityDOList; + } - @Override - public List selectByPointId(Long pointId) { - PointDO entityDO = pointManager.getById(pointId); - return selectByProfileId(entityDO.getProfileId()); - } + @Override + public List selectByPointId(Long pointId) { + PointDO entityDO = pointManager.getById(pointId); + return selectByProfileId(entityDO.getProfileId()); + } - @Override - public DriverBO selectByDeviceId(Long deviceId) { - DeviceDO entityDO = deviceManager.getById(deviceId); - return selectById(entityDO.getDriverId()); - } + @Override + public DriverBO selectByDeviceId(Long deviceId) { + DeviceDO entityDO = deviceManager.getById(deviceId); + return selectById(entityDO.getDriverId()); + } - /** - * @param entityQuery {@link DriverQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(DriverQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getDriverName()), DriverDO::getDriverName, - entityQuery.getDriverName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getDriverCode()), DriverDO::getDriverCode, - entityQuery.getDriverCode()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceName()), DriverDO::getServiceName, - entityQuery.getServiceName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceHost()), DriverDO::getServiceHost, - entityQuery.getServiceHost()); - wrapper.eq(Objects.nonNull(entityQuery.getDriverTypeFlag()), DriverDO::getDriverTypeFlag, - entityQuery.getDriverTypeFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), DriverDO::getEnableFlag, entityQuery.getEnableFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link DriverQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(DriverQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getDriverName()), DriverDO::getDriverName, + entityQuery.getDriverName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getDriverCode()), DriverDO::getDriverCode, + entityQuery.getDriverCode()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceName()), DriverDO::getServiceName, + entityQuery.getServiceName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getServiceHost()), DriverDO::getServiceHost, + entityQuery.getServiceHost()); + wrapper.eq(Objects.nonNull(entityQuery.getDriverTypeFlag()), DriverDO::getDriverTypeFlag, + entityQuery.getDriverTypeFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), DriverDO::getEnableFlag, entityQuery.getEnableFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), DriverDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link DriverBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(DriverBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(DriverDO::getDriverName, entityBO.getDriverName()); - wrapper.eq(DriverDO::getDriverCode, entityBO.getDriverCode()); - wrapper.eq(DriverDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - DriverDO one = driverManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Driver has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link DriverBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(DriverBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(DriverDO::getDriverName, entityBO.getDriverName()); + wrapper.eq(DriverDO::getDriverCode, entityBO.getDriverCode()); + wrapper.eq(DriverDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + DriverDO one = driverManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Driver has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link DriverDO} - */ - private DriverDO getDOById(Long id, boolean throwException) { - DriverDO entityDO = driverManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Driver does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link DriverDO} + */ + private DriverDO getDOById(Long id, boolean throwException) { + DriverDO entityDO = driverManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Driver does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeConfigServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeConfigServiceImpl.java index eebeaaa57..7335e1b2f 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeConfigServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeConfigServiceImpl.java @@ -60,193 +60,194 @@ import java.util.stream.Collectors; @Service public class PointAttributeConfigServiceImpl implements PointAttributeConfigService { - @Resource - private PointAttributeConfigBuilder pointAttributeConfigBuilder; + @Resource + private PointAttributeConfigBuilder pointAttributeConfigBuilder; - @Resource - private PointAttributeConfigManager pointAttributeConfigManager; + @Resource + private PointAttributeConfigManager pointAttributeConfigManager; - @Resource - private MetadataEventPublisher metadataEventPublisher; + @Resource + private MetadataEventPublisher metadataEventPublisher; - @Resource - private PointService pointService; + @Resource + private PointService pointService; - @Override - public void save(PointAttributeConfigBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException( - "Failed to create point attribute config: point attribute config has been duplicated"); - } + @Override + public void save(PointAttributeConfigBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException( + "Failed to create point attribute config: point attribute config has been duplicated"); + } - PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); - if (!pointAttributeConfigManager.save(entityDO)) { - throw new AddException("Failed to create point attribute config"); - } + PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); + if (!pointAttributeConfigManager.save(entityDO)) { + throw new AddException("Failed to create point attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public PointAttributeConfigBO innerSave(PointAttributeConfigBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException( - "Failed to create point attribute config: point attribute config has been duplicated"); - } + @Override + public PointAttributeConfigBO innerSave(PointAttributeConfigBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException( + "Failed to create point attribute config: point attribute config has been duplicated"); + } - PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); - if (!pointAttributeConfigManager.save(entityDO)) { - throw new AddException("Failed to create point attribute config"); - } + PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); + if (!pointAttributeConfigManager.save(entityDO)) { + throw new AddException("Failed to create point attribute config"); + } - return pointAttributeConfigBuilder.buildBOByDO(entityDO); - } + return pointAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public void remove(Long id) { - PointAttributeConfigDO entityDO = getDOById(id, true); + @Override + public void remove(Long id) { + PointAttributeConfigDO entityDO = getDOById(id, true); - if (!pointAttributeConfigManager.removeById(id)) { - throw new DeleteException("Failed to remove point attribute config"); - } + if (!pointAttributeConfigManager.removeById(id)) { + throw new DeleteException("Failed to remove point attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public void update(PointAttributeConfigBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(PointAttributeConfigBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException( - "Failed to update point attribute config: point attribute config has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException( + "Failed to update point attribute config: point attribute config has been duplicated"); + } - PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); - entityBO.setOperateTime(null); - if (!pointAttributeConfigManager.updateById(entityDO)) { - throw new UpdateException("Failed to update point attribute config"); - } + PointAttributeConfigDO entityDO = pointAttributeConfigBuilder.buildDOByBO(entityBO); + entityBO.setOperateTime(null); + if (!pointAttributeConfigManager.updateById(entityDO)) { + throw new UpdateException("Failed to update point attribute config"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getDeviceId(), MetadataTypeEnum.DEVICE, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public PointAttributeConfigBO selectById(Long id) { - PointAttributeConfigDO entityDO = getDOById(id, true); - return pointAttributeConfigBuilder.buildBOByDO(entityDO); - } + @Override + public PointAttributeConfigBO selectById(Long id) { + PointAttributeConfigDO entityDO = getDOById(id, true); + return pointAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public PointAttributeConfigBO selectByAttributeIdAndDeviceIdAndPointId(Long attributeId, Long deviceId, - Long pointId) { - LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() - .eq(PointAttributeConfigDO::getDeviceId, deviceId) - .eq(PointAttributeConfigDO::getPointId, pointId) - .last(QueryWrapperConstant.LIMIT_ONE); - PointAttributeConfigDO entityDO = wrapper.one(); - return pointAttributeConfigBuilder.buildBOByDO(entityDO); - } + @Override + public PointAttributeConfigBO selectByAttributeIdAndDeviceIdAndPointId(Long attributeId, Long deviceId, + Long pointId) { + LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() + .eq(PointAttributeConfigDO::getDeviceId, deviceId) + .eq(PointAttributeConfigDO::getPointId, pointId) + .last(QueryWrapperConstant.LIMIT_ONE); + PointAttributeConfigDO entityDO = wrapper.one(); + return pointAttributeConfigBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByAttributeId(Long attributeId) { - LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() - .eq(PointAttributeConfigDO::getAttributeId, attributeId); - List entityDO = wrapper.list(); - return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByAttributeId(Long attributeId) { + LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() + .eq(PointAttributeConfigDO::getAttributeId, attributeId); + List entityDO = wrapper.list(); + return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); + } - @Override - public List selectByDeviceId(Long deviceId) { - List pointBOList = pointService.selectByDeviceId(deviceId); - Set pointIds = pointBOList.stream().map(PointBO::getId).collect(Collectors.toSet()); - if (CollectionUtils.isEmpty(pointIds)) { - return Collections.emptyList(); - } + @Override + public List selectByDeviceId(Long deviceId) { + List pointBOList = pointService.selectByDeviceId(deviceId); + Set pointIds = pointBOList.stream().map(PointBO::getId).collect(Collectors.toSet()); + if (CollectionUtils.isEmpty(pointIds)) { + return Collections.emptyList(); + } - LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() - .eq(PointAttributeConfigDO::getDeviceId, deviceId) - .in(PointAttributeConfigDO::getPointId, pointIds); - List entityDO = wrapper.list(); - return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); - } + LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() + .eq(PointAttributeConfigDO::getDeviceId, deviceId) + .in(PointAttributeConfigDO::getPointId, pointIds); + List entityDO = wrapper.list(); + return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); + } - @Override - public List selectByDeviceIdAndPointId(Long deviceId, Long pointId) { - LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() - .eq(PointAttributeConfigDO::getDeviceId, deviceId) - .eq(PointAttributeConfigDO::getPointId, pointId); - List entityDO = wrapper.list(); - return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByDeviceIdAndPointId(Long deviceId, Long pointId) { + LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() + .eq(PointAttributeConfigDO::getDeviceId, deviceId) + .eq(PointAttributeConfigDO::getPointId, pointId); + List entityDO = wrapper.list(); + return pointAttributeConfigBuilder.buildBOListByDOList(entityDO); + } - @Override - public Page selectByPage(PointAttributeConfigQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = pointAttributeConfigManager - .page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); - return pointAttributeConfigBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(PointAttributeConfigQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = pointAttributeConfigManager + .page(PageUtil.page(entityQuery.getPage()), fuzzyQuery(entityQuery)); + return pointAttributeConfigBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link PointAttributeConfigQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(PointAttributeConfigQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getAttributeId()), PointAttributeConfigDO::getAttributeId, - entityQuery.getAttributeId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), PointAttributeConfigDO::getDeviceId, - entityQuery.getDeviceId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getPointId()), PointAttributeConfigDO::getPointId, - entityQuery.getPointId()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointAttributeConfigDO::getTenantId, - entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link PointAttributeConfigQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(PointAttributeConfigQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getAttributeId()), PointAttributeConfigDO::getAttributeId, + entityQuery.getAttributeId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), PointAttributeConfigDO::getDeviceId, + entityQuery.getDeviceId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getPointId()), PointAttributeConfigDO::getPointId, + entityQuery.getPointId()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointAttributeConfigDO::getTenantId, + entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link PointAttributeConfigBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(PointAttributeConfigBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointAttributeConfigDO::getAttributeId, entityBO.getAttributeId()); - wrapper.eq(PointAttributeConfigDO::getDeviceId, entityBO.getDeviceId()); - wrapper.eq(PointAttributeConfigDO::getPointId, entityBO.getPointId()); - wrapper.eq(PointAttributeConfigDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - PointAttributeConfigDO one = pointAttributeConfigManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link PointAttributeConfigBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(PointAttributeConfigBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointAttributeConfigDO::getAttributeId, entityBO.getAttributeId()); + wrapper.eq(PointAttributeConfigDO::getDeviceId, entityBO.getDeviceId()); + wrapper.eq(PointAttributeConfigDO::getPointId, entityBO.getPointId()); + wrapper.eq(PointAttributeConfigDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + PointAttributeConfigDO one = pointAttributeConfigManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link PointAttributeConfigDO} - */ - private PointAttributeConfigDO getDOById(Long id, boolean throwException) { - PointAttributeConfigDO entityDO = pointAttributeConfigManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Point attribute config does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link PointAttributeConfigDO} + */ + private PointAttributeConfigDO getDOById(Long id, boolean throwException) { + PointAttributeConfigDO entityDO = pointAttributeConfigManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Point attribute config does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeServiceImpl.java index ef1e65ee4..df087d6fc 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointAttributeServiceImpl.java @@ -51,132 +51,133 @@ import java.util.Objects; @Service public class PointAttributeServiceImpl implements PointAttributeService { - @Resource - private PointAttributeBuilder pointAttributeBuilder; + @Resource + private PointAttributeBuilder pointAttributeBuilder; - @Resource - private PointAttributeManager pointAttributeManager; + @Resource + private PointAttributeManager pointAttributeManager; - @Override - public void save(PointAttributeBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(PointAttributeBO entityBO) { + checkDuplicate(entityBO, false, true); - PointAttributeDO entityDO = pointAttributeBuilder.buildDOByBO(entityBO); - if (!pointAttributeManager.save(entityDO)) { - throw new AddException("Failed to create point attribute"); - } - } + PointAttributeDO entityDO = pointAttributeBuilder.buildDOByBO(entityBO); + if (!pointAttributeManager.save(entityDO)) { + throw new AddException("Failed to create point attribute"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!pointAttributeManager.removeById(id)) { - throw new DeleteException("Failed to remove point attribute"); - } - } + if (!pointAttributeManager.removeById(id)) { + throw new DeleteException("Failed to remove point attribute"); + } + } - @Override - public void update(PointAttributeBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(PointAttributeBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - PointAttributeDO entityDO = pointAttributeBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!pointAttributeManager.updateById(entityDO)) { - throw new UpdateException("Failed to update point attribute"); - } - } + PointAttributeDO entityDO = pointAttributeBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!pointAttributeManager.updateById(entityDO)) { + throw new UpdateException("Failed to update point attribute"); + } + } - @Override - public PointAttributeBO selectById(Long id) { - PointAttributeDO entityDO = getDOById(id, true); - return pointAttributeBuilder.buildBOByDO(entityDO); - } + @Override + public PointAttributeBO selectById(Long id) { + PointAttributeDO entityDO = getDOById(id, true); + return pointAttributeBuilder.buildBOByDO(entityDO); + } - @Override - public PointAttributeBO selectByNameAndDriverId(String name, Long driverId) { - LambdaQueryChainWrapper wrapper = pointAttributeManager.lambdaQuery() - .eq(PointAttributeDO::getAttributeCode, name) - .eq(PointAttributeDO::getDriverId, driverId) - .last(QueryWrapperConstant.LIMIT_ONE); - PointAttributeDO entityDO = wrapper.one(); - return pointAttributeBuilder.buildBOByDO(entityDO); - } + @Override + public PointAttributeBO selectByNameAndDriverId(String name, Long driverId) { + LambdaQueryChainWrapper wrapper = pointAttributeManager.lambdaQuery() + .eq(PointAttributeDO::getAttributeCode, name) + .eq(PointAttributeDO::getDriverId, driverId) + .last(QueryWrapperConstant.LIMIT_ONE); + PointAttributeDO entityDO = wrapper.one(); + return pointAttributeBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByDriverId(Long driverId) { - LambdaQueryChainWrapper wrapper = pointAttributeManager.lambdaQuery() - .eq(PointAttributeDO::getDriverId, driverId); - List entityDO = wrapper.list(); - return pointAttributeBuilder.buildBOListByDOList(entityDO); - } + @Override + public List selectByDriverId(Long driverId) { + LambdaQueryChainWrapper wrapper = pointAttributeManager.lambdaQuery() + .eq(PointAttributeDO::getDriverId, driverId); + List entityDO = wrapper.list(); + return pointAttributeBuilder.buildBOListByDOList(entityDO); + } - @Override - public Page selectByPage(PointAttributeQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = pointAttributeManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return pointAttributeBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(PointAttributeQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = pointAttributeManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return pointAttributeBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link PointAttributeQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(PointAttributeQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeCode()), PointAttributeDO::getAttributeCode, - entityQuery.getAttributeCode()); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeName()), PointAttributeDO::getAttributeName, - entityQuery.getAttributeName()); - wrapper.eq(Objects.nonNull(entityQuery.getAttributeTypeFlag()), PointAttributeDO::getAttributeTypeFlag, - entityQuery.getAttributeTypeFlag()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), PointAttributeDO::getDriverId, - entityQuery.getDriverId()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointAttributeDO::getTenantId, - entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link PointAttributeQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(PointAttributeQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeCode()), PointAttributeDO::getAttributeCode, + entityQuery.getAttributeCode()); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getAttributeName()), PointAttributeDO::getAttributeName, + entityQuery.getAttributeName()); + wrapper.eq(Objects.nonNull(entityQuery.getAttributeTypeFlag()), PointAttributeDO::getAttributeTypeFlag, + entityQuery.getAttributeTypeFlag()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDriverId()), PointAttributeDO::getDriverId, + entityQuery.getDriverId()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), PointAttributeDO::getTenantId, + entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link PointAttributeBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(PointAttributeBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointAttributeDO::getAttributeCode, entityBO.getAttributeCode()); - wrapper.eq(PointAttributeDO::getDriverId, entityBO.getDriverId()); - wrapper.eq(PointAttributeDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - PointAttributeDO one = pointAttributeManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Point attribute has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link PointAttributeBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(PointAttributeBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointAttributeDO::getAttributeCode, entityBO.getAttributeCode()); + wrapper.eq(PointAttributeDO::getDriverId, entityBO.getDriverId()); + wrapper.eq(PointAttributeDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + PointAttributeDO one = pointAttributeManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Point attribute has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link PointAttributeDO} - */ - private PointAttributeDO getDOById(Long id, boolean throwException) { - PointAttributeDO entityDO = pointAttributeManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Point attribute does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link PointAttributeDO} + */ + private PointAttributeDO getDOById(Long id, boolean throwException) { + PointAttributeDO entityDO = pointAttributeManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Point attribute does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointServiceImpl.java index 59ea0274e..f275071fc 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/PointServiceImpl.java @@ -67,416 +67,415 @@ import java.util.stream.Collectors; @Service public class PointServiceImpl implements PointService { - @Resource - private PointBuilder pointBuilder; + @Resource + private PointBuilder pointBuilder; - @Resource - private PointManager pointManager; + @Resource + private PointManager pointManager; - @Resource - private ProfileBindManager profileBindManager; + @Resource + private ProfileBindManager profileBindManager; - @Resource - private PointMapper pointMapper; + @Resource + private PointMapper pointMapper; - @Resource - private MetadataEventPublisher metadataEventPublisher; + @Resource + private MetadataEventPublisher metadataEventPublisher; - @Resource - private PointDataVolumeRunManager pointDataVolumeRunManager; + @Resource + private PointDataVolumeRunManager pointDataVolumeRunManager; - @Resource - private ProfileBindService profileBindService; + @Resource + private ProfileBindService profileBindService; - @Resource - private PointAttributeConfigManager pointAttributeConfigManager; + @Resource + private PointAttributeConfigManager pointAttributeConfigManager; - @Resource - private DeviceMapper deviceMapper; + @Resource + private DeviceMapper deviceMapper; - @Resource - private DriverMapper driverMapper; + @Resource + private DriverMapper driverMapper; - @Override - public void save(PointBO entityBO) { - checkDuplicate(entityBO, false, true); + @Override + public void save(PointBO entityBO) { + checkDuplicate(entityBO, false, true); - PointDO entityDO = pointBuilder.buildDOByBO(entityBO); - if (!pointManager.save(entityDO)) { - throw new AddException("Failed to create 位号"); - } + PointDO entityDO = pointBuilder.buildDOByBO(entityBO); + if (!pointManager.save(entityDO)) { + throw new AddException("Failed to create 位号"); + } - // - metadataEventPublisher.publishEvent( - new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, MetadataOperateTypeEnum.ADD)); - List deviceIds = profileBindService.selectDeviceIdsByProfileId(entityDO.getProfileId()); - deviceIds.forEach(entityId -> metadataEventPublisher - .publishEvent(new MetadataEvent(this, entityId, MetadataTypeEnum.DEVICE, MetadataOperateTypeEnum.UPDATE))); - } + // + metadataEventPublisher.publishEvent( + new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, MetadataOperateTypeEnum.ADD)); + List deviceIds = profileBindService.selectDeviceIdsByProfileId(entityDO.getProfileId()); + deviceIds.forEach(entityId -> metadataEventPublisher + .publishEvent(new MetadataEvent(this, entityId, MetadataTypeEnum.DEVICE, MetadataOperateTypeEnum.UPDATE))); + } - @Override - public void remove(Long id) { - PointDO entityDO = getDOById(id, true); + @Override + public void remove(Long id) { + PointDO entityDO = getDOById(id, true); - if (!pointManager.removeById(id)) { - throw new DeleteException("Failed to remove "); - } + if (!pointManager.removeById(id)) { + throw new DeleteException("Failed to remove "); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, - MetadataOperateTypeEnum.DELETE); - metadataEventPublisher.publishEvent(metadataEvent); - List deviceIds = profileBindService.selectDeviceIdsByProfileId(entityDO.getProfileId()); - deviceIds.forEach(entityId -> metadataEventPublisher - .publishEvent(new MetadataEvent(this, entityId, MetadataTypeEnum.DEVICE, MetadataOperateTypeEnum.UPDATE))); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, + MetadataOperateTypeEnum.DELETE); + metadataEventPublisher.publishEvent(metadataEvent); + List deviceIds = profileBindService.selectDeviceIdsByProfileId(entityDO.getProfileId()); + deviceIds.forEach(entityId -> metadataEventPublisher + .publishEvent(new MetadataEvent(this, entityId, MetadataTypeEnum.DEVICE, MetadataOperateTypeEnum.UPDATE))); + } - @Override - public void update(PointBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(PointBO entityBO) { + getDOById(entityBO.getId(), true); - checkDuplicate(entityBO, true, true); + checkDuplicate(entityBO, true, true); - PointDO entityDO = pointBuilder.buildDOByBO(entityBO); - entityDO.setOperateTime(null); - if (!pointManager.updateById(entityDO)) { - throw new UpdateException("Failed to update point"); - } + PointDO entityDO = pointBuilder.buildDOByBO(entityBO); + entityDO.setOperateTime(null); + if (!pointManager.updateById(entityDO)) { + throw new UpdateException("Failed to update point"); + } - // - MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, - MetadataOperateTypeEnum.UPDATE); - metadataEventPublisher.publishEvent(metadataEvent); - } + // + MetadataEvent metadataEvent = new MetadataEvent(this, entityDO.getId(), MetadataTypeEnum.POINT, + MetadataOperateTypeEnum.UPDATE); + metadataEventPublisher.publishEvent(metadataEvent); + } - @Override - public PointBO selectById(Long id) { - PointDO entityDO = getDOById(id, true); - return pointBuilder.buildBOByDO(entityDO); - } + @Override + public PointBO selectById(Long id) { + PointDO entityDO = getDOById(id, true); + return pointBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByIds(Set ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyList(); - } - List entityDOList = pointManager.listByIds(ids); - return pointBuilder.buildBOListByDOList(entityDOList); - } + @Override + public List selectByIds(Set ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyList(); + } + List entityDOList = pointManager.listByIds(ids); + return pointBuilder.buildBOListByDOList(entityDOList); + } - @Override - public List selectByDeviceId(Long deviceId) { - LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() - .eq(ProfileBindDO::getDeviceId, deviceId); - List entityDOList = wrapper.list(); - List profileIds = entityDOList.stream().map(ProfileBindDO::getProfileId).toList(); - return selectByProfileIds(profileIds); - } + @Override + public List selectByDeviceId(Long deviceId) { + LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() + .eq(ProfileBindDO::getDeviceId, deviceId); + List entityDOList = wrapper.list(); + List profileIds = entityDOList.stream().map(ProfileBindDO::getProfileId).toList(); + return selectByProfileIds(profileIds); + } - @Override - public List selectByProfileId(Long profileId) { - LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().eq(PointDO::getProfileId, profileId); - List entityDOList = wrapper.list(); - return pointBuilder.buildBOListByDOList(entityDOList); - } + @Override + public List selectByProfileId(Long profileId) { + LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().eq(PointDO::getProfileId, profileId); + List entityDOList = wrapper.list(); + return pointBuilder.buildBOListByDOList(entityDOList); + } - @Override - public List selectByProfileIds(List profileIds) { - if (CollectionUtils.isEmpty(profileIds)) { - return Collections.emptyList(); - } - LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().in(PointDO::getProfileId, profileIds); - List entityDOList = wrapper.list(); - return pointBuilder.buildBOListByDOList(entityDOList); - } + @Override + public List selectByProfileIds(List profileIds) { + if (CollectionUtils.isEmpty(profileIds)) { + return Collections.emptyList(); + } + LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().in(PointDO::getProfileId, profileIds); + List entityDOList = wrapper.list(); + return pointBuilder.buildBOListByDOList(entityDOList); + } - @Override - public Page selectByPage(PointQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = pointMapper.selectPageWithDevice(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery), entityQuery.getDeviceId()); - return pointBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(PointQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = pointMapper.selectPageWithDevice(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery), entityQuery.getDeviceId()); + return pointBuilder.buildBOPageByDOPage(entityPageDO); + } - @Override - public Map unit(Set ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyMap(); - } - List pointDOList = pointManager.listByIds(ids); - return pointDOList.stream().collect(Collectors.toMap(PointDO::getId, PointDO::getUnit)); - } + @Override + public Map unit(Set ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyMap(); + } + List pointDOList = pointManager.listByIds(ids); + return pointDOList.stream().collect(Collectors.toMap(PointDO::getId, PointDO::getUnit)); + } - @Override - public DeviceByPointBO selectPointStatisticsWithDevice(Long pointId) { - PointBO pointBO = selectById(pointId); - Set deviceIds = new HashSet<>(); + @Override + public DeviceByPointBO selectPointStatisticsWithDevice(Long pointId) { + PointBO pointBO = selectById(pointId); + Set deviceIds = new HashSet<>(); - profileBindService.selectDeviceIdsByProfileId(pointBO.getProfileId()).forEach(deviceId -> { - List dos = selectByDeviceIdAndPointId(deviceId, pointId); - if (!dos.isEmpty()) { - deviceIds.add(deviceId); - } - }); - DeviceByPointBO deviceByPointBO = new DeviceByPointBO(); - if (Objects.nonNull(deviceIds)) { - List deviceDOList = deviceMapper - .selectList(new LambdaQueryWrapper().in(DeviceDO::getId, deviceIds)); - deviceByPointBO.setDevices(deviceDOList); - deviceByPointBO.setCount(deviceDOList.stream().count()); - } - else { - deviceByPointBO.setCount(0L); - } - return deviceByPointBO; - } + profileBindService.selectDeviceIdsByProfileId(pointBO.getProfileId()).forEach(deviceId -> { + List dos = selectByDeviceIdAndPointId(deviceId, pointId); + if (!dos.isEmpty()) { + deviceIds.add(deviceId); + } + }); + DeviceByPointBO deviceByPointBO = new DeviceByPointBO(); + if (Objects.nonNull(deviceIds)) { + List deviceDOList = deviceMapper + .selectList(new LambdaQueryWrapper().in(DeviceDO::getId, deviceIds)); + deviceByPointBO.setDevices(deviceDOList); + deviceByPointBO.setCount(deviceDOList.stream().count()); + } else { + deviceByPointBO.setCount(0L); + } + return deviceByPointBO; + } - @Override - public List selectPointStatisticsByDeviceId(Long pointId, Set deviceIds) { - List list = new ArrayList<>(); - LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) - .minusDays(7); - if (Objects.isNull(deviceIds)) { - return list; - } - List deviceDOList = deviceMapper - .selectList(new LambdaQueryWrapper().in(DeviceDO::getId, deviceIds)); - List zero = Collections.nCopies(7, 0L); - ArrayList zeroList = new ArrayList<>(zero); - deviceDOList.forEach(deviceDO -> { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointDataVolumeRunDO::getPointId, pointId) - .eq(PointDataVolumeRunDO::getDeviceId, deviceDO.getId()) - .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo); - PointDataVolumeRunBO pointDataVolumeRunBO = new PointDataVolumeRunBO(); - pointDataVolumeRunBO.setDeviceName(deviceDO.getDeviceName()); - List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper); - if (Objects.nonNull(pointDataVolumeRunDOList)) { - for (int i = 0; i < 7; i++) { - zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); - } - } - pointDataVolumeRunBO.setTotal(zeroList); - list.add(pointDataVolumeRunBO); - }); - return list; - } + @Override + public List selectPointStatisticsByDeviceId(Long pointId, Set deviceIds) { + List list = new ArrayList<>(); + LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) + .minusDays(7); + if (Objects.isNull(deviceIds)) { + return list; + } + List deviceDOList = deviceMapper + .selectList(new LambdaQueryWrapper().in(DeviceDO::getId, deviceIds)); + List zero = Collections.nCopies(7, 0L); + ArrayList zeroList = new ArrayList<>(zero); + deviceDOList.forEach(deviceDO -> { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointDataVolumeRunDO::getPointId, pointId) + .eq(PointDataVolumeRunDO::getDeviceId, deviceDO.getId()) + .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo); + PointDataVolumeRunBO pointDataVolumeRunBO = new PointDataVolumeRunBO(); + pointDataVolumeRunBO.setDeviceName(deviceDO.getDeviceName()); + List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper); + if (Objects.nonNull(pointDataVolumeRunDOList)) { + for (int i = 0; i < 7; i++) { + zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); + } + } + pointDataVolumeRunBO.setTotal(zeroList); + list.add(pointDataVolumeRunBO); + }); + return list; + } - @Override - public PointDataVolumeRunDO selectPointStatisticsByPointId(Long pointId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.select("sum(total) as total"); - wrapper.lambda().eq(PointDataVolumeRunDO::getPointId, pointId); - return pointDataVolumeRunManager.getOne(wrapper); - } + @Override + public PointDataVolumeRunDO selectPointStatisticsByPointId(Long pointId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.select("sum(total) as total"); + wrapper.lambda().eq(PointDataVolumeRunDO::getPointId, pointId); + return pointDataVolumeRunManager.getOne(wrapper); + } - @Override - public Long selectPointByDeviceId(Long deviceId) { - ProfileBindDO bindDO = profileBindManager - .getOne(new LambdaQueryWrapper().eq(ProfileBindDO::getDeviceId, deviceId)); - Long count = 0L; - if (Objects.nonNull(bindDO)) { - List list = pointManager - .list(new LambdaQueryWrapper().eq(PointDO::getProfileId, bindDO.getProfileId())); - count = list.stream().count(); - } - return count; - } + @Override + public Long selectPointByDeviceId(Long deviceId) { + ProfileBindDO bindDO = profileBindManager + .getOne(new LambdaQueryWrapper().eq(ProfileBindDO::getDeviceId, deviceId)); + Long count = 0L; + if (Objects.nonNull(bindDO)) { + List list = pointManager + .list(new LambdaQueryWrapper().eq(PointDO::getProfileId, bindDO.getProfileId())); + count = list.stream().count(); + } + return count; + } - @Override - public PointConfigByDeviceBO selectPointConfigByDeviceId(Long deviceId) { - PointConfigByDeviceBO pointConfigByDeviceBO = new PointConfigByDeviceBO(); - ProfileBindDO bindDO = profileBindManager - .getOne(new LambdaQueryWrapper().eq(ProfileBindDO::getDeviceId, deviceId)); - List configCount = new ArrayList<>(); - List unConfigCount = new ArrayList<>(); - if (Objects.nonNull(bindDO)) { - List list = pointManager - .list(new LambdaQueryWrapper().eq(PointDO::getProfileId, bindDO.getProfileId())); - if (Objects.nonNull(list)) { - List profileList = list.stream().map(PointDO::getId).toList(); - List list2 = pointAttributeConfigManager - .list(new LambdaQueryWrapper().eq(PointAttributeConfigDO::getDeviceId, - deviceId)); - if (Objects.nonNull(list2)) { - List attrList = new ArrayList<>( - list2.stream().map(PointAttributeConfigDO::getPointId).toList()); - // - attrList.retainAll(profileList); - configCount.addAll(attrList); - unConfigCount.addAll(profileList); - } - else { - unConfigCount.addAll(profileList); - } - } - } - pointConfigByDeviceBO.setConfigCount(0L); - if (Objects.nonNull(configCount) && Objects.nonNull(unConfigCount)) { - List list = pointManager.list(new LambdaQueryWrapper().in(PointDO::getId, configCount)); - pointConfigByDeviceBO.setPoints(list); - pointConfigByDeviceBO.setConfigCount(list.stream().count()); - } - pointConfigByDeviceBO.setUnConfigCount(unConfigCount.stream().count() - pointConfigByDeviceBO.getConfigCount()); - return pointConfigByDeviceBO; - } + @Override + public PointConfigByDeviceBO selectPointConfigByDeviceId(Long deviceId) { + PointConfigByDeviceBO pointConfigByDeviceBO = new PointConfigByDeviceBO(); + ProfileBindDO bindDO = profileBindManager + .getOne(new LambdaQueryWrapper().eq(ProfileBindDO::getDeviceId, deviceId)); + List configCount = new ArrayList<>(); + List unConfigCount = new ArrayList<>(); + if (Objects.nonNull(bindDO)) { + List list = pointManager + .list(new LambdaQueryWrapper().eq(PointDO::getProfileId, bindDO.getProfileId())); + if (Objects.nonNull(list)) { + List profileList = list.stream().map(PointDO::getId).toList(); + List list2 = pointAttributeConfigManager + .list(new LambdaQueryWrapper().eq(PointAttributeConfigDO::getDeviceId, + deviceId)); + if (Objects.nonNull(list2)) { + List attrList = new ArrayList<>( + list2.stream().map(PointAttributeConfigDO::getPointId).toList()); + // + attrList.retainAll(profileList); + configCount.addAll(attrList); + unConfigCount.addAll(profileList); + } else { + unConfigCount.addAll(profileList); + } + } + } + pointConfigByDeviceBO.setConfigCount(0L); + if (Objects.nonNull(configCount) && Objects.nonNull(unConfigCount)) { + List list = pointManager.list(new LambdaQueryWrapper().in(PointDO::getId, configCount)); + pointConfigByDeviceBO.setPoints(list); + pointConfigByDeviceBO.setConfigCount(list.stream().count()); + } + pointConfigByDeviceBO.setUnConfigCount(unConfigCount.stream().count() - pointConfigByDeviceBO.getConfigCount()); + return pointConfigByDeviceBO; + } - @Override - public List selectDeviceStatisticsByPointId(Long deviceId, Set pointIds) { - List list = new ArrayList<>(); - LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) - .minusDays(7); - if (Objects.isNull(pointIds)) { - return list; - } - List pointDOList = pointManager.list(new LambdaQueryWrapper().in(PointDO::getId, pointIds)); - List zero = Collections.nCopies(7, 0L); - ArrayList zeroList = new ArrayList<>(zero); - pointDOList.forEach(pointDO -> { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointDataVolumeRunDO::getPointId, pointDO.getId()) - .eq(PointDataVolumeRunDO::getDeviceId, deviceId) - .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo); - DeviceDataVolumeRunBO deviceDataVolumeRunBO = new DeviceDataVolumeRunBO(); - deviceDataVolumeRunBO.setPointName(pointDO.getPointName()); - List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper); - if (Objects.nonNull(pointDataVolumeRunDOList)) { - for (int i = 0; i < pointDataVolumeRunDOList.size(); i++) { - zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); - } - } - deviceDataVolumeRunBO.setTotal(zeroList); - list.add(deviceDataVolumeRunBO); - }); - return list; - } + @Override + public List selectDeviceStatisticsByPointId(Long deviceId, Set pointIds) { + List list = new ArrayList<>(); + LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) + .minusDays(7); + if (Objects.isNull(pointIds)) { + return list; + } + List pointDOList = pointManager.list(new LambdaQueryWrapper().in(PointDO::getId, pointIds)); + List zero = Collections.nCopies(7, 0L); + ArrayList zeroList = new ArrayList<>(zero); + pointDOList.forEach(pointDO -> { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointDataVolumeRunDO::getPointId, pointDO.getId()) + .eq(PointDataVolumeRunDO::getDeviceId, deviceId) + .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo); + DeviceDataVolumeRunBO deviceDataVolumeRunBO = new DeviceDataVolumeRunBO(); + deviceDataVolumeRunBO.setPointName(pointDO.getPointName()); + List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper); + if (Objects.nonNull(pointDataVolumeRunDOList)) { + for (int i = 0; i < pointDataVolumeRunDOList.size(); i++) { + zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); + } + } + deviceDataVolumeRunBO.setTotal(zeroList); + list.add(deviceDataVolumeRunBO); + }); + return list; + } - @Override - public PointDataVolumeRunDO selectPointDataByDriverId(Long driverId) { - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.select("sum(total) as total"); - wrapper.lambda().eq(PointDataVolumeRunDO::getDriverId, driverId); - PointDataVolumeRunDO one = pointDataVolumeRunManager.getOne(wrapper); - if (Objects.isNull(one)) { - return new PointDataVolumeRunDO(); - } - return one; - } + @Override + public PointDataVolumeRunDO selectPointDataByDriverId(Long driverId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.select("sum(total) as total"); + wrapper.lambda().eq(PointDataVolumeRunDO::getDriverId, driverId); + PointDataVolumeRunDO one = pointDataVolumeRunManager.getOne(wrapper); + if (Objects.isNull(one)) { + return new PointDataVolumeRunDO(); + } + return one; + } - @Override - public Long selectPointByDriverId(Long driverId) { - LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.select(PointDataVolumeRunDO::getPointId); - queryWrapper.eq(PointDataVolumeRunDO::getDriverId, driverId).groupBy(PointDataVolumeRunDO::getPointId); - List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(queryWrapper); - if (Objects.nonNull(pointDataVolumeRunDOList)) { - return pointDataVolumeRunDOList.stream().count(); - } - else { - return 0L; - } - } + @Override + public Long selectPointByDriverId(Long driverId) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.select(PointDataVolumeRunDO::getPointId); + queryWrapper.eq(PointDataVolumeRunDO::getDriverId, driverId).groupBy(PointDataVolumeRunDO::getPointId); + List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(queryWrapper); + if (Objects.nonNull(pointDataVolumeRunDOList)) { + return pointDataVolumeRunDOList.stream().count(); + } else { + return 0L; + } + } - @Override - public PointDataStatisticsByDriverIdBO selectPointDataStatisticsByDriverId(Long driverId) { - PointDataStatisticsByDriverIdBO result = new PointDataStatisticsByDriverIdBO(); - DriverDO driverDO = driverMapper.selectById(driverId); - if (Objects.isNull(driverDO)) { - throw new NotFoundException("Driver does not exist"); - } - result.setDriverName(driverDO.getDriverName()); - List zero = Collections.nCopies(7, 0L); - ArrayList zeroList = new ArrayList<>(zero); - LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) - .minusDays(6); - QueryWrapper wrapper = new QueryWrapper<>(); - wrapper.select("sum(total) as total"); - List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper.lambda() - .eq(PointDataVolumeRunDO::getDriverId, driverId) - .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo) - .groupBy(PointDataVolumeRunDO::getCreateTime) - .orderByDesc(PointDataVolumeRunDO::getCreateTime)); - if (Objects.isNull(pointDataVolumeRunDOList)) { - result.setTotal(zeroList); - return result; - } - for (int i = 0; i < pointDataVolumeRunDOList.size(); i++) { - zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); - } - result.setTotal(zeroList); - return result; - } + @Override + public PointDataStatisticsByDriverIdBO selectPointDataStatisticsByDriverId(Long driverId) { + PointDataStatisticsByDriverIdBO result = new PointDataStatisticsByDriverIdBO(); + DriverDO driverDO = driverMapper.selectById(driverId); + if (Objects.isNull(driverDO)) { + throw new NotFoundException("Driver does not exist"); + } + result.setDriverName(driverDO.getDriverName()); + List zero = Collections.nCopies(7, 0L); + ArrayList zeroList = new ArrayList<>(zero); + LocalDateTime sevenDaysAgo = LocalDateTime.of(LocalDateTimeUtil.now().toLocalDate(), LocalTime.MIN) + .minusDays(6); + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.select("sum(total) as total"); + List pointDataVolumeRunDOList = pointDataVolumeRunManager.list(wrapper.lambda() + .eq(PointDataVolumeRunDO::getDriverId, driverId) + .ge(PointDataVolumeRunDO::getCreateTime, sevenDaysAgo) + .groupBy(PointDataVolumeRunDO::getCreateTime) + .orderByDesc(PointDataVolumeRunDO::getCreateTime)); + if (Objects.isNull(pointDataVolumeRunDOList)) { + result.setTotal(zeroList); + return result; + } + for (int i = 0; i < pointDataVolumeRunDOList.size(); i++) { + zeroList.set(i, pointDataVolumeRunDOList.get(i).getTotal()); + } + result.setTotal(zeroList); + return result; + } - /** - * @param entityQuery {@link PointQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(PointQuery entityQuery) { - QueryWrapper wrapper = Wrappers.query(); - wrapper.eq("dp.deleted", 0); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getPointName()), "dp.point_name", entityQuery.getPointName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getPointCode()), "dp.point_code", entityQuery.getPointCode()); - wrapper.eq(Objects.nonNull(entityQuery.getPointTypeFlag()), "dp.point_type_flag", - entityQuery.getPointTypeFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getRwFlag()), "dp.rw_flag", entityQuery.getRwFlag()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getProfileId()), "dp.profile_id", entityQuery.getProfileId()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dp.enable_flag", entityQuery.getEnableFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dp.tenant_id", entityQuery.getTenantId()); - return wrapper.lambda(); - } + /** + * @param entityQuery {@link PointQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(PointQuery entityQuery) { + QueryWrapper wrapper = Wrappers.query(); + wrapper.eq("dp.deleted", 0); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getPointName()), "dp.point_name", entityQuery.getPointName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getPointCode()), "dp.point_code", entityQuery.getPointCode()); + wrapper.eq(Objects.nonNull(entityQuery.getPointTypeFlag()), "dp.point_type_flag", + entityQuery.getPointTypeFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getRwFlag()), "dp.rw_flag", entityQuery.getRwFlag()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getProfileId()), "dp.profile_id", entityQuery.getProfileId()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dp.enable_flag", entityQuery.getEnableFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dp.tenant_id", entityQuery.getTenantId()); + return wrapper.lambda(); + } - /** - * @param entityBO {@link PointBO} - * @param isUpdate - * @param throwException - * @return - */ - private boolean checkDuplicate(PointBO entityBO, boolean isUpdate, boolean throwException) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(PointDO::getPointName, entityBO.getPointName()); - wrapper.eq(PointDO::getPointCode, entityBO.getPointCode()); - wrapper.eq(PointDO::getProfileId, entityBO.getProfileId()); - wrapper.eq(PointDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - PointDO one = pointManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); - if (throwException && duplicate) { - throw new DuplicateException("Point has been duplicated"); - } - return duplicate; - } + /** + * @param entityBO {@link PointBO} + * @param isUpdate + * @param throwException + * @return + */ + private boolean checkDuplicate(PointBO entityBO, boolean isUpdate, boolean throwException) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(PointDO::getPointName, entityBO.getPointName()); + wrapper.eq(PointDO::getPointCode, entityBO.getPointCode()); + wrapper.eq(PointDO::getProfileId, entityBO.getProfileId()); + wrapper.eq(PointDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + PointDO one = pointManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + boolean duplicate = !isUpdate || !one.getId().equals(entityBO.getId()); + if (throwException && duplicate) { + throw new DuplicateException("Point has been duplicated"); + } + return duplicate; + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link PointDO} - */ - private PointDO getDOById(Long id, boolean throwException) { - PointDO entityDO = pointManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Point does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link PointDO} + */ + private PointDO getDOById(Long id, boolean throwException) { + PointDO entityDO = pointManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Point does not exist"); + } + return entityDO; + } - /** - * Device ID Point ID - * @param deviceId Device ID - * @param pointId Point ID - * @return PointConfig Array - */ - private List selectByDeviceIdAndPointId(Long deviceId, Long pointId) { - LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() - .eq(PointAttributeConfigDO::getDeviceId, deviceId) - .eq(PointAttributeConfigDO::getPointId, pointId); - List entityDO = wrapper.list(); - return entityDO; - } + /** + * Device ID Point ID + * + * @param deviceId Device ID + * @param pointId Point ID + * @return PointConfig Array + */ + private List selectByDeviceIdAndPointId(Long deviceId, Long pointId) { + LambdaQueryChainWrapper wrapper = pointAttributeConfigManager.lambdaQuery() + .eq(PointAttributeConfigDO::getDeviceId, deviceId) + .eq(PointAttributeConfigDO::getPointId, pointId); + List entityDO = wrapper.list(); + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileBindServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileBindServiceImpl.java index 2f492253c..8fc3a12f6 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileBindServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileBindServiceImpl.java @@ -50,149 +50,150 @@ import java.util.Objects; @Service public class ProfileBindServiceImpl implements ProfileBindService { - @Resource - private ProfileBindBuilder profileBindBuilder; + @Resource + private ProfileBindBuilder profileBindBuilder; - @Resource - private ProfileBindManager profileBindManager; + @Resource + private ProfileBindManager profileBindManager; - @Override - public void save(ProfileBindBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException("Failed to create profile bind: profile bind has been duplicated"); - } + @Override + public void save(ProfileBindBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException("Failed to create profile bind: profile bind has been duplicated"); + } - ProfileBindDO entityDO = profileBindBuilder.buildDOByBO(entityBO); - if (!profileBindManager.save(entityDO)) { - throw new AddException("Failed to create profile bind"); - } - } + ProfileBindDO entityDO = profileBindBuilder.buildDOByBO(entityBO); + if (!profileBindManager.save(entityDO)) { + throw new AddException("Failed to create profile bind"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - if (!profileBindManager.removeById(id)) { - throw new DeleteException("Failed to remove profile bind"); - } - } + if (!profileBindManager.removeById(id)) { + throw new DeleteException("Failed to remove profile bind"); + } + } - @Override - public Boolean removeByDeviceId(Long deviceId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ProfileBindDO::getDeviceId, deviceId); - return profileBindManager.remove(wrapper); - } + @Override + public Boolean removeByDeviceId(Long deviceId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ProfileBindDO::getDeviceId, deviceId); + return profileBindManager.remove(wrapper); + } - @Override - public Boolean removeByDeviceIdAndProfileId(Long deviceId, Long profileId) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ProfileBindDO::getDeviceId, deviceId); - wrapper.eq(ProfileBindDO::getProfileId, profileId); - return profileBindManager.remove(wrapper); - } + @Override + public Boolean removeByDeviceIdAndProfileId(Long deviceId, Long profileId) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ProfileBindDO::getDeviceId, deviceId); + wrapper.eq(ProfileBindDO::getProfileId, profileId); + return profileBindManager.remove(wrapper); + } - @Override - public void update(ProfileBindBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(ProfileBindBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException("Failed to update profile bind: profile bind has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException("Failed to update profile bind: profile bind has been duplicated"); + } - ProfileBindDO entityDO = profileBindBuilder.buildDOByBO(entityBO); - entityBO.setOperateTime(null); - if (!profileBindManager.updateById(entityDO)) { - throw new UpdateException("Failed to update profile bind"); - } - } + ProfileBindDO entityDO = profileBindBuilder.buildDOByBO(entityBO); + entityBO.setOperateTime(null); + if (!profileBindManager.updateById(entityDO)) { + throw new UpdateException("Failed to update profile bind"); + } + } - @Override - public ProfileBindBO selectById(Long id) { - ProfileBindDO entityDO = getDOById(id, true); - return profileBindBuilder.buildBOByDO(entityDO); - } + @Override + public ProfileBindBO selectById(Long id) { + ProfileBindDO entityDO = getDOById(id, true); + return profileBindBuilder.buildBOByDO(entityDO); + } - @Override - public ProfileBindBO selectByDeviceIdAndProfileId(Long deviceId, Long profileId) { - LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() - .eq(ProfileBindDO::getDeviceId, deviceId) - .eq(ProfileBindDO::getProfileId, profileId) - .last(QueryWrapperConstant.LIMIT_ONE); - ProfileBindDO entityDO = wrapper.one(); - return profileBindBuilder.buildBOByDO(entityDO); - } + @Override + public ProfileBindBO selectByDeviceIdAndProfileId(Long deviceId, Long profileId) { + LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() + .eq(ProfileBindDO::getDeviceId, deviceId) + .eq(ProfileBindDO::getProfileId, profileId) + .last(QueryWrapperConstant.LIMIT_ONE); + ProfileBindDO entityDO = wrapper.one(); + return profileBindBuilder.buildBOByDO(entityDO); + } - @Override - public List selectDeviceIdsByProfileId(Long profileId) { - LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() - .eq(ProfileBindDO::getProfileId, profileId) - .select(ProfileBindDO::getDeviceId); - return wrapper.list().stream().map(ProfileBindDO::getDeviceId).toList(); - } + @Override + public List selectDeviceIdsByProfileId(Long profileId) { + LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() + .eq(ProfileBindDO::getProfileId, profileId) + .select(ProfileBindDO::getDeviceId); + return wrapper.list().stream().map(ProfileBindDO::getDeviceId).toList(); + } - @Override - public List selectProfileIdsByDeviceId(Long deviceId) { - LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() - .eq(ProfileBindDO::getDeviceId, deviceId) - .select(ProfileBindDO::getProfileId); - return wrapper.list().stream().map(ProfileBindDO::getProfileId).toList(); - } + @Override + public List selectProfileIdsByDeviceId(Long deviceId) { + LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() + .eq(ProfileBindDO::getDeviceId, deviceId) + .select(ProfileBindDO::getProfileId); + return wrapper.list().stream().map(ProfileBindDO::getProfileId).toList(); + } - @Override - public Page selectByPage(ProfileBindQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = profileBindManager.page(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery)); - return profileBindBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(ProfileBindQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = profileBindManager.page(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery)); + return profileBindBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link ProfileBindQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(ProfileBindQuery entityQuery) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getProfileId()), ProfileBindDO::getProfileId, - entityQuery.getProfileId()); - wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), ProfileBindDO::getDeviceId, - entityQuery.getDeviceId()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), ProfileBindDO::getTenantId, entityQuery.getTenantId()); - return wrapper; - } + /** + * @param entityQuery {@link ProfileBindQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(ProfileBindQuery entityQuery) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getProfileId()), ProfileBindDO::getProfileId, + entityQuery.getProfileId()); + wrapper.eq(FieldUtil.isValidIdField(entityQuery.getDeviceId()), ProfileBindDO::getDeviceId, + entityQuery.getDeviceId()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), ProfileBindDO::getTenantId, entityQuery.getTenantId()); + return wrapper; + } - /** - * @param entityBO {@link ProfileBindBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(ProfileBindBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ProfileBindDO::getDeviceId, entityBO.getDeviceId()); - wrapper.eq(ProfileBindDO::getProfileId, entityBO.getProfileId()); - wrapper.eq(ProfileBindDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - ProfileBindDO one = profileBindManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link ProfileBindBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(ProfileBindBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ProfileBindDO::getDeviceId, entityBO.getDeviceId()); + wrapper.eq(ProfileBindDO::getProfileId, entityBO.getProfileId()); + wrapper.eq(ProfileBindDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + ProfileBindDO one = profileBindManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link ProfileBindDO} - */ - private ProfileBindDO getDOById(Long id, boolean throwException) { - ProfileBindDO entityDO = profileBindManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Profile bind does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link ProfileBindDO} + */ + private ProfileBindDO getDOById(Long id, boolean throwException) { + ProfileBindDO entityDO = profileBindManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Profile bind does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileServiceImpl.java index b10311d2a..e0befd760 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/ProfileServiceImpl.java @@ -61,158 +61,159 @@ import java.util.stream.Collectors; @Service public class ProfileServiceImpl implements ProfileService { - @Resource - private ProfileBuilder profileBuilder; + @Resource + private ProfileBuilder profileBuilder; - @Resource - private ProfileManager profileManager; + @Resource + private ProfileManager profileManager; - @Resource - private ProfileBindManager profileBindManager; + @Resource + private ProfileBindManager profileBindManager; - @Resource - private PointManager pointManager; + @Resource + private PointManager pointManager; - @Resource - private ProfileMapper profileMapper; + @Resource + private ProfileMapper profileMapper; - @Override - public void save(ProfileBO entityBO) { - if (checkDuplicate(entityBO, false)) { - throw new DuplicateException("Failed to create profile: profile has been duplicated"); - } + @Override + public void save(ProfileBO entityBO) { + if (checkDuplicate(entityBO, false)) { + throw new DuplicateException("Failed to create profile: profile has been duplicated"); + } - ProfileDO entityDO = profileBuilder.buildDOByBO(entityBO); - if (!profileManager.save(entityDO)) { - throw new AddException("Failed to create profile"); - } - } + ProfileDO entityDO = profileBuilder.buildDOByBO(entityBO); + if (!profileManager.save(entityDO)) { + throw new AddException("Failed to create profile"); + } + } - @Override - public void remove(Long id) { - getDOById(id, true); + @Override + public void remove(Long id) { + getDOById(id, true); - // - LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().eq(PointDO::getProfileId, id); - long count = wrapper.count(); - if (count > 0) { - throw new AssociatedException("Failed to remove profile: some points exists in the template"); - } + // + LambdaQueryChainWrapper wrapper = pointManager.lambdaQuery().eq(PointDO::getProfileId, id); + long count = wrapper.count(); + if (count > 0) { + throw new AssociatedException("Failed to remove profile: some points exists in the template"); + } - if (!profileManager.removeById(id)) { - throw new DeleteException("Failed to remove profile"); - } - } + if (!profileManager.removeById(id)) { + throw new DeleteException("Failed to remove profile"); + } + } - @Override - public void update(ProfileBO entityBO) { - getDOById(entityBO.getId(), true); + @Override + public void update(ProfileBO entityBO) { + getDOById(entityBO.getId(), true); - if (checkDuplicate(entityBO, true)) { - throw new DuplicateException("Failed to update profile: profile has been duplicated"); - } + if (checkDuplicate(entityBO, true)) { + throw new DuplicateException("Failed to update profile: profile has been duplicated"); + } - ProfileDO entityDO = profileBuilder.buildDOByBO(entityBO); - entityBO.setOperateTime(null); - if (!profileManager.updateById(entityDO)) { - throw new UpdateException("Failed to update profile"); - } - } + ProfileDO entityDO = profileBuilder.buildDOByBO(entityBO); + entityBO.setOperateTime(null); + if (!profileManager.updateById(entityDO)) { + throw new UpdateException("Failed to update profile"); + } + } - @Override - public ProfileBO selectById(Long id) { - ProfileDO entityDO = getDOById(id, true); - return profileBuilder.buildBOByDO(entityDO); - } + @Override + public ProfileBO selectById(Long id) { + ProfileDO entityDO = getDOById(id, true); + return profileBuilder.buildBOByDO(entityDO); + } - @Override - public ProfileBO selectByNameAndType(Long tenantId, String name, ProfileTypeFlagEnum type) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ProfileDO::getProfileName, name); - wrapper.eq(ProfileDO::getProfileTypeFlag, type); - wrapper.eq(ProfileDO::getTenantId, tenantId); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - ProfileDO entityDO = profileManager.getOne(wrapper); - return profileBuilder.buildBOByDO(entityDO); - } + @Override + public ProfileBO selectByNameAndType(Long tenantId, String name, ProfileTypeFlagEnum type) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ProfileDO::getProfileName, name); + wrapper.eq(ProfileDO::getProfileTypeFlag, type); + wrapper.eq(ProfileDO::getTenantId, tenantId); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + ProfileDO entityDO = profileManager.getOne(wrapper); + return profileBuilder.buildBOByDO(entityDO); + } - @Override - public List selectByIds(Set ids) { - if (CollectionUtils.isEmpty(ids)) { - return Collections.emptyList(); - } - List entityDOList = profileManager.listByIds(ids); - return profileBuilder.buildBOListByDOList(entityDOList); - } + @Override + public List selectByIds(Set ids) { + if (CollectionUtils.isEmpty(ids)) { + return Collections.emptyList(); + } + List entityDOList = profileManager.listByIds(ids); + return profileBuilder.buildBOListByDOList(entityDOList); + } - @Override - public List selectByDeviceId(Long deviceId) { - LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() - .eq(ProfileBindDO::getDeviceId, deviceId); - List entityDOList = wrapper.list(); - Set profileIds = entityDOList.stream().map(ProfileBindDO::getProfileId).collect(Collectors.toSet()); - return selectByIds(profileIds); - } + @Override + public List selectByDeviceId(Long deviceId) { + LambdaQueryChainWrapper wrapper = profileBindManager.lambdaQuery() + .eq(ProfileBindDO::getDeviceId, deviceId); + List entityDOList = wrapper.list(); + Set profileIds = entityDOList.stream().map(ProfileBindDO::getProfileId).collect(Collectors.toSet()); + return selectByIds(profileIds); + } - @Override - public Page selectByPage(ProfileQuery entityQuery) { - if (Objects.isNull(entityQuery.getPage())) { - entityQuery.setPage(new Pages()); - } - Page entityPageDO = profileMapper.selectPageWithDevice(PageUtil.page(entityQuery.getPage()), - fuzzyQuery(entityQuery), entityQuery.getDeviceId()); - return profileBuilder.buildBOPageByDOPage(entityPageDO); - } + @Override + public Page selectByPage(ProfileQuery entityQuery) { + if (Objects.isNull(entityQuery.getPage())) { + entityQuery.setPage(new Pages()); + } + Page entityPageDO = profileMapper.selectPageWithDevice(PageUtil.page(entityQuery.getPage()), + fuzzyQuery(entityQuery), entityQuery.getDeviceId()); + return profileBuilder.buildBOPageByDOPage(entityPageDO); + } - /** - * @param entityQuery {@link ProfileQuery} - * @return {@link LambdaQueryWrapper} - */ - private LambdaQueryWrapper fuzzyQuery(ProfileQuery entityQuery) { - QueryWrapper wrapper = Wrappers.query(); - wrapper.eq("dp.deleted", 0); - wrapper.like(StringUtils.isNotEmpty(entityQuery.getProfileName()), "dp.profile_name", - entityQuery.getProfileName()); - wrapper.eq(StringUtils.isNotEmpty(entityQuery.getProfileCode()), "dp.profile_code", - entityQuery.getProfileCode()); - wrapper.eq(Objects.nonNull(entityQuery.getProfileShareFlag()), "dp.profile_share_flag", - entityQuery.getProfileShareFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dp.enable_flag", entityQuery.getEnableFlag()); - wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dp.tenant_id", entityQuery.getTenantId()); - return wrapper.lambda(); - } + /** + * @param entityQuery {@link ProfileQuery} + * @return {@link LambdaQueryWrapper} + */ + private LambdaQueryWrapper fuzzyQuery(ProfileQuery entityQuery) { + QueryWrapper wrapper = Wrappers.query(); + wrapper.eq("dp.deleted", 0); + wrapper.like(StringUtils.isNotEmpty(entityQuery.getProfileName()), "dp.profile_name", + entityQuery.getProfileName()); + wrapper.eq(StringUtils.isNotEmpty(entityQuery.getProfileCode()), "dp.profile_code", + entityQuery.getProfileCode()); + wrapper.eq(Objects.nonNull(entityQuery.getProfileShareFlag()), "dp.profile_share_flag", + entityQuery.getProfileShareFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getEnableFlag()), "dp.enable_flag", entityQuery.getEnableFlag()); + wrapper.eq(Objects.nonNull(entityQuery.getTenantId()), "dp.tenant_id", entityQuery.getTenantId()); + return wrapper.lambda(); + } - /** - * @param entityBO {@link ProfileBO} - * @param isUpdate - * @return - */ - private boolean checkDuplicate(ProfileBO entityBO, boolean isUpdate) { - LambdaQueryWrapper wrapper = Wrappers.query().lambda(); - wrapper.eq(ProfileDO::getProfileName, entityBO.getProfileName()); - wrapper.eq(ProfileDO::getProfileCode, entityBO.getProfileCode()); - wrapper.eq(ProfileDO::getProfileTypeFlag, entityBO.getProfileTypeFlag()); - wrapper.eq(ProfileDO::getTenantId, entityBO.getTenantId()); - wrapper.last(QueryWrapperConstant.LIMIT_ONE); - ProfileDO one = profileManager.getOne(wrapper); - if (Objects.isNull(one)) { - return false; - } - return !isUpdate || !one.getId().equals(entityBO.getId()); - } + /** + * @param entityBO {@link ProfileBO} + * @param isUpdate + * @return + */ + private boolean checkDuplicate(ProfileBO entityBO, boolean isUpdate) { + LambdaQueryWrapper wrapper = Wrappers.query().lambda(); + wrapper.eq(ProfileDO::getProfileName, entityBO.getProfileName()); + wrapper.eq(ProfileDO::getProfileCode, entityBO.getProfileCode()); + wrapper.eq(ProfileDO::getProfileTypeFlag, entityBO.getProfileTypeFlag()); + wrapper.eq(ProfileDO::getTenantId, entityBO.getTenantId()); + wrapper.last(QueryWrapperConstant.LIMIT_ONE); + ProfileDO one = profileManager.getOne(wrapper); + if (Objects.isNull(one)) { + return false; + } + return !isUpdate || !one.getId().equals(entityBO.getId()); + } - /** - * Primary key ID - * @param id ID - * @param throwException - * @return {@link ProfileDO} - */ - private ProfileDO getDOById(Long id, boolean throwException) { - ProfileDO entityDO = profileManager.getById(id); - if (throwException && Objects.isNull(entityDO)) { - throw new NotFoundException("Profile does not exist"); - } - return entityDO; - } + /** + * Primary key ID + * + * @param id ID + * @param throwException + * @return {@link ProfileDO} + */ + private ProfileDO getDOById(Long id, boolean throwException) { + ProfileDO entityDO = profileManager.getById(id); + if (throwException && Objects.isNull(entityDO)) { + throw new NotFoundException("Profile does not exist"); + } + return entityDO; + } } diff --git a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/TopicServiceImpl.java b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/TopicServiceImpl.java index ea93b0c31..a19f0b446 100644 --- a/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/TopicServiceImpl.java +++ b/dc3-common/dc3-common-manager/src/main/java/io/github/pnoker/common/manager/service/impl/TopicServiceImpl.java @@ -43,56 +43,56 @@ import java.util.List; @Service public class TopicServiceImpl extends ServiceImpl implements TopicService { - @Override - public Page> query(TopicQuery topicQuery) { - int page = (int) topicQuery.getPage().getCurrent(); - int size = (int) topicQuery.getPage().getSize(); - Page> resultPage = new Page<>(page, size); - List topicVOList = new ArrayList<>(); - String topic = topicQuery.getTopic(); - Long deviceIdL = null; - if (topic != null && topic.length() > 0) { - String[] parts = topic.split("/"); - deviceIdL = Long.parseLong(parts[parts.length - 1]); - } - String dName = topicQuery.getDeviceName(); - List deviceList = lambdaQuery().eq(deviceIdL != null, DeviceDO::getId, deviceIdL) - .eq(!dName.isEmpty(), DeviceDO::getDeviceName, dName) - // .eq(DeviceDO::getEnableFlag, 1) - .list(); + @Override + public Page> query(TopicQuery topicQuery) { + int page = (int) topicQuery.getPage().getCurrent(); + int size = (int) topicQuery.getPage().getSize(); + Page> resultPage = new Page<>(page, size); + List topicVOList = new ArrayList<>(); + String topic = topicQuery.getTopic(); + Long deviceIdL = null; + if (topic != null && topic.length() > 0) { + String[] parts = topic.split("/"); + deviceIdL = Long.parseLong(parts[parts.length - 1]); + } + String dName = topicQuery.getDeviceName(); + List deviceList = lambdaQuery().eq(deviceIdL != null, DeviceDO::getId, deviceIdL) + .eq(!dName.isEmpty(), DeviceDO::getDeviceName, dName) + // .eq(DeviceDO::getEnableFlag, 1) + .list(); - for (DeviceDO device : deviceList) { - String deviceName = device.getDeviceName(); - Long deviceId = device.getId(); - ProfileBindDO profileBind = Db.lambdaQuery(ProfileBindDO.class) - .eq(ProfileBindDO::getDeviceId, deviceId) - .one(); - if (profileBind != null) { - Long profileBindId = profileBind.getProfileId(); - List points = Db.lambdaQuery(PointDO.class) - .eq(PointDO::getProfileId, profileBindId) - // .eq(PointDO::getEnableFlag, 1) - .eq(PointDO::getDeleted, 0) - .list(); - for (PointDO point : points) { - TopicVO topicVO = new TopicVO(); - topicVO.setTopic("dc3/dc3-center-data/device/" + deviceId); - topicVO.setDeviceName(deviceName); - topicVO.setPointName(point.getPointName()); - topicVOList.add(topicVO); - } - } - } - int totalItems = topicVOList.size(); - int fromIndex = Math.max(0, (page - 1) * size); - int toIndex = Math.min(fromIndex + size, totalItems); - List> paginatedData = new ArrayList<>(); - if (fromIndex < toIndex) { - paginatedData.add(topicVOList.subList(fromIndex, toIndex)); - } - resultPage.setRecords(paginatedData); - resultPage.setTotal(totalItems); - return resultPage; - } + for (DeviceDO device : deviceList) { + String deviceName = device.getDeviceName(); + Long deviceId = device.getId(); + ProfileBindDO profileBind = Db.lambdaQuery(ProfileBindDO.class) + .eq(ProfileBindDO::getDeviceId, deviceId) + .one(); + if (profileBind != null) { + Long profileBindId = profileBind.getProfileId(); + List points = Db.lambdaQuery(PointDO.class) + .eq(PointDO::getProfileId, profileBindId) + // .eq(PointDO::getEnableFlag, 1) + .eq(PointDO::getDeleted, 0) + .list(); + for (PointDO point : points) { + TopicVO topicVO = new TopicVO(); + topicVO.setTopic("dc3/dc3-center-data/device/" + deviceId); + topicVO.setDeviceName(deviceName); + topicVO.setPointName(point.getPointName()); + topicVOList.add(topicVO); + } + } + } + int totalItems = topicVOList.size(); + int fromIndex = Math.max(0, (page - 1) * size); + int toIndex = Math.min(fromIndex + size, totalItems); + List> paginatedData = new ArrayList<>(); + if (fromIndex < toIndex) { + paginatedData.add(topicVOList.subList(fromIndex, toIndex)); + } + resultPage.setRecords(paginatedData); + resultPage.setTotal(totalItems); + return resultPage; + } } diff --git a/dc3-common/dc3-common-model/README.md b/dc3-common/dc3-common-model/README.md index 16760cf2e..f3f84a411 100644 --- a/dc3-common/dc3-common-model/README.md +++ b/dc3-common/dc3-common-model/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-model` is the shared domain model module of the IoT DC3 platform. It defines all base classes, domain entities (BO/VO/DTO/DO), validation group interfaces, and query +`dc3-common-model` is the shared domain model module of the IoT DC3 platform. It defines all base classes, domain +entities (BO/VO/DTO/DO), validation group interfaces, and query objects used across all services and drivers. ## Module Information diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseBO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseBO.java index 5e2197bb1..1f05ba114 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseBO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseBO.java @@ -37,47 +37,47 @@ import java.time.LocalDateTime; @AllArgsConstructor public class BaseBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - private Long id; + /** + * Primary key ID + */ + private Long id; - /** - * Description - */ - private String remark; + /** + * Description + */ + private String remark; - /** - * Creator ID - */ - private Long creatorId; + /** + * Creator ID + */ + private Long creatorId; - /** - * Creator Name - */ - private String creatorName; + /** + * Creator Name + */ + private String creatorName; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - /** - * Operator ID - */ - private Long operatorId; + /** + * Operator ID + */ + private Long operatorId; - /** - * Operator Name - */ - private String operatorName; + /** + * Operator Name + */ + private String operatorName; - /** - * Operate Time - */ - private LocalDateTime operateTime; + /** + * Operate Time + */ + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseDTO.java index a59f24830..0042c3a1f 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseDTO.java @@ -39,47 +39,47 @@ import java.time.LocalDateTime; @AllArgsConstructor public class BaseDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - private Long id; + /** + * Primary key ID + */ + private Long id; - /** - * Description - */ - private String remark; + /** + * Description + */ + private String remark; - /** - * Creator ID - */ - private Long creatorId; + /** + * Creator ID + */ + private Long creatorId; - /** - * Creator Name - */ - private String creatorName; + /** + * Creator Name + */ + private String creatorName; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - /** - * Operator ID - */ - private Long operatorId; + /** + * Operator ID + */ + private Long operatorId; - /** - * Operator Name - */ - private String operatorName; + /** + * Operator Name + */ + private String operatorName; - /** - * Operate Time - */ - private LocalDateTime operateTime; + /** + * Operate Time + */ + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseVO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseVO.java index 5869ac458..cf2962ee7 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseVO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/base/BaseVO.java @@ -43,50 +43,50 @@ import java.time.LocalDateTime; @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class BaseVO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Primary key ID - */ - @NotNull(message = "主键ID不能为空", groups = { Update.class }) - private Long id; + /** + * Primary key ID + */ + @NotNull(message = "主键ID不能为空", groups = {Update.class}) + private Long id; - /** - * Description - */ - private String remark; + /** + * Description + */ + private String remark; - /** - * Creator ID - */ - private Long creatorId; + /** + * Creator ID + */ + private Long creatorId; - /** - * Creator Name - */ - private String creatorName; + /** + * Creator Name + */ + private String creatorName; - /** - * Create Time - */ - @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) - private LocalDateTime createTime; + /** + * Create Time + */ + @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) + private LocalDateTime createTime; - /** - * Operator ID - */ - private Long operatorId; + /** + * Operator ID + */ + private Long operatorId; - /** - * Operator Name - */ - private String operatorName; + /** + * Operator Name + */ + private String operatorName; - /** - * Operate Time - */ - @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) - private LocalDateTime operateTime; + /** + * Operate Time + */ + @JsonFormat(pattern = TimeConstant.COMPLETE_DATE_FORMAT, timezone = TimeConstant.DEFAULT_TIMEZONE) + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/builder/BaseBuilder.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/builder/BaseBuilder.java index 93ebb683a..256347984 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/builder/BaseBuilder.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/builder/BaseBuilder.java @@ -32,63 +32,71 @@ import java.util.List; * @version 2025.9.0 * @since 2022.1.0 */ -@Mapper(componentModel = "spring", uses = { MapStructUtil.class }) +@Mapper(componentModel = "spring", uses = {MapStructUtil.class}) public interface BaseBuilder { - /** - * VO to BO - * @param entityVO EntityVO - * @return EntityBO - */ - BaseBO buildBOByVO(BaseVO entityVO); + /** + * VO to BO + * + * @param entityVO EntityVO + * @return EntityBO + */ + BaseBO buildBOByVO(BaseVO entityVO); - /** - * VOList to BOList - * @param entityVOList EntityVO collection - * @return EntityBO collection - */ - List buildBOListByVOList(List entityVOList); + /** + * VOList to BOList + * + * @param entityVOList EntityVO collection + * @return EntityBO collection + */ + List buildBOListByVOList(List entityVOList); - /** - * BO to VO - * @param entityBO EntityBO - * @return EntityVO - */ - BaseVO buildVOByBO(BaseBO entityBO); + /** + * BO to VO + * + * @param entityBO EntityBO + * @return EntityVO + */ + BaseVO buildVOByBO(BaseBO entityBO); - /** - * BOList to VOList - * @param entityBOList EntityBO collection - * @return EntityVO collection - */ - List buildVOListByBOList(List entityBOList); + /** + * BOList to VOList + * + * @param entityBOList EntityBO collection + * @return EntityVO collection + */ + List buildVOListByBOList(List entityBOList); - /** - * DTO to BO - * @param entityDTO EntityDTO - * @return EntityBO - */ - BaseBO buildBOByDTO(BaseDTO entityDTO); + /** + * DTO to BO + * + * @param entityDTO EntityDTO + * @return EntityBO + */ + BaseBO buildBOByDTO(BaseDTO entityDTO); - /** - * DTOList to BOList - * @param entityDTOList EntityDTO collection - * @return EntityBO collection - */ - List buildBOListByDTOList(List entityDTOList); + /** + * DTOList to BOList + * + * @param entityDTOList EntityDTO collection + * @return EntityBO collection + */ + List buildBOListByDTOList(List entityDTOList); - /** - * BO to DTO - * @param entityBO EntityBO - * @return EntityDTO - */ - BaseDTO buildDTOByBO(BaseBO entityBO); + /** + * BO to DTO + * + * @param entityBO EntityBO + * @return EntityDTO + */ + BaseDTO buildDTOByBO(BaseBO entityBO); - /** - * BOList to DTOList - * @param entityBOList EntityBO collection - * @return EntityDTO collection - */ - List buildDTOListByBOList(List entityBOList); + /** + * BOList to DTOList + * + * @param entityBOList EntityBO collection + * @return EntityDTO collection + */ + List buildDTOListByBOList(List entityBOList); } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/CmdParameterDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/CmdParameterDTO.java index 1bb51caff..d911938a2 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/CmdParameterDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/CmdParameterDTO.java @@ -35,22 +35,22 @@ import java.io.Serializable; @AllArgsConstructor public class CmdParameterDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * - */ - private String value; + /** + * + */ + private String value; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceCommandDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceCommandDTO.java index 351a2dc8f..f72e47219 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceCommandDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceCommandDTO.java @@ -38,108 +38,108 @@ import java.time.LocalDateTime; @AllArgsConstructor public class DeviceCommandDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type - */ - private DeviceCommandTypeEnum type; + /** + * Type + */ + private DeviceCommandTypeEnum type; - /** - * - */ - private String content; + /** + * + */ + private String content; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DeviceCommandDTO(DeviceCommandTypeEnum type, String content) { - this.type = type; - this.content = content; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceCommandDTO(DeviceCommandTypeEnum type, String content) { + this.type = type; + this.content = content; + this.createTime = LocalDateTimeUtil.now(); + } - /** - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class DeviceRead implements Serializable { + /** + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class DeviceRead implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DeviceRead(Long deviceId, Long pointId) { - this.deviceId = deviceId; - this.pointId = pointId; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceRead(Long deviceId, Long pointId) { + this.deviceId = deviceId; + this.pointId = pointId; + this.createTime = LocalDateTimeUtil.now(); + } - } + } - /** - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class DeviceWrite implements Serializable { + /** + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class DeviceWrite implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Point ID - */ - private Long pointId; + /** + * Point ID + */ + private Long pointId; - /** - * - */ - private String value; + /** + * + */ + private String value; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DeviceWrite(Long deviceId, Long pointId, String value) { - this.deviceId = deviceId; - this.pointId = pointId; - this.value = value; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceWrite(Long deviceId, Long pointId, String value) { + this.deviceId = deviceId; + this.pointId = pointId; + this.value = value; + this.createTime = LocalDateTimeUtil.now(); + } - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceEventDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceEventDTO.java index 90270e7bb..2a89c5177 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceEventDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DeviceEventDTO.java @@ -42,103 +42,103 @@ import java.util.concurrent.TimeUnit; @AllArgsConstructor public class DeviceEventDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type - */ - private DeviceEventTypeEnum type; + /** + * Type + */ + private DeviceEventTypeEnum type; - /** - * - */ - private String content; + /** + * + */ + private String content; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DeviceEventDTO(DeviceEventTypeEnum type, String content) { - this.type = type; - this.content = content; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceEventDTO(DeviceEventTypeEnum type, String content) { + this.type = type; + this.content = content; + this.createTime = LocalDateTimeUtil.now(); + } - /** - * Device status - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - @Getter - @Setter - @Builder - @NoArgsConstructor - @AllArgsConstructor - public static class DeviceStatus implements Serializable { + /** + * Device status + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + @Getter + @Setter + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class DeviceStatus implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Driver ID that reports this status. Populated by the sender. - */ - private Long driverId; + /** + * Driver ID that reports this status. Populated by the sender. + */ + private Long driverId; - /** - * Tenant ID the device belongs to. Populated by the sender. - */ - private Long tenantId; + /** + * Tenant ID the device belongs to. Populated by the sender. + */ + private Long tenantId; - /** - * Device ID - */ - private Long deviceId; + /** + * Device ID + */ + private Long deviceId; - /** - * Device status - */ - private DeviceStatusEnum status; + /** + * Device status + */ + private DeviceStatusEnum status; - /** - * Device status - */ - @Builder.Default - private int timeOut = 15; + /** + * Device status + */ + @Builder.Default + private int timeOut = 15; - /** - * Device status - */ - @Builder.Default - private TimeUnit timeUnit = TimeUnit.MINUTES; + /** + * Device status + */ + @Builder.Default + private TimeUnit timeUnit = TimeUnit.MINUTES; - /** - * Human-readable message. Populated for ALARM events; null for HEARTBEAT. - */ - private String message; + /** + * Human-readable message. Populated for ALARM events; null for HEARTBEAT. + */ + private String message; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DeviceStatus(Long deviceId, DeviceStatusEnum status) { - this.deviceId = deviceId; - this.status = status; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceStatus(Long deviceId, DeviceStatusEnum status) { + this.deviceId = deviceId; + this.status = status; + this.createTime = LocalDateTimeUtil.now(); + } - public DeviceStatus(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { - this.deviceId = deviceId; - this.status = status; - this.timeOut = timeOut; - this.timeUnit = timeUnit; - this.createTime = LocalDateTimeUtil.now(); - } + public DeviceStatus(Long deviceId, DeviceStatusEnum status, int timeOut, TimeUnit timeUnit) { + this.deviceId = deviceId; + this.status = status; + this.timeOut = timeOut; + this.timeUnit = timeUnit; + this.createTime = LocalDateTimeUtil.now(); + } - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverCommandDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverCommandDTO.java index b4cbeee7a..68851c895 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverCommandDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverCommandDTO.java @@ -37,22 +37,22 @@ import java.time.LocalDateTime; @AllArgsConstructor public class DriverCommandDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type - */ - private DriverCommandTypeEnum type; + /** + * Type + */ + private DriverCommandTypeEnum type; - /** - * - */ - private String content; + /** + * + */ + private String content; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverEventDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverEventDTO.java index 07db4ad27..714a86a6f 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverEventDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/DriverEventDTO.java @@ -41,77 +41,77 @@ import java.time.LocalDateTime; @AllArgsConstructor public class DriverEventDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type - */ - private DriverEventTypeEnum type; + /** + * Type + */ + private DriverEventTypeEnum type; - /** - * - */ - private String content; + /** + * + */ + private String content; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DriverEventDTO(DriverEventTypeEnum type, String content) { - this.type = type; - this.content = content; - this.createTime = LocalDateTimeUtil.now(); - } + public DriverEventDTO(DriverEventTypeEnum type, String content) { + this.type = type; + this.content = content; + this.createTime = LocalDateTimeUtil.now(); + } - /** - * Status - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class DriverStatus implements Serializable { + /** + * Status + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class DriverStatus implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Driver ID - */ - private Long driverId; + /** + * Driver ID + */ + private Long driverId; - /** - * Tenant ID the driver belongs to. Populated by the sender. - */ - private Long tenantId; + /** + * Tenant ID the driver belongs to. Populated by the sender. + */ + private Long tenantId; - /** - * Status - */ - private DriverStatusEnum status; + /** + * Status + */ + private DriverStatusEnum status; - /** - * Human-readable message. Populated for ALARM events; null for HEARTBEAT. - */ - private String message; + /** + * Human-readable message. Populated for ALARM events; null for HEARTBEAT. + */ + private String message; - /** - * Create Time - */ - private LocalDateTime createTime; + /** + * Create Time + */ + private LocalDateTime createTime; - public DriverStatus(Long driverId, DriverStatusEnum status) { - this.driverId = driverId; - this.status = status; - this.createTime = LocalDateTimeUtil.now(); - } + public DriverStatus(Long driverId, DriverStatusEnum status) { + this.driverId = driverId; + this.status = status; + this.createTime = LocalDateTimeUtil.now(); + } - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/MetadataEventDTO.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/MetadataEventDTO.java index a2779c77d..b4b551121 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/MetadataEventDTO.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/dto/MetadataEventDTO.java @@ -40,22 +40,22 @@ import java.io.Serializable; @AllArgsConstructor public class MetadataEventDTO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type{@link MetadataTypeEnum}, , - */ - private Long id; + /** + * Type{@link MetadataTypeEnum}, , + */ + private Long id; - /** - * Type - */ - private MetadataTypeEnum metadataType; + /** + * Type + */ + private MetadataTypeEnum metadataType; - /** - * Type, , , - */ - private MetadataOperateTypeEnum operateType; + /** + * Type, , , + */ + private MetadataOperateTypeEnum operateType; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/event/MetadataEvent.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/event/MetadataEvent.java index 5486c8ee9..10d93a73f 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/event/MetadataEvent.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/event/MetadataEvent.java @@ -32,24 +32,25 @@ import org.springframework.context.ApplicationEvent; @Getter public class MetadataEvent extends ApplicationEvent { - private final Long id; + private final Long id; - private final MetadataTypeEnum metadataType; + private final MetadataTypeEnum metadataType; - private final MetadataOperateTypeEnum operateType; + private final MetadataOperateTypeEnum operateType; - /** - * Constructor. - * @param source Event source object - * @param id Metadata ID - * @param metadataType Metadata type - * @param operateType Metadata operation type - */ - public MetadataEvent(Object source, Long id, MetadataTypeEnum metadataType, MetadataOperateTypeEnum operateType) { - super(source); - this.id = id; - this.metadataType = metadataType; - this.operateType = operateType; - } + /** + * Constructor. + * + * @param source Event source object + * @param id Metadata ID + * @param metadataType Metadata type + * @param operateType Metadata operation type + */ + public MetadataEvent(Object source, Long id, MetadataTypeEnum metadataType, MetadataOperateTypeEnum operateType) { + super(source); + this.id = id; + this.metadataType = metadataType; + this.operateType = operateType; + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ApiExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ApiExt.java index ac6ea47a9..3605cbf08 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ApiExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ApiExt.java @@ -37,34 +37,34 @@ import lombok.Setter; @AllArgsConstructor public class ApiExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - /** - * Title. - */ - private String title; + /** + * Title. + */ + private String title; - /** - * URL link. - */ - private String url; + /** + * URL link. + */ + private String url; - /** - * Description. - */ - private String remark; + /** + * Description. + */ + private String remark; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/BaseExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/BaseExt.java index e8036591c..8f783089a 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/BaseExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/BaseExt.java @@ -37,23 +37,23 @@ import java.io.Serializable; @AllArgsConstructor public class BaseExt implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type, used to parse JSON strings. - */ - private String type; + /** + * Type, used to parse JSON strings. + */ + private String type; - /** - * Version, used for optimistic locking. - */ - @Builder.Default - private Integer version = 1; + /** + * Version, used for optimistic locking. + */ + @Builder.Default + private Integer version = 1; - /** - * Description. - */ - private String remark; + /** + * Description. + */ + private String remark; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DeviceExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DeviceExt.java index 9b6bc59b2..0777cd7fc 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DeviceExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DeviceExt.java @@ -39,24 +39,24 @@ import java.io.Serializable; @AllArgsConstructor public class DeviceExt extends BaseExt { - /** - * - *

- * Type Version - */ - private Content content; + /** + * + *

+ * Type Version + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content implements Serializable { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverAttributeExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverAttributeExt.java index 2362a1ea9..9fb1919b6 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverAttributeExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverAttributeExt.java @@ -36,21 +36,21 @@ import lombok.Setter; @AllArgsConstructor public class DriverAttributeExt extends BaseExt { - /** - * - *

- * Type Version - */ - private Content content; + /** + * + *

+ * Type Version + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverExt.java index 63b6bab69..196090f69 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/DriverExt.java @@ -36,21 +36,21 @@ import lombok.Setter; @AllArgsConstructor public class DriverExt extends BaseExt { - /** - * - *

- * Type Version - */ - private Content content; + /** + * + *

+ * Type Version + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/JsonExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/JsonExt.java index 0dad79e3d..8e4867597 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/JsonExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/JsonExt.java @@ -37,28 +37,28 @@ import java.io.Serializable; @AllArgsConstructor public class JsonExt implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Type, Json - */ - private String type; + /** + * Type, Json + */ + private String type; - /** - * , Json - */ - private String content; + /** + * , Json + */ + private String content; - /** - * , - */ - @Builder.Default - private Integer version = 1; + /** + * , + */ + @Builder.Default + private Integer version = 1; - /** - * Description - */ - private String remark; + /** + * Description + */ + private String remark; } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MenuExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MenuExt.java index 3f6615a5e..55e74e097 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MenuExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MenuExt.java @@ -39,50 +39,50 @@ import java.util.Map; @AllArgsConstructor public class MenuExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - /** - * Localized titles keyed by locale code (e.g. {@code zh}, {@code en}). - *

- * Authoritative source for the menu display name. When rendering, the UI picks - * {@code titles[currentLocale]} with fallback to {@code titles["en"]}. - */ - private Map titles; + /** + * Localized titles keyed by locale code (e.g. {@code zh}, {@code en}). + *

+ * Authoritative source for the menu display name. When rendering, the UI picks + * {@code titles[currentLocale]} with fallback to {@code titles["en"]}. + */ + private Map titles; - /** - * Legacy i18n key (e.g. {@code nav.home}) kept only for backward compatibility - * with pre-multilingual menu records. New menus must populate {@link #titles} - * instead; the UI treats this as a final fallback when {@code titles} is empty. - */ - @Deprecated - private String title; + /** + * Legacy i18n key (e.g. {@code nav.home}) kept only for backward compatibility + * with pre-multilingual menu records. New menus must populate {@link #titles} + * instead; the UI treats this as a final fallback when {@code titles} is empty. + */ + @Deprecated + private String title; - /** - * Icon. - */ - private String icon; + /** + * Icon. + */ + private String icon; - /** - * URL link. - */ - private String url; + /** + * URL link. + */ + private String url; - /** - * Description. - */ - private String remark; + /** + * Description. + */ + private String remark; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MessageExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MessageExt.java index 14d764984..64c3a9ac5 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MessageExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/MessageExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class MessageExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/NotifyExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/NotifyExt.java index 026eb50c4..9660def30 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/NotifyExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/NotifyExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class NotifyExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointAttributeExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointAttributeExt.java index df1c59f93..42451b194 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointAttributeExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointAttributeExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class PointAttributeExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointExt.java index 8fa1b28ef..99da018d4 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/PointExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class PointExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ProfileExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ProfileExt.java index 9dbe87d5d..d5931645e 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ProfileExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ProfileExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class ProfileExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ResourceExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ResourceExt.java index 71bde7e76..248eec22c 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ResourceExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/ResourceExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class ResourceExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RoleExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RoleExt.java index fe289f18f..f2ba7e936 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RoleExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RoleExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class RoleExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RuleExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RuleExt.java index 00574af84..d5f9b483e 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RuleExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/RuleExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class RuleExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/TenantExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/TenantExt.java index 7a5cb2044..42e5aed24 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/TenantExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/TenantExt.java @@ -37,21 +37,21 @@ import lombok.Setter; @AllArgsConstructor public class TenantExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - private String keep; + private String keep; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserIdentityExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserIdentityExt.java index a629fea9d..6a9297a7a 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserIdentityExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserIdentityExt.java @@ -37,39 +37,39 @@ import lombok.Setter; @AllArgsConstructor public class UserIdentityExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - /** - * Real name. - */ - private String realName; + /** + * Real name. + */ + private String realName; - /** - * Gender. - */ - private String gender; + /** + * Gender. + */ + private String gender; - /** - * Nationality. - */ - private String nationality; + /** + * Nationality. + */ + private String nationality; - /** - * Identification number. - */ - private String idNumber; + /** + * Identification number. + */ + private String idNumber; - } + } } diff --git a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserSocialExt.java b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserSocialExt.java index ad6262d38..13475282f 100644 --- a/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserSocialExt.java +++ b/dc3-common/dc3-common-model/src/main/java/io/github/pnoker/common/entity/ext/UserSocialExt.java @@ -37,44 +37,44 @@ import lombok.Setter; @AllArgsConstructor public class UserSocialExt extends BaseExt { - /** - * Extended content. - *

- * The content can be distinguished by Type and Version. - */ - private Content content; + /** + * Extended content. + *

+ * The content can be distinguished by Type and Version. + */ + private Content content; - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Content { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Content { - /** - * WeChat account. - */ - private String wechat; + /** + * WeChat account. + */ + private String wechat; - /** - * QQ - */ - private String qq; + /** + * QQ + */ + private String qq; - /** - * Lark (Feishu) account. - */ - private String lark; + /** + * Lark (Feishu) account. + */ + private String lark; - /** - * DingTalk account. - */ - private String dingTalk; + /** + * DingTalk account. + */ + private String dingTalk; - /** - * Social home page URL. - */ - private String homeUrl; + /** + * Social home page URL. + */ + private String homeUrl; - } + } } diff --git a/dc3-common/dc3-common-mqtt/README.md b/dc3-common/dc3-common-mqtt/README.md index c4736513d..76216d7aa 100644 --- a/dc3-common/dc3-common-mqtt/README.md +++ b/dc3-common/dc3-common-mqtt/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-mqtt` is the shared MQTT client configuration module of the IoT DC3 platform. It provides auto-configuration for MQTT connection, message handling, and topic +`dc3-common-mqtt` is the shared MQTT client configuration module of the IoT DC3 platform. It provides auto-configuration +for MQTT connection, message handling, and topic subscription used by the MQTT driver and any service requiring MQTT connectivity. ## Module Information @@ -36,7 +37,8 @@ mqtt: ## Usage -This module is activated when the `mqtt` profile is included or MQTT-related auto-configuration is on the classpath. The MQTT driver (`dc3-driver-mqtt`) depends on this module as +This module is activated when the `mqtt` profile is included or MQTT-related auto-configuration is on the classpath. The +MQTT driver (`dc3-driver-mqtt`) depends on this module as its primary integration layer. ## Build Instructions diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/ActiveMqttProfileConfig.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/ActiveMqttProfileConfig.java index 70e4ebf18..d0ef74c56 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/ActiveMqttProfileConfig.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/ActiveMqttProfileConfig.java @@ -42,14 +42,14 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveMqttProfileConfig implements EnvironmentPostProcessor { - @Override - /** - * Post-process Spring environment to activate MQTT profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("mqtt"); - } + @Override + /** + * Post-process Spring environment to activate MQTT profile + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("mqtt"); + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttConfig.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttConfig.java index 1ad7f988c..3fb83353d 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttConfig.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttConfig.java @@ -52,86 +52,92 @@ import java.util.Objects; @Configuration public class MqttConfig { - private final MqttProperties mqttProperties; + private final MqttProperties mqttProperties; - /** - * Constructor for MQTT configuration - * @param mqttProperties MQTT configuration properties - */ - public MqttConfig(MqttProperties mqttProperties) { - this.mqttProperties = mqttProperties; - } + /** + * Constructor for MQTT configuration + * + * @param mqttProperties MQTT configuration properties + */ + public MqttConfig(MqttProperties mqttProperties) { + this.mqttProperties = mqttProperties; + } - /** - * MQTT inbound message channel bean - * @return DirectChannel for inbound MQTT messages - */ - @Bean - public MessageChannel mqttInboundChannel() { - return new DirectChannel(); - } + /** + * MQTT inbound message channel bean + * + * @return DirectChannel for inbound MQTT messages + */ + @Bean + public MessageChannel mqttInboundChannel() { + return new DirectChannel(); + } - /** - * MQTT outbound message channel bean - * @return DirectChannel for outbound MQTT messages - */ - @Bean - public MessageChannel mqttOutboundChannel() { - return new DirectChannel(); - } + /** + * MQTT outbound message channel bean + * + * @return DirectChannel for outbound MQTT messages + */ + @Bean + public MessageChannel mqttOutboundChannel() { + return new DirectChannel(); + } - /** - * MQTT client factory bean configuration - * @return Configured MqttPahoClientFactory with connection options - */ - @Bean - public MqttPahoClientFactory mqttClientFactory() { - DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); - factory.setConnectionOptions(MqttUtil.getMqttConnectOptions(mqttProperties)); - return factory; - } + /** + * MQTT client factory bean configuration + * + * @return Configured MqttPahoClientFactory with connection options + */ + @Bean + public MqttPahoClientFactory mqttClientFactory() { + DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); + factory.setConnectionOptions(MqttUtil.getMqttConnectOptions(mqttProperties)); + return factory; + } - /** - * MQTT inbound message producer bean configuration - * @param mqttClientFactory MQTT client factory - * @return Configured MessageProducer for MQTT inbound processing - */ - @Bean - public MessageProducer mqttInbound(MqttPahoClientFactory mqttClientFactory) { - if (Objects.isNull(mqttProperties.getReceiveTopics())) { - mqttProperties.setReceiveTopics(new ArrayList<>()); - } + /** + * MQTT inbound message producer bean configuration + * + * @param mqttClientFactory MQTT client factory + * @return Configured MessageProducer for MQTT inbound processing + */ + @Bean + public MessageProducer mqttInbound(MqttPahoClientFactory mqttClientFactory) { + if (Objects.isNull(mqttProperties.getReceiveTopics())) { + mqttProperties.setReceiveTopics(new ArrayList<>()); + } - mqttProperties.getReceiveTopics() - .forEach(topic -> topic.setName(mqttProperties.getTopicPrefix() + topic.getName())); - MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter( - mqttProperties.getClient() + "_in", mqttClientFactory, - mqttProperties.getReceiveTopics().stream().map(MqttProperties.Topic::getName).toArray(String[]::new)); - adapter.setQos(mqttProperties.getReceiveTopics().stream().mapToInt(MqttProperties.Topic::getQos).toArray()); - adapter.setOutputChannel(mqttInboundChannel()); - adapter.setConverter(new DefaultPahoMessageConverter()); - adapter.setCompletionTimeout(mqttProperties.getCompletionTimeout()); - log.info("Set receive topics: {}", JsonUtil.toJsonString(mqttProperties.getReceiveTopics())); - return adapter; - } + mqttProperties.getReceiveTopics() + .forEach(topic -> topic.setName(mqttProperties.getTopicPrefix() + topic.getName())); + MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter( + mqttProperties.getClient() + "_in", mqttClientFactory, + mqttProperties.getReceiveTopics().stream().map(MqttProperties.Topic::getName).toArray(String[]::new)); + adapter.setQos(mqttProperties.getReceiveTopics().stream().mapToInt(MqttProperties.Topic::getQos).toArray()); + adapter.setOutputChannel(mqttInboundChannel()); + adapter.setConverter(new DefaultPahoMessageConverter()); + adapter.setCompletionTimeout(mqttProperties.getCompletionTimeout()); + log.info("Set receive topics: {}", JsonUtil.toJsonString(mqttProperties.getReceiveTopics())); + return adapter; + } - /** - * MQTT outbound message handler bean configuration - * @param mqttClientFactory MQTT client factory - * @return Configured MessageHandler for MQTT outbound processing - */ - @Bean - @ServiceActivator(inputChannel = "mqttOutboundChannel") - public MessageHandler mqttOutbound(MqttPahoClientFactory mqttClientFactory) { - mqttProperties.getDefaultSendTopic() - .setName(mqttProperties.getTopicPrefix() + mqttProperties.getDefaultSendTopic().getName()); - MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClient() + "_out", - mqttClientFactory); - messageHandler.setAsync(true); - messageHandler.setDefaultQos(mqttProperties.getDefaultSendTopic().getQos()); - messageHandler.setDefaultTopic(mqttProperties.getDefaultSendTopic().getName()); - log.info("Set default send topic: {}", JsonUtil.toJsonString(mqttProperties.getDefaultSendTopic())); - return messageHandler; - } + /** + * MQTT outbound message handler bean configuration + * + * @param mqttClientFactory MQTT client factory + * @return Configured MessageHandler for MQTT outbound processing + */ + @Bean + @ServiceActivator(inputChannel = "mqttOutboundChannel") + public MessageHandler mqttOutbound(MqttPahoClientFactory mqttClientFactory) { + mqttProperties.getDefaultSendTopic() + .setName(mqttProperties.getTopicPrefix() + mqttProperties.getDefaultSendTopic().getName()); + MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperties.getClient() + "_out", + mqttClientFactory); + messageHandler.setAsync(true); + messageHandler.setDefaultQos(mqttProperties.getDefaultSendTopic().getQos()); + messageHandler.setDefaultTopic(mqttProperties.getDefaultSendTopic().getName()); + log.info("Set default send topic: {}", JsonUtil.toJsonString(mqttProperties.getDefaultSendTopic())); + return messageHandler; + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttEnvironmentConfig.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttEnvironmentConfig.java index fb7b5ea9b..7cc7b5d3c 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttEnvironmentConfig.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/config/MqttEnvironmentConfig.java @@ -50,28 +50,28 @@ import java.util.Map; @Configuration public class MqttEnvironmentConfig implements EnvironmentPostProcessor { - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - String node = environment.getProperty(EnvironmentConstant.DRIVER_NODE, String.class); - if (StringUtils.isEmpty(node)) { - node = EnvironmentUtil.getNodeId(); - } + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + String node = environment.getProperty(EnvironmentConstant.DRIVER_NODE, String.class); + if (StringUtils.isEmpty(node)) { + node = EnvironmentUtil.getNodeId(); + } - String tenant = environment.getProperty(EnvironmentConstant.DRIVER_TENANT, String.class); - String name = environment.getProperty(EnvironmentConstant.SPRING_APPLICATION_NAME, String.class); - String client = MessageFormat.format("{0}/{1}/{2}", tenant, name, node); + String tenant = environment.getProperty(EnvironmentConstant.DRIVER_TENANT, String.class); + String name = environment.getProperty(EnvironmentConstant.SPRING_APPLICATION_NAME, String.class); + String client = MessageFormat.format("{0}/{1}/{2}", tenant, name, node); - String prefix = environment.getProperty(EnvironmentConstant.MQTT_PREFIX, String.class); - if (StringUtils.isEmpty(node)) { - prefix = MessageFormat.format("dc3/{0}/{1}/", tenant, name); - } + String prefix = environment.getProperty(EnvironmentConstant.MQTT_PREFIX, String.class); + if (StringUtils.isEmpty(node)) { + prefix = MessageFormat.format("dc3/{0}/{1}/", tenant, name); + } - Map source = new HashMap<>(2); - source.put(EnvironmentConstant.DRIVER_NODE, node); - source.put(EnvironmentConstant.MQTT_CLIENT, client); - source.put(EnvironmentConstant.MQTT_PREFIX, prefix); - MutablePropertySources propertySources = environment.getPropertySources(); - propertySources.addFirst(new MapPropertySource("mqtt", source)); - } + Map source = new HashMap<>(2); + source.put(EnvironmentConstant.DRIVER_NODE, node); + source.put(EnvironmentConstant.MQTT_CLIENT, client); + source.put(EnvironmentConstant.MQTT_PREFIX, prefix); + MutablePropertySources propertySources = environment.getPropertySources(); + propertySources.addFirst(new MapPropertySource("mqtt", source)); + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/init/MqttInitRunner.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/init/MqttInitRunner.java index e8c937c7e..7538b9610 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/init/MqttInitRunner.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/init/MqttInitRunner.java @@ -36,29 +36,31 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.mqtt" }) -@EnableConfigurationProperties({ MqttProperties.class }) +@ComponentScan(basePackages = {"io.github.pnoker.common.mqtt"}) +@EnableConfigurationProperties({MqttProperties.class}) public class MqttInitRunner implements ApplicationRunner { - private final MqttScheduleService mqttScheduleService; + private final MqttScheduleService mqttScheduleService; - /** - * Creates a new MQTT initialization runner with the specified MQTT schedule service. - * @param mqttScheduleService The MQTT schedule service to be initialized - */ - public MqttInitRunner(MqttScheduleService mqttScheduleService) { - this.mqttScheduleService = mqttScheduleService; - } + /** + * Creates a new MQTT initialization runner with the specified MQTT schedule service. + * + * @param mqttScheduleService The MQTT schedule service to be initialized + */ + public MqttInitRunner(MqttScheduleService mqttScheduleService) { + this.mqttScheduleService = mqttScheduleService; + } - /** - * Executes the MQTT initialization process when the application starts. This method - * is called automatically by Spring Boot after the application context is loaded. - * @param args Application arguments passed during startup - * @throws Exception If an error occurs during MQTT initialization - */ - @Override - public void run(ApplicationArguments args) throws Exception { - mqttScheduleService.initial(); - } + /** + * Executes the MQTT initialization process when the application starts. This method + * is called automatically by Spring Boot after the application context is loaded. + * + * @param args Application arguments passed during startup + * @throws Exception If an error occurs during MQTT initialization + */ + @Override + public void run(ApplicationArguments args) throws Exception { + mqttScheduleService.initial(); + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MessageHeader.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MessageHeader.java index 9a17f489c..4443bc8fd 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MessageHeader.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MessageHeader.java @@ -43,48 +43,48 @@ import java.util.UUID; @Slf4j public class MessageHeader implements Serializable { - private UUID id; + private UUID id; - private Integer mqttId; + private Integer mqttId; - private Integer mqttReceivedQos; + private Integer mqttReceivedQos; - private String mqttReceivedTopic; + private String mqttReceivedTopic; - private Boolean mqttDuplicate; + private Boolean mqttDuplicate; - private Boolean mqttReceivedRetained; + private Boolean mqttReceivedRetained; - private Long timestamp; + private Long timestamp; - public MessageHeader(MessageHeaders messageHeaders) { - if (Objects.nonNull(messageHeaders)) { - this.id = messageHeaders.getId(); - this.mqttId = getMessageHeader(messageHeaders, "mqtt_id", Integer.class); - this.mqttReceivedQos = getMessageHeader(messageHeaders, "mqtt_receivedQos", Integer.class); - this.mqttReceivedTopic = getMessageHeader(messageHeaders, "mqtt_receivedTopic", String.class); - this.mqttDuplicate = getMessageHeader(messageHeaders, "mqtt_duplicate", Boolean.class); - this.mqttReceivedRetained = getMessageHeader(messageHeaders, "mqtt_receivedRetained", Boolean.class); - this.timestamp = getMessageHeader(messageHeaders, "timestamp", Long.class); - } - } + public MessageHeader(MessageHeaders messageHeaders) { + if (Objects.nonNull(messageHeaders)) { + this.id = messageHeaders.getId(); + this.mqttId = getMessageHeader(messageHeaders, "mqtt_id", Integer.class); + this.mqttReceivedQos = getMessageHeader(messageHeaders, "mqtt_receivedQos", Integer.class); + this.mqttReceivedTopic = getMessageHeader(messageHeaders, "mqtt_receivedTopic", String.class); + this.mqttDuplicate = getMessageHeader(messageHeaders, "mqtt_duplicate", Boolean.class); + this.mqttReceivedRetained = getMessageHeader(messageHeaders, "mqtt_receivedRetained", Boolean.class); + this.timestamp = getMessageHeader(messageHeaders, "timestamp", Long.class); + } + } - /** - * Get message header - * @param messageHeaders MessageHeaders - * @param key Header Key - * @param type Header Key Type - * @param Header Key Type - * @return Header Value - */ - private T getMessageHeader(MessageHeaders messageHeaders, String key, Class type) { - try { - return messageHeaders.get(key, type); - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - return null; - } + /** + * Get message header + * + * @param messageHeaders MessageHeaders + * @param key Header Key + * @param type Header Key Type + * @param Header Key Type + * @return Header Value + */ + private T getMessageHeader(MessageHeaders messageHeaders, String key, Class type) { + try { + return messageHeaders.get(key, type); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MqttMessage.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MqttMessage.java index 0d10b0c41..65ddba762 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MqttMessage.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/MqttMessage.java @@ -40,8 +40,8 @@ import java.io.Serializable; @AllArgsConstructor public class MqttMessage implements Serializable { - private MessageHeader header; + private MessageHeader header; - private String payload; + private String payload; } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/property/MqttProperties.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/property/MqttProperties.java index 018ea85e9..88c4a7edb 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/property/MqttProperties.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/entity/property/MqttProperties.java @@ -45,65 +45,65 @@ import java.util.List; @ConfigurationProperties(prefix = "driver.mqtt") public class MqttProperties { - @NotBlank(message = "Url can't be empty, ssl://host:port") - private String url; + @NotBlank(message = "Url can't be empty, ssl://host:port") + private String url; - @NotNull(message = "Auth type can't be empty") - private AuthTypeEnum authType = AuthTypeEnum.NONE; + @NotNull(message = "Auth type can't be empty") + private AuthTypeEnum authType = AuthTypeEnum.NONE; - private String username; + private String username; - private String password; + private String password; - private String caCrt = "classpath:/certs/ca.crt"; + private String caCrt = "classpath:/certs/ca.crt"; - private String clientKeyPass = "dc3-client"; + private String clientKeyPass = "dc3-client"; - private String clientKey = "classpath:/certs/client.key"; + private String clientKey = "classpath:/certs/client.key"; - private String clientCrt = "classpath:/certs/client.crt"; + private String clientCrt = "classpath:/certs/client.crt"; - @NotBlank(message = "Client name can't be empty") - private String client; + @NotBlank(message = "Client name can't be empty") + private String client; - @NotBlank(message = "Topic prefix name can't be empty") - private String topicPrefix; + @NotBlank(message = "Topic prefix name can't be empty") + private String topicPrefix; - @NotNull(message = "Default topic can't be empty") - private Topic defaultSendTopic = new Topic("dc3/d/v/dc3-driver-mqtt_default", 2); + @NotNull(message = "Default topic can't be empty") + private Topic defaultSendTopic = new Topic("dc3/d/v/dc3-driver-mqtt_default", 2); - @Size(min = 1, message = "Receive topic at least one topic") - private List receiveTopics; + @Size(min = 1, message = "Receive topic at least one topic") + private List receiveTopics; - @NotNull(message = "Keep alive interval can't be empty") - private Integer keepAlive = 15; + @NotNull(message = "Keep alive interval can't be empty") + private Integer keepAlive = 15; - @NotNull(message = "Completion timeout can't be empty") - private Integer completionTimeout = 3000; + @NotNull(message = "Completion timeout can't be empty") + private Integer completionTimeout = 3000; - /** - * MQTT authentication type enum - */ - @NoArgsConstructor - public enum AuthTypeEnum { + /** + * MQTT authentication type enum + */ + @NoArgsConstructor + public enum AuthTypeEnum { - NONE, CLIENT_ID, USERNAME, X509, + NONE, CLIENT_ID, USERNAME, X509, - } + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Topic { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Topic { - @NotBlank(message = "Topic name can't be empty") - private String name; + @NotBlank(message = "Topic name can't be empty") + private String name; - @Min(0) - @Max(2) - private Integer qos; + @Min(0) + @Max(2) + private Integer qos; - } + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/handler/MqttReceiveHandler.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/handler/MqttReceiveHandler.java index bf8b4d6da..79a1e7d45 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/handler/MqttReceiveHandler.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/handler/MqttReceiveHandler.java @@ -48,57 +48,56 @@ import java.util.concurrent.ExecutorService; @Component public class MqttReceiveHandler { - @Value("${driver.mqtt.batch.speed}") - private Integer batchSpeed; + @Value("${driver.mqtt.batch.speed}") + private Integer batchSpeed; - @Resource - private MqttReceiveService mqttReceiveService; + @Resource + private MqttReceiveService mqttReceiveService; - @Resource - private ExecutorService virtualThreadExecutor; + @Resource + private ExecutorService virtualThreadExecutor; - /** - * Configure MQTT inbound message handler bean - *

- * Receives data from MQTT; subscribed topics are defined in application.yml under - * mqtt.receive-topics + (plus): matches exactly one word # (hash): matches multiple - * words (or none) - * @return Configured MessageHandler for MQTT inbound processing - */ - @Bean - @ServiceActivator(inputChannel = "mqttInboundChannel") - public MessageHandler mqttInboundReceive() { - return message -> { - try { - MessageHeader messageHeader = new MessageHeader(message.getHeaders()); - String payload = message.getPayload().toString(); - if (StringUtils.isEmpty(payload)) { - log.error("Invalid mqtt inbound, From: {}, Qos: {}, Payload: null", - messageHeader.getMqttReceivedTopic(), messageHeader.getMqttReceivedQos()); - return; - } - MqttScheduleJob.messageCount.getAndIncrement(); - MqttMessage mqttMessage = MqttMessage.builder().header(messageHeader).payload(payload).build(); - log.debug("Mqtt inbound, From: {}, Qos: {}, Payload: {}", messageHeader.getMqttReceivedTopic(), - messageHeader.getMqttReceivedQos(), payload); + /** + * Configure MQTT inbound message handler bean + *

+ * Receives data from MQTT; subscribed topics are defined in application.yml under + * mqtt.receive-topics + (plus): matches exactly one word # (hash): matches multiple + * words (or none) + * + * @return Configured MessageHandler for MQTT inbound processing + */ + @Bean + @ServiceActivator(inputChannel = "mqttInboundChannel") + public MessageHandler mqttInboundReceive() { + return message -> { + try { + MessageHeader messageHeader = new MessageHeader(message.getHeaders()); + String payload = message.getPayload().toString(); + if (StringUtils.isEmpty(payload)) { + log.error("Invalid mqtt inbound, From: {}, Qos: {}, Payload: null", + messageHeader.getMqttReceivedTopic(), messageHeader.getMqttReceivedQos()); + return; + } + MqttScheduleJob.messageCount.getAndIncrement(); + MqttMessage mqttMessage = MqttMessage.builder().header(messageHeader).payload(payload).build(); + log.debug("Mqtt inbound, From: {}, Qos: {}, Payload: {}", messageHeader.getMqttReceivedTopic(), + messageHeader.getMqttReceivedQos(), payload); - // Determine whether to process data in batch based on transmission speed - if (MqttScheduleJob.messageSpeed.get() < batchSpeed) { - virtualThreadExecutor.execute(() -> - // Process single MQTT message - mqttReceiveService.receiveValue(mqttMessage)); - } - else { - // Save message to batch schedule for processing - MqttScheduleJob.messageLock.writeLock().lock(); - MqttScheduleJob.addMqttMessages(mqttMessage); - MqttScheduleJob.messageLock.writeLock().unlock(); - } - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - }; - } + // Determine whether to process data in batch based on transmission speed + if (MqttScheduleJob.messageSpeed.get() < batchSpeed) { + virtualThreadExecutor.execute(() -> + // Process single MQTT message + mqttReceiveService.receiveValue(mqttMessage)); + } else { + // Save message to batch schedule for processing + MqttScheduleJob.messageLock.writeLock().lock(); + MqttScheduleJob.addMqttMessages(mqttMessage); + MqttScheduleJob.messageLock.writeLock().unlock(); + } + } catch (Exception e) { + log.error(e.getMessage(), e); + } + }; + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttReceiveService.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttReceiveService.java index 4e4429a85..c03dd0bc7 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttReceiveService.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttReceiveService.java @@ -35,24 +35,26 @@ import java.util.List; */ public interface MqttReceiveService { - /** - * Must implement single-point processing logic - *

- * Parse incoming data into io.github.pnoker.common.bean.point.PointValue then call - * driverService.pointValueSender(pointValue) to publish data Tip: Refer to the - * dc3-driver-listening-virtual driver for examples - * @param mqttMessage MqttMessage - */ - void receiveValue(MqttMessage mqttMessage); + /** + * Must implement single-point processing logic + *

+ * Parse incoming data into io.github.pnoker.common.bean.point.PointValue then call + * driverService.pointValueSender(pointValue) to publish data Tip: Refer to the + * dc3-driver-listening-virtual driver for examples + * + * @param mqttMessage MqttMessage + */ + void receiveValue(MqttMessage mqttMessage); - /** - * Must implement batch processing logic - *

- * Parse incoming data into io.github.pnoker.common.bean.point.PointValue then call - * driverService.pointValueSender(pointValue) to publish data Tip: Refer to the - * dc3-driver-listening-virtual driver for examples - * @param mqttMessageList String Array List - */ - void receiveValues(List mqttMessageList); + /** + * Must implement batch processing logic + *

+ * Parse incoming data into io.github.pnoker.common.bean.point.PointValue then call + * driverService.pointValueSender(pointValue) to publish data Tip: Refer to the + * dc3-driver-listening-virtual driver for examples + * + * @param mqttMessageList String Array List + */ + void receiveValues(List mqttMessageList); } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttScheduleService.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttScheduleService.java index 3724ff162..326cb3235 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttScheduleService.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/MqttScheduleService.java @@ -30,9 +30,9 @@ package io.github.pnoker.common.mqtt.service; */ public interface MqttScheduleService { - /** - * Initialize scheduling tasks - */ - void initial(); + /** + * Initialize scheduling tasks + */ + void initial(); } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/impl/MqttScheduleServiceImpl.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/impl/MqttScheduleServiceImpl.java index c61f9bfbc..4bc49abc3 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/impl/MqttScheduleServiceImpl.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/impl/MqttScheduleServiceImpl.java @@ -42,23 +42,22 @@ import org.springframework.stereotype.Service; @Service public class MqttScheduleServiceImpl implements MqttScheduleService { - @Value("${driver.mqtt.batch.interval}") - private Integer interval; + @Value("${driver.mqtt.batch.interval}") + private Integer interval; - @Resource - private QuartzService quartzService; + @Resource + private QuartzService quartzService; - @Override - public void initial() { - try { - quartzService.createJobWithInterval("ScheduleGroup", "MqttScheduleJob", interval, - DateBuilder.IntervalUnit.SECOND, MqttScheduleJob.class); + @Override + public void initial() { + try { + quartzService.createJobWithInterval("ScheduleGroup", "MqttScheduleJob", interval, + DateBuilder.IntervalUnit.SECOND, MqttScheduleJob.class); - quartzService.startScheduler(); - } - catch (SchedulerException e) { - log.error(e.getMessage(), e); - } - } + quartzService.startScheduler(); + } catch (SchedulerException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/job/MqttScheduleJob.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/job/MqttScheduleJob.java index 00f92cb21..f2b91bd83 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/job/MqttScheduleJob.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/mqtt/service/job/MqttScheduleJob.java @@ -48,74 +48,76 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; @Component public class MqttScheduleJob extends QuartzJobBean { - public static final ReentrantReadWriteLock messageLock = new ReentrantReadWriteLock(); + public static final ReentrantReadWriteLock messageLock = new ReentrantReadWriteLock(); - public static final AtomicLong messageCount = new AtomicLong(0); + public static final AtomicLong messageCount = new AtomicLong(0); - public static final AtomicLong messageSpeed = new AtomicLong(0); + public static final AtomicLong messageSpeed = new AtomicLong(0); - private static final List mqttMessages = new ArrayList<>(); + private static final List mqttMessages = new ArrayList<>(); - @Value("${driver.mqtt.batch.speed}") - private Integer batchSpeed; + @Value("${driver.mqtt.batch.speed}") + private Integer batchSpeed; - @Value("${driver.mqtt.batch.interval}") - private Integer interval; + @Value("${driver.mqtt.batch.interval}") + private Integer interval; - @Resource - private MqttReceiveService mqttReceiveService; + @Resource + private MqttReceiveService mqttReceiveService; - @Resource - private ExecutorService virtualThreadExecutor; + @Resource + private ExecutorService virtualThreadExecutor; - /** - * Get MqttMessage list size - * @return message size - */ - public static int getMqttMessagesSize() { - return mqttMessages.size(); - } + /** + * Get MqttMessage list size + * + * @return message size + */ + public static int getMqttMessagesSize() { + return mqttMessages.size(); + } - /** - * Clear MqttMessage list - */ - public static void clearMqttMessages() { - mqttMessages.clear(); - } + /** + * Clear MqttMessage list + */ + public static void clearMqttMessages() { + mqttMessages.clear(); + } - /** - * Add MqttMessage to list - * @param mqttMessage MqttMessage - */ - public static void addMqttMessages(MqttMessage mqttMessage) { - mqttMessages.add(mqttMessage); - } + /** + * Add MqttMessage to list + * + * @param mqttMessage MqttMessage + */ + public static void addMqttMessages(MqttMessage mqttMessage) { + mqttMessages.add(mqttMessage); + } - @Override - /** - * Execute scheduled job for batch MQTT message processing - * @param context Job execution context - * @throws JobExecutionException if job execution fails - */ - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - // Calculate MQTT message receive rate - long speed = messageCount.getAndSet(0); - messageSpeed.set(speed); - speed /= interval; - if (speed >= batchSpeed) { - log.debug("Mqtt message receiver speed: {} /s, value size: {}, interval: {}", speed, getMqttMessagesSize(), - interval); - } + @Override + /** + * Execute scheduled job for batch MQTT message processing + * @param context Job execution context + * @throws JobExecutionException if job execution fails + */ + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + // Calculate MQTT message receive rate + long speed = messageCount.getAndSet(0); + messageSpeed.set(speed); + speed /= interval; + if (speed >= batchSpeed) { + log.debug("Mqtt message receiver speed: {} /s, value size: {}, interval: {}", speed, getMqttMessagesSize(), + interval); + } - // Process batch MQTT messages - virtualThreadExecutor.execute(() -> { - messageLock.writeLock().lock(); - if (!mqttMessages.isEmpty()) { - mqttReceiveService.receiveValues(mqttMessages); - clearMqttMessages(); - } - messageLock.writeLock().unlock(); - }); - } + // Process batch MQTT messages + virtualThreadExecutor.execute(() -> { + messageLock.writeLock().lock(); + if (!mqttMessages.isEmpty()) { + mqttReceiveService.receiveValues(mqttMessages); + clearMqttMessages(); + } + messageLock.writeLock().unlock(); + }); + } } diff --git a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/utils/MqttUtil.java b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/utils/MqttUtil.java index e3e56a3dc..556dcc209 100644 --- a/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/utils/MqttUtil.java +++ b/dc3-common/dc3-common-mqtt/src/main/java/io/github/pnoker/common/utils/MqttUtil.java @@ -35,44 +35,45 @@ import org.eclipse.paho.client.mqttv3.MqttConnectOptions; */ public class MqttUtil { - private MqttUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private MqttUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Create MQTT connection options based on properties - * @param mqttProperties MQTT configuration properties - * @return Configured MqttConnectOptions - */ - public static MqttConnectOptions getMqttConnectOptions(MqttProperties mqttProperties) { - MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); + /** + * Create MQTT connection options based on properties + * + * @param mqttProperties MQTT configuration properties + * @return Configured MqttConnectOptions + */ + public static MqttConnectOptions getMqttConnectOptions(MqttProperties mqttProperties) { + MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); - // Configure username & password authentication - if (MqttProperties.AuthTypeEnum.USERNAME.equals(mqttProperties.getAuthType()) - || MqttProperties.AuthTypeEnum.X509.equals(mqttProperties.getAuthType())) { - if (StringUtils.isNotEmpty(mqttProperties.getUsername())) { - mqttConnectOptions.setUserName(mqttProperties.getUsername()); - } - if (StringUtils.isNotEmpty(mqttProperties.getPassword())) { - mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray()); - } - } + // Configure username & password authentication + if (MqttProperties.AuthTypeEnum.USERNAME.equals(mqttProperties.getAuthType()) + || MqttProperties.AuthTypeEnum.X509.equals(mqttProperties.getAuthType())) { + if (StringUtils.isNotEmpty(mqttProperties.getUsername())) { + mqttConnectOptions.setUserName(mqttProperties.getUsername()); + } + if (StringUtils.isNotEmpty(mqttProperties.getPassword())) { + mqttConnectOptions.setPassword(mqttProperties.getPassword().toCharArray()); + } + } - // Configure TLS X509 certificate authentication - if (MqttProperties.AuthTypeEnum.X509.equals(mqttProperties.getAuthType())) { - mqttConnectOptions - .setSocketFactory(X509Util.getSSLSocketFactory(mqttProperties.getCaCrt(), mqttProperties.getClientCrt(), - mqttProperties.getClientKey(), StringUtils.isEmpty(mqttProperties.getClientKeyPass()) - ? StringUtils.EMPTY : mqttProperties.getClientKeyPass())); + // Configure TLS X509 certificate authentication + if (MqttProperties.AuthTypeEnum.X509.equals(mqttProperties.getAuthType())) { + mqttConnectOptions + .setSocketFactory(X509Util.getSSLSocketFactory(mqttProperties.getCaCrt(), mqttProperties.getClientCrt(), + mqttProperties.getClientKey(), StringUtils.isEmpty(mqttProperties.getClientKeyPass()) + ? StringUtils.EMPTY : mqttProperties.getClientKeyPass())); - } + } - // Disable HTTPS hostname verification - mqttConnectOptions.setHttpsHostnameVerificationEnabled(false); - mqttConnectOptions.setServerURIs(new String[] { mqttProperties.getUrl() }); - mqttConnectOptions.setKeepAliveInterval(mqttProperties.getKeepAlive()); - return mqttConnectOptions; + // Disable HTTPS hostname verification + mqttConnectOptions.setHttpsHostnameVerificationEnabled(false); + mqttConnectOptions.setServerURIs(new String[]{mqttProperties.getUrl()}); + mqttConnectOptions.setKeepAliveInterval(mqttProperties.getKeepAlive()); + return mqttConnectOptions; - } + } } diff --git a/dc3-common/dc3-common-postgres/README.md b/dc3-common/dc3-common-postgres/README.md index d265682d6..b709794ce 100644 --- a/dc3-common/dc3-common-postgres/README.md +++ b/dc3-common/dc3-common-postgres/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-postgres` is the shared PostgreSQL and MyBatis-Plus configuration module of the IoT DC3 platform. It auto-configures datasource, paging plugin, and common MyBatis +`dc3-common-postgres` is the shared PostgreSQL and MyBatis-Plus configuration module of the IoT DC3 platform. It +auto-configures datasource, paging plugin, and common MyBatis utility support for all services that use PostgreSQL as their primary storage. ## Module Information diff --git a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/ActivePostgresProfileConfig.java b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/ActivePostgresProfileConfig.java index 2d0e86f75..55d2f888e 100644 --- a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/ActivePostgresProfileConfig.java +++ b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/ActivePostgresProfileConfig.java @@ -42,14 +42,14 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActivePostgresProfileConfig implements EnvironmentPostProcessor { - @Override - /** - * Post-process the Spring environment to activate PostgreSQL profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("postgres"); - } + @Override + /** + * Post-process the Spring environment to activate PostgreSQL profile + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("postgres"); + } } diff --git a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/MybatisPlusConfig.java b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/MybatisPlusConfig.java index aa53bfebd..5f8257a01 100644 --- a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/MybatisPlusConfig.java +++ b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/config/MybatisPlusConfig.java @@ -40,15 +40,16 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement public class MybatisPlusConfig { - /** - * Pagination interceptor bean configuration - * @return Configured MybatisPlusInterceptor with PostgreSQL pagination support - */ - @Bean - public MybatisPlusInterceptor mybatisPlusInterceptor() { - MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); - interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL)); - return interceptor; - } + /** + * Pagination interceptor bean configuration + * + * @return Configured MybatisPlusInterceptor with PostgreSQL pagination support + */ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL)); + return interceptor; + } } diff --git a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/handler/TimestamptzLocalDateTimeTypeHandler.java b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/handler/TimestamptzLocalDateTimeTypeHandler.java index 9d1cc7fff..872e9c564 100644 --- a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/handler/TimestamptzLocalDateTimeTypeHandler.java +++ b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/handler/TimestamptzLocalDateTimeTypeHandler.java @@ -41,29 +41,29 @@ import java.time.OffsetDateTime; @MappedTypes(LocalDateTime.class) public class TimestamptzLocalDateTimeTypeHandler extends BaseTypeHandler { - @Override - public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) - throws SQLException { - ps.setObject(i, parameter.atZone(TimeConstant.DEFAULT_ZONEID).toOffsetDateTime()); - } + @Override + public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType) + throws SQLException { + ps.setObject(i, parameter.atZone(TimeConstant.DEFAULT_ZONEID).toOffsetDateTime()); + } - @Override - public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { - return toLocalDateTime(rs.getObject(columnName, OffsetDateTime.class)); - } + @Override + public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException { + return toLocalDateTime(rs.getObject(columnName, OffsetDateTime.class)); + } - @Override - public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException { - return toLocalDateTime(rs.getObject(columnIndex, OffsetDateTime.class)); - } + @Override + public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return toLocalDateTime(rs.getObject(columnIndex, OffsetDateTime.class)); + } - @Override - public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { - return toLocalDateTime(cs.getObject(columnIndex, OffsetDateTime.class)); - } + @Override + public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return toLocalDateTime(cs.getObject(columnIndex, OffsetDateTime.class)); + } - private LocalDateTime toLocalDateTime(OffsetDateTime odt) { - return odt == null ? null : odt.atZoneSameInstant(TimeConstant.DEFAULT_ZONEID).toLocalDateTime(); - } + private LocalDateTime toLocalDateTime(OffsetDateTime odt) { + return odt == null ? null : odt.atZoneSameInstant(TimeConstant.DEFAULT_ZONEID).toLocalDateTime(); + } } diff --git a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/utils/MybatisUtil.java b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/utils/MybatisUtil.java index 317bcd07d..c755d0c8f 100644 --- a/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/utils/MybatisUtil.java +++ b/dc3-common/dc3-common-postgres/src/main/java/io/github/pnoker/common/utils/MybatisUtil.java @@ -46,102 +46,106 @@ import java.sql.Types; @Slf4j public class MybatisUtil { - private MybatisUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private MybatisUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Default code generator for MyBatis-Plus - *

- * Database connection parameters can be overridden by environment variables - * @param defaultHost Default database host - * @param defaultPort Default database port - * @param defaultDb Default database name - * @param defaultSchema Default database schema - * @param defaultUsername Default database username - * @param defaultPassword Default database password - * @return Configured FastAutoGenerator instance - */ - public static FastAutoGenerator defaultGenerator(String defaultHost, String defaultPort, String defaultDb, - String defaultSchema, String defaultUsername, String defaultPassword) { - String host = System.getenv("POSTGRES_HOST"); - if (StringUtils.isEmpty(host)) { - host = defaultHost; - } - String port = System.getenv("POSTGRES_PORT"); - if (StringUtils.isEmpty(port)) { - port = defaultPort; - } - String db = System.getenv("POSTGRES_DB"); - if (StringUtils.isEmpty(db)) { - db = defaultDb; - } - String schema = System.getenv("POSTGRES_SCHEMA"); - if (StringUtils.isEmpty(schema)) { - schema = defaultSchema; - } - String username = System.getenv("POSTGRES_USERNAME"); - if (StringUtils.isEmpty(username)) { - username = defaultUsername; - } - String password = System.getenv("POSTGRES_PASSWORD"); - if (StringUtils.isEmpty(password)) { - password = defaultPassword; - } + /** + * Default code generator for MyBatis-Plus + *

+ * Database connection parameters can be overridden by environment variables + * + * @param defaultHost Default database host + * @param defaultPort Default database port + * @param defaultDb Default database name + * @param defaultSchema Default database schema + * @param defaultUsername Default database username + * @param defaultPassword Default database password + * @return Configured FastAutoGenerator instance + */ + public static FastAutoGenerator defaultGenerator(String defaultHost, String defaultPort, String defaultDb, + String defaultSchema, String defaultUsername, String defaultPassword) { + String host = System.getenv("POSTGRES_HOST"); + if (StringUtils.isEmpty(host)) { + host = defaultHost; + } + String port = System.getenv("POSTGRES_PORT"); + if (StringUtils.isEmpty(port)) { + port = defaultPort; + } + String db = System.getenv("POSTGRES_DB"); + if (StringUtils.isEmpty(db)) { + db = defaultDb; + } + String schema = System.getenv("POSTGRES_SCHEMA"); + if (StringUtils.isEmpty(schema)) { + schema = defaultSchema; + } + String username = System.getenv("POSTGRES_USERNAME"); + if (StringUtils.isEmpty(username)) { + username = defaultUsername; + } + String password = System.getenv("POSTGRES_PASSWORD"); + if (StringUtils.isEmpty(password)) { + password = defaultPassword; + } - return FastAutoGenerator.create( - String.format("jdbc:postgresql://%s:%s/%s?currentSchema=%s&useSSL=false", host, port, db, schema), - username, password); - } + return FastAutoGenerator.create( + String.format("jdbc:postgresql://%s:%s/%s?currentSchema=%s&useSSL=false", host, port, db, schema), + username, password); + } - /** - * Default global configuration for code generation - * @param builder GlobalConfig.Builder instance - * @param path Root directory for generated files - */ - public static void defaultGlobalConfig(GlobalConfig.Builder builder, String path) { - builder.outputDir(path + "/java") - .author(DefaultConstant.USER_NAME) - .commentDate(TimeConstant.DAY_DATE_FORMAT1) - .disableOpenDir(); - } + /** + * Default global configuration for code generation + * + * @param builder GlobalConfig.Builder instance + * @param path Root directory for generated files + */ + public static void defaultGlobalConfig(GlobalConfig.Builder builder, String path) { + builder.outputDir(path + "/java") + .author(DefaultConstant.USER_NAME) + .commentDate(TimeConstant.DAY_DATE_FORMAT1) + .disableOpenDir(); + } - /** - * Default data source configuration for code generation - * @param builder DataSourceConfig.Builder instance - */ - public static void defaultDataSourceConfig(DataSourceConfig.Builder builder) { - builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> { - int typeCode = metaInfo.getJdbcType().TYPE_CODE; - if (typeCode == Types.SMALLINT) { - return DbColumnType.BYTE; - } - return typeRegistry.getColumnType(metaInfo); - }); - } + /** + * Default data source configuration for code generation + * + * @param builder DataSourceConfig.Builder instance + */ + public static void defaultDataSourceConfig(DataSourceConfig.Builder builder) { + builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> { + int typeCode = metaInfo.getJdbcType().TYPE_CODE; + if (typeCode == Types.SMALLINT) { + return DbColumnType.BYTE; + } + return typeRegistry.getColumnType(metaInfo); + }); + } - /** - * Default strategy configuration for code generation - * @param builder StrategyConfig.Builder instance - */ - public static void defaultStrategyConfig(StrategyConfig.Builder builder) { - builder.addTablePrefix("dc3_") - .entityBuilder() - .idType(IdType.ASSIGN_ID) - .enableLombok() - .formatFileName("%sDO") - .enableTableFieldAnnotation() - .enableRemoveIsPrefix() - .enableFileOverride() - .logicDeleteColumnName("deleted") - .controllerBuilder() - .disable() - .serviceBuilder() - .formatServiceFileName("%sManager") - .formatServiceImplFileName("%sManagerImpl") - .enableFileOverride() - .mapperBuilder() - .enableFileOverride(); - } + /** + * Default strategy configuration for code generation + * + * @param builder StrategyConfig.Builder instance + */ + public static void defaultStrategyConfig(StrategyConfig.Builder builder) { + builder.addTablePrefix("dc3_") + .entityBuilder() + .idType(IdType.ASSIGN_ID) + .enableLombok() + .formatFileName("%sDO") + .enableTableFieldAnnotation() + .enableRemoveIsPrefix() + .enableFileOverride() + .logicDeleteColumnName("deleted") + .controllerBuilder() + .disable() + .serviceBuilder() + .formatServiceFileName("%sManager") + .formatServiceImplFileName("%sManagerImpl") + .enableFileOverride() + .mapperBuilder() + .enableFileOverride(); + } } diff --git a/dc3-common/dc3-common-public/README.md b/dc3-common/dc3-common-public/README.md index 46d0e075b..b10f210df 100644 --- a/dc3-common/dc3-common-public/README.md +++ b/dc3-common/dc3-common-public/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-public` is the foundational common utilities module of the IoT DC3 platform. It provides the universal response wrapper (`R`), base entity classes, JWT key +`dc3-common-public` is the foundational common utilities module of the IoT DC3 platform. It provides the universal +response wrapper (`R`), base entity classes, JWT key management, HTTP client configuration, and shared utility functions used across all platform modules. ## Module Information diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/base/service/BaseService.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/base/service/BaseService.java index 7b9ad9537..2d7382406 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/base/service/BaseService.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/base/service/BaseService.java @@ -33,36 +33,41 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; */ public interface BaseService { - /** - * Save entity to database - * @param entityBO Business object to save - */ - void save(B entityBO); + /** + * Save entity to database + * + * @param entityBO Business object to save + */ + void save(B entityBO); - /** - * Remove entity by ID - * @param id Entity ID to remove - */ - void remove(Long id); + /** + * Remove entity by ID + * + * @param id Entity ID to remove + */ + void remove(Long id); - /** - * Update existing entity - * @param entityBO Business object with updated data - */ - void update(B entityBO); + /** + * Update existing entity + * + * @param entityBO Business object with updated data + */ + void update(B entityBO); - /** - * Select entity by primary key - * @param id Entity ID to query - * @return Business object of the entity - */ - B selectById(Long id); + /** + * Select entity by primary key + * + * @param id Entity ID to query + * @return Business object of the entity + */ + B selectById(Long id); - /** - * Select entities with pagination - * @param entityQuery Query object with pagination parameters - * @return Paginated result of business objects - */ - Page selectByPage(Q entityQuery); + /** + * Select entities with pagination + * + * @param entityQuery Query object with pagination parameters + * @return Paginated result of business objects + */ + Page selectByPage(Q entityQuery); } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/config/OkHttpConfig.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/config/OkHttpConfig.java index 0c3e28cfa..e1fc33377 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/config/OkHttpConfig.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/config/OkHttpConfig.java @@ -41,20 +41,21 @@ import java.util.concurrent.TimeUnit; @Configuration public class OkHttpConfig { - /** - * Configure OkHttpClient bean with optimized settings - * @return Configured OkHttpClient instance - */ - @Bean - public OkHttpClient okHttpClient() { - ConnectionPool pool = new ConnectionPool(16, 5, TimeUnit.SECONDS); - return new OkHttpClient.Builder().retryOnConnectionFailure(true) - .connectionPool(pool) - .callTimeout(Duration.ofSeconds(15)) - .connectTimeout(Duration.ofSeconds(15)) - .readTimeout(Duration.ofSeconds(15)) - .writeTimeout(Duration.ofSeconds(15)) - .build(); - } + /** + * Configure OkHttpClient bean with optimized settings + * + * @return Configured OkHttpClient instance + */ + @Bean + public OkHttpClient okHttpClient() { + ConnectionPool pool = new ConnectionPool(16, 5, TimeUnit.SECONDS); + return new OkHttpClient.Builder().retryOnConnectionFailure(true) + .connectionPool(pool) + .callTimeout(Duration.ofSeconds(15)) + .connectTimeout(Duration.ofSeconds(15)) + .readTimeout(Duration.ofSeconds(15)) + .writeTimeout(Duration.ofSeconds(15)) + .build(); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/R.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/R.java index 755743c2f..6fb288a25 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/R.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/R.java @@ -43,236 +43,255 @@ import java.io.Serializable; @JsonInclude(JsonInclude.Include.NON_NULL) public class R implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Response status flag - */ - private boolean ok = false; + /** + * Response status flag + */ + private boolean ok = false; - /** - * Response status code - */ - private String code = ResponseEnum.OK.getCode(); + /** + * Response status code + */ + private String code = ResponseEnum.OK.getCode(); - /** - * Response message - */ - private String message = ResponseEnum.OK.getText(); + /** + * Response message + */ + private String message = ResponseEnum.OK.getText(); - /** - * Response data payload - */ - @SuppressWarnings("all") - private T data; + /** + * Response data payload + */ + @SuppressWarnings("all") + private T data; - /** - * Private default constructor - */ - private R() { - } + /** + * Private default constructor + */ + private R() { + } - /** - * Private constructor with data - * @param data Response data payload - */ - private R(T data) { - this.data = data; - } + /** + * Private constructor with data + * + * @param data Response data payload + */ + private R(T data) { + this.data = data; + } - /** - * Create success response with default settings - * @param Response data type - * @return Response with success status - */ - public static R ok() { - return new R().success(); - } + /** + * Create success response with default settings + * + * @param Response data type + * @return Response with success status + */ + public static R ok() { + return new R().success(); + } - /** - * Create success response with custom message - * @param Response data type - * @param message Custom success message - * @return Response with success status and custom message - */ - public static R ok(String message) { - return new R().success(message); - } + /** + * Create success response with custom message + * + * @param Response data type + * @param message Custom success message + * @return Response with success status and custom message + */ + public static R ok(String message) { + return new R().success(message); + } - /** - * Create success response with custom code and message - * @param Response data type - * @param code {@link ResponseEnum} custom response code - * @return Response with success status and custom code/message - */ - public static R ok(ResponseEnum code) { - return new R().success(code.getCode(), code.getText()); - } + /** + * Create success response with custom code and message + * + * @param Response data type + * @param code {@link ResponseEnum} custom response code + * @return Response with success status and custom code/message + */ + public static R ok(ResponseEnum code) { + return new R().success(code.getCode(), code.getText()); + } - /** - * Success response with custom code and message. - * @param Object - * @param code {@link ResponseEnum} - * @param message Success message - * @return Response - */ - public static R ok(ResponseEnum code, String message) { - return new R().success(code.getCode(), message); - } + /** + * Success response with custom code and message. + * + * @param Object + * @param code {@link ResponseEnum} + * @param message Success message + * @return Response + */ + public static R ok(ResponseEnum code, String message) { + return new R().success(code.getCode(), message); + } - /** - * Success response with data. - * @param Object - * @param data Response data - * @return Response - */ - public static R ok(T data) { - return new R(data).success(); - } + /** + * Success response with data. + * + * @param Object + * @param data Response data + * @return Response + */ + public static R ok(T data) { + return new R(data).success(); + } - /** - * Success response with data and custom message. - * @param Object - * @param data Response data - * @param message Success message - * @return Response - */ - public static R ok(T data, String message) { - return new R(data).success(message); - } + /** + * Success response with data and custom message. + * + * @param Object + * @param data Response data + * @param message Success message + * @return Response + */ + public static R ok(T data, String message) { + return new R(data).success(message); + } - /** - * Failure response with default settings. - * @param Object - * @return Response - */ - public static R fail() { - return new R().failure(); - } + /** + * Failure response with default settings. + * + * @param Object + * @return Response + */ + public static R fail() { + return new R().failure(); + } - /** - * Failure response with custom message. - * @param Object - * @param message Failure message - * @return Response - */ - public static R fail(String message) { - return new R().failure(message); - } + /** + * Failure response with custom message. + * + * @param Object + * @param message Failure message + * @return Response + */ + public static R fail(String message) { + return new R().failure(message); + } - /** - * Failure response with custom code. - * @param Object - * @param code {@link ResponseEnum} - * @return Response - */ - public static R fail(ResponseEnum code) { - return new R().failure(code.getCode(), code.getText()); - } + /** + * Failure response with custom code. + * + * @param Object + * @param code {@link ResponseEnum} + * @return Response + */ + public static R fail(ResponseEnum code) { + return new R().failure(code.getCode(), code.getText()); + } - /** - * Failure response with custom code and message. - * @param Object - * @param code {@link ResponseEnum} - * @param message Failure message - * @return Response - */ - public static R fail(ResponseEnum code, String message) { - return new R().failure(code.getCode(), message); - } + /** + * Failure response with custom code and message. + * + * @param Object + * @param code {@link ResponseEnum} + * @param message Failure message + * @return Response + */ + public static R fail(ResponseEnum code, String message) { + return new R().failure(code.getCode(), message); + } - /** - * Failure response with data. - * @param Object - * @param data Response data - * @return Response - */ - public static R fail(T data) { - return new R(data).failure(); - } + /** + * Failure response with data. + * + * @param Object + * @param data Response data + * @return Response + */ + public static R fail(T data) { + return new R(data).failure(); + } - /** - * Failure response with data and custom message. - * @param Object - * @param data Response data - * @param message Failure message - * @return Response - */ - public static R fail(T data, String message) { - return new R(data).failure(message); - } + /** + * Failure response with data and custom message. + * + * @param Object + * @param data Response data + * @param message Failure message + * @return Response + */ + public static R fail(T data, String message) { + return new R(data).failure(message); + } - /** - * Internal success handler with default settings. - * @return Response - */ - private R success() { - this.ok = true; - this.code = ResponseEnum.OK.getCode(); - this.message = ResponseEnum.OK.getText(); - return this; - } + /** + * Internal success handler with default settings. + * + * @return Response + */ + private R success() { + this.ok = true; + this.code = ResponseEnum.OK.getCode(); + this.message = ResponseEnum.OK.getText(); + return this; + } - /** - * Internal success handler with custom message. - * @param message Success message - * @return Response - */ - private R success(String message) { - this.ok = true; - this.code = ResponseEnum.OK.getCode(); - this.message = message; - return this; - } + /** + * Internal success handler with custom message. + * + * @param message Success message + * @return Response + */ + private R success(String message) { + this.ok = true; + this.code = ResponseEnum.OK.getCode(); + this.message = message; + return this; + } - /** - * Internal success handler with custom code and message. - * @param code Code - * @param message Success message - * @return Response - */ - private R success(String code, String message) { - this.ok = true; - this.code = code; - this.message = message; - return this; - } + /** + * Internal success handler with custom code and message. + * + * @param code Code + * @param message Success message + * @return Response + */ + private R success(String code, String message) { + this.ok = true; + this.code = code; + this.message = message; + return this; + } - /** - * Internal failure handler with default settings. - * @return Response - */ - private R failure() { - this.ok = false; - this.code = ResponseEnum.FAILURE.getCode(); - this.message = ResponseEnum.FAILURE.getText(); - return this; - } + /** + * Internal failure handler with default settings. + * + * @return Response + */ + private R failure() { + this.ok = false; + this.code = ResponseEnum.FAILURE.getCode(); + this.message = ResponseEnum.FAILURE.getText(); + return this; + } - /** - * Internal failure handler with custom message. - * @param message Error message - * @return Response - */ - private R failure(String message) { - this.ok = false; - this.code = ResponseEnum.FAILURE.getCode(); - this.message = message; - return this; - } + /** + * Internal failure handler with custom message. + * + * @param message Error message + * @return Response + */ + private R failure(String message) { + this.ok = false; + this.code = ResponseEnum.FAILURE.getCode(); + this.message = message; + return this; + } - /** - * Internal failure handler with custom code and message. - * @param code Code - * @param message Error message - * @return Response - */ - private R failure(String code, String message) { - this.ok = false; - this.code = code; - this.message = message; - return this; - } + /** + * Internal failure handler with custom code and message. + * + * @param code Code + * @param message Error message + * @return Response + */ + private R failure(String code, String message) { + this.ok = false; + this.code = code; + this.message = message; + return this; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/auth/Keys.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/auth/Keys.java index b0c9acda9..ef7a13c00 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/auth/Keys.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/auth/Keys.java @@ -36,36 +36,36 @@ import lombok.Setter; */ public class Keys { - private Keys() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private Keys() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * AES private key for symmetric encryption - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Aes { + /** + * AES private key for symmetric encryption + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Aes { - private String privateKey; + private String privateKey; - } + } - /** - * RSA key pair for asymmetric encryption - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class Rsa { + /** + * RSA key pair for asymmetric encryption + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class Rsa { - private String publicKey; + private String publicKey; - private String privateKey; + private String privateKey; - } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/Pages.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/Pages.java index 0d8a9380d..b520acdea 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/Pages.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/Pages.java @@ -43,17 +43,17 @@ import java.util.List; @Setter public class Pages implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private long current = 1; + private long current = 1; - private long size = DefaultConstant.PAGE_SIZE; + private long size = DefaultConstant.PAGE_SIZE; - private long startTime; + private long startTime; - private long endTime; + private long endTime; - private List orders = new ArrayList<>(2); + private List orders = new ArrayList<>(2); } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/RequestHeader.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/RequestHeader.java index 7ecab4155..6974d0215 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/RequestHeader.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/RequestHeader.java @@ -39,54 +39,54 @@ import lombok.Setter; @Setter public class RequestHeader { - private RequestHeader() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private RequestHeader() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class TokenHeader { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class TokenHeader { - /** - * Salt value for token encryption - */ - private String salt; + /** + * Salt value for token encryption + */ + private String salt; - /** - * JWT token string - */ - private String token; + /** + * JWT token string + */ + private String token; - } + } - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - public static class UserHeader { + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + public static class UserHeader { - /** - * User ID for identification - */ - private Long userId; + /** + * User ID for identification + */ + private Long userId; - /** - * User nickname or alias - */ - private String nickName; + /** + * User nickname or alias + */ + private String nickName; - /** - * User account name - */ - private String userName; + /** + * User account name + */ + private String userName; - /** - * Tenant ID for multi-tenant isolation - */ - private Long tenantId; + /** + * Tenant ID for multi-tenant isolation + */ + private Long tenantId; - } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/TreeNode.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/TreeNode.java index 30d9c5854..693b29b27 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/TreeNode.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/entity/common/TreeNode.java @@ -42,21 +42,22 @@ import java.util.List; @Setter public class TreeNode implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private int id; + private int id; - private int parentId; + private int parentId; - private List children = new ArrayList<>(16); + private List children = new ArrayList<>(16); - /** - * Add child node to current node - * @param node Tree node to add as child - */ - public void add(TreeNode node) { - children.add(node); - } + /** + * Add child node to current node + * + * @param node Tree node to add as child + */ + public void add(TreeNode node) { + children.add(node); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/CollectionOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/CollectionOptional.java index b73823e6b..4be9c1612 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/CollectionOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/CollectionOptional.java @@ -35,29 +35,28 @@ import java.util.function.Consumer; */ public final class CollectionOptional { - private final Collection value; + private final Collection value; - private CollectionOptional(Collection value) { - this.value = value; - } + private CollectionOptional(Collection value) { + this.value = value; + } - public static CollectionOptional ofNullable(Collection value) { - return new CollectionOptional<>(value); - } + public static CollectionOptional ofNullable(Collection value) { + return new CollectionOptional<>(value); + } - public void ifPresent(Consumer> action) { - if (CollectionUtils.isNotEmpty(value)) { - action.accept(value); - } - } + public void ifPresent(Consumer> action) { + if (CollectionUtils.isNotEmpty(value)) { + action.accept(value); + } + } - public void ifPresentOrElse(Consumer> action, Runnable emptyAction) { - if (CollectionUtils.isNotEmpty(value)) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(Consumer> action, Runnable emptyAction) { + if (CollectionUtils.isNotEmpty(value)) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/EnableOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/EnableOptional.java index 9a7443d8b..0dae12d66 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/EnableOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/EnableOptional.java @@ -35,37 +35,36 @@ import java.util.function.Consumer; */ public final class EnableOptional { - private final EnableFlagEnum value; + private final EnableFlagEnum value; - private EnableOptional(byte index) { - this.value = EnableFlagEnum.ofIndex(index); - } + private EnableOptional(byte index) { + this.value = EnableFlagEnum.ofIndex(index); + } - private EnableOptional(int index) { - this.value = EnableFlagEnum.ofIndex((byte) index); - } + private EnableOptional(int index) { + this.value = EnableFlagEnum.ofIndex((byte) index); + } - public static EnableOptional ofNullable(byte index) { - return new EnableOptional(index); - } + public static EnableOptional ofNullable(byte index) { + return new EnableOptional(index); + } - public static EnableOptional ofNullable(int index) { - return new EnableOptional(index); - } + public static EnableOptional ofNullable(int index) { + return new EnableOptional(index); + } - public void ifPresent(Consumer action) { - if (Objects.nonNull(value)) { - action.accept(value); - } - } + public void ifPresent(Consumer action) { + if (Objects.nonNull(value)) { + action.accept(value); + } + } - public void ifPresentOrElse(Consumer action, Runnable emptyAction) { - if (Objects.nonNull(value)) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(Consumer action, Runnable emptyAction) { + if (Objects.nonNull(value)) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/IntegerOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/IntegerOptional.java index 2cde14596..0adccdfa2 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/IntegerOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/IntegerOptional.java @@ -35,29 +35,28 @@ import java.util.function.IntConsumer; */ public final class IntegerOptional { - private final Integer value; + private final Integer value; - private IntegerOptional(Integer value) { - this.value = value; - } + private IntegerOptional(Integer value) { + this.value = value; + } - public static IntegerOptional ofNullable(Integer value) { - return new IntegerOptional(value); - } + public static IntegerOptional ofNullable(Integer value) { + return new IntegerOptional(value); + } - public void ifPresent(IntConsumer action) { - if (Objects.nonNull(value) && value > DefaultConstant.ZERO) { - action.accept(value); - } - } + public void ifPresent(IntConsumer action) { + if (Objects.nonNull(value) && value > DefaultConstant.ZERO) { + action.accept(value); + } + } - public void ifPresentOrElse(IntConsumer action, Runnable emptyAction) { - if (value > DefaultConstant.ZERO) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(IntConsumer action, Runnable emptyAction) { + if (value > DefaultConstant.ZERO) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/JsonOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/JsonOptional.java index e0f418685..925ef44c9 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/JsonOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/JsonOptional.java @@ -35,29 +35,28 @@ import java.util.function.Consumer; */ public final class JsonOptional { - private final String value; + private final String value; - private JsonOptional(String value) { - this.value = value; - } + private JsonOptional(String value) { + this.value = value; + } - public static JsonOptional ofNullable(String value) { - return new JsonOptional(value); - } + public static JsonOptional ofNullable(String value) { + return new JsonOptional(value); + } - public void ifPresent(Consumer action) { - if (StringUtils.isNotEmpty(value) && JsonUtil.isJson(value)) { - action.accept(value); - } - } + public void ifPresent(Consumer action) { + if (StringUtils.isNotEmpty(value) && JsonUtil.isJson(value)) { + action.accept(value); + } + } - public void ifPresentOrElse(Consumer action, Runnable emptyAction) { - if (StringUtils.isNotEmpty(value) && JsonUtil.isJson(value)) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(Consumer action, Runnable emptyAction) { + if (StringUtils.isNotEmpty(value) && JsonUtil.isJson(value)) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/LongOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/LongOptional.java index 430e3c8e3..0a18202a4 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/LongOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/LongOptional.java @@ -31,29 +31,28 @@ import java.util.function.LongConsumer; */ public final class LongOptional { - private final Long value; + private final Long value; - private LongOptional(Long value) { - this.value = value; - } + private LongOptional(Long value) { + this.value = value; + } - public static LongOptional ofNullable(Long value) { - return new LongOptional(value); - } + public static LongOptional ofNullable(Long value) { + return new LongOptional(value); + } - public void ifPresent(LongConsumer action) { - if (Objects.nonNull(value) && value > DefaultConstant.ZERO) { - action.accept(value); - } - } + public void ifPresent(LongConsumer action) { + if (Objects.nonNull(value) && value > DefaultConstant.ZERO) { + action.accept(value); + } + } - public void ifPresentOrElse(LongConsumer action, Runnable emptyAction) { - if (value > DefaultConstant.ZERO) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(LongConsumer action, Runnable emptyAction) { + if (value > DefaultConstant.ZERO) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/StringOptional.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/StringOptional.java index ec1aedc0c..fde04d84e 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/StringOptional.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/optional/StringOptional.java @@ -34,29 +34,28 @@ import java.util.function.Consumer; */ public final class StringOptional { - private final String value; + private final String value; - private StringOptional(String value) { - this.value = value; - } + private StringOptional(String value) { + this.value = value; + } - public static StringOptional ofNullable(String value) { - return new StringOptional(value); - } + public static StringOptional ofNullable(String value) { + return new StringOptional(value); + } - public void ifPresent(Consumer action) { - if (StringUtils.isNotEmpty(value)) { - action.accept(value); - } - } + public void ifPresent(Consumer action) { + if (StringUtils.isNotEmpty(value)) { + action.accept(value); + } + } - public void ifPresentOrElse(Consumer action, Runnable emptyAction) { - if (StringUtils.isNotEmpty(value)) { - action.accept(value); - } - else { - emptyAction.run(); - } - } + public void ifPresentOrElse(Consumer action, Runnable emptyAction) { + if (StringUtils.isNotEmpty(value)) { + action.accept(value); + } else { + emptyAction.run(); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ArithmeticUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ArithmeticUtil.java index a54a70d0a..2c4483938 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ArithmeticUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ArithmeticUtil.java @@ -36,192 +36,207 @@ import java.math.RoundingMode; */ public class ArithmeticUtil { - private ArithmeticUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ArithmeticUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Provide precise addition operation. - * @param value1 Augend - * @param value2 Addend - * @return Sum of the two parameters - */ - public static BigDecimal add(String value1, String value2) { - BigDecimal bigDecimal1 = new BigDecimal(value1); - BigDecimal bigDecimal2 = new BigDecimal(value2); - return bigDecimal1.add(bigDecimal2); - } + /** + * Provide precise addition operation. + * + * @param value1 Augend + * @param value2 Addend + * @return Sum of the two parameters + */ + public static BigDecimal add(String value1, String value2) { + BigDecimal bigDecimal1 = new BigDecimal(value1); + BigDecimal bigDecimal2 = new BigDecimal(value2); + return bigDecimal1.add(bigDecimal2); + } - /** - * Provide float addition operation. - * @param value1 Augend - * @param value2 Addend - * @return Sum of the two parameters - */ - public static float add(float value1, float value2) { - return add(Float.toString(value1), Float.toString(value2)).floatValue(); - } + /** + * Provide float addition operation. + * + * @param value1 Augend + * @param value2 Addend + * @return Sum of the two parameters + */ + public static float add(float value1, float value2) { + return add(Float.toString(value1), Float.toString(value2)).floatValue(); + } - /** - * Provide double addition operation. - * @param value1 Augend - * @param value2 Addend - * @return Sum of the two parameters - */ - public static double add(double value1, double value2) { - return add(Double.toString(value1), Double.toString(value2)).doubleValue(); - } + /** + * Provide double addition operation. + * + * @param value1 Augend + * @param value2 Addend + * @return Sum of the two parameters + */ + public static double add(double value1, double value2) { + return add(Double.toString(value1), Double.toString(value2)).doubleValue(); + } - /** - * Provide precise subtraction operation. - * @param value1 Minuend - * @param value2 Subtrahend - * @return Difference of the two parameters - */ - public static BigDecimal subtract(String value1, String value2) { - BigDecimal bigDecimal1 = new BigDecimal(value1); - BigDecimal bigDecimal2 = new BigDecimal(value2); - return bigDecimal1.subtract(bigDecimal2); - } + /** + * Provide precise subtraction operation. + * + * @param value1 Minuend + * @param value2 Subtrahend + * @return Difference of the two parameters + */ + public static BigDecimal subtract(String value1, String value2) { + BigDecimal bigDecimal1 = new BigDecimal(value1); + BigDecimal bigDecimal2 = new BigDecimal(value2); + return bigDecimal1.subtract(bigDecimal2); + } - /** - * Provide float subtraction operation. - * @param value1 Minuend - * @param value2 Subtrahend - * @return Difference of the two parameters - */ - public static float subtract(float value1, float value2) { - return subtract(Float.toString(value1), Float.toString(value2)).floatValue(); - } + /** + * Provide float subtraction operation. + * + * @param value1 Minuend + * @param value2 Subtrahend + * @return Difference of the two parameters + */ + public static float subtract(float value1, float value2) { + return subtract(Float.toString(value1), Float.toString(value2)).floatValue(); + } - /** - * Provide double subtraction operation. - * @param value1 Minuend - * @param value2 Subtrahend - * @return Difference of the two parameters - */ - public static double subtract(double value1, double value2) { - return subtract(Double.toString(value1), Double.toString(value2)).doubleValue(); - } + /** + * Provide double subtraction operation. + * + * @param value1 Minuend + * @param value2 Subtrahend + * @return Difference of the two parameters + */ + public static double subtract(double value1, double value2) { + return subtract(Double.toString(value1), Double.toString(value2)).doubleValue(); + } - /** - * Provide precise multiplication operation. - * @param value1 Multiplicand - * @param value2 Multiplier - * @return Product of the two parameters - */ - public static BigDecimal multiply(String value1, String value2) { - BigDecimal bigDecimal1 = new BigDecimal(value1); - BigDecimal bigDecimal2 = new BigDecimal(value2); - return bigDecimal1.multiply(bigDecimal2); - } + /** + * Provide precise multiplication operation. + * + * @param value1 Multiplicand + * @param value2 Multiplier + * @return Product of the two parameters + */ + public static BigDecimal multiply(String value1, String value2) { + BigDecimal bigDecimal1 = new BigDecimal(value1); + BigDecimal bigDecimal2 = new BigDecimal(value2); + return bigDecimal1.multiply(bigDecimal2); + } - /** - * Provide float multiplication operation. - * @param value1 Multiplicand - * @param value2 Multiplier - * @return Product of the two parameters - */ - public static float multiply(float value1, float value2) { - return multiply(Float.toString(value1), Float.toString(value2)).floatValue(); - } + /** + * Provide float multiplication operation. + * + * @param value1 Multiplicand + * @param value2 Multiplier + * @return Product of the two parameters + */ + public static float multiply(float value1, float value2) { + return multiply(Float.toString(value1), Float.toString(value2)).floatValue(); + } - /** - * Provide double multiplication operation. - * @param value1 Multiplicand - * @param value2 Multiplier - * @return Product of the two parameters - */ - public static double multiply(double value1, double value2) { - return multiply(Double.toString(value1), Double.toString(value2)).doubleValue(); - } + /** + * Provide double multiplication operation. + * + * @param value1 Multiplicand + * @param value2 Multiplier + * @return Product of the two parameters + */ + public static double multiply(double value1, double value2) { + return multiply(Double.toString(value1), Double.toString(value2)).doubleValue(); + } - /** - * Provide (relatively) precise division operation. - *

- * When an inexact division occurs, the {@code scale} parameter specifies the - * precision, and the result is rounded using the half-up rule. - * @param value1 Dividend - * @param value2 Divisor - * @param scale Number of decimal places to keep - * @return Quotient of the two parameters - */ - public static BigDecimal divide(String value1, String value2, int scale) { - BigDecimal bigDecimal1 = new BigDecimal(value1); - BigDecimal bigDecimal2 = new BigDecimal(value2); - return bigDecimal1.divide(bigDecimal2, scale, RoundingMode.HALF_UP); - } + /** + * Provide (relatively) precise division operation. + *

+ * When an inexact division occurs, the {@code scale} parameter specifies the + * precision, and the result is rounded using the half-up rule. + * + * @param value1 Dividend + * @param value2 Divisor + * @param scale Number of decimal places to keep + * @return Quotient of the two parameters + */ + public static BigDecimal divide(String value1, String value2, int scale) { + BigDecimal bigDecimal1 = new BigDecimal(value1); + BigDecimal bigDecimal2 = new BigDecimal(value2); + return bigDecimal1.divide(bigDecimal2, scale, RoundingMode.HALF_UP); + } - /** - * Provide float division operation. - *

- * When an inexact division occurs, the {@code scale} parameter specifies the - * precision, and the result is rounded using the half-up rule. - * @param value1 Dividend - * @param value2 Divisor - * @param scale Number of decimal places to keep - * @return Quotient of the two parameters - */ - public static float divide(float value1, float value2, int scale) { - if (scale < 0 || scale > 7) { - throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 7)"); - } - return divide(Float.toString(value1), Float.toString(value2), scale).floatValue(); - } + /** + * Provide float division operation. + *

+ * When an inexact division occurs, the {@code scale} parameter specifies the + * precision, and the result is rounded using the half-up rule. + * + * @param value1 Dividend + * @param value2 Divisor + * @param scale Number of decimal places to keep + * @return Quotient of the two parameters + */ + public static float divide(float value1, float value2, int scale) { + if (scale < 0 || scale > 7) { + throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 7)"); + } + return divide(Float.toString(value1), Float.toString(value2), scale).floatValue(); + } - /** - * Provide double division operation. - *

- * When an inexact division occurs, the {@code scale} parameter specifies the - * precision, and the result is rounded using the half-up rule. - * @param value1 Dividend - * @param value2 Divisor - * @param scale Number of decimal places to keep - * @return Quotient of the two parameters - */ - public static double divide(double value1, double value2, int scale) { - if (scale < 0 || scale > 16) { - throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 16)"); - } - return divide(Double.toString(value1), Double.toString(value2), scale).doubleValue(); - } + /** + * Provide double division operation. + *

+ * When an inexact division occurs, the {@code scale} parameter specifies the + * precision, and the result is rounded using the half-up rule. + * + * @param value1 Dividend + * @param value2 Divisor + * @param scale Number of decimal places to keep + * @return Quotient of the two parameters + */ + public static double divide(double value1, double value2, int scale) { + if (scale < 0 || scale > 16) { + throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 16)"); + } + return divide(Double.toString(value1), Double.toString(value2), scale).doubleValue(); + } - /** - * Provide precise decimal rounding operation. - * @param value Number to be rounded - * @param scale Number of decimal places to keep - * @return Rounded result - */ - public static BigDecimal round(String value, int scale) { - BigDecimal bigDecimal = new BigDecimal(value); - BigDecimal tmp = new BigDecimal("1"); - return bigDecimal.divide(tmp, scale, RoundingMode.HALF_UP); - } + /** + * Provide precise decimal rounding operation. + * + * @param value Number to be rounded + * @param scale Number of decimal places to keep + * @return Rounded result + */ + public static BigDecimal round(String value, int scale) { + BigDecimal bigDecimal = new BigDecimal(value); + BigDecimal tmp = new BigDecimal("1"); + return bigDecimal.divide(tmp, scale, RoundingMode.HALF_UP); + } - /** - * Provide float decimal rounding operation. - * @param value Number to be rounded - * @param scale Number of decimal places to keep - * @return Rounded result - */ - public static float round(float value, int scale) { - if (scale < 0 || scale > 7) { - throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 7)"); - } - return round(Float.toString(value), scale).floatValue(); - } + /** + * Provide float decimal rounding operation. + * + * @param value Number to be rounded + * @param scale Number of decimal places to keep + * @return Rounded result + */ + public static float round(float value, int scale) { + if (scale < 0 || scale > 7) { + throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 7)"); + } + return round(Float.toString(value), scale).floatValue(); + } - /** - * Provide double decimal rounding operation. - * @param value Number to be rounded - * @param scale Number of decimal places to keep - * @return Rounded result - */ - public static double round(double value, int scale) { - if (scale < 0 || scale > 16) { - throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 16)"); - } - return round(Double.toString(value), scale).doubleValue(); - } + /** + * Provide double decimal rounding operation. + * + * @param value Number to be rounded + * @param scale Number of decimal places to keep + * @return Rounded result + */ + public static double round(double value, int scale) { + if (scale < 0 || scale > 16) { + throw new IllegalArgumentException("The scale must be a positive integer(0 ~ 16)"); + } + return round(Double.toString(value), scale).doubleValue(); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CmdUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CmdUtil.java index b3c2f8306..64b2a6982 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CmdUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CmdUtil.java @@ -39,29 +39,29 @@ import java.io.OutputStreamWriter; @Slf4j public class CmdUtil { - private CmdUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private CmdUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Destroy process with exit command Writes the command to process output stream and - * forcibly destroys the process - * @param process Process to destroy - * @param cmd Exit command to send before destroying - */ - public static void destroyProcessWithCmd(Process process, String cmd) { - BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); - try { - if (!cmd.equals(StringUtils.EMPTY)) { - writer.write(cmd); - writer.flush(); - writer.close(); - } - process.destroyForcibly(); - } - catch (IOException e) { - log.error(e.getMessage(), e); - } - } + /** + * Destroy process with exit command Writes the command to process output stream and + * forcibly destroys the process + * + * @param process Process to destroy + * @param cmd Exit command to send before destroying + */ + public static void destroyProcessWithCmd(Process process, String cmd) { + BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream())); + try { + if (!cmd.equals(StringUtils.EMPTY)) { + writer.write(cmd); + writer.flush(); + writer.close(); + } + process.destroyForcibly(); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CodeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CodeUtil.java index 7c929705c..e3610de85 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CodeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/CodeUtil.java @@ -36,16 +36,17 @@ import java.util.UUID; @Slf4j public class CodeUtil { - private CodeUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private CodeUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Generate a simplified UUID as a unique code. - * @return Simplified UUID string - */ - public static String getCode() { - return UUID.randomUUID().toString(); - } + /** + * Generate a simplified UUID as a unique code. + * + * @return Simplified UUID string + */ + public static String getCode() { + return UUID.randomUUID().toString(); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/DecodeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/DecodeUtil.java index 79a851135..462641b14 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/DecodeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/DecodeUtil.java @@ -40,99 +40,109 @@ import java.util.HexFormat; @Slf4j public class DecodeUtil { - private DecodeUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private DecodeUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Convert byte array to string using UTF-8 encoding - * @param bytes Byte array to convert - * @return String representation of byte array - */ - public static String byteToString(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } + /** + * Convert byte array to string using UTF-8 encoding + * + * @param bytes Byte array to convert + * @return String representation of byte array + */ + public static String byteToString(byte[] bytes) { + return new String(bytes, StandardCharsets.UTF_8); + } - /** - * Convert string to byte array using UTF-8 encoding - * @param content String to convert - * @return Byte array representation of string - */ - public static byte[] stringToByte(String content) { - return content.getBytes(StandardCharsets.UTF_8); - } + /** + * Convert string to byte array using UTF-8 encoding + * + * @param content String to convert + * @return Byte array representation of string + */ + public static byte[] stringToByte(String content) { + return content.getBytes(StandardCharsets.UTF_8); + } - /** - * Generate MD5 hash of content - * @param content String to hash - * @return MD5 hash string - */ - public static String md5(String content) { - return DigestUtils.md5Hex(content); - } + /** + * Generate MD5 hash of content + * + * @param content String to hash + * @return MD5 hash string + */ + public static String md5(String content) { + return DigestUtils.md5Hex(content); + } - /** - * Generate MD5 hash of content with salt - * @param content String to hash - * @param salt Salt value for additional security - * @return MD5 hash string - */ - public static String md5(String content, String salt) { - return md5(content + salt); - } + /** + * Generate MD5 hash of content with salt + * + * @param content String to hash + * @param salt Salt value for additional security + * @return MD5 hash string + */ + public static String md5(String content, String salt) { + return md5(content + salt); + } - /** - * Encode byte array using Base64 encoding - * @param bytes Byte array to encode - * @return Base64 encoded byte array - */ - public static byte[] encode(byte[] bytes) { - return Base64.getEncoder().encode(bytes); - } + /** + * Encode byte array using Base64 encoding + * + * @param bytes Byte array to encode + * @return Base64 encoded byte array + */ + public static byte[] encode(byte[] bytes) { + return Base64.getEncoder().encode(bytes); + } - /** - * Encode string using Base64 encoding - * @param content String to encode - * @return Base64 encoded byte array - */ - public static byte[] encode(String content) { - return encode(stringToByte(content)); - } + /** + * Encode string using Base64 encoding + * + * @param content String to encode + * @return Base64 encoded byte array + */ + public static byte[] encode(String content) { + return encode(stringToByte(content)); + } - /** - * Decode Base64 encoded byte array Must be used with encode method - * @param bytes Base64 encoded byte array - * @return Decoded byte array - */ - public static byte[] decode(byte[] bytes) { - return Base64.getDecoder().decode(bytes); - } + /** + * Decode Base64 encoded byte array Must be used with encode method + * + * @param bytes Base64 encoded byte array + * @return Decoded byte array + */ + public static byte[] decode(byte[] bytes) { + return Base64.getDecoder().decode(bytes); + } - /** - * Decode Base64 encoded string Must be used with encode method - * @param content Base64 encoded string - * @return Decoded byte array - */ - public static byte[] decode(String content) { - return decode(stringToByte(content)); - } + /** + * Decode Base64 encoded string Must be used with encode method + * + * @param content Base64 encoded string + * @return Decoded byte array + */ + public static byte[] decode(String content) { + return decode(stringToByte(content)); + } - /** - * Encode string to hexadecimal representation - * @param content String to encode - * @return Hexadecimal string representation - */ - public static String enHexCode(String content) { - return HexFormat.of().formatHex((stringToByte(content))); - } + /** + * Encode string to hexadecimal representation + * + * @param content String to encode + * @return Hexadecimal string representation + */ + public static String enHexCode(String content) { + return HexFormat.of().formatHex((stringToByte(content))); + } - /** - * Decode hexadecimal string to byte array Must be used with enHexCode method - * @param content Hexadecimal string to decode - * @return Decoded byte array - */ - public static byte[] deHexCode(String content) { - return HexFormat.of().parseHex(content); - } + /** + * Decode hexadecimal string to byte array Must be used with enHexCode method + * + * @param content Hexadecimal string to decode + * @return Decoded byte array + */ + public static byte[] deHexCode(String content) { + return HexFormat.of().parseHex(content); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/EnvironmentUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/EnvironmentUtil.java index 374382f71..8a0753d83 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/EnvironmentUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/EnvironmentUtil.java @@ -39,40 +39,43 @@ import java.util.UUID; @Slf4j public class EnvironmentUtil { - private EnvironmentUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private EnvironmentUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get a unique node ID. - * @return Node ID string - */ - public static String getNodeId() { - return UUID.randomUUID().toString(); - } + /** + * Get a unique node ID. + * + * @return Node ID string + */ + public static String getNodeId() { + return UUID.randomUUID().toString(); + } - /** - * Get the topic tag. In the development environment, it is used to distinguish - * multi-person development. - * @param env Environment type - * @param group Group identifier - * @return Topic tag string - */ - public static String getTag(String env, String group) { - String exchangeTag = ""; - if (isDev(env)) { - exchangeTag = env.toLowerCase() + SymbolConstant.UNDERSCORE + group.toLowerCase() + SymbolConstant.DOT; - } - return exchangeTag; - } + /** + * Get the topic tag. In the development environment, it is used to distinguish + * multi-person development. + * + * @param env Environment type + * @param group Group identifier + * @return Topic tag string + */ + public static String getTag(String env, String group) { + String exchangeTag = ""; + if (isDev(env)) { + exchangeTag = env.toLowerCase() + SymbolConstant.UNDERSCORE + group.toLowerCase() + SymbolConstant.DOT; + } + return exchangeTag; + } - /** - * Check whether the current environment is a development environment. - * @param env Environment type - * @return true if it is a development environment, false otherwise - */ - public static boolean isDev(String env) { - return EnvironmentConstant.ENV_DEV.equals(env); - } + /** + * Check whether the current environment is a development environment. + * + * @param env Environment type + * @return true if it is a development environment, false otherwise + */ + public static boolean isDev(String env) { + return EnvironmentConstant.ENV_DEV.equals(env); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FieldUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FieldUtil.java index 51588dcc2..a2483c23c 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FieldUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FieldUtil.java @@ -42,37 +42,40 @@ import java.util.Objects; @Slf4j public class FieldUtil { - private FieldUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private FieldUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get the field name mapping from a lambda expression. - * @param column Lambda object to be parsed - * @param Object type - * @return Field name - */ - public static String getField(SFunction column) { - LambdaMeta meta = LambdaUtils.extract(column); - return PropertyNamer.methodToProperty(meta.getImplMethodName()); - } + /** + * Get the field name mapping from a lambda expression. + * + * @param column Lambda object to be parsed + * @param Object type + * @return Field name + */ + public static String getField(SFunction column) { + LambdaMeta meta = LambdaUtils.extract(column); + return PropertyNamer.methodToProperty(meta.getImplMethodName()); + } - /** - * Determine whether the given ID field is valid. - * @param id ID - * @return Whether the ID is valid - */ - public static boolean isValidIdField(Long id) { - return Objects.nonNull(id) && id > DefaultConstant.ZERO; - } + /** + * Determine whether the given ID field is valid. + * + * @param id ID + * @return Whether the ID is valid + */ + public static boolean isValidIdField(Long id) { + return Objects.nonNull(id) && id > DefaultConstant.ZERO; + } - /** - * Determine whether the given enum index field is valid. - * @param id ID - * @return Whether the enum index is valid - */ - public static boolean isValidEnumIndexField(Byte id) { - return Objects.nonNull(id) && id > DefaultConstant.ZERO; - } + /** + * Determine whether the given enum index field is valid. + * + * @param id ID + * @return Whether the enum index is valid + */ + public static boolean isValidEnumIndexField(Byte id) { + return Objects.nonNull(id) && id > DefaultConstant.ZERO; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FileUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FileUtil.java index 3e1d74a30..bc2751546 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FileUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/FileUtil.java @@ -41,34 +41,35 @@ import java.util.UUID; @Slf4j public class FileUtil { - private FileUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private FileUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get temporary upload file directory - * @return Temporary upload file directory path - */ - public static String getTempPath() { - String path = FolderConstant.TEMP_FILE_PATH; - Path dir = Paths.get(path); - if (Files.notExists(dir) || !Files.isDirectory(dir)) { - try { - Files.createDirectories(dir); - } - catch (IOException e) { - log.error(e.getMessage(), e); - } - } - return path; - } + /** + * Get temporary upload file directory + * + * @return Temporary upload file directory path + */ + public static String getTempPath() { + String path = FolderConstant.TEMP_FILE_PATH; + Path dir = Paths.get(path); + if (Files.notExists(dir) || !Files.isDirectory(dir)) { + try { + Files.createDirectories(dir); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } + return path; + } - /** - * Generate random XLSX file name - * @return Random XLSX file name with UUID - */ - public static String getRandomXlsxName() { - return UUID.randomUUID().toString() + ".xlsx"; - } + /** + * Generate random XLSX file name + * + * @return Random XLSX file name with UUID + */ + public static String getRandomXlsxName() { + return UUID.randomUUID().toString() + ".xlsx"; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/HostUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/HostUtil.java index 00330fe6a..278cae0d9 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/HostUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/HostUtil.java @@ -20,14 +20,8 @@ package io.github.pnoker.common.utils; import io.github.pnoker.common.constant.common.ExceptionConstant; import lombok.extern.slf4j.Slf4j; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.net.*; +import java.util.*; /** * Host Utility Class @@ -43,141 +37,143 @@ import java.util.Set; @Slf4j public class HostUtil { - private HostUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private HostUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get the local host address of the current machine. - * @return Local host IP address as String, or {@code null} if unavailable - */ - public static String localHost() { - try { - InetAddress address = InetAddress.getLocalHost(); - return address.getHostAddress(); - } - catch (Exception e) { - log.error(e.getMessage(), e); - } - return null; - } + /** + * Get the local host address of the current machine. + * + * @return Local host IP address as String, or {@code null} if unavailable + */ + public static String localHost() { + try { + InetAddress address = InetAddress.getLocalHost(); + return address.getHostAddress(); + } catch (Exception e) { + log.error(e.getMessage(), e); + } + return null; + } - /** - * Given an address resolve it to as many unique addresses or hostnames as can be - * found. - * @param address the address to resolve. - * @return the addresses and hostnames that were resolved from {@code address}. - */ - public static Set getHostNames(String address) { - return getHostNames(address, true); - } + /** + * Given an address resolve it to as many unique addresses or hostnames as can be + * found. + * + * @param address the address to resolve. + * @return the addresses and hostnames that were resolved from {@code address}. + */ + public static Set getHostNames(String address) { + return getHostNames(address, true); + } - /** - * Given an address resolve it to as many unique addresses or hostnames as can be - * found. - * @param address the address to resolve. - * @param includeLoopBack if {@code true} loopback addresses will be included in the - * returned set. - * @return the addresses and hostnames that were resolved from {@code address}. - */ - public static Set getHostNames(String address, boolean includeLoopBack) { - Set hostNames = new HashSet<>(4); + /** + * Given an address resolve it to as many unique addresses or hostnames as can be + * found. + * + * @param address the address to resolve. + * @param includeLoopBack if {@code true} loopback addresses will be included in the + * returned set. + * @return the addresses and hostnames that were resolved from {@code address}. + */ + public static Set getHostNames(String address, boolean includeLoopBack) { + Set hostNames = new HashSet<>(4); - try { - InetAddress inetAddress = InetAddress.getByName(address); + try { + InetAddress inetAddress = InetAddress.getByName(address); - if (inetAddress.isAnyLocalAddress()) { - loopBackAddresses(hostNames, includeLoopBack); - } - else { - boolean loopback = inetAddress.isLoopbackAddress(); + if (inetAddress.isAnyLocalAddress()) { + loopBackAddresses(hostNames, includeLoopBack); + } else { + boolean loopback = inetAddress.isLoopbackAddress(); - if (!loopback || includeLoopBack) { - hostNames.add(inetAddress.getHostName()); - hostNames.add(inetAddress.getHostAddress()); - hostNames.add(inetAddress.getCanonicalHostName()); - } - } - } - catch (UnknownHostException | SocketException e) { - log.warn("Failed to get hostname for bind address: {}", address, e); - } + if (!loopback || includeLoopBack) { + hostNames.add(inetAddress.getHostName()); + hostNames.add(inetAddress.getHostAddress()); + hostNames.add(inetAddress.getCanonicalHostName()); + } + } + } catch (UnknownHostException | SocketException e) { + log.warn("Failed to get hostname for bind address: {}", address, e); + } - return hostNames; - } + return hostNames; + } - /** - * Get the list of MAC (physical) addresses of the current machine. - * @return List of MAC addresses - */ - public static List localMacList() { - ArrayList macList = new ArrayList<>(16); - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - while (interfaces.hasMoreElements()) { - NetworkInterface networkInterface = interfaces.nextElement(); - lookupLocalMac(macList, networkInterface); - } - if (!macList.isEmpty()) { - return macList.stream().distinct().toList(); - } - } - catch (Exception e) { - log.warn("Failed to get local mac address"); - } - return macList; - } + /** + * Get the list of MAC (physical) addresses of the current machine. + * + * @return List of MAC addresses + */ + public static List localMacList() { + ArrayList macList = new ArrayList<>(16); + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + while (interfaces.hasMoreElements()) { + NetworkInterface networkInterface = interfaces.nextElement(); + lookupLocalMac(macList, networkInterface); + } + if (!macList.isEmpty()) { + return macList.stream().distinct().toList(); + } + } catch (Exception e) { + log.warn("Failed to get local mac address"); + } + return macList; + } - /** - * Get loopback addresses - * @param hostNames HostName Set - * @param includeLoopBack includeLoopBack if {@code true} loopback addresses will be - * included in the returned set. - * @throws SocketException SocketException - */ - private static void loopBackAddresses(Set hostNames, boolean includeLoopBack) throws SocketException { - Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces(); + /** + * Get loopback addresses + * + * @param hostNames HostName Set + * @param includeLoopBack includeLoopBack if {@code true} loopback addresses will be + * included in the returned set. + * @throws SocketException SocketException + */ + private static void loopBackAddresses(Set hostNames, boolean includeLoopBack) throws SocketException { + Enumeration interfaceEnumeration = NetworkInterface.getNetworkInterfaces(); - for (NetworkInterface networkInterface : Collections.list(interfaceEnumeration)) { - Collections.list(networkInterface.getInetAddresses()).forEach(inetAddress -> { - if (inetAddress instanceof Inet4Address) { - boolean loopback = inetAddress.isLoopbackAddress(); + for (NetworkInterface networkInterface : Collections.list(interfaceEnumeration)) { + Collections.list(networkInterface.getInetAddresses()).forEach(inetAddress -> { + if (inetAddress instanceof Inet4Address) { + boolean loopback = inetAddress.isLoopbackAddress(); - if (!loopback || includeLoopBack) { - hostNames.add(inetAddress.getHostName()); - hostNames.add(inetAddress.getHostAddress()); - hostNames.add(inetAddress.getCanonicalHostName()); - } - } - }); - } - } + if (!loopback || includeLoopBack) { + hostNames.add(inetAddress.getHostName()); + hostNames.add(inetAddress.getHostAddress()); + hostNames.add(inetAddress.getCanonicalHostName()); + } + } + }); + } + } - /** - * Lookup local mac - * @param macList Mac List - * @param networkInterface NetworkInterface - * @throws SocketException SocketException - */ - private static void lookupLocalMac(ArrayList macList, NetworkInterface networkInterface) - throws SocketException { - List interfaceAddressList = networkInterface.getInterfaceAddresses(); - for (InterfaceAddress interfaceAddress : interfaceAddressList) { - InetAddress inetAddress = interfaceAddress.getAddress(); - NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress); - if (network == null) { - continue; - } + /** + * Lookup local mac + * + * @param macList Mac List + * @param networkInterface NetworkInterface + * @throws SocketException SocketException + */ + private static void lookupLocalMac(ArrayList macList, NetworkInterface networkInterface) + throws SocketException { + List interfaceAddressList = networkInterface.getInterfaceAddresses(); + for (InterfaceAddress interfaceAddress : interfaceAddressList) { + InetAddress inetAddress = interfaceAddress.getAddress(); + NetworkInterface network = NetworkInterface.getByInetAddress(inetAddress); + if (network == null) { + continue; + } - byte[] mac = network.getHardwareAddress(); - if (mac != null) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < mac.length; i++) { - stringBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); - } - macList.add(stringBuilder.toString()); - } - } - } + byte[] mac = network.getHardwareAddress(); + if (mac != null) { + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < mac.length; i++) { + stringBuilder.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : "")); + } + macList.add(stringBuilder.toString()); + } + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/JsonUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/JsonUtil.java index 8f8934a8f..ba3f1a548 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/JsonUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/JsonUtil.java @@ -50,390 +50,392 @@ import java.util.List; */ public final class JsonUtil { - private static final ObjectMapper OBJECT_MAPPER = getObjectMapper(); + private static final ObjectMapper OBJECT_MAPPER = getObjectMapper(); - private JsonUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private JsonUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get a JsonMapper object - * @return ObjectMapper configured with proper settings - */ - public static JsonMapper getJsonMapper() { - LocalDateTimeSerializer serializer = new LocalDateTimeSerializer( - LocalDateTimeUtil.getCompleteDateTimeFormatter()); - LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer( - LocalDateTimeUtil.getCompleteDateTimeFormatter()); - return JsonMapper.builder() - .findAndAddModules() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE) - .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, Boolean.FALSE) - .build(); - } + /** + * Get a JsonMapper object + * + * @return ObjectMapper configured with proper settings + */ + public static JsonMapper getJsonMapper() { + LocalDateTimeSerializer serializer = new LocalDateTimeSerializer( + LocalDateTimeUtil.getCompleteDateTimeFormatter()); + LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer( + LocalDateTimeUtil.getCompleteDateTimeFormatter()); + return JsonMapper.builder() + .findAndAddModules() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE) + .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, Boolean.FALSE) + .build(); + } - /** - * Get a ObjectMapper object - * @return ObjectMapper configured with proper settings - */ - public static ObjectMapper getObjectMapper() { - LocalDateTimeSerializer serializer = new LocalDateTimeSerializer( - LocalDateTimeUtil.getCompleteDateTimeFormatter()); - LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer( - LocalDateTimeUtil.getCompleteDateTimeFormatter()); - return JsonMapper.builder() - .findAndAddModules() - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE) - .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, Boolean.FALSE) - .build(); - } + /** + * Get a ObjectMapper object + * + * @return ObjectMapper configured with proper settings + */ + public static ObjectMapper getObjectMapper() { + LocalDateTimeSerializer serializer = new LocalDateTimeSerializer( + LocalDateTimeUtil.getCompleteDateTimeFormatter()); + LocalDateTimeDeserializer deserializer = new LocalDateTimeDeserializer( + LocalDateTimeUtil.getCompleteDateTimeFormatter()); + return JsonMapper.builder() + .findAndAddModules() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE) + .configure(MapperFeature.DEFAULT_VIEW_INCLUSION, Boolean.FALSE) + .build(); + } - /** - * Deserialize JSON string to Java object - * @param text JSON string - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(String text, Class valueType) { - try { - if (StringUtils.isEmpty(text)) { - return null; - } + /** + * Deserialize JSON string to Java object + * + * @param text JSON string + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(String text, Class valueType) { + try { + if (StringUtils.isEmpty(text)) { + return null; + } - return OBJECT_MAPPER.readValue(text, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + return OBJECT_MAPPER.readValue(text, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON byte array to Java object - * @param bytes JSON byte array - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(byte[] bytes, Class valueType) { - try { - return OBJECT_MAPPER.readValue(bytes, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON byte array to Java object + * + * @param bytes JSON byte array + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(byte[] bytes, Class valueType) { + try { + return OBJECT_MAPPER.readValue(bytes, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON string to Java object using JsonParser - * @param jsonParser JsonParser instance for parsing - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(JsonParser jsonParser, Class valueType) { - try { - return OBJECT_MAPPER.readValue(jsonParser, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON string to Java object using JsonParser + * + * @param jsonParser JsonParser instance for parsing + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(JsonParser jsonParser, Class valueType) { + try { + return OBJECT_MAPPER.readValue(jsonParser, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON string to Java object using DataInput - * @param dataInput DataInput instance for parsing - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(DataInput dataInput, Class valueType) { - try { - return OBJECT_MAPPER.readValue(dataInput, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON string to Java object using DataInput + * + * @param dataInput DataInput instance for parsing + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(DataInput dataInput, Class valueType) { + try { + return OBJECT_MAPPER.readValue(dataInput, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from an {@link InputStream} into a Java object. - * @param inputStream Json InputStream - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(InputStream inputStream, Class valueType) { - try { - return OBJECT_MAPPER.readValue(inputStream, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from an {@link InputStream} into a Java object. + * + * @param inputStream Json InputStream + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(InputStream inputStream, Class valueType) { + try { + return OBJECT_MAPPER.readValue(inputStream, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from a {@link Reader} into a Java object. - * @param reader Json Reader - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(Reader reader, Class valueType) { - try { - return OBJECT_MAPPER.readValue(reader, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from a {@link Reader} into a Java object. + * + * @param reader Json Reader + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(Reader reader, Class valueType) { + try { + return OBJECT_MAPPER.readValue(reader, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from a {@link File} into a Java object. - * @param file Json file - * @param valueType Java object type - * @param Java object type - * @return Java object - */ - public static T parseObject(File file, Class valueType) { - try { - return OBJECT_MAPPER.readValue(file, valueType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from a {@link File} into a Java object. + * + * @param file Json file + * @param valueType Java object type + * @param Java object type + * @return Java object + */ + public static T parseObject(File file, Class valueType) { + try { + return OBJECT_MAPPER.readValue(file, valueType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON string into a specified generic Java object. - * @param text Json string - * @param typeReference TypeReference, T is the target data type - * @param Java object type - * @return Java object - */ - public static T parseObject(String text, TypeReference typeReference) { - try { - return OBJECT_MAPPER.readValue(text, typeReference); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON string into a specified generic Java object. + * + * @param text Json string + * @param typeReference TypeReference, T is the target data type + * @param Java object type + * @return Java object + */ + public static T parseObject(String text, TypeReference typeReference) { + try { + return OBJECT_MAPPER.readValue(text, typeReference); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON string to Java object collection - * @param text JSON string - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(String text, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(text, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON string to Java object collection + * + * @param text JSON string + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(String text, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(text, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON byte array into a collection of Java objects. - * @param bytes Json byte array - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(byte[] bytes, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(bytes, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON byte array into a collection of Java objects. + * + * @param bytes Json byte array + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(byte[] bytes, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(bytes, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content using {@link JsonParser} into a collection of Java - * objects. - * @param jsonParser Json JsonParser - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(JsonParser jsonParser, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(jsonParser, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content using {@link JsonParser} into a collection of Java + * objects. + * + * @param jsonParser Json JsonParser + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(JsonParser jsonParser, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(jsonParser, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content using {@link DataInput} into a collection of Java objects. - * @param dataInput Json DataInput - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(DataInput dataInput, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(dataInput, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content using {@link DataInput} into a collection of Java objects. + * + * @param dataInput Json DataInput + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(DataInput dataInput, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(dataInput, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from an {@link InputStream} into a collection of Java - * objects. - * @param inputStream Json InputStream - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(InputStream inputStream, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(inputStream, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from an {@link InputStream} into a collection of Java + * objects. + * + * @param inputStream Json InputStream + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(InputStream inputStream, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(inputStream, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from a {@link Reader} into a collection of Java objects. - * @param reader Json Reader - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(Reader reader, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(reader, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from a {@link Reader} into a collection of Java objects. + * + * @param reader Json Reader + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(Reader reader, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(reader, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Deserialize JSON content from a {@link File} into a collection of Java objects. - * @param file Json file - * @param valueType Java object type - * @param Java object type - * @return Java object collection - */ - public static List parseArray(File file, Class valueType) { - try { - JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); - return OBJECT_MAPPER.readValue(file, javaType); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Deserialize JSON content from a {@link File} into a collection of Java objects. + * + * @param file Json file + * @param valueType Java object type + * @param Java object type + * @return Java object collection + */ + public static List parseArray(File file, Class valueType) { + try { + JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, valueType); + return OBJECT_MAPPER.readValue(file, javaType); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Serialize Java object or collection to JSON string - * @param type Java object reference - * @param Java object type - * @return JSON string - */ - public static String toJsonString(T type) { - try { - return OBJECT_MAPPER.writeValueAsString(type); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Serialize Java object or collection to JSON string + * + * @param type Java object reference + * @param Java object type + * @return JSON string + */ + public static String toJsonString(T type) { + try { + return OBJECT_MAPPER.writeValueAsString(type); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Serialize Java object to JSON string with custom view - * @param type Java object reference - * @param serializationView Custom view class for JSON content - * @param Java object type - * @return JSON string - */ - public static String toJsonString(T type, Class serializationView) { - try { - return OBJECT_MAPPER.writerWithView(serializationView).writeValueAsString(type); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Serialize Java object to JSON string with custom view + * + * @param type Java object reference + * @param serializationView Custom view class for JSON content + * @param Java object type + * @return JSON string + */ + public static String toJsonString(T type, Class serializationView) { + try { + return OBJECT_MAPPER.writerWithView(serializationView).writeValueAsString(type); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Serialize Java object to pretty JSON string - * @param type Java object reference - * @param Java object type - * @return Pretty formatted JSON string - */ - public static String toPrettyJsonString(T type) { - try { - return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(type); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Serialize Java object to pretty JSON string + * + * @param type Java object reference + * @param Java object type + * @return Pretty formatted JSON string + */ + public static String toPrettyJsonString(T type) { + try { + return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(type); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Serialize Java object to pretty JSON string with custom view - * @param type Java object reference - * @param serializationView Custom view class for JSON content - * @param Java object type - * @return Pretty formatted JSON string with custom view - */ - public static String toPrettyJsonString(T type, Class serializationView) { - try { - return OBJECT_MAPPER.writerWithView(serializationView).withDefaultPrettyPrinter().writeValueAsString(type); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Serialize Java object to pretty JSON string with custom view + * + * @param type Java object reference + * @param serializationView Custom view class for JSON content + * @param Java object type + * @return Pretty formatted JSON string with custom view + */ + public static String toPrettyJsonString(T type, Class serializationView) { + try { + return OBJECT_MAPPER.writerWithView(serializationView).withDefaultPrettyPrinter().writeValueAsString(type); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Serialize Java object to JSON byte array - * @param type Java object reference - * @param Java object type - * @return JSON byte array - */ - public static byte[] toJsonBytes(T type) { - try { - return DecodeUtil.stringToByte(OBJECT_MAPPER.writeValueAsString(type)); - } - catch (Exception e) { - throw new JsonException(e); - } - } + /** + * Serialize Java object to JSON byte array + * + * @param type Java object reference + * @param Java object type + * @return JSON byte array + */ + public static byte[] toJsonBytes(T type) { + try { + return DecodeUtil.stringToByte(OBJECT_MAPPER.writeValueAsString(type)); + } catch (Exception e) { + throw new JsonException(e); + } + } - /** - * Check if string is valid JSON format - * @param text JSON string to validate - * @return true if valid JSON, false otherwise - */ - public static boolean isJson(String text) { - if (text == null || text.isEmpty()) { - return false; - } - try { - OBJECT_MAPPER.readTree(text); - return true; - } - catch (Exception e) { - return false; - } - } + /** + * Check if string is valid JSON format + * + * @param text JSON string to validate + * @return true if valid JSON, false otherwise + */ + public static boolean isJson(String text) { + if (text == null || text.isEmpty()) { + return false; + } + try { + OBJECT_MAPPER.readTree(text); + return true; + } catch (Exception e) { + return false; + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyStoreUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyStoreUtil.java index 7cac45ac2..2c6f33235 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyStoreUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyStoreUtil.java @@ -48,59 +48,58 @@ import java.security.cert.CertificateFactory; @Slf4j public class KeyStoreUtil { - private KeyStoreUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private KeyStoreUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - public static void importKeystore(String crtFileName, String crtNameAlias) { - DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); - String[] resourcePaths = new String[] { "classpath:/ssl/", "file:./ssl/" }; - String passphrase = "changeit"; - try (InputStream inputStream = getResource(resourceLoader, resourcePaths, crtFileName).getInputStream()) { - KeyStoreUtil.importKeystore(inputStream, crtNameAlias, passphrase); - } - catch (Exception e) { - throw new SecurityException(e); - } - } + public static void importKeystore(String crtFileName, String crtNameAlias) { + DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); + String[] resourcePaths = new String[]{"classpath:/ssl/", "file:./ssl/"}; + String passphrase = "changeit"; + try (InputStream inputStream = getResource(resourceLoader, resourcePaths, crtFileName).getInputStream()) { + KeyStoreUtil.importKeystore(inputStream, crtNameAlias, passphrase); + } catch (Exception e) { + throw new SecurityException(e); + } + } - private static Resource getResource(ResourceLoader resourceLoader, String[] resourcePaths, String fileName) { - for (String path : resourcePaths) { - Resource resource = resourceLoader.getResource(path + fileName); - if (resource.exists()) { - return resource; - } - } - throw new NotFoundException("Certificate file '{}' doesn't exist", fileName); - } + private static Resource getResource(ResourceLoader resourceLoader, String[] resourcePaths, String fileName) { + for (String path : resourcePaths) { + Resource resource = resourceLoader.getResource(path + fileName); + if (resource.exists()) { + return resource; + } + } + throw new NotFoundException("Certificate file '{}' doesn't exist", fileName); + } - private static void importKeystore(InputStream crtInputStream, String crtAliasName, String passphrase) - throws Exception { - log.info("Importing certificate '{}'", crtAliasName); - final char separator = File.separatorChar; - final char[] passphraseArray = passphrase.toCharArray(); - File securityFile = new File(System.getProperty("java.home") + separator + "lib" + separator + "security"); - File keyStoreFile = new File(securityFile, "cacerts"); - Path path = keyStoreFile.toPath(); - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - try (InputStream inputStream = Files.newInputStream(path)) { - keystore.load(inputStream, passphraseArray); - if (keystore.containsAlias(crtAliasName)) { - log.info("Skip import, certificate '{}' already exists", crtAliasName); - return; - } - } + private static void importKeystore(InputStream crtInputStream, String crtAliasName, String passphrase) + throws Exception { + log.info("Importing certificate '{}'", crtAliasName); + final char separator = File.separatorChar; + final char[] passphraseArray = passphrase.toCharArray(); + File securityFile = new File(System.getProperty("java.home") + separator + "lib" + separator + "security"); + File keyStoreFile = new File(securityFile, "cacerts"); + Path path = keyStoreFile.toPath(); + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + try (InputStream inputStream = Files.newInputStream(path)) { + keystore.load(inputStream, passphraseArray); + if (keystore.containsAlias(crtAliasName)) { + log.info("Skip import, certificate '{}' already exists", crtAliasName); + return; + } + } - try (OutputStream outputStream = Files.newOutputStream(path)) { - BufferedInputStream bis = new BufferedInputStream(crtInputStream); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - while (bis.available() > 0) { - Certificate cert = cf.generateCertificate(bis); - keystore.setCertificateEntry(crtAliasName, cert); - } - keystore.store(outputStream, passphraseArray); - } - log.info("Certificate '{}' imported successfully", crtAliasName); - } + try (OutputStream outputStream = Files.newOutputStream(path)) { + BufferedInputStream bis = new BufferedInputStream(crtInputStream); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + while (bis.available() > 0) { + Certificate cert = cf.generateCertificate(bis); + keystore.setCertificateEntry(crtAliasName, cert); + } + keystore.store(outputStream, passphraseArray); + } + log.info("Certificate '{}' imported successfully", crtAliasName); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyUtil.java index 75ee93a7c..544497e0c 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/KeyUtil.java @@ -28,15 +28,9 @@ import io.jsonwebtoken.JwtParser; import io.jsonwebtoken.Jwts; import lombok.extern.slf4j.Slf4j; -import javax.crypto.Cipher; -import javax.crypto.KeyGenerator; -import javax.crypto.SecretKey; +import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; -import java.security.Key; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.SecureRandom; +import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; @@ -61,174 +55,182 @@ import java.util.Date; @Slf4j public class KeyUtil { - private KeyUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private KeyUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Generate an AES key. - * @return Keys.Aes - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - */ - public static Keys.Aes genAesKey() throws NoSuchAlgorithmException { - KeyGenerator keyGenerator = KeyGenerator.getInstance(AlgorithmConstant.ALGORITHM_AES); - keyGenerator.init(256); - SecretKey secretKey = keyGenerator.generateKey(); - return new Keys.Aes(DecodeUtil.byteToString(DecodeUtil.encode(secretKey.getEncoded()))); - } + /** + * Generate an AES key. + * + * @return Keys.Aes + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + */ + public static Keys.Aes genAesKey() throws NoSuchAlgorithmException { + KeyGenerator keyGenerator = KeyGenerator.getInstance(AlgorithmConstant.ALGORITHM_AES); + keyGenerator.init(256); + SecretKey secretKey = keyGenerator.generateKey(); + return new Keys.Aes(DecodeUtil.byteToString(DecodeUtil.encode(secretKey.getEncoded()))); + } - /** - * Encrypt content using an AES key. - * @param content String - * @param privateKey Private key in Base64 encoding - * @return Encrypted AES content - * @throws NoSuchPaddingException NoSuchPaddingException - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - * @throws InvalidKeyException InvalidKeyException - * @throws IllegalBlockSizeException IllegalBlockSizeException - * @throws BadPaddingException BadPaddingException - */ - public static String encryptAes(String content, String privateKey) throws NoSuchPaddingException, - NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - // Base64-encoded private key - byte[] keyBytes = DecodeUtil.decode(privateKey); - Key key = new SecretKeySpec(keyBytes, AlgorithmConstant.ALGORITHM_AES); - // AES encryption - Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); - cipher.init(Cipher.ENCRYPT_MODE, key); - return DecodeUtil.byteToString(DecodeUtil.encode(cipher.doFinal(DecodeUtil.stringToByte(content)))); - } + /** + * Encrypt content using an AES key. + * + * @param content String + * @param privateKey Private key in Base64 encoding + * @return Encrypted AES content + * @throws NoSuchPaddingException NoSuchPaddingException + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + * @throws InvalidKeyException InvalidKeyException + * @throws IllegalBlockSizeException IllegalBlockSizeException + * @throws BadPaddingException BadPaddingException + */ + public static String encryptAes(String content, String privateKey) throws NoSuchPaddingException, + NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + // Base64-encoded private key + byte[] keyBytes = DecodeUtil.decode(privateKey); + Key key = new SecretKeySpec(keyBytes, AlgorithmConstant.ALGORITHM_AES); + // AES encryption + Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); + cipher.init(Cipher.ENCRYPT_MODE, key); + return DecodeUtil.byteToString(DecodeUtil.encode(cipher.doFinal(DecodeUtil.stringToByte(content)))); + } - /** - * Decrypt content using an AES key. - * @param content String - * @param privateKey Private key in Base64 encoding - * @return Decrypted AES content - * @throws NoSuchPaddingException NoSuchPaddingException - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - * @throws InvalidKeyException InvalidKeyException - * @throws IllegalBlockSizeException IllegalBlockSizeException - * @throws BadPaddingException BadPaddingException - */ - public static String decryptAes(String content, String privateKey) throws NoSuchPaddingException, - NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - // Base64-encoded private key - byte[] keyBytes = DecodeUtil.decode(privateKey); - Key key = new SecretKeySpec(keyBytes, AlgorithmConstant.ALGORITHM_AES); - // AES decryption - Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); - cipher.init(Cipher.DECRYPT_MODE, key); - // Decode the encrypted string from Base64 - byte[] inputByte = DecodeUtil.decode(DecodeUtil.stringToByte(content)); - return DecodeUtil.byteToString(cipher.doFinal(inputByte)); - } + /** + * Decrypt content using an AES key. + * + * @param content String + * @param privateKey Private key in Base64 encoding + * @return Decrypted AES content + * @throws NoSuchPaddingException NoSuchPaddingException + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + * @throws InvalidKeyException InvalidKeyException + * @throws IllegalBlockSizeException IllegalBlockSizeException + * @throws BadPaddingException BadPaddingException + */ + public static String decryptAes(String content, String privateKey) throws NoSuchPaddingException, + NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { + // Base64-encoded private key + byte[] keyBytes = DecodeUtil.decode(privateKey); + Key key = new SecretKeySpec(keyBytes, AlgorithmConstant.ALGORITHM_AES); + // AES decryption + Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); + cipher.init(Cipher.DECRYPT_MODE, key); + // Decode the encrypted string from Base64 + byte[] inputByte = DecodeUtil.decode(DecodeUtil.stringToByte(content)); + return DecodeUtil.byteToString(cipher.doFinal(inputByte)); + } - /** - * Generate an RSA key pair. - * @return Keys.Rsa - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - */ - public static Keys.Rsa genRsaKey() throws NoSuchAlgorithmException { - KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(AlgorithmConstant.ALGORITHM_RSA); - keyPairGen.initialize(2048, new SecureRandom()); - KeyPair keyPair = keyPairGen.generateKeyPair(); - RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); - RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); - String publicKeyString = DecodeUtil.byteToString(DecodeUtil.encode(publicKey.getEncoded())); - String privateKeyString = DecodeUtil.byteToString(DecodeUtil.encode((privateKey.getEncoded()))); - return new Keys.Rsa(publicKeyString, privateKeyString); - } + /** + * Generate an RSA key pair. + * + * @return Keys.Rsa + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + */ + public static Keys.Rsa genRsaKey() throws NoSuchAlgorithmException { + KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(AlgorithmConstant.ALGORITHM_RSA); + keyPairGen.initialize(2048, new SecureRandom()); + KeyPair keyPair = keyPairGen.generateKeyPair(); + RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); + RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); + String publicKeyString = DecodeUtil.byteToString(DecodeUtil.encode(publicKey.getEncoded())); + String privateKeyString = DecodeUtil.byteToString(DecodeUtil.encode((privateKey.getEncoded()))); + return new Keys.Rsa(publicKeyString, privateKeyString); + } - /** - * Encrypt content using an RSA public key. - * @param content String - * @param publicKey Public key in Base64 encoding - * @return Encrypted RSA content - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - * @throws NoSuchPaddingException NoSuchPaddingException - * @throws InvalidKeyException InvalidKeyException - * @throws IllegalBlockSizeException IllegalBlockSizeException - * @throws BadPaddingException BadPaddingException - * @throws InvalidKeySpecException InvalidKeySpecException - */ - public static String encryptRsa(String content, String publicKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, - BadPaddingException, InvalidKeySpecException { - // Base64-encoded public key - byte[] keyBytes = DecodeUtil.decode(publicKey); - KeySpec keySpec = new X509EncodedKeySpec(keyBytes); - RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(AlgorithmConstant.ALGORITHM_RSA) - .generatePublic(keySpec); - // RSA encryption - Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); - cipher.init(Cipher.ENCRYPT_MODE, pubKey); - return DecodeUtil.byteToString(DecodeUtil.encode(cipher.doFinal(DecodeUtil.stringToByte(content)))); - } + /** + * Encrypt content using an RSA public key. + * + * @param content String + * @param publicKey Public key in Base64 encoding + * @return Encrypted RSA content + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + * @throws NoSuchPaddingException NoSuchPaddingException + * @throws InvalidKeyException InvalidKeyException + * @throws IllegalBlockSizeException IllegalBlockSizeException + * @throws BadPaddingException BadPaddingException + * @throws InvalidKeySpecException InvalidKeySpecException + */ + public static String encryptRsa(String content, String publicKey) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, + BadPaddingException, InvalidKeySpecException { + // Base64-encoded public key + byte[] keyBytes = DecodeUtil.decode(publicKey); + KeySpec keySpec = new X509EncodedKeySpec(keyBytes); + RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(AlgorithmConstant.ALGORITHM_RSA) + .generatePublic(keySpec); + // RSA encryption + Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_AES); + cipher.init(Cipher.ENCRYPT_MODE, pubKey); + return DecodeUtil.byteToString(DecodeUtil.encode(cipher.doFinal(DecodeUtil.stringToByte(content)))); + } - /** - * Decrypt content using an RSA private key. - * @param content String - * @param privateKey Private key in Base64 encoding - * @return Decrypted RSA content - * @throws NoSuchAlgorithmException NoSuchAlgorithmException - * @throws NoSuchPaddingException NoSuchPaddingException - * @throws InvalidKeyException InvalidKeyException - * @throws IllegalBlockSizeException IllegalBlockSizeException - * @throws BadPaddingException BadPaddingException - * @throws InvalidKeySpecException InvalidKeySpecException - */ - public static String decryptRsa(String content, String privateKey) - throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, - BadPaddingException, InvalidKeySpecException { - // Base64-encoded private key - byte[] keyBytes = DecodeUtil.decode(privateKey); - KeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); - RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(AlgorithmConstant.ALGORITHM_RSA) - .generatePrivate(keySpec); - // RSA decryption - Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_RSA); - cipher.init(Cipher.DECRYPT_MODE, priKey); - // Decode the encrypted string from Base64 - byte[] inputByte = DecodeUtil.decode(DecodeUtil.stringToByte(content)); - return DecodeUtil.byteToString(cipher.doFinal(inputByte)); - } + /** + * Decrypt content using an RSA private key. + * + * @param content String + * @param privateKey Private key in Base64 encoding + * @return Decrypted RSA content + * @throws NoSuchAlgorithmException NoSuchAlgorithmException + * @throws NoSuchPaddingException NoSuchPaddingException + * @throws InvalidKeyException InvalidKeyException + * @throws IllegalBlockSizeException IllegalBlockSizeException + * @throws BadPaddingException BadPaddingException + * @throws InvalidKeySpecException InvalidKeySpecException + */ + public static String decryptRsa(String content, String privateKey) + throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, + BadPaddingException, InvalidKeySpecException { + // Base64-encoded private key + byte[] keyBytes = DecodeUtil.decode(privateKey); + KeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); + RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(AlgorithmConstant.ALGORITHM_RSA) + .generatePrivate(keySpec); + // RSA decryption + Cipher cipher = Cipher.getInstance(AlgorithmConstant.ALGORITHM_RSA); + cipher.init(Cipher.DECRYPT_MODE, priKey); + // Decode the encrypted string from Base64 + byte[] inputByte = DecodeUtil.decode(DecodeUtil.stringToByte(content)); + return DecodeUtil.byteToString(cipher.doFinal(inputByte)); + } - /** - * Generate a JWT token. - * @param userName User name - * @param salt Salt - * @param tenantId Tenant ID - * @return Token string - */ - public static String generateToken(String userName, String salt, Long tenantId) { - SecretKey key = io.jsonwebtoken.security.Keys - .hmacShaKeyFor(DecodeUtil.stringToByte(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + salt)); - JwtBuilder builder = Jwts.builder() - .issuer(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + tenantId) - .subject(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + userName) - .issuedAt(new Date()) - .signWith(key, Jwts.SIG.HS256) - .expiration(TimeUtil.expireTime(TimeoutConstant.TOKEN_CACHE_TIMEOUT, Calendar.HOUR)); - return builder.compact(); - } + /** + * Generate a JWT token. + * + * @param userName User name + * @param salt Salt + * @param tenantId Tenant ID + * @return Token string + */ + public static String generateToken(String userName, String salt, Long tenantId) { + SecretKey key = io.jsonwebtoken.security.Keys + .hmacShaKeyFor(DecodeUtil.stringToByte(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + salt)); + JwtBuilder builder = Jwts.builder() + .issuer(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + tenantId) + .subject(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + userName) + .issuedAt(new Date()) + .signWith(key, Jwts.SIG.HS256) + .expiration(TimeUtil.expireTime(TimeoutConstant.TOKEN_CACHE_TIMEOUT, Calendar.HOUR)); + return builder.compact(); + } - /** - * Parse and validate a JWT token. - * @param userName User name - * @param salt Salt - * @param token Token string - * @param tenantId Tenant ID - * @return Claims - */ - public static Claims parserToken(String userName, String salt, String token, Long tenantId) { - SecretKey key = io.jsonwebtoken.security.Keys - .hmacShaKeyFor(DecodeUtil.stringToByte(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + salt)); - JwtParser parser = Jwts.parser() - .requireIssuer(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + tenantId) - .requireSubject(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + userName) - .verifyWith(key) - .build(); - return parser.parseSignedClaims(token).getPayload(); - } + /** + * Parse and validate a JWT token. + * + * @param userName User name + * @param salt Salt + * @param token Token string + * @param tenantId Tenant ID + * @return Claims + */ + public static Claims parserToken(String userName, String salt, String token, Long tenantId) { + SecretKey key = io.jsonwebtoken.security.Keys + .hmacShaKeyFor(DecodeUtil.stringToByte(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + salt)); + JwtParser parser = Jwts.parser() + .requireIssuer(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + tenantId) + .requireSubject(AlgorithmConstant.DEFAULT_KEY + SymbolConstant.COLON + userName) + .verifyWith(key) + .build(); + return parser.parseSignedClaims(token).getPayload(); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/LocalDateTimeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/LocalDateTimeUtil.java index b944833d7..731fb2160 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/LocalDateTimeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/LocalDateTimeUtil.java @@ -37,117 +37,125 @@ import java.time.temporal.ChronoUnit; @Slf4j public class LocalDateTimeUtil { - private LocalDateTimeUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private LocalDateTimeUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get the default date-time format. - *

- * Pattern: yyyy-MM-dd HH:mm:ss - * @return {@link DateTimeFormatter} - */ - public static DateTimeFormatter getDefaultDateTimeFormatter() { - return DateTimeFormatter.ofPattern(TimeConstant.DEFAULT_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the default date-time format. + *

+ * Pattern: yyyy-MM-dd HH:mm:ss + * + * @return {@link DateTimeFormatter} + */ + public static DateTimeFormatter getDefaultDateTimeFormatter() { + return DateTimeFormatter.ofPattern(TimeConstant.DEFAULT_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get the complete date-time format. - *

- * Pattern: yyyy-MM-dd HH:mm:ss.SSS - * @return {@link DateTimeFormatter} - */ - public static DateTimeFormatter getCompleteDateTimeFormatter() { - return DateTimeFormatter.ofPattern(TimeConstant.COMPLETE_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the complete date-time format. + *

+ * Pattern: yyyy-MM-dd HH:mm:ss.SSS + * + * @return {@link DateTimeFormatter} + */ + public static DateTimeFormatter getCompleteDateTimeFormatter() { + return DateTimeFormatter.ofPattern(TimeConstant.COMPLETE_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get the current time with default time zone. - * @return LocalDateTime {@link LocalDateTime} - */ - public static LocalDateTime now() { - return LocalDateTime.now(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the current time with default time zone. + * + * @return LocalDateTime {@link LocalDateTime} + */ + public static LocalDateTime now() { + return LocalDateTime.now(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get milliseconds from the given {@link LocalDateTime}. - * @param localDateTime {@link LocalDateTime} - * @return Milliseconds - */ - public static long milliSeconds(LocalDateTime localDateTime) { - return localDateTime.atZone(TimeConstant.DEFAULT_ZONEID).toInstant().toEpochMilli(); - } + /** + * Get milliseconds from the given {@link LocalDateTime}. + * + * @param localDateTime {@link LocalDateTime} + * @return Milliseconds + */ + public static long milliSeconds(LocalDateTime localDateTime) { + return localDateTime.atZone(TimeConstant.DEFAULT_ZONEID).toInstant().toEpochMilli(); + } - /** - * Get a {@link LocalDateTime} from milliseconds. - * @param milliSeconds Milliseconds - * @return LocalDateTime {@link LocalDateTime} - */ - public static LocalDateTime dateTime(long milliSeconds) { - Instant instant = Instant.ofEpochMilli(milliSeconds); - return LocalDateTime.ofInstant(instant, TimeConstant.DEFAULT_ZONEID); - } + /** + * Get a {@link LocalDateTime} from milliseconds. + * + * @param milliSeconds Milliseconds + * @return LocalDateTime {@link LocalDateTime} + */ + public static LocalDateTime dateTime(long milliSeconds) { + Instant instant = Instant.ofEpochMilli(milliSeconds); + return LocalDateTime.ofInstant(instant, TimeConstant.DEFAULT_ZONEID); + } - /** - * Delay time by the specified amount and unit, e.g., HOUR/MINUTE/... - * @param amount Integer - * @param field ChronoUnit field : {@link ChronoUnit ChronoUnit.HOUR/MINUTE/...} - * @return LocalDateTime - */ - public static LocalDateTime expireTime(int amount, ChronoUnit field) { - LocalDateTime localDateTime = LocalDateTimeUtil.now(); - return localDateTime.plus(amount, field); - } + /** + * Delay time by the specified amount and unit, e.g., HOUR/MINUTE/... + * + * @param amount Integer + * @param field ChronoUnit field : {@link ChronoUnit ChronoUnit.HOUR/MINUTE/...} + * @return LocalDateTime + */ + public static LocalDateTime expireTime(int amount, ChronoUnit field) { + LocalDateTime localDateTime = LocalDateTimeUtil.now(); + return localDateTime.plus(amount, field); + } - /** - * Format time using the pattern yyyy-MM-dd HH:mm:ss. - * @param localDateTime {@link LocalDateTime} - * @return Formatted time string - */ - public static String defaultFormat(LocalDateTime localDateTime) { - DateTimeFormatter formatter = getDefaultDateTimeFormatter(); - return localDateTime.format(formatter); - } + /** + * Format time using the pattern yyyy-MM-dd HH:mm:ss. + * + * @param localDateTime {@link LocalDateTime} + * @return Formatted time string + */ + public static String defaultFormat(LocalDateTime localDateTime) { + DateTimeFormatter formatter = getDefaultDateTimeFormatter(); + return localDateTime.format(formatter); + } - /** - * Format time using the pattern yyyy-MM-dd HH:mm:ss.SSS. - * @param localDateTime {@link LocalDateTime} - * @return Formatted time string - */ - public static String completeFormat(LocalDateTime localDateTime) { - DateTimeFormatter formatter = getCompleteDateTimeFormatter(); - return localDateTime.format(formatter); - } + /** + * Format time using the pattern yyyy-MM-dd HH:mm:ss.SSS. + * + * @param localDateTime {@link LocalDateTime} + * @return Formatted time string + */ + public static String completeFormat(LocalDateTime localDateTime) { + DateTimeFormatter formatter = getCompleteDateTimeFormatter(); + return localDateTime.format(formatter); + } - /** - * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss to {@link LocalDateTime}. - * @param dateString yyyy-MM-dd HH:mm:ss - * @return LocalDateTime or {@code null} if parsing fails - */ - public static LocalDateTime defaultDate(String dateString) { - try { - DateTimeFormatter formatter = getDefaultDateTimeFormatter(); - return LocalDateTime.parse(dateString, formatter); - } - catch (DateTimeParseException e) { - return null; - } - } + /** + * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss to {@link LocalDateTime}. + * + * @param dateString yyyy-MM-dd HH:mm:ss + * @return LocalDateTime or {@code null} if parsing fails + */ + public static LocalDateTime defaultDate(String dateString) { + try { + DateTimeFormatter formatter = getDefaultDateTimeFormatter(); + return LocalDateTime.parse(dateString, formatter); + } catch (DateTimeParseException e) { + return null; + } + } - /** - * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss.SSS to - * {@link LocalDateTime}. - * @param dateString Date string - * @return LocalDateTime or {@code null} if parsing fails - */ - public static LocalDateTime completeDate(String dateString) { - try { - DateTimeFormatter formatter = getCompleteDateTimeFormatter(); - return LocalDateTime.parse(dateString, formatter); - } - catch (DateTimeParseException e) { - return null; - } - } + /** + * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss.SSS to + * {@link LocalDateTime}. + * + * @param dateString Date string + * @return LocalDateTime or {@code null} if parsing fails + */ + public static LocalDateTime completeDate(String dateString) { + try { + DateTimeFormatter formatter = getCompleteDateTimeFormatter(); + return LocalDateTime.parse(dateString, formatter); + } catch (DateTimeParseException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/MapStructUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/MapStructUtil.java index 50646d1d4..af15f0eb8 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/MapStructUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/MapStructUtil.java @@ -36,23 +36,23 @@ import org.mapstruct.Condition; @Slf4j public class MapStructUtil { - private MapStructUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private MapStructUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - @Condition - public static boolean isNotEmpty(String value) { - return StringUtils.isNotEmpty(value); - } + @Condition + public static boolean isNotEmpty(String value) { + return StringUtils.isNotEmpty(value); + } - @Condition - public static boolean isValidNumber(Number value) { - return switch (value) { - case null -> false; - case Double d -> !Double.isNaN(d) && !Double.isInfinite(d); - case Float f -> !Float.isNaN(f) && !Float.isInfinite(f); - default -> true; - }; - } + @Condition + public static boolean isValidNumber(Number value) { + return switch (value) { + case null -> false; + case Double d -> !Double.isNaN(d) && !Double.isInfinite(d); + case Float f -> !Float.isNaN(f) && !Float.isInfinite(f); + default -> true; + }; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PageUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PageUtil.java index 82240c661..e54c128b9 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PageUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PageUtil.java @@ -42,44 +42,45 @@ import java.util.Objects; @Slf4j public class PageUtil { - private PageUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private PageUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Convert custom {@link Pages} object to MyBatis-Plus {@link Page}. - * @param pages {@link Pages} - * @param Entity type - * @return MyBatis-Plus {@link Page} - */ - public static Page page(Pages pages) { - Page page = new Page<>(); - if (Objects.isNull(pages)) { - pages = new Pages(); - } + /** + * Convert custom {@link Pages} object to MyBatis-Plus {@link Page}. + * + * @param pages {@link Pages} + * @param Entity type + * @return MyBatis-Plus {@link Page} + */ + public static Page page(Pages pages) { + Page page = new Page<>(); + if (Objects.isNull(pages)) { + pages = new Pages(); + } - if (pages.getCurrent() < DefaultConstant.ONE) { - pages.setCurrent(DefaultConstant.ONE); - } - page.setCurrent(pages.getCurrent()); + if (pages.getCurrent() < DefaultConstant.ONE) { + pages.setCurrent(DefaultConstant.ONE); + } + page.setCurrent(pages.getCurrent()); - if (pages.getSize() > DefaultConstant.MAX_PAGE_SIZE) { - pages.setSize(DefaultConstant.MAX_PAGE_SIZE); - } - page.setSize(pages.getSize()); + if (pages.getSize() > DefaultConstant.MAX_PAGE_SIZE) { + pages.setSize(DefaultConstant.MAX_PAGE_SIZE); + } + page.setSize(pages.getSize()); - List orders = pages.getOrders(); - boolean anyMatch = orders.stream() - .filter(order -> Objects.nonNull(order) && StringUtils.isNotEmpty(order.getColumn())) - .anyMatch(order -> "create_time".equals(order.getColumn())); - if (!anyMatch) { - orders.add(OrderItem.desc("create_time")); - } - List orderItemList = orders.stream() - .filter(order -> Objects.nonNull(order) && StringUtils.isNotEmpty(order.getColumn())) - .toList(); - page.setOrders(orderItemList); - return page; - } + List orders = pages.getOrders(); + boolean anyMatch = orders.stream() + .filter(order -> Objects.nonNull(order) && StringUtils.isNotEmpty(order.getColumn())) + .anyMatch(order -> "create_time".equals(order.getColumn())); + if (!anyMatch) { + orders.add(OrderItem.desc("create_time")); + } + List orderItemList = orders.stream() + .filter(order -> Objects.nonNull(order) && StringUtils.isNotEmpty(order.getColumn())) + .toList(); + page.setOrders(orderItemList); + return page; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PoiUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PoiUtil.java index 020ec14ef..113ad2077 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PoiUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/PoiUtil.java @@ -19,13 +19,7 @@ package io.github.pnoker.common.utils; import io.github.pnoker.common.constant.common.ExceptionConstant; import lombok.extern.slf4j.Slf4j; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import java.util.Objects; @@ -44,86 +38,91 @@ import java.util.Objects; @Slf4j public class PoiUtil { - private PoiUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private PoiUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get a {@link CellStyle} with both horizontal and vertical alignment set to center. - * @param workbook Workbook - * @return Centered CellStyle - */ - public static CellStyle getCenterCellStyle(Workbook workbook) { - CellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setAlignment(HorizontalAlignment.CENTER); - cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - return cellStyle; - } + /** + * Get a {@link CellStyle} with both horizontal and vertical alignment set to center. + * + * @param workbook Workbook + * @return Centered CellStyle + */ + public static CellStyle getCenterCellStyle(Workbook workbook) { + CellStyle cellStyle = workbook.createCellStyle(); + cellStyle.setAlignment(HorizontalAlignment.CENTER); + cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + return cellStyle; + } - /** - * Merge a range of cells. - * @param sheet Sheet - * @param firstRow Index of first row - * @param lastRow Index of last row (inclusive), must be equal to or larger than - * {@code firstRow} - * @param firstCol Index of first column - * @param lastCol Index of last column (inclusive), must be equal to or larger than - * {@code firstCol} - */ - public static void mergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { - if ((lastRow - firstRow) < 1 && (lastCol - firstCol) < 1) { - return; - } + /** + * Merge a range of cells. + * + * @param sheet Sheet + * @param firstRow Index of first row + * @param lastRow Index of last row (inclusive), must be equal to or larger than + * {@code firstRow} + * @param firstCol Index of first column + * @param lastCol Index of last column (inclusive), must be equal to or larger than + * {@code firstCol} + */ + public static void mergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { + if ((lastRow - firstRow) < 1 && (lastCol - firstCol) < 1) { + return; + } - sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); - } + sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); + } - /** - * Get the string content of the specified cell. - * @param sheet Sheet - * @param rowIndex Row index - * @param cellIndex Cell index - * @return String value of the cell, or an empty string if the cell is null - */ - public static String getCellStringValue(Sheet sheet, int rowIndex, int cellIndex) { - Row driverAttributesRow = sheet.getRow(rowIndex); - if (Objects.isNull(driverAttributesRow)) { - return ""; - } + /** + * Get the string content of the specified cell. + * + * @param sheet Sheet + * @param rowIndex Row index + * @param cellIndex Cell index + * @return String value of the cell, or an empty string if the cell is null + */ + public static String getCellStringValue(Sheet sheet, int rowIndex, int cellIndex) { + Row driverAttributesRow = sheet.getRow(rowIndex); + if (Objects.isNull(driverAttributesRow)) { + return ""; + } - Cell driverAttributesCell = driverAttributesRow.getCell(cellIndex); - if (Objects.isNull(driverAttributesCell)) { - return ""; - } + Cell driverAttributesCell = driverAttributesRow.getCell(cellIndex); + if (Objects.isNull(driverAttributesCell)) { + return ""; + } - DataFormatter formatter = new DataFormatter(); - return formatter.formatCellValue(driverAttributesCell); - } + DataFormatter formatter = new DataFormatter(); + return formatter.formatCellValue(driverAttributesCell); + } - /** - * Create a cell with the specified value. - * @param row Row - * @param cellIndex Cell index - * @param cellValue Cell value - */ - public static void createCell(Row row, int cellIndex, String cellValue) { - createCellWithStyle(row, cellIndex, cellValue, null); - } + /** + * Create a cell with the specified value. + * + * @param row Row + * @param cellIndex Cell index + * @param cellValue Cell value + */ + public static void createCell(Row row, int cellIndex, String cellValue) { + createCellWithStyle(row, cellIndex, cellValue, null); + } - /** - * Create a cell with the specified value and style. - * @param row Row - * @param cellIndex Cell index - * @param cellValue Cell value - * @param cellStyle Cell style - */ - public static void createCellWithStyle(Row row, int cellIndex, String cellValue, CellStyle cellStyle) { - Cell deviceNameCell = row.createCell(cellIndex); - deviceNameCell.setCellValue(cellValue); + /** + * Create a cell with the specified value and style. + * + * @param row Row + * @param cellIndex Cell index + * @param cellValue Cell value + * @param cellStyle Cell style + */ + public static void createCellWithStyle(Row row, int cellIndex, String cellValue, CellStyle cellStyle) { + Cell deviceNameCell = row.createCell(cellIndex); + deviceNameCell.setCellValue(cellValue); - if (Objects.nonNull(cellStyle)) { - deviceNameCell.setCellStyle(cellStyle); - } - } + if (Objects.nonNull(cellStyle)) { + deviceNameCell.setCellStyle(cellStyle); + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/RegexUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/RegexUtil.java index 629d3b1fb..ae3b3d836 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/RegexUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/RegexUtil.java @@ -35,85 +35,91 @@ import java.math.BigDecimal; */ public class RegexUtil { - private RegexUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private RegexUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Check if string is in numeric format - * @param content String to check - * @return true if numeric, false otherwise - */ - public static boolean isNumeric(String content) { - if (StringUtils.isEmpty(content)) { - return false; - } - try { - new BigDecimal(content); - return true; - } - catch (NumberFormatException e) { - return false; - } - } + /** + * Check if string is in numeric format + * + * @param content String to check + * @return true if numeric, false otherwise + */ + public static boolean isNumeric(String content) { + if (StringUtils.isEmpty(content)) { + return false; + } + try { + new BigDecimal(content); + return true; + } catch (NumberFormatException e) { + return false; + } + } - /** - * Check if string is in name format (2-32 characters) - * @param name String to check - * @return true if valid name format, false otherwise - */ - public static boolean isName(String name) { - String regex = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$"; - return name.matches(regex); - } + /** + * Check if string is in name format (2-32 characters) + * + * @param name String to check + * @return true if valid name format, false otherwise + */ + public static boolean isName(String name) { + String regex = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_#@/.|]{1,31}$"; + return name.matches(regex); + } - /** - * Check if string is in mobile phone format - * @param phone Phone number string to check - * @return true if valid mobile format, false otherwise - */ - public static boolean isPhone(String phone) { - String regex = "^1([3-9])\\d{9}$"; - return phone.matches(regex); - } + /** + * Check if string is in mobile phone format + * + * @param phone Phone number string to check + * @return true if valid mobile format, false otherwise + */ + public static boolean isPhone(String phone) { + String regex = "^1([3-9])\\d{9}$"; + return phone.matches(regex); + } - /** - * Check if string is in email address format - * @param mail Email address to check - * @return true if valid email format, false otherwise - */ - public static boolean isMail(String mail) { - String regex = "^[A-Za-z0-9_.-]+@[A-Za-z0-9]+\\.[A-Za-z0-9]+$"; - return mail.matches(regex); - } + /** + * Check if string is in email address format + * + * @param mail Email address to check + * @return true if valid email format, false otherwise + */ + public static boolean isMail(String mail) { + String regex = "^[A-Za-z0-9_.-]+@[A-Za-z0-9]+\\.[A-Za-z0-9]+$"; + return mail.matches(regex); + } - /** - * Check if string is in password format (8-16 characters) - * @param password Password string to check - * @return true if valid password format, false otherwise - */ - public static boolean isPassword(String password) { - String regex = "^[a-zA-Z]\\w{7,15}$"; - return password.matches(regex); - } + /** + * Check if string is in password format (8-16 characters) + * + * @param password Password string to check + * @return true if valid password format, false otherwise + */ + public static boolean isPassword(String password) { + String regex = "^[a-zA-Z]\\w{7,15}$"; + return password.matches(regex); + } - /** - * Check if string is in host format - * @param host Host string to check - * @return true if valid host format, false otherwise - */ - public static boolean isHost(String host) { - String regex = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$"; - return host.matches(regex); - } + /** + * Check if string is in host format + * + * @param host Host string to check + * @return true if valid host format, false otherwise + */ + public static boolean isHost(String host) { + String regex = "^((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}$"; + return host.matches(regex); + } - /** - * Check if port is in valid driver port range - * @param port Port number to check - * @return true if valid driver port (8600-8799), false otherwise - */ - public static boolean isDriverPort(int port) { - return port >= 8600 && port <= 8799; - } + /** + * Check if port is in valid driver port range + * + * @param port Port number to check + * @return true if valid driver port (8600-8799), false otherwise + */ + public static boolean isDriverPort(int port) { + return port >= 8600 && port <= 8799; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeRangeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeRangeUtil.java index f317ecb2e..5b78408a2 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeRangeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeRangeUtil.java @@ -42,110 +42,113 @@ import java.time.LocalDateTime; */ public final class TimeRangeUtil { - /** - * Default hour spans for each rolling preset. - */ - public static final int HOURS_24H = 24; + /** + * Default hour spans for each rolling preset. + */ + public static final int HOURS_24H = 24; - public static final int HOURS_7D = 24 * 7; + public static final int HOURS_7D = 24 * 7; - public static final int HOURS_30D = 24 * 30; + public static final int HOURS_30D = 24 * 30; - private TimeRangeUtil() { - } + private TimeRangeUtil() { + } - /** - * Resolve the lower-bound timestamp for a range query. - * @param rangeKey parsed key enum; {@code null} falls back to {@code rangeHours} - * @param rangeHours legacy integer fallback; {@code null} or non-positive means "no - * bound" - * @return lower-bound {@code LocalDateTime}, or {@code null} when the caller should - * not filter by {@code create_time} - */ - public static LocalDateTime resolveFrom(TimeRangeKeyEnum rangeKey, Integer rangeHours) { - if (rangeKey != null) { - return switch (rangeKey) { - case TODAY -> LocalDate.now().atStartOfDay(); - case H24 -> LocalDateTime.now().minusHours(HOURS_24H); - case D7 -> LocalDateTime.now().minusHours(HOURS_7D); - case D30 -> LocalDateTime.now().minusHours(HOURS_30D); - }; - } - if (rangeHours != null && rangeHours > 0) { - return LocalDateTime.now().minusHours(rangeHours); - } - return null; - } + /** + * Resolve the lower-bound timestamp for a range query. + * + * @param rangeKey parsed key enum; {@code null} falls back to {@code rangeHours} + * @param rangeHours legacy integer fallback; {@code null} or non-positive means "no + * bound" + * @return lower-bound {@code LocalDateTime}, or {@code null} when the caller should + * not filter by {@code create_time} + */ + public static LocalDateTime resolveFrom(TimeRangeKeyEnum rangeKey, Integer rangeHours) { + if (rangeKey != null) { + return switch (rangeKey) { + case TODAY -> LocalDate.now().atStartOfDay(); + case H24 -> LocalDateTime.now().minusHours(HOURS_24H); + case D7 -> LocalDateTime.now().minusHours(HOURS_7D); + case D30 -> LocalDateTime.now().minusHours(HOURS_30D); + }; + } + if (rangeHours != null && rangeHours > 0) { + return LocalDateTime.now().minusHours(rangeHours); + } + return null; + } - /** - * Convenience overload that accepts the raw wire-format code. - */ - public static LocalDateTime resolveFrom(String rangeKeyCode, Integer rangeHours) { - return resolveFrom(TimeRangeKeyEnum.ofCode(rangeKeyCode), rangeHours); - } + /** + * Convenience overload that accepts the raw wire-format code. + */ + public static LocalDateTime resolveFrom(String rangeKeyCode, Integer rangeHours) { + return resolveFrom(TimeRangeKeyEnum.ofCode(rangeKeyCode), rangeHours); + } - /** - * Convert a range key to the hour span it represents, so existing mappers that only - * accept {@code rangeHours} (e.g. {@code /top}, {@code /stats/timeseries} granularity - * math) can keep working unchanged. {@code TODAY} is reported as the number of hours - * since local midnight rounded up to the next whole hour (minimum 1), which lines up - * with sparkline bucketing. - * @return effective hour span, or {@code null} when no bound applies - */ - public static Integer resolveHours(TimeRangeKeyEnum rangeKey, Integer rangeHours) { - if (rangeKey != null) { - return switch (rangeKey) { - case TODAY -> { - LocalDateTime midnight = LocalDate.now().atStartOfDay(); - long minutes = java.time.Duration.between(midnight, LocalDateTime.now()).toMinutes(); - // round up to the next whole hour so bucketed queries cover the full - // day so far - int hours = (int) Math.max(1, (minutes + 59) / 60); - yield hours; - } - case H24 -> HOURS_24H; - case D7 -> HOURS_7D; - case D30 -> HOURS_30D; - }; - } - if (rangeHours != null && rangeHours > 0) { - return rangeHours; - } - return null; - } + /** + * Convert a range key to the hour span it represents, so existing mappers that only + * accept {@code rangeHours} (e.g. {@code /top}, {@code /stats/timeseries} granularity + * math) can keep working unchanged. {@code TODAY} is reported as the number of hours + * since local midnight rounded up to the next whole hour (minimum 1), which lines up + * with sparkline bucketing. + * + * @return effective hour span, or {@code null} when no bound applies + */ + public static Integer resolveHours(TimeRangeKeyEnum rangeKey, Integer rangeHours) { + if (rangeKey != null) { + return switch (rangeKey) { + case TODAY -> { + LocalDateTime midnight = LocalDate.now().atStartOfDay(); + long minutes = java.time.Duration.between(midnight, LocalDateTime.now()).toMinutes(); + // round up to the next whole hour so bucketed queries cover the full + // day so far + int hours = (int) Math.max(1, (minutes + 59) / 60); + yield hours; + } + case H24 -> HOURS_24H; + case D7 -> HOURS_7D; + case D30 -> HOURS_30D; + }; + } + if (rangeHours != null && rangeHours > 0) { + return rangeHours; + } + return null; + } - /** - * Convenience overload that accepts the raw wire-format code. - */ - public static Integer resolveHours(String rangeKeyCode, Integer rangeHours) { - return resolveHours(TimeRangeKeyEnum.ofCode(rangeKeyCode), rangeHours); - } + /** + * Convenience overload that accepts the raw wire-format code. + */ + public static Integer resolveHours(String rangeKeyCode, Integer rangeHours) { + return resolveHours(TimeRangeKeyEnum.ofCode(rangeKeyCode), rangeHours); + } - /** - * Convert a range key to a day count for endpoints that bucket by day (e.g. - * {@code /alert/trend?days=30}). {@code TODAY} and {@code H24} both map to 1 day; the - * legacy {@code days} integer passes through. - * @return effective day count, or {@code null} when no bound applies - */ - public static Integer resolveDays(TimeRangeKeyEnum rangeKey, Integer days) { - if (rangeKey != null) { - return switch (rangeKey) { - case TODAY, H24 -> 1; - case D7 -> 7; - case D30 -> 30; - }; - } - if (days != null && days > 0) { - return days; - } - return null; - } + /** + * Convert a range key to a day count for endpoints that bucket by day (e.g. + * {@code /alert/trend?days=30}). {@code TODAY} and {@code H24} both map to 1 day; the + * legacy {@code days} integer passes through. + * + * @return effective day count, or {@code null} when no bound applies + */ + public static Integer resolveDays(TimeRangeKeyEnum rangeKey, Integer days) { + if (rangeKey != null) { + return switch (rangeKey) { + case TODAY, H24 -> 1; + case D7 -> 7; + case D30 -> 30; + }; + } + if (days != null && days > 0) { + return days; + } + return null; + } - /** - * Convenience overload that accepts the raw wire-format code. - */ - public static Integer resolveDays(String rangeKeyCode, Integer days) { - return resolveDays(TimeRangeKeyEnum.ofCode(rangeKeyCode), days); - } + /** + * Convenience overload that accepts the raw wire-format code. + */ + public static Integer resolveDays(String rangeKeyCode, Integer days) { + return resolveDays(TimeRangeKeyEnum.ofCode(rangeKeyCode), days); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeUtil.java index 1ef69c5d2..8ac5e975c 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TimeUtil.java @@ -40,102 +40,107 @@ import java.util.Date; @Slf4j public class TimeUtil { - /** - * ThreadLocal SimpleDateFormat to ensure thread safety - */ - private static final ThreadLocal DEFAULT_DATE_FORMAT_THREAD_LOCAL = ThreadLocal - .withInitial(() -> new SimpleDateFormat(TimeConstant.DEFAULT_DATE_FORMAT)); + /** + * ThreadLocal SimpleDateFormat to ensure thread safety + */ + private static final ThreadLocal DEFAULT_DATE_FORMAT_THREAD_LOCAL = ThreadLocal + .withInitial(() -> new SimpleDateFormat(TimeConstant.DEFAULT_DATE_FORMAT)); - private static final ThreadLocal COMPLETE_DATE_FORMAT_THREAD_LOCAL = ThreadLocal - .withInitial(() -> new SimpleDateFormat(TimeConstant.COMPLETE_DATE_FORMAT)); + private static final ThreadLocal COMPLETE_DATE_FORMAT_THREAD_LOCAL = ThreadLocal + .withInitial(() -> new SimpleDateFormat(TimeConstant.COMPLETE_DATE_FORMAT)); - private TimeUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private TimeUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get milliseconds from Date - * @param date {@link Date} - * @return Milliseconds since epoch - */ - public static long milliSeconds(Date date) { - return date.getTime(); - } + /** + * Get milliseconds from Date + * + * @param date {@link Date} + * @return Milliseconds since epoch + */ + public static long milliSeconds(Date date) { + return date.getTime(); + } - /** - * Get Date from milliseconds - * @param milliSeconds Milliseconds since epoch - * @return Date {@link Date} - */ - public static Date localDateTime(long milliSeconds) { - return new Date(milliSeconds); - } + /** + * Get Date from milliseconds + * + * @param milliSeconds Milliseconds since epoch + * @return Date {@link Date} + */ + public static Date localDateTime(long milliSeconds) { + return new Date(milliSeconds); + } - /** - * Calculate expire time by adding amount to specified calendar field - * @param amount Integer amount to add - * @param field Calendar field : {@link Calendar Calendar.HOUR/MINUTE/...} - * @return Date with calculated expire time - */ - public static Date expireTime(int amount, int field) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(new Date()); - calendar.add(field, amount); - return calendar.getTime(); - } + /** + * Calculate expire time by adding amount to specified calendar field + * + * @param amount Integer amount to add + * @param field Calendar field : {@link Calendar Calendar.HOUR/MINUTE/...} + * @return Date with calculated expire time + */ + public static Date expireTime(int amount, int field) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + calendar.add(field, amount); + return calendar.getTime(); + } - /** - * Format date using yyyy-MM-dd HH:mm:ss pattern - * @param date {@link Date} - * @return Formatted date string - */ - public static String defaultFormat(Date date) { - return DEFAULT_DATE_FORMAT_THREAD_LOCAL.get().format(date); - } + /** + * Format date using yyyy-MM-dd HH:mm:ss pattern + * + * @param date {@link Date} + * @return Formatted date string + */ + public static String defaultFormat(Date date) { + return DEFAULT_DATE_FORMAT_THREAD_LOCAL.get().format(date); + } - /** - * Format date using yyyy-MM-dd HH:mm:ss.SSS pattern - * @param date {@link Date} - * @return Formatted date string with milliseconds - */ - public static String completeFormat(Date date) { - return COMPLETE_DATE_FORMAT_THREAD_LOCAL.get().format(date); - } + /** + * Format date using yyyy-MM-dd HH:mm:ss.SSS pattern + * + * @param date {@link Date} + * @return Formatted date string with milliseconds + */ + public static String completeFormat(Date date) { + return COMPLETE_DATE_FORMAT_THREAD_LOCAL.get().format(date); + } - /** - * Parse date string yyyy-MM-dd HH:mm:ss to Date - * @param dateString Date string in yyyy-MM-dd HH:mm:ss format - * @return Date object - */ - public static Date defaultDate(String dateString) { - try { - return DEFAULT_DATE_FORMAT_THREAD_LOCAL.get().parse(dateString); - } - catch (ParseException e) { - return null; - } - } + /** + * Parse date string yyyy-MM-dd HH:mm:ss to Date + * + * @param dateString Date string in yyyy-MM-dd HH:mm:ss format + * @return Date object + */ + public static Date defaultDate(String dateString) { + try { + return DEFAULT_DATE_FORMAT_THREAD_LOCAL.get().parse(dateString); + } catch (ParseException e) { + return null; + } + } - /** - * Parse date string yyyy-MM-dd HH:mm:ss.SSS to Date - * @param dateString Date string in yyyy-MM-dd HH:mm:ss.SSS format - * @return Date object - */ - public static Date completeDate(String dateString) { - try { - return COMPLETE_DATE_FORMAT_THREAD_LOCAL.get().parse(dateString); - } - catch (ParseException e) { - return null; - } - } + /** + * Parse date string yyyy-MM-dd HH:mm:ss.SSS to Date + * + * @param dateString Date string in yyyy-MM-dd HH:mm:ss.SSS format + * @return Date object + */ + public static Date completeDate(String dateString) { + try { + return COMPLETE_DATE_FORMAT_THREAD_LOCAL.get().parse(dateString); + } catch (ParseException e) { + return null; + } + } - /** - * Remove the current thread's values from the ThreadLocal variables. - */ - public static void clean() { - DEFAULT_DATE_FORMAT_THREAD_LOCAL.remove(); - COMPLETE_DATE_FORMAT_THREAD_LOCAL.remove(); - } + /** + * Remove the current thread's values from the ThreadLocal variables. + */ + public static void clean() { + DEFAULT_DATE_FORMAT_THREAD_LOCAL.remove(); + COMPLETE_DATE_FORMAT_THREAD_LOCAL.remove(); + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TreeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TreeUtil.java index d5c29c5e1..e2c403f8f 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TreeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/TreeUtil.java @@ -37,65 +37,68 @@ import java.util.List; @Slf4j public class TreeUtil { - /** - * Build a tree structure using a two-level loop. - * @param Object type extending {@link TreeNode} - * @param treeNodes List of tree nodes to be processed - * @param root Root node identifier - * @return T Tree - */ - public List buildByLoop(List treeNodes, Object root) { - List trees = new ArrayList<>(16); - for (T treeNode : treeNodes) { - if (root.equals(treeNode.getParentId())) { - trees.add(treeNode); - } - for (T it : treeNodes) { - if (it.getParentId() == treeNode.getId()) { - if (treeNode.getChildren() == null) { - treeNode.setChildren(new ArrayList<>(16)); - } - treeNode.add(it); - } - } - } - return trees; - } + /** + * Build a tree structure using a two-level loop. + * + * @param Object type extending {@link TreeNode} + * @param treeNodes List of tree nodes to be processed + * @param root Root node identifier + * @return T Tree + */ + public List buildByLoop(List treeNodes, Object root) { + List trees = new ArrayList<>(16); + for (T treeNode : treeNodes) { + if (root.equals(treeNode.getParentId())) { + trees.add(treeNode); + } + for (T it : treeNodes) { + if (it.getParentId() == treeNode.getId()) { + if (treeNode.getChildren() == null) { + treeNode.setChildren(new ArrayList<>(16)); + } + treeNode.add(it); + } + } + } + return trees; + } - /** - * Build a tree structure using recursive calls. - * @param Object type extending {@link TreeNode} - * @param treeNodes List of tree nodes to be processed - * @param root Root node identifier - * @return T Tree - */ - public List buildByRecursive(List treeNodes, Object root) { - List trees = new ArrayList<>(16); - for (T treeNode : treeNodes) { - if (root.equals(treeNode.getParentId())) { - trees.add(findChildren(treeNode, treeNodes)); - } - } - return trees; - } + /** + * Build a tree structure using recursive calls. + * + * @param Object type extending {@link TreeNode} + * @param treeNodes List of tree nodes to be processed + * @param root Root node identifier + * @return T Tree + */ + public List buildByRecursive(List treeNodes, Object root) { + List trees = new ArrayList<>(16); + for (T treeNode : treeNodes) { + if (root.equals(treeNode.getParentId())) { + trees.add(findChildren(treeNode, treeNodes)); + } + } + return trees; + } - /** - * Recursively find and attach child nodes. - * @param Object type extending {@link TreeNode} - * @param treeNode Current node - * @param treeNodes List of all tree nodes - * @return T Tree - */ - public T findChildren(T treeNode, List treeNodes) { - for (T it : treeNodes) { - if (treeNode.getId() == it.getParentId()) { - if (treeNode.getChildren() == null) { - treeNode.setChildren(new ArrayList<>(16)); - } - treeNode.add(findChildren(it, treeNodes)); - } - } - return treeNode; - } + /** + * Recursively find and attach child nodes. + * + * @param Object type extending {@link TreeNode} + * @param treeNode Current node + * @param treeNodes List of all tree nodes + * @return T Tree + */ + public T findChildren(T treeNode, List treeNodes) { + for (T it : treeNodes) { + if (treeNode.getId() == it.getParentId()) { + if (treeNode.getChildren() == null) { + treeNode.setChildren(new ArrayList<>(16)); + } + treeNode.add(findChildren(it, treeNodes)); + } + } + return treeNode; + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/X509Util.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/X509Util.java index 61259d445..134c5711b 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/X509Util.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/X509Util.java @@ -55,99 +55,95 @@ import java.util.Objects; @Slf4j public class X509Util { - private X509Util() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private X509Util() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - // TODO: 2023.10.16 There are issues here, currently in an unavailable state + // TODO: 2023.10.16 There are issues here, currently in an unavailable state - /** - * Create SSL socket factory with custom certificates - * @param caCrtFile CA certificate file path - * @param crtFile Client certificate file path - * @param keyFile Client private key file path - * @param password Private key password - * @return Configured SSL socket factory - */ - public static SSLSocketFactory getSSLSocketFactory(final String caCrtFile, final String crtFile, - final String keyFile, final String password) { - try { - Security.addProvider(new BouncyCastleProvider()); + /** + * Create SSL socket factory with custom certificates + * + * @param caCrtFile CA certificate file path + * @param crtFile Client certificate file path + * @param keyFile Client private key file path + * @param password Private key password + * @return Configured SSL socket factory + */ + public static SSLSocketFactory getSSLSocketFactory(final String caCrtFile, final String crtFile, + final String keyFile, final String password) { + try { + Security.addProvider(new BouncyCastleProvider()); - // load CA certificate - X509Certificate caCert = loadCertificate(caCrtFile); - // CA certificate is used to authenticate server - KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - caKeyStore.load(null, null); - caKeyStore.setCertificateEntry("cacertfile", caCert); - TrustManagerFactory trustManagerFactory = TrustManagerFactory - .getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init(caKeyStore); + // load CA certificate + X509Certificate caCert = loadCertificate(caCrtFile); + // CA certificate is used to authenticate server + KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + caKeyStore.load(null, null); + caKeyStore.setCertificateEntry("cacertfile", caCert); + TrustManagerFactory trustManagerFactory = TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); - // load client certificate - X509Certificate cert = loadCertificate(crtFile); - // load client private key - KeyPair key = loadCertificateWithPassword(keyFile, password); - // client key and certificates are sent to server, so it can authenticate us - KeyStore certKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); - certKeyStore.load(null, null); - certKeyStore.setCertificateEntry("certfile", cert); - certKeyStore.setKeyEntry("keyfile", key.getPrivate(), password.toCharArray(), - new java.security.cert.Certificate[] { cert }); - KeyManagerFactory keyManagerFactory = KeyManagerFactory - .getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(certKeyStore, password.toCharArray()); + // load client certificate + X509Certificate cert = loadCertificate(crtFile); + // load client private key + KeyPair key = loadCertificateWithPassword(keyFile, password); + // client key and certificates are sent to server, so it can authenticate us + KeyStore certKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + certKeyStore.load(null, null); + certKeyStore.setCertificateEntry("certfile", cert); + certKeyStore.setKeyEntry("keyfile", key.getPrivate(), password.toCharArray(), + new java.security.cert.Certificate[]{cert}); + KeyManagerFactory keyManagerFactory = KeyManagerFactory + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(certKeyStore, password.toCharArray()); - // finally, create SSL socket factory - SSLContext context = SSLContext.getInstance("TLSv1.2"); - context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); + // finally, create SSL socket factory + SSLContext context = SSLContext.getInstance("TLSv1.2"); + context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); - return context.getSocketFactory(); - } - catch (Exception e) { - throw new ConnectorException(e.getMessage()); - } - } + return context.getSocketFactory(); + } catch (Exception e) { + throw new ConnectorException(e.getMessage()); + } + } - // TODO: 2023.10.16 There are issues here, currently in an unavailable state - private static T loadCertificate(String caCrtFile) throws IOException { - return loadCertificateWithPassword(caCrtFile, null); - } + // TODO: 2023.10.16 There are issues here, currently in an unavailable state + private static T loadCertificate(String caCrtFile) throws IOException { + return loadCertificateWithPassword(caCrtFile, null); + } - // TODO: 2023.10.16 There are issues here, currently in an unavailable state - @SuppressWarnings("unchecked") - private static T loadCertificateWithPassword(String caCrtFile, String password) throws IOException { - PemReader reader = null; - try { - String classPath = "classpath:"; - if (caCrtFile.startsWith(classPath)) { - InputStream inputStream = X509Util.class.getResourceAsStream(caCrtFile.replace(classPath, "")); - InputStreamReader inputStreamReader = new InputStreamReader(inputStream); - if (Objects.nonNull(password)) { - reader = new PemReader(inputStreamReader); - } - else { - reader = new PemReader(inputStreamReader); - } - } - else { - Path path = Paths.get(caCrtFile); - ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(path)); - InputStreamReader inputStreamReader = new InputStreamReader(inputStream); - if (Objects.nonNull(password)) { - reader = new PemReader(inputStreamReader); - } - else { - reader = new PemReader(inputStreamReader); - } - } - return (T) reader.readPemObject(); - } - finally { - if (Objects.nonNull(reader)) { - reader.close(); - } - } - } + // TODO: 2023.10.16 There are issues here, currently in an unavailable state + @SuppressWarnings("unchecked") + private static T loadCertificateWithPassword(String caCrtFile, String password) throws IOException { + PemReader reader = null; + try { + String classPath = "classpath:"; + if (caCrtFile.startsWith(classPath)) { + InputStream inputStream = X509Util.class.getResourceAsStream(caCrtFile.replace(classPath, "")); + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + if (Objects.nonNull(password)) { + reader = new PemReader(inputStreamReader); + } else { + reader = new PemReader(inputStreamReader); + } + } else { + Path path = Paths.get(caCrtFile); + ByteArrayInputStream inputStream = new ByteArrayInputStream(Files.readAllBytes(path)); + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + if (Objects.nonNull(password)) { + reader = new PemReader(inputStreamReader); + } else { + reader = new PemReader(inputStreamReader); + } + } + return (T) reader.readPemObject(); + } finally { + if (Objects.nonNull(reader)) { + reader.close(); + } + } + } } diff --git a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ZoneDateTimeUtil.java b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ZoneDateTimeUtil.java index 179927063..39eb73806 100644 --- a/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ZoneDateTimeUtil.java +++ b/dc3-common/dc3-common-public/src/main/java/io/github/pnoker/common/utils/ZoneDateTimeUtil.java @@ -37,117 +37,125 @@ import java.time.temporal.ChronoUnit; @Slf4j public class ZoneDateTimeUtil { - private ZoneDateTimeUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ZoneDateTimeUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get the default date-time format. - *

- * Pattern: yyyy-MM-dd HH:mm:ss - * @return {@link DateTimeFormatter} - */ - public static DateTimeFormatter getDefaultDateTimeFormatter() { - return DateTimeFormatter.ofPattern(TimeConstant.DEFAULT_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the default date-time format. + *

+ * Pattern: yyyy-MM-dd HH:mm:ss + * + * @return {@link DateTimeFormatter} + */ + public static DateTimeFormatter getDefaultDateTimeFormatter() { + return DateTimeFormatter.ofPattern(TimeConstant.DEFAULT_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get the complete date-time format. - *

- * Pattern: yyyy-MM-dd HH:mm:ss.SSS - * @return {@link DateTimeFormatter} - */ - public static DateTimeFormatter getCompleteDateTimeFormatter() { - return DateTimeFormatter.ofPattern(TimeConstant.COMPLETE_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the complete date-time format. + *

+ * Pattern: yyyy-MM-dd HH:mm:ss.SSS + * + * @return {@link DateTimeFormatter} + */ + public static DateTimeFormatter getCompleteDateTimeFormatter() { + return DateTimeFormatter.ofPattern(TimeConstant.COMPLETE_DATE_FORMAT).withZone(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get the current time with default time zone. - * @return ZonedDateTime {@link ZonedDateTime} - */ - public static ZonedDateTime now() { - return ZonedDateTime.now(TimeConstant.DEFAULT_ZONEID); - } + /** + * Get the current time with default time zone. + * + * @return ZonedDateTime {@link ZonedDateTime} + */ + public static ZonedDateTime now() { + return ZonedDateTime.now(TimeConstant.DEFAULT_ZONEID); + } - /** - * Get milliseconds from the given {@link ZonedDateTime}. - * @param zonedDateTime {@link ZonedDateTime} - * @return Milliseconds - */ - public static long milliSeconds(ZonedDateTime zonedDateTime) { - return zonedDateTime.toInstant().toEpochMilli(); - } + /** + * Get milliseconds from the given {@link ZonedDateTime}. + * + * @param zonedDateTime {@link ZonedDateTime} + * @return Milliseconds + */ + public static long milliSeconds(ZonedDateTime zonedDateTime) { + return zonedDateTime.toInstant().toEpochMilli(); + } - /** - * Get a {@link ZonedDateTime} from milliseconds. - * @param milliSeconds Milliseconds - * @return ZonedDateTime {@link ZonedDateTime} - */ - public static ZonedDateTime dateTime(long milliSeconds) { - Instant instant = Instant.ofEpochMilli(milliSeconds); - return ZonedDateTime.ofInstant(instant, TimeConstant.DEFAULT_ZONEID); - } + /** + * Get a {@link ZonedDateTime} from milliseconds. + * + * @param milliSeconds Milliseconds + * @return ZonedDateTime {@link ZonedDateTime} + */ + public static ZonedDateTime dateTime(long milliSeconds) { + Instant instant = Instant.ofEpochMilli(milliSeconds); + return ZonedDateTime.ofInstant(instant, TimeConstant.DEFAULT_ZONEID); + } - /** - * Delay time by the specified amount and unit, e.g., HOUR/MINUTE/... - * @param amount Integer - * @param field ChronoUnit field : {@link ChronoUnit ChronoUnit.HOUR/MINUTE/...} - * @return ZonedDateTime - */ - public static ZonedDateTime expireTime(int amount, ChronoUnit field) { - ZonedDateTime zonedDateTime = ZoneDateTimeUtil.now(); - return zonedDateTime.plus(amount, field); - } + /** + * Delay time by the specified amount and unit, e.g., HOUR/MINUTE/... + * + * @param amount Integer + * @param field ChronoUnit field : {@link ChronoUnit ChronoUnit.HOUR/MINUTE/...} + * @return ZonedDateTime + */ + public static ZonedDateTime expireTime(int amount, ChronoUnit field) { + ZonedDateTime zonedDateTime = ZoneDateTimeUtil.now(); + return zonedDateTime.plus(amount, field); + } - /** - * Format time using the pattern yyyy-MM-dd HH:mm:ss. - * @param zonedDateTime {@link ZonedDateTime} - * @return Formatted time string - */ - public static String defaultFormat(ZonedDateTime zonedDateTime) { - DateTimeFormatter formatter = getDefaultDateTimeFormatter(); - return zonedDateTime.format(formatter); - } + /** + * Format time using the pattern yyyy-MM-dd HH:mm:ss. + * + * @param zonedDateTime {@link ZonedDateTime} + * @return Formatted time string + */ + public static String defaultFormat(ZonedDateTime zonedDateTime) { + DateTimeFormatter formatter = getDefaultDateTimeFormatter(); + return zonedDateTime.format(formatter); + } - /** - * Format time using the pattern yyyy-MM-dd HH:mm:ss.SSS. - * @param zonedDateTime {@link ZonedDateTime} - * @return Formatted time string - */ - public static String completeFormat(ZonedDateTime zonedDateTime) { - DateTimeFormatter formatter = getCompleteDateTimeFormatter(); - return zonedDateTime.format(formatter); - } + /** + * Format time using the pattern yyyy-MM-dd HH:mm:ss.SSS. + * + * @param zonedDateTime {@link ZonedDateTime} + * @return Formatted time string + */ + public static String completeFormat(ZonedDateTime zonedDateTime) { + DateTimeFormatter formatter = getCompleteDateTimeFormatter(); + return zonedDateTime.format(formatter); + } - /** - * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss to {@link ZonedDateTime}. - * @param dateString yyyy-MM-dd HH:mm:ss - * @return ZonedDateTime or {@code null} if parsing fails - */ - public static ZonedDateTime defaultDate(String dateString) { - try { - DateTimeFormatter formatter = getDefaultDateTimeFormatter(); - return ZonedDateTime.parse(dateString, formatter); - } - catch (DateTimeParseException e) { - return null; - } - } + /** + * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss to {@link ZonedDateTime}. + * + * @param dateString yyyy-MM-dd HH:mm:ss + * @return ZonedDateTime or {@code null} if parsing fails + */ + public static ZonedDateTime defaultDate(String dateString) { + try { + DateTimeFormatter formatter = getDefaultDateTimeFormatter(); + return ZonedDateTime.parse(dateString, formatter); + } catch (DateTimeParseException e) { + return null; + } + } - /** - * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss.SSS to - * {@link ZonedDateTime}. - * @param dateString Date string - * @return ZonedDateTime or {@code null} if parsing fails - */ - public static ZonedDateTime completeDate(String dateString) { - try { - DateTimeFormatter formatter = getCompleteDateTimeFormatter(); - return ZonedDateTime.parse(dateString, formatter); - } - catch (DateTimeParseException e) { - return null; - } - } + /** + * Parse a time string in the pattern yyyy-MM-dd HH:mm:ss.SSS to + * {@link ZonedDateTime}. + * + * @param dateString Date string + * @return ZonedDateTime or {@code null} if parsing fails + */ + public static ZonedDateTime completeDate(String dateString) { + try { + DateTimeFormatter formatter = getCompleteDateTimeFormatter(); + return ZonedDateTime.parse(dateString, formatter); + } catch (DateTimeParseException e) { + return null; + } + } } diff --git a/dc3-common/dc3-common-quartz/README.md b/dc3-common/dc3-common-quartz/README.md index b3cae7a82..96c55c102 100644 --- a/dc3-common/dc3-common-quartz/README.md +++ b/dc3-common/dc3-common-quartz/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-quartz` is the shared Quartz scheduler module of the IoT DC3 platform. It provides a reusable `QuartzService` for programmatically creating, updating, pausing, and +`dc3-common-quartz` is the shared Quartz scheduler module of the IoT DC3 platform. It provides a reusable +`QuartzService` for programmatically creating, updating, pausing, and triggering scheduled jobs across services, primarily used in the Manager Center for platform-level periodic tasks. ## Module Information diff --git a/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/config/ActiveQuartzProfileConfig.java b/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/config/ActiveQuartzProfileConfig.java index 4de839ed1..66bedf997 100644 --- a/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/config/ActiveQuartzProfileConfig.java +++ b/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/config/ActiveQuartzProfileConfig.java @@ -42,14 +42,15 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveQuartzProfileConfig implements EnvironmentPostProcessor { - /** - * Post-process environment to add the "quartz" active profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("quartz"); - } + /** + * Post-process environment to add the "quartz" active profile + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("quartz"); + } } diff --git a/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/quartz/QuartzService.java b/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/quartz/QuartzService.java index ff35c271d..e819d3eb9 100644 --- a/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/quartz/QuartzService.java +++ b/dc3-common/dc3-common-quartz/src/main/java/io/github/pnoker/common/quartz/QuartzService.java @@ -19,16 +19,7 @@ package io.github.pnoker.common.quartz; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.quartz.CronScheduleBuilder; -import org.quartz.DateBuilder; -import org.quartz.Job; -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SimpleScheduleBuilder; -import org.quartz.Trigger; -import org.quartz.TriggerBuilder; +import org.quartz.*; import org.springframework.context.annotation.Configuration; /** @@ -48,70 +39,74 @@ import org.springframework.context.annotation.Configuration; @Configuration public class QuartzService { - @Resource - private Scheduler scheduler; + @Resource + private Scheduler scheduler; - /** - * Create scheduled job with interval trigger - * @param group Task group for job organization - * @param name Task name for job identification - * @param interval Time interval between job executions - * @param intervalUnit Time unit for the interval - * @param jobClass Job execution class - * @throws SchedulerException SchedulerException - */ - public void createJobWithInterval(String group, String name, Integer interval, - DateBuilder.IntervalUnit intervalUnit, Class jobClass) throws SchedulerException { - JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build(); - Trigger trigger = TriggerBuilder.newTrigger() - .withIdentity(name, group) - .startAt(DateBuilder.futureDate(1, intervalUnit)) - .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(interval).repeatForever()) - .startNow() - .build(); - scheduler.scheduleJob(jobDetail, trigger); - } + /** + * Create scheduled job with interval trigger + * + * @param group Task group for job organization + * @param name Task name for job identification + * @param interval Time interval between job executions + * @param intervalUnit Time unit for the interval + * @param jobClass Job execution class + * @throws SchedulerException SchedulerException + */ + public void createJobWithInterval(String group, String name, Integer interval, + DateBuilder.IntervalUnit intervalUnit, Class jobClass) throws SchedulerException { + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build(); + Trigger trigger = TriggerBuilder.newTrigger() + .withIdentity(name, group) + .startAt(DateBuilder.futureDate(1, intervalUnit)) + .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(interval).repeatForever()) + .startNow() + .build(); + scheduler.scheduleJob(jobDetail, trigger); + } - /** - * Create scheduled job with cron trigger - * @param group Task group for job organization - * @param name Task name for job identification - * @param cron Cron expression for scheduling - * @param jobClass Job execution class - * @throws SchedulerException SchedulerException - */ - public void createJobWithCron(String group, String name, String cron, Class jobClass) - throws SchedulerException { - JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build(); - Trigger trigger = TriggerBuilder.newTrigger() - .withIdentity(name, group) - .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND)) - .withSchedule(CronScheduleBuilder.cronSchedule(cron)) - .startNow() - .build(); - scheduler.scheduleJob(jobDetail, trigger); - } + /** + * Create scheduled job with cron trigger + * + * @param group Task group for job organization + * @param name Task name for job identification + * @param cron Cron expression for scheduling + * @param jobClass Job execution class + * @throws SchedulerException SchedulerException + */ + public void createJobWithCron(String group, String name, String cron, Class jobClass) + throws SchedulerException { + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(name, group).build(); + Trigger trigger = TriggerBuilder.newTrigger() + .withIdentity(name, group) + .startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND)) + .withSchedule(CronScheduleBuilder.cronSchedule(cron)) + .startNow() + .build(); + scheduler.scheduleJob(jobDetail, trigger); + } - /** - * Start the scheduler service - * @throws SchedulerException SchedulerException - */ - public void startScheduler() throws SchedulerException { - if (!scheduler.isShutdown()) { - scheduler.start(); - } - } + /** + * Start the scheduler service + * + * @throws SchedulerException SchedulerException + */ + public void startScheduler() throws SchedulerException { + if (!scheduler.isShutdown()) { + scheduler.start(); + } + } - /** - * Stop the scheduler service - *

- * Shutdown immediately without waiting for currently executing jobs to complete - * @throws SchedulerException SchedulerException - */ - public void stopScheduler() throws SchedulerException { - if (!scheduler.isShutdown()) { - scheduler.shutdown(); - } - } + /** + * Stop the scheduler service + *

+ * Shutdown immediately without waiting for currently executing jobs to complete + * + * @throws SchedulerException SchedulerException + */ + public void stopScheduler() throws SchedulerException { + if (!scheduler.isShutdown()) { + scheduler.shutdown(); + } + } } diff --git a/dc3-common/dc3-common-rabbitmq/README.md b/dc3-common/dc3-common-rabbitmq/README.md index b2cc8db16..eb8053e2d 100644 --- a/dc3-common/dc3-common-rabbitmq/README.md +++ b/dc3-common/dc3-common-rabbitmq/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-rabbitmq` is the shared RabbitMQ configuration module of the IoT DC3 platform. It defines all topic exchanges, queue bindings, and connection configuration used for +`dc3-common-rabbitmq` is the shared RabbitMQ configuration module of the IoT DC3 platform. It defines all topic +exchanges, queue bindings, and connection configuration used for asynchronous communication between services and drivers. ## Module Information diff --git a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ActiveRabbitProfileConfig.java b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ActiveRabbitProfileConfig.java index d3b5e5d6c..7088e2d3d 100644 --- a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ActiveRabbitProfileConfig.java +++ b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ActiveRabbitProfileConfig.java @@ -42,14 +42,15 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveRabbitProfileConfig implements EnvironmentPostProcessor { - /** - * Post-process environment to add the "rabbitmq" active profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("rabbitmq"); - } + /** + * Post-process environment to add the "rabbitmq" active profile + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("rabbitmq"); + } } diff --git a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ExchangeConfig.java b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ExchangeConfig.java index 8bf21d334..c5766e656 100644 --- a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ExchangeConfig.java +++ b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/ExchangeConfig.java @@ -43,49 +43,54 @@ import org.springframework.context.annotation.Configuration; @Configuration public class ExchangeConfig { - /** - * Event exchange for platform-side load balancing - * @return TopicExchange bean for event messages - */ - @Bean - TopicExchange eventExchange() { - return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_EVENT, true, false); - } + /** + * Event exchange for platform-side load balancing + * + * @return TopicExchange bean for event messages + */ + @Bean + TopicExchange eventExchange() { + return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_EVENT, true, false); + } - /** - * Metadata exchange for platform broadcasting and driver subscription - * @return TopicExchange bean for metadata messages - */ - @Bean - TopicExchange metadataExchange() { - return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_METADATA, true, false); - } + /** + * Metadata exchange for platform broadcasting and driver subscription + * + * @return TopicExchange bean for metadata messages + */ + @Bean + TopicExchange metadataExchange() { + return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_METADATA, true, false); + } - /** - * Command exchange for driver-side load balancing - * @return TopicExchange bean for command messages - */ - @Bean - TopicExchange commandExchange() { - return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_COMMAND, true, false); - } + /** + * Command exchange for driver-side load balancing + * + * @return TopicExchange bean for command messages + */ + @Bean + TopicExchange commandExchange() { + return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_COMMAND, true, false); + } - /** - * Data exchange for platform-side load balancing - * @return TopicExchange bean for data messages - */ - @Bean - TopicExchange valueExchange() { - return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_VALUE, true, false); - } + /** + * Data exchange for platform-side load balancing + * + * @return TopicExchange bean for data messages + */ + @Bean + TopicExchange valueExchange() { + return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_VALUE, true, false); + } - /** - * MQTT exchange for platform-side load balancing - * @return TopicExchange bean for MQTT messages - */ - @Bean - TopicExchange mqttExchange() { - return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_MQTT, true, false); - } + /** + * MQTT exchange for platform-side load balancing + * + * @return TopicExchange bean for MQTT messages + */ + @Bean + TopicExchange mqttExchange() { + return new TopicExchange(RabbitConstant.TOPIC_EXCHANGE_MQTT, true, false); + } } diff --git a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitConfig.java b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitConfig.java index 7c3d1859c..0587cab03 100644 --- a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitConfig.java +++ b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitConfig.java @@ -46,58 +46,61 @@ import org.springframework.context.annotation.Configuration; @Configuration public class RabbitConfig { - private final ConnectionFactory connectionFactory; + private final ConnectionFactory connectionFactory; - public RabbitConfig(ConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory; - } + public RabbitConfig(ConnectionFactory connectionFactory) { + this.connectionFactory = connectionFactory; + } - /** - * Configure RabbitTemplate for message publishing - * @param messageConverter Message converter for JSON serialization - * @return Configured RabbitTemplate bean - */ - @Bean - RabbitTemplate rabbitTemplate(MessageConverter messageConverter) { - RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); - rabbitTemplate.setMessageConverter(messageConverter); - rabbitTemplate.setMandatory(true); - rabbitTemplate - .setReturnsCallback(message -> log.error("Send message[{}] to exchange[{}], routingKey[{}] failed: {}", - message.getMessage(), message.getExchange(), message.getRoutingKey(), message.getReplyText())); - rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { - if (!ack) { - log.error("CorrelationData[{}] ack failed: {}", correlationData, cause); - } - }); - return rabbitTemplate; - } + /** + * Configure RabbitTemplate for message publishing + * + * @param messageConverter Message converter for JSON serialization + * @return Configured RabbitTemplate bean + */ + @Bean + RabbitTemplate rabbitTemplate(MessageConverter messageConverter) { + RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory); + rabbitTemplate.setMessageConverter(messageConverter); + rabbitTemplate.setMandatory(true); + rabbitTemplate + .setReturnsCallback(message -> log.error("Send message[{}] to exchange[{}], routingKey[{}] failed: {}", + message.getMessage(), message.getExchange(), message.getRoutingKey(), message.getReplyText())); + rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { + if (!ack) { + log.error("CorrelationData[{}] ack failed: {}", correlationData, cause); + } + }); + return rabbitTemplate; + } - /** - * Configure Rabbit listener container factory - * @param messageConverter Message converter for JSON deserialization - * @return Configured RabbitListenerContainerFactory bean - */ - @Bean - public RabbitListenerContainerFactory rabbitListenerContainerFactory( - MessageConverter messageConverter) { - SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); - factory.setConnectionFactory(connectionFactory); - factory.setMessageConverter(messageConverter); - factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); - factory.setConcurrentConsumers(2); - factory.setMaxConcurrentConsumers(8); - factory.setPrefetchCount(10); - return factory; - } + /** + * Configure Rabbit listener container factory + * + * @param messageConverter Message converter for JSON deserialization + * @return Configured RabbitListenerContainerFactory bean + */ + @Bean + public RabbitListenerContainerFactory rabbitListenerContainerFactory( + MessageConverter messageConverter) { + SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); + factory.setConnectionFactory(connectionFactory); + factory.setMessageConverter(messageConverter); + factory.setAcknowledgeMode(AcknowledgeMode.MANUAL); + factory.setConcurrentConsumers(2); + factory.setMaxConcurrentConsumers(8); + factory.setPrefetchCount(10); + return factory; + } - /** - * Configure message converter for JSON serialization/deserialization - * @return JacksonJsonMessageConverter bean - */ - @Bean - public MessageConverter messageConverter() { - return new JacksonJsonMessageConverter(JsonUtil.getJsonMapper()); - } + /** + * Configure message converter for JSON serialization/deserialization + * + * @return JacksonJsonMessageConverter bean + */ + @Bean + public MessageConverter messageConverter() { + return new JacksonJsonMessageConverter(JsonUtil.getJsonMapper()); + } } diff --git a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitmqEnvironmentConfig.java b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitmqEnvironmentConfig.java index 8db0ee0ad..e9d0c0615 100644 --- a/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitmqEnvironmentConfig.java +++ b/dc3-common/dc3-common-rabbitmq/src/main/java/io/github/pnoker/common/config/RabbitmqEnvironmentConfig.java @@ -44,43 +44,44 @@ import org.springframework.core.env.ConfigurableEnvironment; @Configuration public class RabbitmqEnvironmentConfig implements EnvironmentPostProcessor { - /** - * Post-process environment to configure RabbitMQ constants - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - // This configuration is used for multi-developer scenarios, - // distinguishing different exchanges, queues, and topics based on env and group - // identifiers - String env = environment.getProperty(EnvironmentConstant.SPRING_ENV, String.class); - String group = environment.getProperty(EnvironmentConstant.SPRING_GROUP, String.class); + /** + * Post-process environment to configure RabbitMQ constants + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + // This configuration is used for multi-developer scenarios, + // distinguishing different exchanges, queues, and topics based on env and group + // identifiers + String env = environment.getProperty(EnvironmentConstant.SPRING_ENV, String.class); + String group = environment.getProperty(EnvironmentConstant.SPRING_GROUP, String.class); - String tag = EnvironmentUtil.getTag(env, group); + String tag = EnvironmentUtil.getTag(env, group); - // Sync registration related constants - RabbitConstant.TOPIC_EXCHANGE_REGISTER = tag + RabbitConstant.TOPIC_EXCHANGE_REGISTER; - RabbitConstant.QUEUE_REGISTER_UP = tag + RabbitConstant.QUEUE_REGISTER_UP; - RabbitConstant.QUEUE_REGISTER_DOWN_PREFIX = tag + RabbitConstant.QUEUE_REGISTER_DOWN_PREFIX; + // Sync registration related constants + RabbitConstant.TOPIC_EXCHANGE_REGISTER = tag + RabbitConstant.TOPIC_EXCHANGE_REGISTER; + RabbitConstant.QUEUE_REGISTER_UP = tag + RabbitConstant.QUEUE_REGISTER_UP; + RabbitConstant.QUEUE_REGISTER_DOWN_PREFIX = tag + RabbitConstant.QUEUE_REGISTER_DOWN_PREFIX; - // Event related constants - RabbitConstant.TOPIC_EXCHANGE_EVENT = tag + RabbitConstant.TOPIC_EXCHANGE_EVENT; - RabbitConstant.QUEUE_DRIVER_EVENT = tag + RabbitConstant.QUEUE_DRIVER_EVENT; - RabbitConstant.QUEUE_DEVICE_EVENT = tag + RabbitConstant.QUEUE_DEVICE_EVENT; + // Event related constants + RabbitConstant.TOPIC_EXCHANGE_EVENT = tag + RabbitConstant.TOPIC_EXCHANGE_EVENT; + RabbitConstant.QUEUE_DRIVER_EVENT = tag + RabbitConstant.QUEUE_DRIVER_EVENT; + RabbitConstant.QUEUE_DEVICE_EVENT = tag + RabbitConstant.QUEUE_DEVICE_EVENT; - // Metadata related constants - RabbitConstant.TOPIC_EXCHANGE_METADATA = tag + RabbitConstant.TOPIC_EXCHANGE_METADATA; - RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX = tag + RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX; + // Metadata related constants + RabbitConstant.TOPIC_EXCHANGE_METADATA = tag + RabbitConstant.TOPIC_EXCHANGE_METADATA; + RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX = tag + RabbitConstant.QUEUE_DRIVER_METADATA_PREFIX; - // Command related constants - RabbitConstant.TOPIC_EXCHANGE_COMMAND = tag + RabbitConstant.TOPIC_EXCHANGE_COMMAND; - RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX = tag + RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX; - RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX = tag + RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX; + // Command related constants + RabbitConstant.TOPIC_EXCHANGE_COMMAND = tag + RabbitConstant.TOPIC_EXCHANGE_COMMAND; + RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX = tag + RabbitConstant.QUEUE_DRIVER_COMMAND_PREFIX; + RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX = tag + RabbitConstant.QUEUE_DEVICE_COMMAND_PREFIX; - // Point Value related constants - RabbitConstant.TOPIC_EXCHANGE_VALUE = tag + RabbitConstant.TOPIC_EXCHANGE_VALUE; - RabbitConstant.QUEUE_POINT_VALUE = tag + RabbitConstant.QUEUE_POINT_VALUE; - } + // Point Value related constants + RabbitConstant.TOPIC_EXCHANGE_VALUE = tag + RabbitConstant.TOPIC_EXCHANGE_VALUE; + RabbitConstant.QUEUE_POINT_VALUE = tag + RabbitConstant.QUEUE_POINT_VALUE; + } } diff --git a/dc3-common/dc3-common-repository/README.md b/dc3-common/dc3-common-repository/README.md index d3884bb79..f6895881b 100644 --- a/dc3-common/dc3-common-repository/README.md +++ b/dc3-common/dc3-common-repository/README.md @@ -2,8 +2,10 @@ ## Overview -`dc3-common-repository` is the pluggable data storage interface module of the IoT DC3 platform. It abstracts point value persistence through a `RepositoryService` interface, -allowing the Data Center to store telemetry data in different backends without coupling business logic to a specific storage implementation. +`dc3-common-repository` is the pluggable data storage interface module of the IoT DC3 platform. It abstracts point value +persistence through a `RepositoryService` interface, +allowing the Data Center to store telemetry data in different backends without coupling business logic to a specific +storage implementation. ## Module Information @@ -21,7 +23,8 @@ allowing the Data Center to store telemetry data in different backends without c ## Usage Pattern -The Data Center depends on `RepositoryService` via Spring injection. The active implementation is selected by the application profile. Add a concrete storage implementation (e.g., +The Data Center depends on `RepositoryService` via Spring injection. The active implementation is selected by the +application profile. Add a concrete storage implementation (e.g., TimescaleDB, InfluxDB, MongoDB) by implementing `RepositoryService` and registering it as a Spring bean. ```java diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/config/ActiveRepositoryProfileConfig.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/config/ActiveRepositoryProfileConfig.java index be84478bb..fdd780c06 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/config/ActiveRepositoryProfileConfig.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/config/ActiveRepositoryProfileConfig.java @@ -42,14 +42,15 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveRepositoryProfileConfig implements EnvironmentPostProcessor { - /** - * Post-process environment to add the "repository" active profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("repository"); - } + /** + * Post-process environment to add the "repository" active profile + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("repository"); + } } diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointQueryBO.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointQueryBO.java index 8ce13e2a7..640a52d4b 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointQueryBO.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointQueryBO.java @@ -42,17 +42,17 @@ import java.io.Serializable; @AllArgsConstructor public class PointQueryBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID for querying point data - */ - private Long deviceId; + /** + * Device ID for querying point data + */ + private Long deviceId; - /** - * Point ID for querying specific point - */ - private Long pointId; + /** + * Point ID for querying specific point + */ + private Long pointId; } diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointValueBO.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointValueBO.java index e30f19677..7a0509a42 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointValueBO.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/bo/PointValueBO.java @@ -43,47 +43,47 @@ import java.time.LocalDateTime; @AllArgsConstructor public class PointValueBO implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - * Device ID associated with the point value - */ - private Long deviceId; + /** + * Device ID associated with the point value + */ + private Long deviceId; - /** - * Point ID associated with the value - */ - private Long pointId; + /** + * Point ID associated with the value + */ + private Long pointId; - /** - * Raw value as received from the device - */ - private String rawValue; + /** + * Raw value as received from the device + */ + private String rawValue; - /** - * Calculated/processed value after transformations - */ - private String calValue; + /** + * Calculated/processed value after transformations + */ + private String calValue; - /** - * Driver ID that collected the data - */ - private Long driverId; + /** + * Driver ID that collected the data + */ + private Long driverId; - /** - * Tenant ID the data belongs to - */ - private Long tenantId; + /** + * Tenant ID the data belongs to + */ + private Long tenantId; - /** - * Timestamp when the value was created - */ - private LocalDateTime createTime; + /** + * Timestamp when the value was created + */ + private LocalDateTime createTime; - /** - * Timestamp when the value was last operated on - */ - private LocalDateTime operateTime; + /** + * Timestamp when the value was last operated on + */ + private LocalDateTime operateTime; } diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/query/PointValueQuery.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/query/PointValueQuery.java index 44e2d3d15..20de40a0d 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/query/PointValueQuery.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/entity/query/PointValueQuery.java @@ -44,61 +44,61 @@ import java.io.Serializable; @AllArgsConstructor public class PointValueQuery implements Serializable { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - private Pages page; + private Pages page; - /** - * Tenant ID for multi-tenant data isolation - */ - private Long tenantId; + /** + * Tenant ID for multi-tenant data isolation + */ + private Long tenantId; - // Query fields + // Query fields - /** - * Device ID to filter by specific device - */ - private Long deviceId; + /** + * Device ID to filter by specific device + */ + private Long deviceId; - /** - * Device name for text-based filtering - */ - private String deviceName; + /** + * Device name for text-based filtering + */ + private String deviceName; - /** - * Point ID to filter by specific point - */ - private Long pointId; + /** + * Point ID to filter by specific point + */ + private Long pointId; - /** - * Point name for text-based filtering - */ - private String pointName; + /** + * Point name for text-based filtering + */ + private String pointName; - /** - * Enable flag to filter active/inactive points - */ - private EnableFlagEnum enableFlag; + /** + * Enable flag to filter active/inactive points + */ + private EnableFlagEnum enableFlag; - /** - * Optional lower bound for create_time filtering (time range feature). - */ - private java.time.LocalDateTime createTimeFrom; + /** + * Optional lower bound for create_time filtering (time range feature). + */ + private java.time.LocalDateTime createTimeFrom; - /** - * Convenience field: when set (e.g. 24, 168, 720), the service layer converts it to - * createTimeFrom = now - rangeHours. Retained for backward compatibility; new callers - * should set {@link #rangeKey}. - */ - private Integer rangeHours; + /** + * Convenience field: when set (e.g. 24, 168, 720), the service layer converts it to + * createTimeFrom = now - rangeHours. Retained for backward compatibility; new callers + * should set {@link #rangeKey}. + */ + private Integer rangeHours; - /** - * Preferred time-range selector. Accepts one of the - * {@link io.github.pnoker.common.enums.TimeRangeKeyEnum} codes ({@code today}, - * {@code 24h}, {@code 7d}, {@code 30d}). Takes precedence over {@link #rangeHours} - * when both are supplied. - */ - private String rangeKey; + /** + * Preferred time-range selector. Accepts one of the + * {@link io.github.pnoker.common.enums.TimeRangeKeyEnum} codes ({@code today}, + * {@code 24h}, {@code 7d}, {@code 30d}). Takes precedence over {@link #rangeHours} + * when both are supplied. + */ + private String rangeKey; } diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/repository/RepositoryService.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/repository/RepositoryService.java index 00a1195a2..4a1d8f11c 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/repository/RepositoryService.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/repository/RepositoryService.java @@ -33,59 +33,66 @@ import java.util.List; */ public interface RepositoryService { - /** - * Get repository service name - * @return Repository Name - */ - String getRepositoryName(); + /** + * Get repository service name + * + * @return Repository Name + */ + String getRepositoryName(); - /** - * Save PointValue - * @param entityBO PointValue - * @throws IOException IOException - */ - void savePointValue(PointValueBO entityBO) throws IOException; + /** + * Save PointValue + * + * @param entityBO PointValue + * @throws IOException IOException + */ + void savePointValue(PointValueBO entityBO) throws IOException; - /** - * Save PointValue list - * @param entityBOList PointValue Array - * @throws IOException IOException - */ - void savePointValues(List entityBOList) throws IOException; + /** + * Save PointValue list + * + * @param entityBOList PointValue Array + * @throws IOException IOException + */ + void savePointValues(List entityBOList) throws IOException; - /** - * Get historical PointValue within the tenant scope. - * @param tenantId Tenant ID (required for tenant isolation) - * @param deviceId Device ID - * @param pointId Point ID - * @param count Count - * @return History Value Array - */ - List selectHistoryPointValue(Long tenantId, Long deviceId, Long pointId, int count); + /** + * Get historical PointValue within the tenant scope. + * + * @param tenantId Tenant ID (required for tenant isolation) + * @param deviceId Device ID + * @param pointId Point ID + * @param count Count + * @return History Value Array + */ + List selectHistoryPointValue(Long tenantId, Long deviceId, Long pointId, int count); - /** - * Query latest PointValue within the tenant scope. - * @param tenantId Tenant ID (required for tenant isolation) - * @param deviceId Device ID - * @param pointId Point ID - * @return PointValueBO - */ - PointValueBO selectLatestPointValue(Long tenantId, Long deviceId, Long pointId); + /** + * Query latest PointValue within the tenant scope. + * + * @param tenantId Tenant ID (required for tenant isolation) + * @param deviceId Device ID + * @param pointId Point ID + * @return PointValueBO + */ + PointValueBO selectLatestPointValue(Long tenantId, Long deviceId, Long pointId); - /** - * Query latest PointValue list within the tenant scope. - * @param tenantId Tenant ID (required for tenant isolation) - * @param deviceId Device ID - * @param pointIds Point ID list - * @return PointValueBO Array - */ - List selectLatestPointValues(Long tenantId, Long deviceId, List pointIds); + /** + * Query latest PointValue list within the tenant scope. + * + * @param tenantId Tenant ID (required for tenant isolation) + * @param deviceId Device ID + * @param pointIds Point ID list + * @return PointValueBO Array + */ + List selectLatestPointValues(Long tenantId, Long deviceId, List pointIds); - /** - * Page query PointValue - * @param entityQuery Entry of Query - * @return Entity of BO Page - */ - Page selectPagePointValue(PointValueQuery entityQuery); + /** + * Page query PointValue + * + * @param entityQuery Entry of Query + * @return Entity of BO Page + */ + Page selectPagePointValue(PointValueQuery entityQuery); } diff --git a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/strategy/RepositoryStrategyFactory.java b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/strategy/RepositoryStrategyFactory.java index f9cf83319..800d55732 100644 --- a/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/strategy/RepositoryStrategyFactory.java +++ b/dc3-common/dc3-common-repository/src/main/java/io/github/pnoker/common/strategy/RepositoryStrategyFactory.java @@ -35,38 +35,41 @@ import java.util.concurrent.ConcurrentHashMap; */ public class RepositoryStrategyFactory { - // Map to store repository services with name as key - private static final Map savingStrategyServiceMap = new ConcurrentHashMap<>(); + // Map to store repository services with name as key + private static final Map savingStrategyServiceMap = new ConcurrentHashMap<>(); - // Private constructor to prevent instantiation - private RepositoryStrategyFactory() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + // Private constructor to prevent instantiation + private RepositoryStrategyFactory() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get all registered repository services - * @return List of all repository services - */ - public static List get() { - return new ArrayList<>(savingStrategyServiceMap.values()); - } + /** + * Get all registered repository services + * + * @return List of all repository services + */ + public static List get() { + return new ArrayList<>(savingStrategyServiceMap.values()); + } - /** - * Get repository service by name - * @param name Name of the repository service - * @return RepositoryService instance for the given name - */ - public static RepositoryService get(String name) { - return savingStrategyServiceMap.get(StrategyConstant.Storage.REPOSITORY_PREFIX + name); - } + /** + * Get repository service by name + * + * @param name Name of the repository service + * @return RepositoryService instance for the given name + */ + public static RepositoryService get(String name) { + return savingStrategyServiceMap.get(StrategyConstant.Storage.REPOSITORY_PREFIX + name); + } - /** - * Register a new repository service - * @param name Name of the repository service - * @param service RepositoryService instance to register - */ - public static void put(String name, RepositoryService service) { - savingStrategyServiceMap.put(StrategyConstant.Storage.REPOSITORY_PREFIX + name, service); - } + /** + * Register a new repository service + * + * @param name Name of the repository service + * @param service RepositoryService instance to register + */ + public static void put(String name, RepositoryService service) { + savingStrategyServiceMap.put(StrategyConstant.Storage.REPOSITORY_PREFIX + name, service); + } } diff --git a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/ResourceRegistrar.java b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/ResourceRegistrar.java index 8c105c2eb..d63848b0f 100644 --- a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/ResourceRegistrar.java +++ b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/ResourceRegistrar.java @@ -41,62 +41,61 @@ import java.util.List; @Slf4j public class ResourceRegistrar { - private final ApiEndpointScanner scanner; + private final ApiEndpointScanner scanner; - private final ResourceRegistryFacade facade; + private final ResourceRegistryFacade facade; - private final ResourceRegistrarProperties properties; + private final ResourceRegistrarProperties properties; - private final String fallbackServiceName; + private final String fallbackServiceName; - public ResourceRegistrar(ApiEndpointScanner scanner, ResourceRegistryFacade facade, - ResourceRegistrarProperties properties, @Value("${spring.application.name:}") String fallbackServiceName) { - this.scanner = scanner; - this.facade = facade; - this.properties = properties; - this.fallbackServiceName = fallbackServiceName; - } + public ResourceRegistrar(ApiEndpointScanner scanner, ResourceRegistryFacade facade, + ResourceRegistrarProperties properties, @Value("${spring.application.name:}") String fallbackServiceName) { + this.scanner = scanner; + this.facade = facade; + this.properties = properties; + this.fallbackServiceName = fallbackServiceName; + } - @EventListener(ApplicationReadyEvent.class) - public void register() { - if (!properties.isEnabled()) { - log.info("Resource registrar disabled; skipping endpoint registration"); - return; - } - String serviceName = resolveServiceName(); - if (StringUtils.isBlank(serviceName)) { - String msg = "Resource registrar cannot resolve a service name " - + "(set dc3.resource-registrar.service-name or spring.application.name)"; - if (properties.isFailFast()) { - throw new IllegalStateException(msg); - } - log.warn(msg); - return; - } - try { - List apis = scanner.scan(); - FacadeResourceRegistrySyncCommandBO command = FacadeResourceRegistrySyncCommandBO.builder() - .serviceName(serviceName) - .deleteMissing(properties.isDeleteMissing()) - .apis(apis) - .build(); - FacadeResourceRegistrySyncResultBO result = facade.sync(command); - log.info( - "Resource registrar synced {} endpoints for [{}]: inserted={}, updated={}, deleted={}, unchanged={}", - apis.size(), serviceName, result.getInserted(), result.getUpdated(), result.getDeleted(), - result.getUnchanged()); - } - catch (RuntimeException e) { - if (properties.isFailFast()) { - throw e; - } - log.error("Resource registrar failed to sync endpoints for [{}]", serviceName, e); - } - } + @EventListener(ApplicationReadyEvent.class) + public void register() { + if (!properties.isEnabled()) { + log.info("Resource registrar disabled; skipping endpoint registration"); + return; + } + String serviceName = resolveServiceName(); + if (StringUtils.isBlank(serviceName)) { + String msg = "Resource registrar cannot resolve a service name " + + "(set dc3.resource-registrar.service-name or spring.application.name)"; + if (properties.isFailFast()) { + throw new IllegalStateException(msg); + } + log.warn(msg); + return; + } + try { + List apis = scanner.scan(); + FacadeResourceRegistrySyncCommandBO command = FacadeResourceRegistrySyncCommandBO.builder() + .serviceName(serviceName) + .deleteMissing(properties.isDeleteMissing()) + .apis(apis) + .build(); + FacadeResourceRegistrySyncResultBO result = facade.sync(command); + log.info( + "Resource registrar synced {} endpoints for [{}]: inserted={}, updated={}, deleted={}, unchanged={}", + apis.size(), serviceName, result.getInserted(), result.getUpdated(), result.getDeleted(), + result.getUnchanged()); + } catch (RuntimeException e) { + if (properties.isFailFast()) { + throw e; + } + log.error("Resource registrar failed to sync endpoints for [{}]", serviceName, e); + } + } - private String resolveServiceName() { - String name = properties.getServiceName(); - return StringUtils.isBlank(name) ? fallbackServiceName : name; - } + private String resolveServiceName() { + String name = properties.getServiceName(); + return StringUtils.isBlank(name) ? fallbackServiceName : name; + } } diff --git a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarAutoConfiguration.java b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarAutoConfiguration.java index 7ba495347..cd7e97f7a 100644 --- a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarAutoConfiguration.java +++ b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarAutoConfiguration.java @@ -43,17 +43,17 @@ import org.springframework.web.reactive.result.method.annotation.RequestMappingH @ConditionalOnProperty(prefix = "dc3.resource-registrar", name = "enabled", havingValue = "true", matchIfMissing = true) public class ResourceRegistrarAutoConfiguration { - @Bean - public ApiEndpointScanner apiEndpointScanner(RequestMappingHandlerMapping requestMappingHandlerMapping, - ResourceRegistrarProperties properties) { - return new ApiEndpointScanner(requestMappingHandlerMapping, properties); - } + @Bean + public ApiEndpointScanner apiEndpointScanner(RequestMappingHandlerMapping requestMappingHandlerMapping, + ResourceRegistrarProperties properties) { + return new ApiEndpointScanner(requestMappingHandlerMapping, properties); + } - @Bean - @ConditionalOnBean(ResourceRegistryFacade.class) - public ResourceRegistrar resourceRegistrar(ApiEndpointScanner scanner, ResourceRegistryFacade facade, - ResourceRegistrarProperties properties, @Value("${spring.application.name:}") String applicationName) { - return new ResourceRegistrar(scanner, facade, properties, applicationName); - } + @Bean + @ConditionalOnBean(ResourceRegistryFacade.class) + public ResourceRegistrar resourceRegistrar(ApiEndpointScanner scanner, ResourceRegistryFacade facade, + ResourceRegistrarProperties properties, @Value("${spring.application.name:}") String applicationName) { + return new ResourceRegistrar(scanner, facade, properties, applicationName); + } } diff --git a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarProperties.java b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarProperties.java index dcee9bcf9..2c8542ad4 100644 --- a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarProperties.java +++ b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/config/ResourceRegistrarProperties.java @@ -35,33 +35,33 @@ import java.util.List; @ConfigurationProperties(prefix = "dc3.resource-registrar") public class ResourceRegistrarProperties { - /** - * Master switch. When false, the registrar is a no-op. - */ - private boolean enabled = true; + /** + * Master switch. When false, the registrar is a no-op. + */ + private boolean enabled = true; - /** - * Owning service name. Defaults to {@code spring.application.name} when blank. - */ - private String serviceName; + /** + * Owning service name. Defaults to {@code spring.application.name} when blank. + */ + private String serviceName; - /** - * When true, endpoints that exist in the DB but are absent from the current scan are - * soft-deleted. Leave false in production to avoid accidental wipes during rolling - * deploys of older binaries. - */ - private boolean deleteMissing = true; + /** + * When true, endpoints that exist in the DB but are absent from the current scan are + * soft-deleted. Leave false in production to avoid accidental wipes during rolling + * deploys of older binaries. + */ + private boolean deleteMissing = true; - /** - * Path patterns (Ant-style) to exclude from the scan, in addition to the built-in - * actuator/error defaults. - */ - private List excludePaths = new ArrayList<>(); + /** + * Path patterns (Ant-style) to exclude from the scan, in addition to the built-in + * actuator/error defaults. + */ + private List excludePaths = new ArrayList<>(); - /** - * When true, a registration failure aborts startup. When false, it is logged and - * startup continues. - */ - private boolean failFast = false; + /** + * When true, a registration failure aborts startup. When false, it is logged and + * startup continues. + */ + private boolean failFast = false; } diff --git a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/scan/ApiEndpointScanner.java b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/scan/ApiEndpointScanner.java index 05f7b1a9c..c3582cfeb 100644 --- a/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/scan/ApiEndpointScanner.java +++ b/dc3-common/dc3-common-resource-registrar/src/main/java/io/github/pnoker/common/resource/registrar/scan/ApiEndpointScanner.java @@ -38,89 +38,89 @@ import java.util.*; */ public class ApiEndpointScanner { - private static final Set SUPPORTED_METHODS = Set.of(RequestMethod.GET, RequestMethod.POST, - RequestMethod.PUT, RequestMethod.DELETE); + private static final Set SUPPORTED_METHODS = Set.of(RequestMethod.GET, RequestMethod.POST, + RequestMethod.PUT, RequestMethod.DELETE); - private static final List DEFAULT_EXCLUDES = List.of("/actuator/**", "/error", "/error/**", "/favicon.ico"); + private static final List DEFAULT_EXCLUDES = List.of("/actuator/**", "/error", "/error/**", "/favicon.ico"); - private final RequestMappingHandlerMapping handlerMapping; + private final RequestMappingHandlerMapping handlerMapping; - private final ResourceRegistrarProperties properties; + private final ResourceRegistrarProperties properties; - private final AntPathMatcher matcher = new AntPathMatcher(); + private final AntPathMatcher matcher = new AntPathMatcher(); - public ApiEndpointScanner(RequestMappingHandlerMapping handlerMapping, ResourceRegistrarProperties properties) { - this.handlerMapping = handlerMapping; - this.properties = properties; - } + public ApiEndpointScanner(RequestMappingHandlerMapping handlerMapping, ResourceRegistrarProperties properties) { + this.handlerMapping = handlerMapping; + this.properties = properties; + } - private static String buildApiName(HandlerMethod handler) { - String className = handler.getBeanType().getSimpleName(); - return className + "." + handler.getMethod().getName(); - } + private static String buildApiName(HandlerMethod handler) { + String className = handler.getBeanType().getSimpleName(); + return className + "." + handler.getMethod().getName(); + } - public List scan() { - Map mappings = handlerMapping.getHandlerMethods(); - // Preserve discovery order for deterministic diffs. - Map deduped = new LinkedHashMap<>(); - for (Map.Entry entry : mappings.entrySet()) { - expand(entry.getKey(), entry.getValue(), deduped); - } - return new ArrayList<>(deduped.values()); - } + public List scan() { + Map mappings = handlerMapping.getHandlerMethods(); + // Preserve discovery order for deterministic diffs. + Map deduped = new LinkedHashMap<>(); + for (Map.Entry entry : mappings.entrySet()) { + expand(entry.getKey(), entry.getValue(), deduped); + } + return new ArrayList<>(deduped.values()); + } - private void expand(RequestMappingInfo info, HandlerMethod handler, Map out) { - Set methods = info.getMethodsCondition().getMethods(); - if (methods.isEmpty()) { - // Controllers that don't declare a method expose GET by default at the HTTP - // level, but for permission-registration purposes these are ambiguous — skip. - return; - } - Set patterns; - if (info.getPatternsCondition() == null) { - return; - } - patterns = info.getPatternsCondition().getPatterns(); - if (patterns.isEmpty()) { - return; - } - for (PathPattern pattern : patterns) { - String path = pattern.getPatternString(); - if (isExcluded(path)) { - continue; - } - for (RequestMethod method : methods) { - if (!SUPPORTED_METHODS.contains(method)) { - continue; - } - String key = method.name() + ":" + path; - if (out.containsKey(key)) { - continue; - } - out.put(key, - FacadeScannedApiBO.builder() - .method(method.name()) - .path(path) - .apiName(buildApiName(handler)) - .title(handler.getMethod().getName()) - .remark("") - .apiGroup(handler.getBeanType().getSimpleName()) - .build()); - } - } - } + private void expand(RequestMappingInfo info, HandlerMethod handler, Map out) { + Set methods = info.getMethodsCondition().getMethods(); + if (methods.isEmpty()) { + // Controllers that don't declare a method expose GET by default at the HTTP + // level, but for permission-registration purposes these are ambiguous — skip. + return; + } + Set patterns; + if (info.getPatternsCondition() == null) { + return; + } + patterns = info.getPatternsCondition().getPatterns(); + if (patterns.isEmpty()) { + return; + } + for (PathPattern pattern : patterns) { + String path = pattern.getPatternString(); + if (isExcluded(path)) { + continue; + } + for (RequestMethod method : methods) { + if (!SUPPORTED_METHODS.contains(method)) { + continue; + } + String key = method.name() + ":" + path; + if (out.containsKey(key)) { + continue; + } + out.put(key, + FacadeScannedApiBO.builder() + .method(method.name()) + .path(path) + .apiName(buildApiName(handler)) + .title(handler.getMethod().getName()) + .remark("") + .apiGroup(handler.getBeanType().getSimpleName()) + .build()); + } + } + } - private boolean isExcluded(String path) { - List allExcludes = new ArrayList<>(DEFAULT_EXCLUDES); - if (properties.getExcludePaths() != null) { - allExcludes.addAll(properties.getExcludePaths()); - } - for (String pattern : allExcludes) { - if (matcher.match(pattern, path)) { - return true; - } - } - return false; - } + private boolean isExcluded(String path) { + List allExcludes = new ArrayList<>(DEFAULT_EXCLUDES); + if (properties.getExcludePaths() != null) { + allExcludes.addAll(properties.getExcludePaths()); + } + for (String pattern : allExcludes) { + if (matcher.match(pattern, path)) { + return true; + } + } + return false; + } } diff --git a/dc3-common/dc3-common-thread/README.md b/dc3-common/dc3-common-thread/README.md index 19b9c6f8a..653b34400 100644 --- a/dc3-common/dc3-common-thread/README.md +++ b/dc3-common/dc3-common-thread/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-thread` is the shared thread pool configuration module of the IoT DC3 platform. It configures the platform-wide async task executor used for `@Async` annotated methods +`dc3-common-thread` is the shared thread pool configuration module of the IoT DC3 platform. It configures the +platform-wide async task executor used for `@Async` annotated methods across all services. ## Module Information @@ -33,7 +34,8 @@ thread: ## Usage -Any `@Async` annotated method (e.g., `MetadataEventListener.onApplicationEvent`) executes on this thread pool automatically when `dc3-common-thread` is on the classpath. +Any `@Async` annotated method (e.g., `MetadataEventListener.onApplicationEvent`) executes on this thread pool +automatically when `dc3-common-thread` is on the classpath. ## Build Instructions diff --git a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ActiveThreadProfileConfig.java b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ActiveThreadProfileConfig.java index 88e52736b..30dba8a6b 100644 --- a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ActiveThreadProfileConfig.java +++ b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ActiveThreadProfileConfig.java @@ -42,14 +42,15 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveThreadProfileConfig implements EnvironmentPostProcessor { - /** - * Post-process environment to add the "thread" active profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("thread"); - } + /** + * Post-process environment to add the "thread" active profile + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("thread"); + } } diff --git a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ThreadPoolConfig.java b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ThreadPoolConfig.java index 5612f0946..14803a8b9 100644 --- a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ThreadPoolConfig.java +++ b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/config/ThreadPoolConfig.java @@ -22,14 +22,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionHandler; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** @@ -48,83 +41,86 @@ import java.util.concurrent.atomic.AtomicInteger; @Configuration public class ThreadPoolConfig { - private final AtomicInteger threadPoolAtomic = new AtomicInteger(1); + private final AtomicInteger threadPoolAtomic = new AtomicInteger(1); - private final AtomicInteger scheduledThreadPoolAtomic = new AtomicInteger(1); + private final AtomicInteger scheduledThreadPoolAtomic = new AtomicInteger(1); - private final ThreadProperties thread; + private final ThreadProperties thread; - public ThreadPoolConfig(ThreadProperties thread) { - this.thread = thread; - } + public ThreadPoolConfig(ThreadProperties thread) { + this.thread = thread; + } - /** - * Create ThreadPoolExecutor with LinkedBlockingQueue - * @return Configured ThreadPoolExecutor bean - */ - @Bean(destroyMethod = "shutdown") - public ThreadPoolExecutor threadPoolExecutor() { - return new ThreadPoolExecutor(thread.getCorePoolSize(), thread.getMaximumPoolSize(), thread.getKeepAliveTime(), - TimeUnit.SECONDS, new LinkedBlockingQueue<>(thread.getMaximumPoolSize() * 2), - r -> new Thread(r, "[T]" + thread.getPrefix() + threadPoolAtomic.getAndIncrement()), - (r, e) -> new BlockingRejectedExecutionHandler()); - } + /** + * Create ThreadPoolExecutor with LinkedBlockingQueue + * + * @return Configured ThreadPoolExecutor bean + */ + @Bean(destroyMethod = "shutdown") + public ThreadPoolExecutor threadPoolExecutor() { + return new ThreadPoolExecutor(thread.getCorePoolSize(), thread.getMaximumPoolSize(), thread.getKeepAliveTime(), + TimeUnit.SECONDS, new LinkedBlockingQueue<>(thread.getMaximumPoolSize() * 2), + r -> new Thread(r, "[T]" + thread.getPrefix() + threadPoolAtomic.getAndIncrement()), + (r, e) -> new BlockingRejectedExecutionHandler()); + } - /** - * Create virtual thread executor service Creates one virtual thread per task for - * improved resource utilization - * @return Virtual thread ExecutorService bean - */ - @Bean(destroyMethod = "shutdown") - public ExecutorService virtualThreadExecutor() { - ThreadFactory factory = Thread.ofVirtual().name("[VT]" + thread.getPrefix(), 0).factory(); + /** + * Create virtual thread executor service Creates one virtual thread per task for + * improved resource utilization + * + * @return Virtual thread ExecutorService bean + */ + @Bean(destroyMethod = "shutdown") + public ExecutorService virtualThreadExecutor() { + ThreadFactory factory = Thread.ofVirtual().name("[VT]" + thread.getPrefix(), 0).factory(); - return Executors.newThreadPerTaskExecutor(factory); - } + return Executors.newThreadPerTaskExecutor(factory); + } - /** - * Create ScheduledThreadPoolExecutor for scheduled tasks - * @return Configured ScheduledThreadPoolExecutor bean - */ - @Bean(destroyMethod = "shutdown") - public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() { - return new ScheduledThreadPoolExecutor(thread.getCorePoolSize(), - r -> new Thread(r, "[ST]" + thread.getPrefix() + scheduledThreadPoolAtomic.getAndIncrement()), - (r, e) -> new BlockingRejectedExecutionHandler()); - } + /** + * Create ScheduledThreadPoolExecutor for scheduled tasks + * + * @return Configured ScheduledThreadPoolExecutor bean + */ + @Bean(destroyMethod = "shutdown") + public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() { + return new ScheduledThreadPoolExecutor(thread.getCorePoolSize(), + r -> new Thread(r, "[ST]" + thread.getPrefix() + scheduledThreadPoolAtomic.getAndIncrement()), + (r, e) -> new BlockingRejectedExecutionHandler()); + } - /** - * Custom RejectedExecutionHandler for blocking rejected tasks - *

- * Instead of rejecting tasks when the thread pool is full, this handler attempts to - * execute them in the calling thread. - *

- * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ - private static class BlockingRejectedExecutionHandler implements RejectedExecutionHandler { + /** + * Custom RejectedExecutionHandler for blocking rejected tasks + *

+ * Instead of rejecting tasks when the thread pool is full, this handler attempts to + * execute them in the calling thread. + *

+ * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ + private static class BlockingRejectedExecutionHandler implements RejectedExecutionHandler { - /** - * Handle rejected execution by attempting to run task in calling thread - * @param runnable The runnable task requested to be executed - * @param executor The executor attempting to execute this task - */ - @Override - public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { - try { - log.info("BlockingRejectedExecutionHandler: {}", executor.toString()); + /** + * Handle rejected execution by attempting to run task in calling thread + * + * @param runnable The runnable task requested to be executed + * @param executor The executor attempting to execute this task + */ + @Override + public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { + try { + log.info("BlockingRejectedExecutionHandler: {}", executor.toString()); - if (!executor.isShutdown()) { - runnable.run(); - } - } - catch (Exception e) { - log.error("BlockingRejectedExecutionHandler: {}", e.getMessage(), e); - } - } + if (!executor.isShutdown()) { + runnable.run(); + } + } catch (Exception e) { + log.error("BlockingRejectedExecutionHandler: {}", e.getMessage(), e); + } + } - } + } } diff --git a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/init/ThreadInitRunner.java b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/init/ThreadInitRunner.java index f1a1aca46..6256240e5 100644 --- a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/init/ThreadInitRunner.java +++ b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/init/ThreadInitRunner.java @@ -34,18 +34,19 @@ import org.springframework.context.annotation.Configuration; * @since 2022.1.0 */ @Configuration -@ComponentScan(basePackages = { "io.github.pnoker.common.thread" }) -@EnableConfigurationProperties({ ThreadProperties.class }) +@ComponentScan(basePackages = {"io.github.pnoker.common.thread"}) +@EnableConfigurationProperties({ThreadProperties.class}) public class ThreadInitRunner implements ApplicationRunner { - /** - * Initialize thread components during application startup - * @param args Application arguments passed to the application - * @throws Exception if initialization fails - */ - @Override - public void run(ApplicationArguments args) throws Exception { - // nothing to do - } + /** + * Initialize thread components during application startup + * + * @param args Application arguments passed to the application + * @throws Exception if initialization fails + */ + @Override + public void run(ApplicationArguments args) throws Exception { + // nothing to do + } } diff --git a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/thread/entity/property/ThreadProperties.java b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/thread/entity/property/ThreadProperties.java index 33653b0cd..16f302083 100644 --- a/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/thread/entity/property/ThreadProperties.java +++ b/dc3-common/dc3-common-thread/src/main/java/io/github/pnoker/common/thread/entity/property/ThreadProperties.java @@ -40,24 +40,24 @@ import org.springframework.validation.annotation.Validated; @ConfigurationProperties(prefix = "server.thread") public class ThreadProperties { - /** - * Thread name prefix - */ - private String prefix; + /** + * Thread name prefix + */ + private String prefix; - /** - * Number of thread pool core threads - */ - private int corePoolSize; + /** + * Number of thread pool core threads + */ + private int corePoolSize; - /** - * Maximum number of thread pool threads - */ - private int maximumPoolSize; + /** + * Maximum number of thread pool threads + */ + private int maximumPoolSize; - /** - * Idle thread waiting time, unit: seconds - */ - private int keepAliveTime; + /** + * Idle thread waiting time, unit: seconds + */ + private int keepAliveTime; } diff --git a/dc3-common/dc3-common-web/README.md b/dc3-common/dc3-common-web/README.md index 9b3b8b710..06b5e2829 100644 --- a/dc3-common/dc3-common-web/README.md +++ b/dc3-common/dc3-common-web/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-common-web` is the shared WebFlux configuration module of the IoT DC3 platform. It provides global exception handling, WebFlux request processing configuration, global web +`dc3-common-web` is the shared WebFlux configuration module of the IoT DC3 platform. It provides global exception +handling, WebFlux request processing configuration, global web filters, and reactive response utilities for all REST-based center services. ## Module Information diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/base/BaseController.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/base/BaseController.java index c2531d469..a31d9c12e 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/base/BaseController.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/base/BaseController.java @@ -34,44 +34,49 @@ import reactor.core.publisher.Mono; */ public interface BaseController { - /** - * Get user header information from request context - * @return User header information as Mono - */ - default Mono getUserHeader() { - return UserHeaderUtil.getUserHeader(); - } + /** + * Get user header information from request context + * + * @return User header information as Mono + */ + default Mono getUserHeader() { + return UserHeaderUtil.getUserHeader(); + } - /** - * Get tenant ID from user header - * @return Tenant ID as Mono - */ - default Mono getTenantId() { - return UserHeaderUtil.getTenantId(); - } + /** + * Get tenant ID from user header + * + * @return Tenant ID as Mono + */ + default Mono getTenantId() { + return UserHeaderUtil.getTenantId(); + } - /** - * Get user ID from user header - * @return User ID as Mono - */ - default Mono getUserId() { - return UserHeaderUtil.getUserId(); - } + /** + * Get user ID from user header + * + * @return User ID as Mono + */ + default Mono getUserId() { + return UserHeaderUtil.getUserId(); + } - /** - * Get user nickname from user header - * @return User nickname as Mono - */ - default Mono getNickName() { - return UserHeaderUtil.getNickName(); - } + /** + * Get user nickname from user header + * + * @return User nickname as Mono + */ + default Mono getNickName() { + return UserHeaderUtil.getNickName(); + } - /** - * Get username from user header - * @return Username as Mono - */ - default Mono getUserName() { - return UserHeaderUtil.getUserName(); - } + /** + * Get username from user header + * + * @return Username as Mono + */ + default Mono getUserName() { + return UserHeaderUtil.getUserName(); + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ActiveWebProfileConfig.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ActiveWebProfileConfig.java index c2b30c253..8f2531b62 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ActiveWebProfileConfig.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ActiveWebProfileConfig.java @@ -42,14 +42,15 @@ import org.springframework.core.env.ConfigurableEnvironment; @Order(Ordered.HIGHEST_PRECEDENCE) public class ActiveWebProfileConfig implements EnvironmentPostProcessor { - /** - * Post-process the environment to add the "web" active profile - * @param environment ConfigurableEnvironment to modify - * @param application SpringApplication instance - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - environment.addActiveProfile("web"); - } + /** + * Post-process the environment to add the "web" active profile + * + * @param environment ConfigurableEnvironment to modify + * @param application SpringApplication instance + */ + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + environment.addActiveProfile("web"); + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ExceptionConfig.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ExceptionConfig.java index 82fa407a9..6bd88b4da 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ExceptionConfig.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/ExceptionConfig.java @@ -54,100 +54,103 @@ import java.util.List; @RestControllerAdvice public class ExceptionConfig { - /** - * Handle global exceptions - * @param exception Exception to handle - * @param request ServerHttpRequest that triggered the exception - * @return Mono containing error response - */ - @ExceptionHandler(Exception.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public Mono> globalException(Exception exception, ServerHttpRequest request) { - log.error(""" - Global exception - Request: {} - Exception: {} - """, request.getURI().getRawPath(), exception.getMessage(), exception); - return Mono.just(R.fail(exception.getMessage())); - } + /** + * Handle global exceptions + * + * @param exception Exception to handle + * @param request ServerHttpRequest that triggered the exception + * @return Mono containing error response + */ + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public Mono> globalException(Exception exception, ServerHttpRequest request) { + log.error(""" + Global exception + Request: {} + Exception: {} + """, request.getURI().getRawPath(), exception.getMessage(), exception); + return Mono.just(R.fail(exception.getMessage())); + } - /** - * Handle Spring's framework-level {@link ResponseStatusException} — e.g. 404 from the - * dispatcher when no handler matches a request. These are not application failures, - * so they must not surface as 500 ERROR entries. Preserves the original status on the - * response and logs at a level appropriate to the status class. - * @param exception ResponseStatusException raised by the reactive dispatcher or an - * HTTP client - * @param request ServerHttpRequest that triggered the exception - * @param response ServerHttpResponse to which the original status is applied - * @return Mono containing error response - */ - @ExceptionHandler(ResponseStatusException.class) - public Mono> responseStatusException(ResponseStatusException exception, ServerHttpRequest request, - ServerHttpResponse response) { - HttpStatusCode status = exception.getStatusCode(); - response.setStatusCode(status); + /** + * Handle Spring's framework-level {@link ResponseStatusException} — e.g. 404 from the + * dispatcher when no handler matches a request. These are not application failures, + * so they must not surface as 500 ERROR entries. Preserves the original status on the + * response and logs at a level appropriate to the status class. + * + * @param exception ResponseStatusException raised by the reactive dispatcher or an + * HTTP client + * @param request ServerHttpRequest that triggered the exception + * @param response ServerHttpResponse to which the original status is applied + * @return Mono containing error response + */ + @ExceptionHandler(ResponseStatusException.class) + public Mono> responseStatusException(ResponseStatusException exception, ServerHttpRequest request, + ServerHttpResponse response) { + HttpStatusCode status = exception.getStatusCode(); + response.setStatusCode(status); - String path = request.getURI().getRawPath(); - if (status.is5xxServerError()) { - log.error("Response status exception {} on {}: {}", status.value(), path, exception.getMessage(), - exception); - } - else if (HttpStatus.NOT_FOUND.value() == status.value()) { - log.debug("Not found: {}", path); - } - else { - log.warn("Response status exception {} on {}: {}", status.value(), path, exception.getMessage()); - } + String path = request.getURI().getRawPath(); + if (status.is5xxServerError()) { + log.error("Response status exception {} on {}: {}", status.value(), path, exception.getMessage(), + exception); + } else if (HttpStatus.NOT_FOUND.value() == status.value()) { + log.debug("Not found: {}", path); + } else { + log.warn("Response status exception {} on {}: {}", status.value(), path, exception.getMessage()); + } - String reason = exception.getReason(); - return Mono.just(R.fail(reason != null ? reason : status.toString())); - } + String reason = exception.getReason(); + return Mono.just(R.fail(reason != null ? reason : status.toString())); + } - /** - * Handle NotFoundException - * @param exception NotFoundException to handle - * @param request ServerHttpRequest that triggered the exception - * @return Mono containing error response - */ - @ExceptionHandler(NotFoundException.class) - @ResponseStatus(HttpStatus.NOT_FOUND) - public Mono> notFoundException(NotFoundException exception, ServerHttpRequest request) { - log.warn("NotFound exception handler: {}", exception.getMessage(), exception); - return Mono.just(R.fail(exception.getMessage())); - } + /** + * Handle NotFoundException + * + * @param exception NotFoundException to handle + * @param request ServerHttpRequest that triggered the exception + * @return Mono containing error response + */ + @ExceptionHandler(NotFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + public Mono> notFoundException(NotFoundException exception, ServerHttpRequest request) { + log.warn("NotFound exception handler: {}", exception.getMessage(), exception); + return Mono.just(R.fail(exception.getMessage())); + } - /** - * Handle UnAuthorizedException - * @param exception UnAuthorizedException to handle - * @param request ServerHttpRequest that triggered the exception - * @return Mono containing error response - */ - @ExceptionHandler(UnAuthorizedException.class) - @ResponseStatus(HttpStatus.UNAUTHORIZED) - public Mono> unAuthorizedException(UnAuthorizedException exception, ServerHttpRequest request) { - log.warn("UnAuthorized exception handler: {}", exception.getMessage(), exception); - return Mono.just(R.fail(exception.getMessage())); - } + /** + * Handle UnAuthorizedException + * + * @param exception UnAuthorizedException to handle + * @param request ServerHttpRequest that triggered the exception + * @return Mono containing error response + */ + @ExceptionHandler(UnAuthorizedException.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public Mono> unAuthorizedException(UnAuthorizedException exception, ServerHttpRequest request) { + log.warn("UnAuthorized exception handler: {}", exception.getMessage(), exception); + return Mono.just(R.fail(exception.getMessage())); + } - /** - * Handle validation exceptions - * @param exception MethodArgumentNotValidException or BindException to handle - * @param request ServerHttpRequest that triggered the exception - * @return Mono containing error response with field validation details - */ - @ExceptionHandler({ BindException.class, MethodArgumentNotValidException.class }) - @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) - public Mono> methodArgumentNotValidException(MethodArgumentNotValidException exception, - ServerHttpRequest request) { - HashMap map = new HashMap<>(4); - List errorList = exception.getBindingResult().getFieldErrors(); - errorList.forEach(error -> { - log.warn("Method argument not valid exception handler: {}: {}", error.getField(), - error.getDefaultMessage()); - map.put(error.getField(), error.getDefaultMessage()); - }); - return Mono.just(R.fail(JsonUtil.toJsonString(map))); - } + /** + * Handle validation exceptions + * + * @param exception MethodArgumentNotValidException or BindException to handle + * @param request ServerHttpRequest that triggered the exception + * @return Mono containing error response with field validation details + */ + @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class}) + @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY) + public Mono> methodArgumentNotValidException(MethodArgumentNotValidException exception, + ServerHttpRequest request) { + HashMap map = new HashMap<>(4); + List errorList = exception.getBindingResult().getFieldErrors(); + errorList.forEach(error -> { + log.warn("Method argument not valid exception handler: {}: {}", error.getField(), + error.getDefaultMessage()); + map.put(error.getField(), error.getDefaultMessage()); + }); + return Mono.just(R.fail(JsonUtil.toJsonString(map))); + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFilterConfig.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFilterConfig.java index e2da3cfec..dba861274 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFilterConfig.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFilterConfig.java @@ -48,59 +48,59 @@ import java.util.Optional; @Configuration public class WebFilterConfig { - @Resource - private ServerProperties serverProperties; + @Resource + private ServerProperties serverProperties; - /** - * Custom context path filter - * @return WebFilter for handling context path - */ - @Bean - public WebFilter contextPathWebFilter() { - String contextPath = Optional.ofNullable(serverProperties.getServlet().getContextPath()).orElse("/"); - return (exchange, chain) -> { - ServerHttpRequest request = exchange.getRequest(); - if (request.getURI().getPath().startsWith(contextPath)) { - return chain - .filter(exchange.mutate().request(request.mutate().contextPath(contextPath).build()).build()); - } - return chain.filter(exchange); - }; - } + /** + * Custom context path filter + * + * @return WebFilter for handling context path + */ + @Bean + public WebFilter contextPathWebFilter() { + String contextPath = Optional.ofNullable(serverProperties.getServlet().getContextPath()).orElse("/"); + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + if (request.getURI().getPath().startsWith(contextPath)) { + return chain + .filter(exchange.mutate().request(request.mutate().contextPath(contextPath).build()).build()); + } + return chain.filter(exchange); + }; + } - /** - * Custom user header interceptor filter - * @return WebFilter for intercepting and processing user headers - */ - @Bean - public WebFilter interceptor() { - return (exchange, chain) -> { - ServerHttpRequest request = exchange.getRequest(); - String user = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_USER); + /** + * Custom user header interceptor filter + * + * @return WebFilter for intercepting and processing user headers + */ + @Bean + public WebFilter interceptor() { + return (exchange, chain) -> { + ServerHttpRequest request = exchange.getRequest(); + String user = RequestUtil.getRequestHeader(request, RequestConstant.Header.X_AUTH_USER); - if (StringUtils.isNotEmpty(user)) { - try { - RequestHeader.UserHeader userHeader = JsonUtil.parseObject(user, RequestHeader.UserHeader.class); + if (StringUtils.isNotEmpty(user)) { + try { + RequestHeader.UserHeader userHeader = JsonUtil.parseObject(user, RequestHeader.UserHeader.class); - if (Objects.isNull(userHeader) || Objects.isNull(userHeader.getTenantId()) - || Objects.isNull(userHeader.getUserId())) { - log.warn("Invalid user header: {}", JsonUtil.toJsonString(userHeader)); - return chain.filter(exchange) - .contextWrite(context -> context.delete(RequestConstant.Key.USER_HEADER)); - } - else { - log.debug("User header: {}", JsonUtil.toJsonString(userHeader)); - return chain.filter(exchange) - .contextWrite(context -> context.put(RequestConstant.Key.USER_HEADER, userHeader)); - } - } - catch (Exception e) { - log.error("Error parsing user header", e); - } - } + if (Objects.isNull(userHeader) || Objects.isNull(userHeader.getTenantId()) + || Objects.isNull(userHeader.getUserId())) { + log.warn("Invalid user header: {}", JsonUtil.toJsonString(userHeader)); + return chain.filter(exchange) + .contextWrite(context -> context.delete(RequestConstant.Key.USER_HEADER)); + } else { + log.debug("User header: {}", JsonUtil.toJsonString(userHeader)); + return chain.filter(exchange) + .contextWrite(context -> context.put(RequestConstant.Key.USER_HEADER, userHeader)); + } + } catch (Exception e) { + log.error("Error parsing user header", e); + } + } - return chain.filter(exchange); - }; - } + return chain.filter(exchange); + }; + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFluxConfig.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFluxConfig.java index d28450e9d..32810a1c0 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFluxConfig.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/config/WebFluxConfig.java @@ -44,23 +44,25 @@ import org.springframework.web.reactive.config.WebFluxConfigurer; @Configuration public class WebFluxConfig implements WebFluxConfigurer { - /** - * Configure static resource handlers - * @param registry ResourceHandlerRegistry for configuring static resources - */ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/"); - } + /** + * Configure static resource handlers + * + * @param registry ResourceHandlerRegistry for configuring static resources + */ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/"); + } - /** - * Configure HTTP message codecs for JSON serialization/deserialization - * @param configurer ServerCodecConfigurer for configuring message codecs - */ - @Override - public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { - configurer.customCodecs().registerWithDefaultConfig(new JacksonJsonEncoder(JsonUtil.getJsonMapper())); - configurer.customCodecs().registerWithDefaultConfig(new JacksonJsonDecoder(JsonUtil.getJsonMapper())); - } + /** + * Configure HTTP message codecs for JSON serialization/deserialization + * + * @param configurer ServerCodecConfigurer for configuring message codecs + */ + @Override + public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) { + configurer.customCodecs().registerWithDefaultConfig(new JacksonJsonEncoder(JsonUtil.getJsonMapper())); + configurer.customCodecs().registerWithDefaultConfig(new JacksonJsonDecoder(JsonUtil.getJsonMapper())); + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/RequestUtil.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/RequestUtil.java index 167012152..11113acf4 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/RequestUtil.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/RequestUtil.java @@ -37,76 +37,80 @@ import java.util.Objects; @Slf4j public class RequestUtil { - private RequestUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private RequestUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Extracts the first valid IP address from a comma-separated list of IPs. Used for - * handling X-Forwarded-For and similar headers in reverse proxy scenarios. - * @param ip Comma-separated list of IP addresses - * @return The first valid IP address found, or null if none is valid - */ - public static String getMultistageReverseProxyIp(String ip) { - if (ip == null) { - return null; - } - String[] ips = ip.split(","); - for (String s : ips) { - s = s.trim(); - if (!s.isEmpty() && !"unknown".equalsIgnoreCase(s)) { - return s; - } - } - return null; - } + /** + * Extracts the first valid IP address from a comma-separated list of IPs. Used for + * handling X-Forwarded-For and similar headers in reverse proxy scenarios. + * + * @param ip Comma-separated list of IP addresses + * @return The first valid IP address found, or null if none is valid + */ + public static String getMultistageReverseProxyIp(String ip) { + if (ip == null) { + return null; + } + String[] ips = ip.split(","); + for (String s : ips) { + s = s.trim(); + if (!s.isEmpty() && !"unknown".equalsIgnoreCase(s)) { + return s; + } + } + return null; + } - /** - * Gets the remote client IP address from the request. Checks various headers commonly - * used in proxy scenarios before falling back to the remote address. Headers checked: - * X-Original-Forwarded-For, X-Forwarded-For, X-Real-IP, Proxy-Client-IP, - * WL-Proxy-Client-IP, HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR - * @param request ServerHttpRequest object containing the request information - * @return The client's IP address as a string - */ - public static String getRemoteIp(ServerHttpRequest request) { - String ip = StringUtils.EMPTY; - String[] headers = { "X-Original-Forwarded-For", "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", - "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR" }; - for (String header : headers) { - ip = request.getHeaders().getFirst(header); - if (!(ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip))) { - return getMultistageReverseProxyIp(ip); - } - } - InetSocketAddress remoteAddress = request.getRemoteAddress(); - if (Objects.nonNull(remoteAddress)) { - ip = remoteAddress.getHostString(); - } - return getMultistageReverseProxyIp(ip); - } + /** + * Gets the remote client IP address from the request. Checks various headers commonly + * used in proxy scenarios before falling back to the remote address. Headers checked: + * X-Original-Forwarded-For, X-Forwarded-For, X-Real-IP, Proxy-Client-IP, + * WL-Proxy-Client-IP, HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR + * + * @param request ServerHttpRequest object containing the request information + * @return The client's IP address as a string + */ + public static String getRemoteIp(ServerHttpRequest request) { + String ip = StringUtils.EMPTY; + String[] headers = {"X-Original-Forwarded-For", "X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", + "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"}; + for (String header : headers) { + ip = request.getHeaders().getFirst(header); + if (!(ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip))) { + return getMultistageReverseProxyIp(ip); + } + } + InetSocketAddress remoteAddress = request.getRemoteAddress(); + if (Objects.nonNull(remoteAddress)) { + ip = remoteAddress.getHostString(); + } + return getMultistageReverseProxyIp(ip); + } - /** - * Retrieves a specific header value from the request. Returns the first value if - * multiple values exist for the same header. - * @param request ServerHttpRequest object containing the request information - * @param key The name of the header to retrieve - * @return The value of the specified header, or null if not present - */ - public static String getRequestHeader(ServerHttpRequest request, String key) { - return request.getHeaders().getFirst(key); - } + /** + * Retrieves a specific header value from the request. Returns the first value if + * multiple values exist for the same header. + * + * @param request ServerHttpRequest object containing the request information + * @param key The name of the header to retrieve + * @return The value of the specified header, or null if not present + */ + public static String getRequestHeader(ServerHttpRequest request, String key) { + return request.getHeaders().getFirst(key); + } - /** - * Retrieves a specific cookie value from the request. Returns empty string if the - * cookie is not present. - * @param request ServerHttpRequest object containing the request information - * @param key The name of the cookie to retrieve - * @return The value of the specified cookie, or empty string if not present - */ - public static String getRequestCookie(ServerHttpRequest request, String key) { - HttpCookie cookie = request.getCookies().getFirst(key); - return Objects.isNull(cookie) ? StringUtils.EMPTY : cookie.getValue(); - } + /** + * Retrieves a specific cookie value from the request. Returns empty string if the + * cookie is not present. + * + * @param request ServerHttpRequest object containing the request information + * @param key The name of the cookie to retrieve + * @return The value of the specified cookie, or empty string if not present + */ + public static String getRequestCookie(ServerHttpRequest request, String key) { + HttpCookie cookie = request.getCookies().getFirst(key); + return Objects.isNull(cookie) ? StringUtils.EMPTY : cookie.getValue(); + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/ResponseUtil.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/ResponseUtil.java index d580605c7..3ce257bd3 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/ResponseUtil.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/ResponseUtil.java @@ -43,32 +43,32 @@ import java.nio.file.Path; @Slf4j public class ResponseUtil { - private ResponseUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private ResponseUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Create file download response - * @param path File path to download - * @return ResponseEntity containing the file resource with proper headers - */ - public static ResponseEntity responseFile(Path path) { - try { - Resource resource = new UrlResource(path.toUri()); - if (!resource.exists()) { - throw new NotFoundException("File not found: " + path.getFileName()); - } + /** + * Create file download response + * + * @param path File path to download + * @return ResponseEntity containing the file resource with proper headers + */ + public static ResponseEntity responseFile(Path path) { + try { + Resource resource = new UrlResource(path.toUri()); + if (!resource.exists()) { + throw new NotFoundException("File not found: " + path.getFileName()); + } - HttpHeaders headers = new HttpHeaders(); - headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()); - headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); + HttpHeaders headers = new HttpHeaders(); + headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()); + headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE); - return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).body(resource); - } - catch (Exception e) { - log.error("Error occurred while response file: {}, {}", path.getFileName(), e.getMessage(), e); - return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); - } - } + return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).body(resource); + } catch (Exception e) { + log.error("Error occurred while response file: {}, {}", path.getFileName(), e.getMessage(), e); + return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); + } + } } diff --git a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/UserHeaderUtil.java b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/UserHeaderUtil.java index ecaa6fbb8..83838d814 100644 --- a/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/UserHeaderUtil.java +++ b/dc3-common/dc3-common-web/src/main/java/io/github/pnoker/common/utils/UserHeaderUtil.java @@ -42,78 +42,83 @@ import java.util.Objects; @Slf4j public class UserHeaderUtil { - private UserHeaderUtil() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private UserHeaderUtil() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Get user header information from Reactor context - * @return User header information as Mono - */ - public static Mono getUserHeader() { - return Mono.deferContextual(context -> { - if (!context.hasKey(RequestConstant.Key.USER_HEADER)) { - return Mono.error(new UnAuthorizedException("Unable to get user header")); - } - RequestHeader.UserHeader userHeader = context.get(RequestConstant.Key.USER_HEADER); - return Mono.just(userHeader); - }); - } + /** + * Get user header information from Reactor context + * + * @return User header information as Mono + */ + public static Mono getUserHeader() { + return Mono.deferContextual(context -> { + if (!context.hasKey(RequestConstant.Key.USER_HEADER)) { + return Mono.error(new UnAuthorizedException("Unable to get user header")); + } + RequestHeader.UserHeader userHeader = context.get(RequestConstant.Key.USER_HEADER); + return Mono.just(userHeader); + }); + } - /** - * Get tenant ID from user header - * @return Tenant ID as Mono - */ - public static Mono getTenantId() { - return getUserHeader().flatMap(userHeader -> { - Long tenantId = userHeader.getTenantId(); - if (Objects.isNull(tenantId)) { - return Mono.error(new UnAuthorizedException("Unable to get tenant id of user header")); - } - return Mono.just(tenantId); - }); - } + /** + * Get tenant ID from user header + * + * @return Tenant ID as Mono + */ + public static Mono getTenantId() { + return getUserHeader().flatMap(userHeader -> { + Long tenantId = userHeader.getTenantId(); + if (Objects.isNull(tenantId)) { + return Mono.error(new UnAuthorizedException("Unable to get tenant id of user header")); + } + return Mono.just(tenantId); + }); + } - /** - * Get user ID from user header - * @return User ID as Mono - */ - public static Mono getUserId() { - return getUserHeader().flatMap(userHeader -> { - Long userId = userHeader.getUserId(); - if (Objects.isNull(userId)) { - return Mono.error(new UnAuthorizedException("Unable to get user id of user header")); - } - return Mono.just(userId); - }); - } + /** + * Get user ID from user header + * + * @return User ID as Mono + */ + public static Mono getUserId() { + return getUserHeader().flatMap(userHeader -> { + Long userId = userHeader.getUserId(); + if (Objects.isNull(userId)) { + return Mono.error(new UnAuthorizedException("Unable to get user id of user header")); + } + return Mono.just(userId); + }); + } - /** - * Get user nickname from user header - * @return User nickname as Mono - */ - public static Mono getNickName() { - return getUserHeader().flatMap(userHeader -> { - String nickName = userHeader.getNickName(); - if (StringUtils.isEmpty(nickName)) { - return Mono.error(new UnAuthorizedException("Unable to get nick name of user header")); - } - return Mono.just(nickName); - }); - } + /** + * Get user nickname from user header + * + * @return User nickname as Mono + */ + public static Mono getNickName() { + return getUserHeader().flatMap(userHeader -> { + String nickName = userHeader.getNickName(); + if (StringUtils.isEmpty(nickName)) { + return Mono.error(new UnAuthorizedException("Unable to get nick name of user header")); + } + return Mono.just(nickName); + }); + } - /** - * Get username from user header - * @return Username as Mono - */ - public static Mono getUserName() { - return getUserHeader().flatMap(userHeader -> { - String userName = userHeader.getUserName(); - if (StringUtils.isEmpty(userName)) { - return Mono.error(new UnAuthorizedException("Unable to get user name of user header")); - } - return Mono.just(userName); - }); - } + /** + * Get username from user header + * + * @return Username as Mono + */ + public static Mono getUserName() { + return getUserHeader().flatMap(userHeader -> { + String userName = userHeader.getUserName(); + if (StringUtils.isEmpty(userName)) { + return Mono.error(new UnAuthorizedException("Unable to get user name of user header")); + } + return Mono.just(userName); + }); + } } diff --git a/dc3-common/pom.xml b/dc3-common/pom.xml index 80bcd0942..63e5132d0 100644 --- a/dc3-common/pom.xml +++ b/dc3-common/pom.xml @@ -119,53 +119,6 @@ - - - io.spring.javaformat - spring-javaformat-maven-plugin - 0.0.47 - - - validate - validate - - validate - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.1 - - - com.puppycrawl.tools - checkstyle - 9.3 - - - io.spring.javaformat - spring-javaformat-checkstyle - 0.0.47 - - - - - checkstyle-validation - validate - true - - ${maven.multiModuleProjectDirectory}/checkstyle.xml - true - - - check - - - - diff --git a/dc3-driver/dc3-driver-listening-virtual/README.md b/dc3-driver/dc3-driver-listening-virtual/README.md index 4355b31d0..071161a0b 100644 --- a/dc3-driver/dc3-driver-listening-virtual/README.md +++ b/dc3-driver/dc3-driver-listening-virtual/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-listening-virtual` is the Listening Virtual Driver of the IoT DC3 platform. It operates in passive listening mode, accepting inbound TCP and UDP connections from +`dc3-driver-listening-virtual` is the Listening Virtual Driver of the IoT DC3 platform. It operates in passive listening +mode, accepting inbound TCP and UDP connections from devices that push data. It demonstrates listening-type driver patterns supporting both TCP and UDP transports. ## Module Information diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/ListeningVirtualDriverApplication.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/ListeningVirtualDriverApplication.java index 239559be2..7eb3888fe 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/ListeningVirtualDriverApplication.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/ListeningVirtualDriverApplication.java @@ -35,12 +35,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ListeningVirtualDriverApplication { - /** - * Main method to start the Spring Boot application - * @param args Command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(ListeningVirtualDriverApplication.class, args); - } + /** + * Main method to start the Spring Boot application + * + * @param args Command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(ListeningVirtualDriverApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index a7116e5fb..2fbe64e85 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -58,121 +58,123 @@ import java.util.concurrent.TimeUnit; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Value("${driver.custom.tcp.port}") - private Integer tcpPort; + @Value("${driver.custom.tcp.port}") + private Integer tcpPort; - @Value("${driver.custom.udp.port}") - private Integer udpPort; + @Value("${driver.custom.udp.port}") + private Integer udpPort; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - @Resource - private NettyTcpServer nettyTcpServer; + @Resource + private NettyTcpServer nettyTcpServer; - @Resource - private NettyUdpServer nettyUdpServer; + @Resource + private NettyUdpServer nettyUdpServer; - @Resource - private ThreadPoolExecutor threadPoolExecutor; + @Resource + private ThreadPoolExecutor threadPoolExecutor; - /** - * Initializes the driver by starting TCP and UDP listening services. - *

- * This method is automatically called when the driver starts. It launches separate - * threads to listen for incoming TCP and UDP connections on the configured ports. - *

- */ - @Override - public void initial() { - threadPoolExecutor.execute(() -> { - log.debug("Virtual Listening Driver Starting(TCP::{}) incoming data listener", tcpPort); - nettyTcpServer.start(tcpPort); - }); - threadPoolExecutor.execute(() -> { - log.debug("Virtual Listening Driver Starting(UDP::{}) incoming data listener", udpPort); - nettyUdpServer.start(udpPort); - }); - } + /** + * Initializes the driver by starting TCP and UDP listening services. + *

+ * This method is automatically called when the driver starts. It launches separate + * threads to listen for incoming TCP and UDP connections on the configured ports. + *

+ */ + @Override + public void initial() { + threadPoolExecutor.execute(() -> { + log.debug("Virtual Listening Driver Starting(TCP::{}) incoming data listener", tcpPort); + nettyTcpServer.start(tcpPort); + }); + threadPoolExecutor.execute(() -> { + log.debug("Virtual Listening Driver Starting(UDP::{}) incoming data listener", udpPort); + nettyUdpServer.start(udpPort); + }); + } - /** - * Scheduled task to report device status. - *

- * Sets all devices to ONLINE status with a validity period of 25 seconds. This method - * is called periodically by the driver framework. - *

- */ - @Override - public void schedule() { - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + /** + * Scheduled task to report device status. + *

+ * Sets all devices to ONLINE status with a validity period of 25 seconds. This method + * is called periodically by the driver framework. + *

+ */ + @Override + public void schedule() { + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - /** - * Handles metadata events for drivers, devices, and points. - *

- * Processes addition, update, and deletion events for metadata. Currently, logs - * device and point metadata events for monitoring purposes. - *

- * @param metadataEvent The metadata event containing type and operation details - */ - @Override - public void event(MetadataEventDTO metadataEvent) { - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + /** + * Handles metadata events for drivers, devices, and points. + *

+ * Processes addition, update, and deletion events for metadata. Currently, logs + * device and point metadata events for monitoring purposes. + *

+ * + * @param metadataEvent The metadata event containing type and operation details + */ + @Override + public void event(MetadataEventDTO metadataEvent) { + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - /** - * Reads data from a device point. - *

- * Since this driver passively receives data via TCP/UDP, this method returns null. - * Actual data reading is handled by the TCP and UDP server handlers in their - * respective channelRead methods. - *

- * @param driverConfig Driver configuration attributes - * @param pointConfig Point configuration attributes - * @param device The device to read from - * @param point The point to read - * @return null as data is received passively - */ - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - return null; - } + /** + * Reads data from a device point. + *

+ * Since this driver passively receives data via TCP/UDP, this method returns null. + * Actual data reading is handled by the TCP and UDP server handlers in their + * respective channelRead methods. + *

+ * + * @param driverConfig Driver configuration attributes + * @param pointConfig Point configuration attributes + * @param device The device to read from + * @param point The point to read + * @return null as data is received passively + */ + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + return null; + } - /** - * Writes data to a device point. - *

- * Writes the specified value to the device by sending it through the Netty TCP - * channel associated with the device. If the device channel exists in the - * device-channel mapping, the value is converted to bytes and sent to the device. - *

- * @param driverConfig Driver configuration attributes - * @param pointConfig Point configuration attributes - * @param device The device to write to - * @param point The point to write - * @param wValue The value to write - * @return true if the write operation was processed - */ - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - Long deviceId = device.getId(); - Channel channel = NettyTcpServer.deviceChannelMap.get(deviceId); - if (Objects.nonNull(channel)) { - channel.writeAndFlush(DecodeUtil.stringToByte(wValue.getValue())); - } - return true; - } + /** + * Writes data to a device point. + *

+ * Writes the specified value to the device by sending it through the Netty TCP + * channel associated with the device. If the device channel exists in the + * device-channel mapping, the value is converted to bytes and sent to the device. + *

+ * + * @param driverConfig Driver configuration attributes + * @param pointConfig Point configuration attributes + * @param device The device to write to + * @param point The point to write + * @param wValue The value to write + * @return true if the write operation was processed + */ + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + Long deviceId = device.getId(); + Channel channel = NettyTcpServer.deviceChannelMap.get(deviceId); + if (Objects.nonNull(channel)) { + channel.writeAndFlush(DecodeUtil.stringToByte(wValue.getValue())); + } + return true; + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/NettyServerHandler.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/NettyServerHandler.java index 95af57adb..bd9b4414f 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/NettyServerHandler.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/NettyServerHandler.java @@ -56,64 +56,65 @@ import java.util.Objects; @Service public class NettyServerHandler { - @Resource - private DeviceMetadata deviceMetadata; + @Resource + private DeviceMetadata deviceMetadata; - @Resource - private PointMetadata pointMetadata; + @Resource + private PointMetadata pointMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Processes incoming messages from TCP/UDP clients. - *

- * Parses the byte buffer to extract device information and point values. The message - * format is:

-	 * - Device name: 22 bytes (converted to device ID)
-	 * - Keyword: 1 byte (hex)
-	 * - Point values: variable length based on point configuration
-	 * 
- *

- * @param context The channel handler context for the current connection - * @param byteBuf The byte buffer containing the incoming message - */ - public void read(ChannelHandlerContext context, ByteBuf byteBuf) { - log.info("{}->{}", context.channel().remoteAddress(), ByteBufUtil.hexDump(byteBuf)); - String deviceName = byteBuf.toString(0, 22, StandardCharsets.UTF_8); - long deviceId = Long.parseLong(deviceName); - DeviceBO device = deviceMetadata.getCache(deviceId); + /** + * Processes incoming messages from TCP/UDP clients. + *

+ * Parses the byte buffer to extract device information and point values. The message + * format is:

+     * - Device name: 22 bytes (converted to device ID)
+     * - Keyword: 1 byte (hex)
+     * - Point values: variable length based on point configuration
+     * 
+ *

+ * + * @param context The channel handler context for the current connection + * @param byteBuf The byte buffer containing the incoming message + */ + public void read(ChannelHandlerContext context, ByteBuf byteBuf) { + log.info("{}->{}", context.channel().remoteAddress(), ByteBufUtil.hexDump(byteBuf)); + String deviceName = byteBuf.toString(0, 22, StandardCharsets.UTF_8); + long deviceId = Long.parseLong(deviceName); + DeviceBO device = deviceMetadata.getCache(deviceId); - String hexKey = ByteBufUtil.hexDump(byteBuf, 22, 1); - NettyTcpServer.deviceChannelMap.put(deviceId, context.channel()); + String hexKey = ByteBufUtil.hexDump(byteBuf, 22, 1); + NettyTcpServer.deviceChannelMap.put(deviceId, context.channel()); - Map> pointConfigMap = deviceMetadata.getPointConfig(deviceId); + Map> pointConfigMap = deviceMetadata.getPointConfig(deviceId); - List pointValues = new ArrayList<>(16); - for (Map.Entry> entry : pointConfigMap.entrySet()) { - PointBO point = pointMetadata.getCache(entry.getKey()); - Map infoMap = pointConfigMap.get(entry.getKey()); - int start = infoMap.get("start").getValue(Integer.class); - int end = infoMap.get("end").getValue(Integer.class); + List pointValues = new ArrayList<>(16); + for (Map.Entry> entry : pointConfigMap.entrySet()) { + PointBO point = pointMetadata.getCache(entry.getKey()); + Map infoMap = pointConfigMap.get(entry.getKey()); + int start = infoMap.get("start").getValue(Integer.class); + int end = infoMap.get("end").getValue(Integer.class); - if (infoMap.get("key").getValue().equals(hexKey) && Objects.nonNull(point)) { - String value = switch (point.getPointName()) { - case "altitude" -> String.valueOf(byteBuf.getFloat(start)); - case "speed" -> String.valueOf(byteBuf.getDouble(start)); - case "level" -> String.valueOf(byteBuf.getLong(start)); - case "direction" -> String.valueOf(byteBuf.getInt(start)); - case "locked" -> String.valueOf(byteBuf.getBoolean(start)); - case "coordinate" -> byteBuf.toString(start, end, StandardCharsets.UTF_8).trim(); - default -> StringUtils.EMPTY; - }; + if (infoMap.get("key").getValue().equals(hexKey) && Objects.nonNull(point)) { + String value = switch (point.getPointName()) { + case "altitude" -> String.valueOf(byteBuf.getFloat(start)); + case "speed" -> String.valueOf(byteBuf.getDouble(start)); + case "level" -> String.valueOf(byteBuf.getLong(start)); + case "direction" -> String.valueOf(byteBuf.getInt(start)); + case "locked" -> String.valueOf(byteBuf.getBoolean(start)); + case "coordinate" -> byteBuf.toString(start, end, StandardCharsets.UTF_8).trim(); + default -> StringUtils.EMPTY; + }; - if (StringUtils.isNotEmpty(value)) { - pointValues.add(new PointValue(new RValue(device, point, value))); - } - } - } + if (StringUtils.isNotEmpty(value)) { + pointValues.add(new PointValue(new RValue(device, point, value))); + } + } + } - driverSenderService.pointValueSender(pointValues); - } + driverSenderService.pointValueSender(pointValues); + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServer.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServer.java index 8f7de1ed6..fee8d6235 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServer.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServer.java @@ -46,42 +46,42 @@ import java.util.concurrent.ConcurrentHashMap; @Component public class NettyTcpServer { - /** - * Mapping of device IDs to Netty channels. - *

- * Used to store and retrieve the communication channel for each device. This enables - * sending data back to specific devices when needed. - *

- */ - public static final Map deviceChannelMap = new ConcurrentHashMap<>(16); + /** + * Mapping of device IDs to Netty channels. + *

+ * Used to store and retrieve the communication channel for each device. This enables + * sending data back to specific devices when needed. + *

+ */ + public static final Map deviceChannelMap = new ConcurrentHashMap<>(16); - /** - * Starts the TCP server on the specified port. - * @param port The port number to listen on - */ - @SneakyThrows - public void start(int port) { - EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); - try { - ServerBootstrap bootstrap = new ServerBootstrap(); - bootstrap.group(group) - .channel(NioServerSocketChannel.class) - .localAddress(new InetSocketAddress(port)) - .childHandler(new ChannelInitializer() { - @Override - protected void initChannel(SocketChannel socketChannel) { - socketChannel.pipeline() - .addLast(new StringEncoder()) - .addLast(new ByteArrayEncoder()) - .addLast(new WriteTimeoutHandler(30), new NettyTcpServerHandler()); - } - }); - ChannelFuture future = bootstrap.bind().sync(); - future.channel().closeFuture().sync(); - } - finally { - group.shutdownGracefully().sync(); - } - } + /** + * Starts the TCP server on the specified port. + * + * @param port The port number to listen on + */ + @SneakyThrows + public void start(int port) { + EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); + try { + ServerBootstrap bootstrap = new ServerBootstrap(); + bootstrap.group(group) + .channel(NioServerSocketChannel.class) + .localAddress(new InetSocketAddress(port)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel socketChannel) { + socketChannel.pipeline() + .addLast(new StringEncoder()) + .addLast(new ByteArrayEncoder()) + .addLast(new WriteTimeoutHandler(30), new NettyTcpServerHandler()); + } + }); + ChannelFuture future = bootstrap.bind().sync(); + future.channel().closeFuture().sync(); + } finally { + group.shutdownGracefully().sync(); + } + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServerHandler.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServerHandler.java index 5e8a157e7..ef3f7b008 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServerHandler.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/tcp/NettyTcpServerHandler.java @@ -56,43 +56,45 @@ import org.springframework.stereotype.Component; @ChannelHandler.Sharable public class NettyTcpServerHandler extends ChannelInboundHandlerAdapter { - /** - * Static self-reference for accessing Spring-injected beans from static context. - */ - private static NettyTcpServerHandler nettyTcpServerHandler; + /** + * Static self-reference for accessing Spring-injected beans from static context. + */ + private static NettyTcpServerHandler nettyTcpServerHandler; - @Resource - private NettyServerHandler nettyServerHandler; + @Resource + private NettyServerHandler nettyServerHandler; - /** - * Initializes the handler instance after Spring dependency injection. - */ - @PostConstruct - public void init() { - nettyTcpServerHandler = this; - } + /** + * Initializes the handler instance after Spring dependency injection. + */ + @PostConstruct + public void init() { + nettyTcpServerHandler = this; + } - /** - * Handles incoming TCP messages. - * @param context The channel handler context - * @param msg The received message object - */ - @Override - @SneakyThrows - public void channelRead(ChannelHandlerContext context, Object msg) { - nettyTcpServerHandler.nettyServerHandler.read(context, (ByteBuf) msg); - } + /** + * Handles incoming TCP messages. + * + * @param context The channel handler context + * @param msg The received message object + */ + @Override + @SneakyThrows + public void channelRead(ChannelHandlerContext context, Object msg) { + nettyTcpServerHandler.nettyServerHandler.read(context, (ByteBuf) msg); + } - /** - * Handles exceptions during TCP message processing. - * @param context The channel handler context - * @param throwable The exception that occurred - */ - @Override - @SneakyThrows - public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) { - log.debug(throwable.getMessage()); - context.disconnect(); - } + /** + * Handles exceptions during TCP message processing. + * + * @param context The channel handler context + * @param throwable The exception that occurred + */ + @Override + @SneakyThrows + public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) { + log.debug(throwable.getMessage()); + context.disconnect(); + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServer.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServer.java index 4d30678c4..795e789d6 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServer.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServer.java @@ -41,30 +41,30 @@ import java.net.InetSocketAddress; @Component public class NettyUdpServer { - /** - * Starts the UDP server on the specified port. - * @param port The port number to listen on - */ - @SneakyThrows - public void start(int port) { - EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); - try { - Bootstrap bootstrap = new Bootstrap(); - bootstrap.group(group) - .channel(NioDatagramChannel.class) - .localAddress(new InetSocketAddress(port)) - .handler(new ChannelInitializer() { - @Override - protected void initChannel(Channel channel) { - channel.pipeline().addLast(new WriteTimeoutHandler(30), new NettyUdpServerHandler()); - } - }); - ChannelFuture future = bootstrap.bind().sync(); - future.channel().closeFuture().sync(); - } - finally { - group.shutdownGracefully().sync(); - } - } + /** + * Starts the UDP server on the specified port. + * + * @param port The port number to listen on + */ + @SneakyThrows + public void start(int port) { + EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); + try { + Bootstrap bootstrap = new Bootstrap(); + bootstrap.group(group) + .channel(NioDatagramChannel.class) + .localAddress(new InetSocketAddress(port)) + .handler(new ChannelInitializer() { + @Override + protected void initChannel(Channel channel) { + channel.pipeline().addLast(new WriteTimeoutHandler(30), new NettyUdpServerHandler()); + } + }); + ChannelFuture future = bootstrap.bind().sync(); + future.channel().closeFuture().sync(); + } finally { + group.shutdownGracefully().sync(); + } + } } diff --git a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServerHandler.java b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServerHandler.java index 1fb735a33..4d51fd5fe 100644 --- a/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServerHandler.java +++ b/dc3-driver/dc3-driver-listening-virtual/src/main/java/io/github/pnoker/driver/service/netty/udp/NettyUdpServerHandler.java @@ -56,43 +56,45 @@ import org.springframework.stereotype.Component; @ChannelHandler.Sharable public class NettyUdpServerHandler extends SimpleChannelInboundHandler { - /** - * Static self-reference for accessing Spring-injected beans from static context. - */ - private static NettyUdpServerHandler nettyUdpServerHandler; + /** + * Static self-reference for accessing Spring-injected beans from static context. + */ + private static NettyUdpServerHandler nettyUdpServerHandler; - @Resource - private NettyServerHandler nettyServerHandler; + @Resource + private NettyServerHandler nettyServerHandler; - /** - * Initializes the handler instance after Spring dependency injection. - */ - @PostConstruct - public void init() { - nettyUdpServerHandler = this; - } + /** + * Initializes the handler instance after Spring dependency injection. + */ + @PostConstruct + public void init() { + nettyUdpServerHandler = this; + } - /** - * Handles incoming UDP datagram packets. - * @param context The channel handler context - * @param msg The received datagram packet - */ - @Override - @SneakyThrows - public void channelRead0(ChannelHandlerContext context, DatagramPacket msg) { - nettyUdpServerHandler.nettyServerHandler.read(context, msg.content()); - } + /** + * Handles incoming UDP datagram packets. + * + * @param context The channel handler context + * @param msg The received datagram packet + */ + @Override + @SneakyThrows + public void channelRead0(ChannelHandlerContext context, DatagramPacket msg) { + nettyUdpServerHandler.nettyServerHandler.read(context, msg.content()); + } - /** - * Handles exceptions during UDP packet processing. - * @param context The channel handler context - * @param throwable The exception that occurred - */ - @Override - @SneakyThrows - public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) { - log.debug(throwable.getMessage()); - context.disconnect(); - } + /** + * Handles exceptions during UDP packet processing. + * + * @param context The channel handler context + * @param throwable The exception that occurred + */ + @Override + @SneakyThrows + public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) { + log.debug(throwable.getMessage()); + context.disconnect(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/README.md b/dc3-driver/dc3-driver-modbus-tcp/README.md index 6368ecf12..178590936 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/README.md +++ b/dc3-driver/dc3-driver-modbus-tcp/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-modbus-tcp` is the Modbus TCP protocol driver of the IoT DC3 platform. It connects to Modbus TCP slave devices, reads coil/register values periodically, and supports +`dc3-driver-modbus-tcp` is the Modbus TCP protocol driver of the IoT DC3 platform. It connects to Modbus TCP slave +devices, reads coil/register values periodically, and supports write commands for register control. ## Module Information diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BasicProcessImage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BasicProcessImage.java index dc8584fe8..05245d11e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BasicProcessImage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BasicProcessImage.java @@ -41,570 +41,594 @@ import java.util.Map; */ public class BasicProcessImage implements ProcessImage { - private final int slaveId; - - private final Map coils = new HashMap<>(); - - private final Map inputs = new HashMap<>(); - - private final Map holdingRegisters = new HashMap<>(); - - private final Map inputRegisters = new HashMap<>(); - - private final List writeListeners = new ArrayList<>(); - - private boolean allowInvalidAddress = false; - - private short invalidAddressValue = 0; - - private byte exceptionStatus; - - /** - *

- * Constructor for BasicProcessImage. - *

- * @param slaveId a int. - */ - public BasicProcessImage(int slaveId) { - ModbusUtils.validateSlaveId(slaveId, false); - this.slaveId = slaveId; - } - - @Override - public int getSlaveId() { - return slaveId; - } - - /** - *

- * addListener. - *

- * @param l a {@link ProcessImageListener} object. - */ - public synchronized void addListener(ProcessImageListener l) { - writeListeners.add(l); - } - - /** - *

- * removeListener. - *

- * @param l a {@link ProcessImageListener} object. - */ - public synchronized void removeListener(ProcessImageListener l) { - writeListeners.remove(l); - } - - /** - *

- * isAllowInvalidAddress. - *

- * @return a boolean. - */ - public boolean isAllowInvalidAddress() { - return allowInvalidAddress; - } - - /** - *

- * Setter for the field allowInvalidAddress. - *

- * @param allowInvalidAddress a boolean. - */ - public void setAllowInvalidAddress(boolean allowInvalidAddress) { - this.allowInvalidAddress = allowInvalidAddress; - } - - /** - *

- * Getter for the field invalidAddressValue. - *

- * @return a short. - */ - public short getInvalidAddressValue() { - return invalidAddressValue; - } - - /** - *

- * Setter for the field invalidAddressValue. - *

- * @param invalidAddressValue a short. - */ - public void setInvalidAddressValue(short invalidAddressValue) { - this.invalidAddressValue = invalidAddressValue; - } - - // - // / - // / Additional convenience methods. - // / - // - - /** - *

- * setBinary. - *

- * @param registerId a int. - * @param value a boolean. - */ - public void setBinary(int registerId, boolean value) { - RangeAndOffset rao = new RangeAndOffset(registerId); - setBinary(rao.getRange(), rao.getOffset(), value); - } - - // - // Binaries - - /** - *

- * setBinary. - *

- * @param range a int. - * @param offset a int. - * @param value a boolean. - */ - public void setBinary(int range, int offset, boolean value) { - if (range == RegisterRange.COIL_STATUS) - setCoil(offset, value); - else if (range == RegisterRange.INPUT_STATUS) - setInput(offset, value); - else - throw new ModbusIdException("Invalid range to set binary: " + range); - } - - /** - *

- * setNumeric. - *

- * @param registerId a int. - * @param dataType a int. - * @param value a {@link Number} object. - */ - public synchronized void setNumeric(int registerId, int dataType, Number value) { - RangeAndOffset rao = new RangeAndOffset(registerId); - setNumeric(rao.getRange(), rao.getOffset(), dataType, value); - } - - // - // Numerics - - /** - *

- * setNumeric. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param value a {@link Number} object. - */ - public synchronized void setNumeric(int range, int offset, int dataType, Number value) { - short[] registers = new NumericLocator(slaveId, range, offset, dataType).valueToShorts(value); - - // Write the value. - if (range == RegisterRange.HOLDING_REGISTER) - setHoldingRegister(offset, registers); - else if (range == RegisterRange.INPUT_REGISTER) - setInputRegister(offset, registers); - else - throw new ModbusIdException("Invalid range to set register: " + range); - } - - /** - *

- * setString. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - * @param s a {@link String} object. - */ - public synchronized void setString(int range, int offset, int dataType, int registerCount, String s) { - setString(range, offset, dataType, registerCount, StringLocator.ASCII, s); - } - - // - // Strings - - /** - *

- * setString. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - * @param charset a {@link Charset} object. - * @param s a {@link String} object. - */ - public synchronized void setString(int range, int offset, int dataType, int registerCount, Charset charset, - String s) { - short[] registers = new StringLocator(slaveId, range, offset, dataType, registerCount, charset) - .valueToShorts(s); - - // Write the value. - if (range == RegisterRange.HOLDING_REGISTER) - setHoldingRegister(offset, registers); - else if (range == RegisterRange.INPUT_REGISTER) - setInputRegister(offset, registers); - else - throw new ModbusIdException("Invalid range to set register: " + range); - } - - /** - *

- * setHoldingRegister. - *

- * @param offset a int. - * @param registers an array of {@link short} objects. - */ - public synchronized void setHoldingRegister(int offset, short[] registers) { - validateOffset(offset); - for (int i = 0; i < registers.length; i++) - setHoldingRegister(offset + i, registers[i]); - } - - /** - *

- * setInputRegister. - *

- * @param offset a int. - * @param registers an array of {@link short} objects. - */ - public synchronized void setInputRegister(int offset, short[] registers) { - validateOffset(offset); - for (int i = 0; i < registers.length; i++) - setInputRegister(offset + i, registers[i]); - } - - /** - *

- * setBit. - *

- * @param range a int. - * @param offset a int. - * @param bit a int. - * @param value a boolean. - */ - public synchronized void setBit(int range, int offset, int bit, boolean value) { - if (range == RegisterRange.HOLDING_REGISTER) - setHoldingRegisterBit(offset, bit, value); - else if (range == RegisterRange.INPUT_REGISTER) - setInputRegisterBit(offset, bit, value); - else - throw new ModbusIdException("Invalid range to set register: " + range); - } - - // - // Bits - - /** - *

- * setHoldingRegisterBit. - *

- * @param offset a int. - * @param bit a int. - * @param value a boolean. - */ - public synchronized void setHoldingRegisterBit(int offset, int bit, boolean value) { - validateBit(bit); - short s; - try { - s = getHoldingRegister(offset); - } - catch (IllegalDataAddressException e) { - s = 0; - } - setHoldingRegister(offset, setBit(s, bit, value)); - } - - /** - *

- * setInputRegisterBit. - *

- * @param offset a int. - * @param bit a int. - * @param value a boolean. - */ - public synchronized void setInputRegisterBit(int offset, int bit, boolean value) { - validateBit(bit); - short s; - try { - s = getInputRegister(offset); - } - catch (IllegalDataAddressException e) { - s = 0; - } - setInputRegister(offset, setBit(s, bit, value)); - } - - /** - *

- * getBit. - *

- * @param range a int. - * @param offset a int. - * @param bit a int. - * @return a boolean. - * @throws IllegalDataAddressException if any. - */ - public boolean getBit(int range, int offset, int bit) throws IllegalDataAddressException { - if (range == RegisterRange.HOLDING_REGISTER) - return getHoldingRegisterBit(offset, bit); - if (range == RegisterRange.INPUT_REGISTER) - return getInputRegisterBit(offset, bit); - throw new ModbusIdException("Invalid range to get register: " + range); - } - - /** - *

- * getHoldingRegisterBit. - *

- * @param offset a int. - * @param bit a int. - * @return a boolean. - * @throws IllegalDataAddressException if any. - */ - public boolean getHoldingRegisterBit(int offset, int bit) throws IllegalDataAddressException { - validateBit(bit); - return getBit(getHoldingRegister(offset), bit); - } - - /** - *

- * getInputRegisterBit. - *

- * @param offset a int. - * @param bit a int. - * @return a boolean. - * @throws IllegalDataAddressException if any. - */ - public boolean getInputRegisterBit(int offset, int bit) throws IllegalDataAddressException { - validateBit(bit); - return getBit(getInputRegister(offset), bit); - } - - /** - *

- * getNumeric. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @return a {@link Number} object. - * @throws IllegalDataAddressException if any. - */ - public Number getNumeric(int range, int offset, int dataType) throws IllegalDataAddressException { - return getRegister(new NumericLocator(slaveId, range, offset, dataType)); - } - - /** - *

- * getString. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - * @return a {@link String} object. - * @throws IllegalDataAddressException if any. - */ - public String getString(int range, int offset, int dataType, int registerCount) throws IllegalDataAddressException { - return getRegister(new StringLocator(slaveId, range, offset, dataType, registerCount, null)); - } - - /** - *

- * getString. - *

- * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - * @param charset a {@link Charset} object. - * @return a {@link String} object. - * @throws IllegalDataAddressException if any. - */ - public String getString(int range, int offset, int dataType, int registerCount, Charset charset) - throws IllegalDataAddressException { - return getRegister(new StringLocator(slaveId, range, offset, dataType, registerCount, charset)); - } - - /** - *

- * getRegister. - *

- * @param locator a {@link BaseLocator} object. - * @param a T object. - * @return a T object. - * @throws IllegalDataAddressException if any. - */ - public synchronized T getRegister(BaseLocator locator) throws IllegalDataAddressException { - int words = locator.getRegisterCount(); - byte[] b = new byte[locator.getRegisterCount() * 2]; - for (int i = 0; i < words; i++) { - short s; - if (locator.getRange() == RegisterRange.INPUT_REGISTER) - s = getInputRegister(locator.getOffset() + i); - else if (locator.getRange() == RegisterRange.HOLDING_REGISTER) - s = getHoldingRegister(locator.getOffset() + i); - else if (allowInvalidAddress) - s = invalidAddressValue; - else - throw new IllegalDataAddressException(); - b[i * 2] = ModbusUtils.toByte(s, true); - b[i * 2 + 1] = ModbusUtils.toByte(s, false); - } - - return locator.bytesToValueRealOffset(b, 0); - } - - @Override - public synchronized boolean getCoil(int offset) throws IllegalDataAddressException { - return getBoolean(offset, coils); - } - - // - // - // ProcessImage interface - // - - // - // Coils - - @Override - public synchronized void setCoil(int offset, boolean value) { - validateOffset(offset); - coils.put(offset, value); - } - - @Override - public synchronized void writeCoil(int offset, boolean value) throws IllegalDataAddressException { - boolean old = getBoolean(offset, coils); - setCoil(offset, value); - - for (ProcessImageListener l : writeListeners) - l.coilWrite(offset, old, value); - } - - @Override - public synchronized boolean getInput(int offset) throws IllegalDataAddressException { - return getBoolean(offset, inputs); - } - - // - // Inputs - - @Override - public synchronized void setInput(int offset, boolean value) { - validateOffset(offset); - inputs.put(offset, value); - } - - @Override - public synchronized short getHoldingRegister(int offset) throws IllegalDataAddressException { - return getShort(offset, holdingRegisters); - } - - // - // Holding registers - - @Override - public synchronized void setHoldingRegister(int offset, short value) { - validateOffset(offset); - holdingRegisters.put(offset, value); - } - - @Override - public synchronized void writeHoldingRegister(int offset, short value) throws IllegalDataAddressException { - short old = getShort(offset, holdingRegisters); - setHoldingRegister(offset, value); - - for (ProcessImageListener l : writeListeners) - l.holdingRegisterWrite(offset, old, value); - } - - @Override - public synchronized short getInputRegister(int offset) throws IllegalDataAddressException { - return getShort(offset, inputRegisters); - } - - // - // Input registers - - @Override - public synchronized void setInputRegister(int offset, short value) { - validateOffset(offset); - inputRegisters.put(offset, value); - } - - @Override - public byte getExceptionStatus() { - return exceptionStatus; - } - - // - // Exception status - - /** - *

- * Setter for the field exceptionStatus. - *

- * @param exceptionStatus a byte. - */ - public void setExceptionStatus(byte exceptionStatus) { - this.exceptionStatus = exceptionStatus; - } - - // - // Report slave id - - @Override - public byte[] getReportSlaveIdData() { - return new byte[0]; - } - - // - // - // Private - // - private short getShort(int offset, Map map) throws IllegalDataAddressException { - Short value = map.get(offset); - if (value == null) { - if (allowInvalidAddress) - return invalidAddressValue; - throw new IllegalDataAddressException(); - } - return value.shortValue(); - } - - private boolean getBoolean(int offset, Map map) throws IllegalDataAddressException { - Boolean value = map.get(offset); - if (value == null) { - if (allowInvalidAddress) - return false; - throw new IllegalDataAddressException(); - } - return value.booleanValue(); - } - - private void validateOffset(int offset) { - if (offset < 0 || offset > 65535) - throw new ModbusIdException("Invalid offset: " + offset); - } - - private void validateBit(int bit) { - if (bit < 0 || bit > 15) - throw new ModbusIdException("Invalid bit: " + bit); - } - - private short setBit(short s, int bit, boolean value) { - return (short) (s | ((value ? 1 : 0) << bit)); - } - - private boolean getBit(short s, int bit) { - return ((s >> bit) & 0x1) == 1; - } + private final int slaveId; + + private final Map coils = new HashMap<>(); + + private final Map inputs = new HashMap<>(); + + private final Map holdingRegisters = new HashMap<>(); + + private final Map inputRegisters = new HashMap<>(); + + private final List writeListeners = new ArrayList<>(); + + private boolean allowInvalidAddress = false; + + private short invalidAddressValue = 0; + + private byte exceptionStatus; + + /** + *

+ * Constructor for BasicProcessImage. + *

+ * + * @param slaveId a int. + */ + public BasicProcessImage(int slaveId) { + ModbusUtils.validateSlaveId(slaveId, false); + this.slaveId = slaveId; + } + + @Override + public int getSlaveId() { + return slaveId; + } + + /** + *

+ * addListener. + *

+ * + * @param l a {@link ProcessImageListener} object. + */ + public synchronized void addListener(ProcessImageListener l) { + writeListeners.add(l); + } + + /** + *

+ * removeListener. + *

+ * + * @param l a {@link ProcessImageListener} object. + */ + public synchronized void removeListener(ProcessImageListener l) { + writeListeners.remove(l); + } + + /** + *

+ * isAllowInvalidAddress. + *

+ * + * @return a boolean. + */ + public boolean isAllowInvalidAddress() { + return allowInvalidAddress; + } + + /** + *

+ * Setter for the field allowInvalidAddress. + *

+ * + * @param allowInvalidAddress a boolean. + */ + public void setAllowInvalidAddress(boolean allowInvalidAddress) { + this.allowInvalidAddress = allowInvalidAddress; + } + + /** + *

+ * Getter for the field invalidAddressValue. + *

+ * + * @return a short. + */ + public short getInvalidAddressValue() { + return invalidAddressValue; + } + + /** + *

+ * Setter for the field invalidAddressValue. + *

+ * + * @param invalidAddressValue a short. + */ + public void setInvalidAddressValue(short invalidAddressValue) { + this.invalidAddressValue = invalidAddressValue; + } + + // + // / + // / Additional convenience methods. + // / + // + + /** + *

+ * setBinary. + *

+ * + * @param registerId a int. + * @param value a boolean. + */ + public void setBinary(int registerId, boolean value) { + RangeAndOffset rao = new RangeAndOffset(registerId); + setBinary(rao.getRange(), rao.getOffset(), value); + } + + // + // Binaries + + /** + *

+ * setBinary. + *

+ * + * @param range a int. + * @param offset a int. + * @param value a boolean. + */ + public void setBinary(int range, int offset, boolean value) { + if (range == RegisterRange.COIL_STATUS) + setCoil(offset, value); + else if (range == RegisterRange.INPUT_STATUS) + setInput(offset, value); + else + throw new ModbusIdException("Invalid range to set binary: " + range); + } + + /** + *

+ * setNumeric. + *

+ * + * @param registerId a int. + * @param dataType a int. + * @param value a {@link Number} object. + */ + public synchronized void setNumeric(int registerId, int dataType, Number value) { + RangeAndOffset rao = new RangeAndOffset(registerId); + setNumeric(rao.getRange(), rao.getOffset(), dataType, value); + } + + // + // Numerics + + /** + *

+ * setNumeric. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param value a {@link Number} object. + */ + public synchronized void setNumeric(int range, int offset, int dataType, Number value) { + short[] registers = new NumericLocator(slaveId, range, offset, dataType).valueToShorts(value); + + // Write the value. + if (range == RegisterRange.HOLDING_REGISTER) + setHoldingRegister(offset, registers); + else if (range == RegisterRange.INPUT_REGISTER) + setInputRegister(offset, registers); + else + throw new ModbusIdException("Invalid range to set register: " + range); + } + + /** + *

+ * setString. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + * @param s a {@link String} object. + */ + public synchronized void setString(int range, int offset, int dataType, int registerCount, String s) { + setString(range, offset, dataType, registerCount, StringLocator.ASCII, s); + } + + // + // Strings + + /** + *

+ * setString. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + * @param charset a {@link Charset} object. + * @param s a {@link String} object. + */ + public synchronized void setString(int range, int offset, int dataType, int registerCount, Charset charset, + String s) { + short[] registers = new StringLocator(slaveId, range, offset, dataType, registerCount, charset) + .valueToShorts(s); + + // Write the value. + if (range == RegisterRange.HOLDING_REGISTER) + setHoldingRegister(offset, registers); + else if (range == RegisterRange.INPUT_REGISTER) + setInputRegister(offset, registers); + else + throw new ModbusIdException("Invalid range to set register: " + range); + } + + /** + *

+ * setHoldingRegister. + *

+ * + * @param offset a int. + * @param registers an array of {@link short} objects. + */ + public synchronized void setHoldingRegister(int offset, short[] registers) { + validateOffset(offset); + for (int i = 0; i < registers.length; i++) + setHoldingRegister(offset + i, registers[i]); + } + + /** + *

+ * setInputRegister. + *

+ * + * @param offset a int. + * @param registers an array of {@link short} objects. + */ + public synchronized void setInputRegister(int offset, short[] registers) { + validateOffset(offset); + for (int i = 0; i < registers.length; i++) + setInputRegister(offset + i, registers[i]); + } + + /** + *

+ * setBit. + *

+ * + * @param range a int. + * @param offset a int. + * @param bit a int. + * @param value a boolean. + */ + public synchronized void setBit(int range, int offset, int bit, boolean value) { + if (range == RegisterRange.HOLDING_REGISTER) + setHoldingRegisterBit(offset, bit, value); + else if (range == RegisterRange.INPUT_REGISTER) + setInputRegisterBit(offset, bit, value); + else + throw new ModbusIdException("Invalid range to set register: " + range); + } + + // + // Bits + + /** + *

+ * setHoldingRegisterBit. + *

+ * + * @param offset a int. + * @param bit a int. + * @param value a boolean. + */ + public synchronized void setHoldingRegisterBit(int offset, int bit, boolean value) { + validateBit(bit); + short s; + try { + s = getHoldingRegister(offset); + } catch (IllegalDataAddressException e) { + s = 0; + } + setHoldingRegister(offset, setBit(s, bit, value)); + } + + /** + *

+ * setInputRegisterBit. + *

+ * + * @param offset a int. + * @param bit a int. + * @param value a boolean. + */ + public synchronized void setInputRegisterBit(int offset, int bit, boolean value) { + validateBit(bit); + short s; + try { + s = getInputRegister(offset); + } catch (IllegalDataAddressException e) { + s = 0; + } + setInputRegister(offset, setBit(s, bit, value)); + } + + /** + *

+ * getBit. + *

+ * + * @param range a int. + * @param offset a int. + * @param bit a int. + * @return a boolean. + * @throws IllegalDataAddressException if any. + */ + public boolean getBit(int range, int offset, int bit) throws IllegalDataAddressException { + if (range == RegisterRange.HOLDING_REGISTER) + return getHoldingRegisterBit(offset, bit); + if (range == RegisterRange.INPUT_REGISTER) + return getInputRegisterBit(offset, bit); + throw new ModbusIdException("Invalid range to get register: " + range); + } + + /** + *

+ * getHoldingRegisterBit. + *

+ * + * @param offset a int. + * @param bit a int. + * @return a boolean. + * @throws IllegalDataAddressException if any. + */ + public boolean getHoldingRegisterBit(int offset, int bit) throws IllegalDataAddressException { + validateBit(bit); + return getBit(getHoldingRegister(offset), bit); + } + + /** + *

+ * getInputRegisterBit. + *

+ * + * @param offset a int. + * @param bit a int. + * @return a boolean. + * @throws IllegalDataAddressException if any. + */ + public boolean getInputRegisterBit(int offset, int bit) throws IllegalDataAddressException { + validateBit(bit); + return getBit(getInputRegister(offset), bit); + } + + /** + *

+ * getNumeric. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @return a {@link Number} object. + * @throws IllegalDataAddressException if any. + */ + public Number getNumeric(int range, int offset, int dataType) throws IllegalDataAddressException { + return getRegister(new NumericLocator(slaveId, range, offset, dataType)); + } + + /** + *

+ * getString. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + * @return a {@link String} object. + * @throws IllegalDataAddressException if any. + */ + public String getString(int range, int offset, int dataType, int registerCount) throws IllegalDataAddressException { + return getRegister(new StringLocator(slaveId, range, offset, dataType, registerCount, null)); + } + + /** + *

+ * getString. + *

+ * + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + * @param charset a {@link Charset} object. + * @return a {@link String} object. + * @throws IllegalDataAddressException if any. + */ + public String getString(int range, int offset, int dataType, int registerCount, Charset charset) + throws IllegalDataAddressException { + return getRegister(new StringLocator(slaveId, range, offset, dataType, registerCount, charset)); + } + + /** + *

+ * getRegister. + *

+ * + * @param locator a {@link BaseLocator} object. + * @param a T object. + * @return a T object. + * @throws IllegalDataAddressException if any. + */ + public synchronized T getRegister(BaseLocator locator) throws IllegalDataAddressException { + int words = locator.getRegisterCount(); + byte[] b = new byte[locator.getRegisterCount() * 2]; + for (int i = 0; i < words; i++) { + short s; + if (locator.getRange() == RegisterRange.INPUT_REGISTER) + s = getInputRegister(locator.getOffset() + i); + else if (locator.getRange() == RegisterRange.HOLDING_REGISTER) + s = getHoldingRegister(locator.getOffset() + i); + else if (allowInvalidAddress) + s = invalidAddressValue; + else + throw new IllegalDataAddressException(); + b[i * 2] = ModbusUtils.toByte(s, true); + b[i * 2 + 1] = ModbusUtils.toByte(s, false); + } + + return locator.bytesToValueRealOffset(b, 0); + } + + @Override + public synchronized boolean getCoil(int offset) throws IllegalDataAddressException { + return getBoolean(offset, coils); + } + + // + // + // ProcessImage interface + // + + // + // Coils + + @Override + public synchronized void setCoil(int offset, boolean value) { + validateOffset(offset); + coils.put(offset, value); + } + + @Override + public synchronized void writeCoil(int offset, boolean value) throws IllegalDataAddressException { + boolean old = getBoolean(offset, coils); + setCoil(offset, value); + + for (ProcessImageListener l : writeListeners) + l.coilWrite(offset, old, value); + } + + @Override + public synchronized boolean getInput(int offset) throws IllegalDataAddressException { + return getBoolean(offset, inputs); + } + + // + // Inputs + + @Override + public synchronized void setInput(int offset, boolean value) { + validateOffset(offset); + inputs.put(offset, value); + } + + @Override + public synchronized short getHoldingRegister(int offset) throws IllegalDataAddressException { + return getShort(offset, holdingRegisters); + } + + // + // Holding registers + + @Override + public synchronized void setHoldingRegister(int offset, short value) { + validateOffset(offset); + holdingRegisters.put(offset, value); + } + + @Override + public synchronized void writeHoldingRegister(int offset, short value) throws IllegalDataAddressException { + short old = getShort(offset, holdingRegisters); + setHoldingRegister(offset, value); + + for (ProcessImageListener l : writeListeners) + l.holdingRegisterWrite(offset, old, value); + } + + @Override + public synchronized short getInputRegister(int offset) throws IllegalDataAddressException { + return getShort(offset, inputRegisters); + } + + // + // Input registers + + @Override + public synchronized void setInputRegister(int offset, short value) { + validateOffset(offset); + inputRegisters.put(offset, value); + } + + @Override + public byte getExceptionStatus() { + return exceptionStatus; + } + + // + // Exception status + + /** + *

+ * Setter for the field exceptionStatus. + *

+ * + * @param exceptionStatus a byte. + */ + public void setExceptionStatus(byte exceptionStatus) { + this.exceptionStatus = exceptionStatus; + } + + // + // Report slave id + + @Override + public byte[] getReportSlaveIdData() { + return new byte[0]; + } + + // + // + // Private + // + private short getShort(int offset, Map map) throws IllegalDataAddressException { + Short value = map.get(offset); + if (value == null) { + if (allowInvalidAddress) + return invalidAddressValue; + throw new IllegalDataAddressException(); + } + return value.shortValue(); + } + + private boolean getBoolean(int offset, Map map) throws IllegalDataAddressException { + Boolean value = map.get(offset); + if (value == null) { + if (allowInvalidAddress) + return false; + throw new IllegalDataAddressException(); + } + return value.booleanValue(); + } + + private void validateOffset(int offset) { + if (offset < 0 || offset > 65535) + throw new ModbusIdException("Invalid offset: " + offset); + } + + private void validateBit(int bit) { + if (bit < 0 || bit > 15) + throw new ModbusIdException("Invalid bit: " + bit); + } + + private short setBit(short s, int bit, boolean value) { + return (short) (s | ((value ? 1 : 0) << bit)); + } + + private boolean getBit(short s, int bit) { + return ((s >> bit) & 0x1) == 1; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchRead.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchRead.java index ca03b9473..d0e1f500d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchRead.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchRead.java @@ -45,250 +45,259 @@ import java.util.*; */ public class BatchRead { - private final List> requestValues = new ArrayList<>(); + private final List> requestValues = new ArrayList<>(); - /** - * See documentation above. - */ - private boolean contiguousRequests = false; + /** + * See documentation above. + */ + private boolean contiguousRequests = false; - /** - * If this value is false, any error response received will cause an exception to be - * thrown, and the entire batch to be aborted (unless exceptionsInResults is true - - * see below). If set to true, error responses will be set as the result of all - * affected locators and the entire batch will be attempted with no such exceptions - * thrown. - */ - private boolean errorsInResults = false; + /** + * If this value is false, any error response received will cause an exception to be + * thrown, and the entire batch to be aborted (unless exceptionsInResults is true - + * see below). If set to true, error responses will be set as the result of all + * affected locators and the entire batch will be attempted with no such exceptions + * thrown. + */ + private boolean errorsInResults = false; - /** - * If this value is false, any exceptions thrown will cause the entire batch to be - * aborted. If set to true, the exception will be set as the result of all affected - * locators and the entire batch will be attempted with no such exceptions thrown. - */ - private boolean exceptionsInResults = false; + /** + * If this value is false, any exceptions thrown will cause the entire batch to be + * aborted. If set to true, the exception will be set as the result of all affected + * locators and the entire batch will be attempted with no such exceptions thrown. + */ + private boolean exceptionsInResults = false; - /** - * A batch may be split into an arbitrary number of individual Modbus requests, and so - * a given batch may take an arbitrary amount of time to complete. The cancel field is - * provided to allow the batch to be cancelled. - */ - private boolean cancel; + /** + * A batch may be split into an arbitrary number of individual Modbus requests, and so + * a given batch may take an arbitrary amount of time to complete. The cancel field is + * provided to allow the batch to be cancelled. + */ + private boolean cancel; - /** - * This is what the data looks like after partitioning. - */ - private List> functionGroups; + /** + * This is what the data looks like after partitioning. + */ + private List> functionGroups; - /** - *

- * isContiguousRequests. - *

- * @return a boolean. - */ - public boolean isContiguousRequests() { - return contiguousRequests; - } + /** + *

+ * isContiguousRequests. + *

+ * + * @return a boolean. + */ + public boolean isContiguousRequests() { + return contiguousRequests; + } - /** - *

- * Setter for the field contiguousRequests. - *

- * @param contiguousRequests a boolean. - */ - public void setContiguousRequests(boolean contiguousRequests) { - this.contiguousRequests = contiguousRequests; - functionGroups = null; - } + /** + *

+ * Setter for the field contiguousRequests. + *

+ * + * @param contiguousRequests a boolean. + */ + public void setContiguousRequests(boolean contiguousRequests) { + this.contiguousRequests = contiguousRequests; + functionGroups = null; + } - /** - *

- * isErrorsInResults. - *

- * @return a boolean. - */ - public boolean isErrorsInResults() { - return errorsInResults; - } + /** + *

+ * isErrorsInResults. + *

+ * + * @return a boolean. + */ + public boolean isErrorsInResults() { + return errorsInResults; + } - /** - *

- * Setter for the field errorsInResults. - *

- * @param errorsInResults a boolean. - */ - public void setErrorsInResults(boolean errorsInResults) { - this.errorsInResults = errorsInResults; - } + /** + *

+ * Setter for the field errorsInResults. + *

+ * + * @param errorsInResults a boolean. + */ + public void setErrorsInResults(boolean errorsInResults) { + this.errorsInResults = errorsInResults; + } - /** - *

- * isExceptionsInResults. - *

- * @return a boolean. - */ - public boolean isExceptionsInResults() { - return exceptionsInResults; - } + /** + *

+ * isExceptionsInResults. + *

+ * + * @return a boolean. + */ + public boolean isExceptionsInResults() { + return exceptionsInResults; + } - /** - *

- * Setter for the field exceptionsInResults. - *

- * @param exceptionsInResults a boolean. - */ - public void setExceptionsInResults(boolean exceptionsInResults) { - this.exceptionsInResults = exceptionsInResults; - } + /** + *

+ * Setter for the field exceptionsInResults. + *

+ * + * @param exceptionsInResults a boolean. + */ + public void setExceptionsInResults(boolean exceptionsInResults) { + this.exceptionsInResults = exceptionsInResults; + } - /** - *

- * getReadFunctionGroups. - *

- * @param master a {@link ModbusMaster} object. - * @return a {@link List} object. - */ - public List> getReadFunctionGroups(ModbusMaster master) { - if (functionGroups == null) - doPartition(master); - return functionGroups; - } + /** + *

+ * getReadFunctionGroups. + *

+ * + * @param master a {@link ModbusMaster} object. + * @return a {@link List} object. + */ + public List> getReadFunctionGroups(ModbusMaster master) { + if (functionGroups == null) + doPartition(master); + return functionGroups; + } - /** - *

- * addLocator. - *

- * @param id a K object. - * @param locator a {@link BaseLocator} object. - */ - public void addLocator(K id, BaseLocator locator) { - addLocator(new KeyedModbusLocator<>(id, locator)); - } + /** + *

+ * addLocator. + *

+ * + * @param id a K object. + * @param locator a {@link BaseLocator} object. + */ + public void addLocator(K id, BaseLocator locator) { + addLocator(new KeyedModbusLocator<>(id, locator)); + } - private void addLocator(KeyedModbusLocator locator) { - requestValues.add(locator); - functionGroups = null; - } + private void addLocator(KeyedModbusLocator locator) { + requestValues.add(locator); + functionGroups = null; + } - /** - *

- * isCancel. - *

- * @return a boolean. - */ - public boolean isCancel() { - return cancel; - } + /** + *

+ * isCancel. + *

+ * + * @return a boolean. + */ + public boolean isCancel() { + return cancel; + } - /** - *

- * Setter for the field cancel. - *

- * @param cancel a boolean. - */ - public void setCancel(boolean cancel) { - this.cancel = cancel; - } + /** + *

+ * Setter for the field cancel. + *

+ * + * @param cancel a boolean. + */ + public void setCancel(boolean cancel) { + this.cancel = cancel; + } - // - // - // Private stuff - // - private void doPartition(ModbusMaster master) { - Map>> slaveRangeBatch = new HashMap<>(); + // + // + // Private stuff + // + private void doPartition(ModbusMaster master) { + Map>> slaveRangeBatch = new HashMap<>(); - // Separate the batch into slave ids and read functions. - List> functions; - for (KeyedModbusLocator locator : requestValues) { - // Find the function list for this slave and range. Create it if necessary. - functions = slaveRangeBatch.computeIfAbsent(locator.getSlaveAndRange(), k -> new ArrayList<>()); + // Separate the batch into slave ids and read functions. + List> functions; + for (KeyedModbusLocator locator : requestValues) { + // Find the function list for this slave and range. Create it if necessary. + functions = slaveRangeBatch.computeIfAbsent(locator.getSlaveAndRange(), k -> new ArrayList<>()); - // Add this locator to the function list. - functions.add(locator); - } + // Add this locator to the function list. + functions.add(locator); + } - // Now that we have locators grouped into slave and function, check each read - // function group and break into - // parts as necessary. - Collection>> functionLocatorLists = slaveRangeBatch.values(); - FunctionLocatorComparator comparator = new FunctionLocatorComparator(); - functionGroups = new ArrayList<>(); - for (List> functionLocatorList : functionLocatorLists) { - // Sort the list by offset. - Collections.sort(functionLocatorList, comparator); + // Now that we have locators grouped into slave and function, check each read + // function group and break into + // parts as necessary. + Collection>> functionLocatorLists = slaveRangeBatch.values(); + FunctionLocatorComparator comparator = new FunctionLocatorComparator(); + functionGroups = new ArrayList<>(); + for (List> functionLocatorList : functionLocatorLists) { + // Sort the list by offset. + Collections.sort(functionLocatorList, comparator); - // Break into parts by excessive request length. Remember the max item count - // that we can ask for, for - // this function - int maxReadCount = master.getMaxReadCount(functionLocatorList.get(0).getSlaveAndRange().getRange()); + // Break into parts by excessive request length. Remember the max item count + // that we can ask for, for + // this function + int maxReadCount = master.getMaxReadCount(functionLocatorList.get(0).getSlaveAndRange().getRange()); - // Create the request groups. - createRequestGroups(functionGroups, functionLocatorList, maxReadCount); - // System.out.println("requests: " + functionGroups.size()); - } - } + // Create the request groups. + createRequestGroups(functionGroups, functionLocatorList, maxReadCount); + // System.out.println("requests: " + functionGroups.size()); + } + } - /** - * We aren't trying to do anything fancy here, like some kind of artificial optimal - * group for performance or anything. We pretty much just try to fit as many locators - * as possible into a single valid request, and then move on. - *

- * This method assumes the locators have already been sorted by start offset. - */ - private void createRequestGroups(List> functionGroups, List> locators, - int maxCount) { - ReadFunctionGroup functionGroup; - KeyedModbusLocator locator; - int index; - int endOffset; - // Loop for creation of groups. - while (locators.size() > 0) { - functionGroup = new ReadFunctionGroup<>(locators.remove(0)); - functionGroups.add(functionGroup); - endOffset = functionGroup.getStartOffset() + maxCount - 1; + /** + * We aren't trying to do anything fancy here, like some kind of artificial optimal + * group for performance or anything. We pretty much just try to fit as many locators + * as possible into a single valid request, and then move on. + *

+ * This method assumes the locators have already been sorted by start offset. + */ + private void createRequestGroups(List> functionGroups, List> locators, + int maxCount) { + ReadFunctionGroup functionGroup; + KeyedModbusLocator locator; + int index; + int endOffset; + // Loop for creation of groups. + while (locators.size() > 0) { + functionGroup = new ReadFunctionGroup<>(locators.remove(0)); + functionGroups.add(functionGroup); + endOffset = functionGroup.getStartOffset() + maxCount - 1; - // Loop for adding locators to the current group - index = 0; - while (locators.size() > index) { - locator = locators.get(index); - boolean added = false; + // Loop for adding locators to the current group + index = 0; + while (locators.size() > index) { + locator = locators.get(index); + boolean added = false; - if (locator.getEndOffset() <= endOffset) { - if (contiguousRequests) { - // The locator must at least abut the other locators in the group. - if (locator.getOffset() <= functionGroup.getEndOffset() + 1) { - functionGroup.add(locators.remove(index)); - added = true; - } - } - else { - functionGroup.add(locators.remove(index)); - added = true; - } - } + if (locator.getEndOffset() <= endOffset) { + if (contiguousRequests) { + // The locator must at least abut the other locators in the group. + if (locator.getOffset() <= functionGroup.getEndOffset() + 1) { + functionGroup.add(locators.remove(index)); + added = true; + } + } else { + functionGroup.add(locators.remove(index)); + added = true; + } + } - if (!added) { - // This locator doesn't fit inside the current function... - if (locator.getOffset() > endOffset) - // ... and since the list is sorted by offset, no other locators - // can either, so quit the loop. - break; + if (!added) { + // This locator doesn't fit inside the current function... + if (locator.getOffset() > endOffset) + // ... and since the list is sorted by offset, no other locators + // can either, so quit the loop. + break; - // ... but there still may be other locators that can, so increment - // the index - index++; - } - } - } - } + // ... but there still may be other locators that can, so increment + // the index + index++; + } + } + } + } - class FunctionLocatorComparator implements Comparator> { + class FunctionLocatorComparator implements Comparator> { - @Override - public int compare(KeyedModbusLocator ml1, KeyedModbusLocator ml2) { - return ml1.getOffset() - ml2.getOffset(); - } + @Override + public int compare(KeyedModbusLocator ml1, KeyedModbusLocator ml2) { + return ml1.getOffset() - ml2.getOffset(); + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchResults.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchResults.java index 4d3c4da80..aa5352939 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchResults.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/BatchResults.java @@ -29,77 +29,83 @@ import java.util.Map; */ public class BatchResults { - private final Map data = new HashMap<>(); + private final Map data = new HashMap<>(); - /** - *

- * addResult. - *

- * @param key a K object. - * @param value a {@link Object} object. - */ - public void addResult(K key, Object value) { - data.put(key, value); - } + /** + *

+ * addResult. + *

+ * + * @param key a K object. + * @param value a {@link Object} object. + */ + public void addResult(K key, Object value) { + data.put(key, value); + } - /** - *

- * getValue. - *

- * @param key a K object. - * @return a {@link Object} object. - */ - public Object getValue(K key) { - return data.get(key); - } + /** + *

+ * getValue. + *

+ * + * @param key a K object. + * @return a {@link Object} object. + */ + public Object getValue(K key) { + return data.get(key); + } - /** - *

- * getIntValue. - *

- * @param key a K object. - * @return a {@link Integer} object. - */ - public Integer getIntValue(K key) { - return (Integer) getValue(key); - } + /** + *

+ * getIntValue. + *

+ * + * @param key a K object. + * @return a {@link Integer} object. + */ + public Integer getIntValue(K key) { + return (Integer) getValue(key); + } - /** - *

- * getLongValue. - *

- * @param key a K object. - * @return a {@link Long} object. - */ - public Long getLongValue(K key) { - return (Long) getValue(key); - } + /** + *

+ * getLongValue. + *

+ * + * @param key a K object. + * @return a {@link Long} object. + */ + public Long getLongValue(K key) { + return (Long) getValue(key); + } - /** - *

- * getDoubleValue. - *

- * @param key a K object. - * @return a {@link Double} object. - */ - public Double getDoubleValue(K key) { - return (Double) getValue(key); - } + /** + *

+ * getDoubleValue. + *

+ * + * @param key a K object. + * @return a {@link Double} object. + */ + public Double getDoubleValue(K key) { + return (Double) getValue(key); + } - /** - *

- * getFloatValue. - *

- * @param key a K object. - * @return a {@link Float} object. - */ - public Float getFloatValue(K key) { - return (Float) getValue(key); - } + /** + *

+ * getFloatValue. + *

+ * + * @param key a K object. + * @return a {@link Float} object. + */ + public Float getFloatValue(K key) { + return (Float) getValue(key); + } - @Override - public String toString() { - return data.toString(); - } + @Override + public String toString() { + return data.toString(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ExceptionResult.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ExceptionResult.java index 06d98771a..fa325ecbe 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ExceptionResult.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ExceptionResult.java @@ -28,39 +28,42 @@ import com.serotonin.modbus4j.code.ExceptionCode; */ public class ExceptionResult { - private final byte exceptionCode; + private final byte exceptionCode; - private final String exceptionMessage; + private final String exceptionMessage; - /** - *

- * Constructor for ExceptionResult. - *

- * @param exceptionCode a byte. - */ - public ExceptionResult(byte exceptionCode) { - this.exceptionCode = exceptionCode; - exceptionMessage = ExceptionCode.getExceptionMessage(exceptionCode); - } + /** + *

+ * Constructor for ExceptionResult. + *

+ * + * @param exceptionCode a byte. + */ + public ExceptionResult(byte exceptionCode) { + this.exceptionCode = exceptionCode; + exceptionMessage = ExceptionCode.getExceptionMessage(exceptionCode); + } - /** - *

- * Getter for the field exceptionCode. - *

- * @return a byte. - */ - public byte getExceptionCode() { - return exceptionCode; - } + /** + *

+ * Getter for the field exceptionCode. + *

+ * + * @return a byte. + */ + public byte getExceptionCode() { + return exceptionCode; + } - /** - *

- * Getter for the field exceptionMessage. - *

- * @return a {@link String} object. - */ - public String getExceptionMessage() { - return exceptionMessage; - } + /** + *

+ * Getter for the field exceptionMessage. + *

+ * + * @return a {@link String} object. + */ + public String getExceptionMessage() { + return exceptionMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/Modbus.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/Modbus.java index 3f6283ad4..40c224299 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/Modbus.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/Modbus.java @@ -31,153 +31,164 @@ import com.serotonin.modbus4j.sero.messaging.MessagingExceptionHandler; */ public class Modbus { - /** - * Constant DEFAULT_MAX_READ_BIT_COUNT=2000 - */ - public static final int DEFAULT_MAX_READ_BIT_COUNT = 2000; + /** + * Constant DEFAULT_MAX_READ_BIT_COUNT=2000 + */ + public static final int DEFAULT_MAX_READ_BIT_COUNT = 2000; - /** - * Constant DEFAULT_MAX_READ_REGISTER_COUNT=125 - */ - public static final int DEFAULT_MAX_READ_REGISTER_COUNT = 125; + /** + * Constant DEFAULT_MAX_READ_REGISTER_COUNT=125 + */ + public static final int DEFAULT_MAX_READ_REGISTER_COUNT = 125; - /** - * Constant DEFAULT_MAX_WRITE_REGISTER_COUNT=120 - */ - public static final int DEFAULT_MAX_WRITE_REGISTER_COUNT = 120; + /** + * Constant DEFAULT_MAX_WRITE_REGISTER_COUNT=120 + */ + public static final int DEFAULT_MAX_WRITE_REGISTER_COUNT = 120; - private MessagingExceptionHandler exceptionHandler = new DefaultMessagingExceptionHandler(); + private MessagingExceptionHandler exceptionHandler = new DefaultMessagingExceptionHandler(); - private int maxReadBitCount = DEFAULT_MAX_READ_BIT_COUNT; + private int maxReadBitCount = DEFAULT_MAX_READ_BIT_COUNT; - private int maxReadRegisterCount = DEFAULT_MAX_READ_REGISTER_COUNT; + private int maxReadRegisterCount = DEFAULT_MAX_READ_REGISTER_COUNT; - private int maxWriteRegisterCount = DEFAULT_MAX_WRITE_REGISTER_COUNT; + private int maxWriteRegisterCount = DEFAULT_MAX_WRITE_REGISTER_COUNT; - /** - *

- * getMaxReadCount. - *

- * @param registerRange a int. - * @return a int. - */ - public int getMaxReadCount(int registerRange) { - switch (registerRange) { - case RegisterRange.COIL_STATUS: - case RegisterRange.INPUT_STATUS: - return maxReadBitCount; - case RegisterRange.HOLDING_REGISTER: - case RegisterRange.INPUT_REGISTER: - return maxReadRegisterCount; - } - return -1; - } + /** + *

+ * getMaxReadCount. + *

+ * + * @param registerRange a int. + * @return a int. + */ + public int getMaxReadCount(int registerRange) { + switch (registerRange) { + case RegisterRange.COIL_STATUS: + case RegisterRange.INPUT_STATUS: + return maxReadBitCount; + case RegisterRange.HOLDING_REGISTER: + case RegisterRange.INPUT_REGISTER: + return maxReadRegisterCount; + } + return -1; + } - /** - *

- * validateNumberOfBits. - *

- * @param bits a int. - * @throws ModbusTransportException if any. - */ - public void validateNumberOfBits(int bits) throws ModbusTransportException { - if (bits < 1 || bits > maxReadBitCount) - throw new ModbusTransportException("Invalid number of bits: " + bits); - } + /** + *

+ * validateNumberOfBits. + *

+ * + * @param bits a int. + * @throws ModbusTransportException if any. + */ + public void validateNumberOfBits(int bits) throws ModbusTransportException { + if (bits < 1 || bits > maxReadBitCount) + throw new ModbusTransportException("Invalid number of bits: " + bits); + } - /** - *

- * validateNumberOfRegisters. - *

- * @param registers a int. - * @throws ModbusTransportException if any. - */ - public void validateNumberOfRegisters(int registers) throws ModbusTransportException { - if (registers < 1 || registers > maxReadRegisterCount) - throw new ModbusTransportException("Invalid number of registers: " + registers); - } + /** + *

+ * validateNumberOfRegisters. + *

+ * + * @param registers a int. + * @throws ModbusTransportException if any. + */ + public void validateNumberOfRegisters(int registers) throws ModbusTransportException { + if (registers < 1 || registers > maxReadRegisterCount) + throw new ModbusTransportException("Invalid number of registers: " + registers); + } - /** - *

- * Getter for the field exceptionHandler. - *

- * @return a {@link MessagingExceptionHandler} object. - */ - public MessagingExceptionHandler getExceptionHandler() { - return exceptionHandler; - } + /** + *

+ * Getter for the field exceptionHandler. + *

+ * + * @return a {@link MessagingExceptionHandler} object. + */ + public MessagingExceptionHandler getExceptionHandler() { + return exceptionHandler; + } - /** - *

- * Setter for the field exceptionHandler. - *

- * @param exceptionHandler a {@link MessagingExceptionHandler} object. - */ - public void setExceptionHandler(MessagingExceptionHandler exceptionHandler) { - if (exceptionHandler == null) - this.exceptionHandler = new DefaultMessagingExceptionHandler(); - else - this.exceptionHandler = exceptionHandler; - } + /** + *

+ * Setter for the field exceptionHandler. + *

+ * + * @param exceptionHandler a {@link MessagingExceptionHandler} object. + */ + public void setExceptionHandler(MessagingExceptionHandler exceptionHandler) { + if (exceptionHandler == null) + this.exceptionHandler = new DefaultMessagingExceptionHandler(); + else + this.exceptionHandler = exceptionHandler; + } - /** - *

- * Getter for the field maxReadBitCount. - *

- * @return a int. - */ - public int getMaxReadBitCount() { - return maxReadBitCount; - } + /** + *

+ * Getter for the field maxReadBitCount. + *

+ * + * @return a int. + */ + public int getMaxReadBitCount() { + return maxReadBitCount; + } - /** - *

- * Setter for the field maxReadBitCount. - *

- * @param maxReadBitCount a int. - */ - public void setMaxReadBitCount(int maxReadBitCount) { - this.maxReadBitCount = maxReadBitCount; - } + /** + *

+ * Setter for the field maxReadBitCount. + *

+ * + * @param maxReadBitCount a int. + */ + public void setMaxReadBitCount(int maxReadBitCount) { + this.maxReadBitCount = maxReadBitCount; + } - /** - *

- * Getter for the field maxReadRegisterCount. - *

- * @return a int. - */ - public int getMaxReadRegisterCount() { - return maxReadRegisterCount; - } + /** + *

+ * Getter for the field maxReadRegisterCount. + *

+ * + * @return a int. + */ + public int getMaxReadRegisterCount() { + return maxReadRegisterCount; + } - /** - *

- * Setter for the field maxReadRegisterCount. - *

- * @param maxReadRegisterCount a int. - */ - public void setMaxReadRegisterCount(int maxReadRegisterCount) { - this.maxReadRegisterCount = maxReadRegisterCount; - } + /** + *

+ * Setter for the field maxReadRegisterCount. + *

+ * + * @param maxReadRegisterCount a int. + */ + public void setMaxReadRegisterCount(int maxReadRegisterCount) { + this.maxReadRegisterCount = maxReadRegisterCount; + } - /** - *

- * Getter for the field maxWriteRegisterCount. - *

- * @return a int. - */ - public int getMaxWriteRegisterCount() { - return maxWriteRegisterCount; - } + /** + *

+ * Getter for the field maxWriteRegisterCount. + *

+ * + * @return a int. + */ + public int getMaxWriteRegisterCount() { + return maxWriteRegisterCount; + } - /** - *

- * Setter for the field maxWriteRegisterCount. - *

- * @param maxWriteRegisterCount a int. - */ - public void setMaxWriteRegisterCount(int maxWriteRegisterCount) { - this.maxWriteRegisterCount = maxWriteRegisterCount; - } + /** + *

+ * Setter for the field maxWriteRegisterCount. + *

+ * + * @param maxWriteRegisterCount a int. + */ + public void setMaxWriteRegisterCount(int maxWriteRegisterCount) { + this.maxWriteRegisterCount = maxWriteRegisterCount; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusFactory.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusFactory.java index 155d03170..354fc437d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusFactory.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusFactory.java @@ -43,157 +43,168 @@ import com.serotonin.modbus4j.serial.rtu.RtuSlave; */ public class ModbusFactory { - // - // Modbus masters - // + // + // Modbus masters + // - /** - *

- * createRtuMaster. - *

- * @param wrapper a {@link SerialPortWrapper} object. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createRtuMaster(SerialPortWrapper wrapper) { - return new RtuMaster(wrapper); - } + /** + *

+ * createRtuMaster. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createRtuMaster(SerialPortWrapper wrapper) { + return new RtuMaster(wrapper); + } - /** - *

- * createAsciiMaster. - *

- * @param wrapper a {@link SerialPortWrapper} object. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createAsciiMaster(SerialPortWrapper wrapper) { - return new AsciiMaster(wrapper); - } + /** + *

+ * createAsciiMaster. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createAsciiMaster(SerialPortWrapper wrapper) { + return new AsciiMaster(wrapper); + } - /** - *

- * createTcpMaster. - *

- * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createTcpMaster(IpParameters params, boolean keepAlive) { - return new TcpMaster(params, keepAlive); - } + /** + *

+ * createTcpMaster. + *

+ * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createTcpMaster(IpParameters params, boolean keepAlive) { + return new TcpMaster(params, keepAlive); + } - /** - *

- * createTcpMaster. - *

- * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @param lingerTime an Integer. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createTcpMaster(IpParameters params, boolean keepAlive, Integer lingerTime) { - return new TcpMaster(params, keepAlive, lingerTime); - } + /** + *

+ * createTcpMaster. + *

+ * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @param lingerTime an Integer. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createTcpMaster(IpParameters params, boolean keepAlive, Integer lingerTime) { + return new TcpMaster(params, keepAlive, lingerTime); + } - /** - *

- * createUdpMaster. - *

- * @param params a {@link IpParameters} object. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createUdpMaster(IpParameters params) { - return new UdpMaster(params); - } + /** + *

+ * createUdpMaster. + *

+ * + * @param params a {@link IpParameters} object. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createUdpMaster(IpParameters params) { + return new UdpMaster(params); + } - /** - *

- * createTcpListener. - *

- * @param params a {@link IpParameters} object. - * @return a {@link ModbusMaster} object. - */ - public ModbusMaster createTcpListener(IpParameters params) { - return new TcpListener(params); - } + /** + *

+ * createTcpListener. + *

+ * + * @param params a {@link IpParameters} object. + * @return a {@link ModbusMaster} object. + */ + public ModbusMaster createTcpListener(IpParameters params) { + return new TcpListener(params); + } - // - // Modbus slaves - // + // + // Modbus slaves + // - /** - *

- * createRtuSlave. - *

- * @param wrapper a {@link SerialPortWrapper} object. - * @return a {@link ModbusSlaveSet} object. - */ - public ModbusSlaveSet createRtuSlave(SerialPortWrapper wrapper) { - return new RtuSlave(wrapper); - } + /** + *

+ * createRtuSlave. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + * @return a {@link ModbusSlaveSet} object. + */ + public ModbusSlaveSet createRtuSlave(SerialPortWrapper wrapper) { + return new RtuSlave(wrapper); + } - /** - *

- * createAsciiSlave. - *

- * @param wrapper a {@link SerialPortWrapper} object. - * @return a {@link ModbusSlaveSet} object. - */ - public ModbusSlaveSet createAsciiSlave(SerialPortWrapper wrapper) { - return new AsciiSlave(wrapper); - } + /** + *

+ * createAsciiSlave. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + * @return a {@link ModbusSlaveSet} object. + */ + public ModbusSlaveSet createAsciiSlave(SerialPortWrapper wrapper) { + return new AsciiSlave(wrapper); + } - /** - *

- * createTcpSlave. - *

- * @param encapsulated a boolean. - * @return a {@link ModbusSlaveSet} object. - */ - public ModbusSlaveSet createTcpSlave(boolean encapsulated) { - return new TcpSlave(encapsulated); - } + /** + *

+ * createTcpSlave. + *

+ * + * @param encapsulated a boolean. + * @return a {@link ModbusSlaveSet} object. + */ + public ModbusSlaveSet createTcpSlave(boolean encapsulated) { + return new TcpSlave(encapsulated); + } - /** - *

- * createUdpSlave. - *

- * @param encapsulated a boolean. - * @return a {@link ModbusSlaveSet} object. - */ - public ModbusSlaveSet createUdpSlave(boolean encapsulated) { - return new UdpSlave(encapsulated); - } + /** + *

+ * createUdpSlave. + *

+ * + * @param encapsulated a boolean. + * @return a {@link ModbusSlaveSet} object. + */ + public ModbusSlaveSet createUdpSlave(boolean encapsulated) { + return new UdpSlave(encapsulated); + } - // - // Modbus requests - // + // + // Modbus requests + // - /** - *

- * createReadRequest. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param length a int. - * @return a {@link ModbusRequest} object. - * @throws ModbusTransportException if any. - * @throws ModbusIdException if any. - */ - public ModbusRequest createReadRequest(int slaveId, int range, int offset, int length) - throws ModbusTransportException, ModbusIdException { - ModbusUtils.validateRegisterRange(range); + /** + *

+ * createReadRequest. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param length a int. + * @return a {@link ModbusRequest} object. + * @throws ModbusTransportException if any. + * @throws ModbusIdException if any. + */ + public ModbusRequest createReadRequest(int slaveId, int range, int offset, int length) + throws ModbusTransportException, ModbusIdException { + ModbusUtils.validateRegisterRange(range); - if (range == RegisterRange.COIL_STATUS) - return new ReadCoilsRequest(slaveId, offset, length); + if (range == RegisterRange.COIL_STATUS) + return new ReadCoilsRequest(slaveId, offset, length); - if (range == RegisterRange.INPUT_STATUS) - return new ReadDiscreteInputsRequest(slaveId, offset, length); + if (range == RegisterRange.INPUT_STATUS) + return new ReadDiscreteInputsRequest(slaveId, offset, length); - if (range == RegisterRange.INPUT_REGISTER) - return new ReadInputRegistersRequest(slaveId, offset, length); + if (range == RegisterRange.INPUT_REGISTER) + return new ReadInputRegistersRequest(slaveId, offset, length); - return new ReadHoldingRegistersRequest(slaveId, offset, length); - } + return new ReadHoldingRegistersRequest(slaveId, offset, length); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusMaster.java index cff8cd87d..3fcc3953a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusMaster.java @@ -53,579 +53,600 @@ import java.util.Map; * @since 2022.1.0 */ abstract /** - * Modbus Master - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Master + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusMaster extends Modbus { - private final Map slaveProfiles = new HashMap<>(); + private final Map slaveProfiles = new HashMap<>(); - /** - * Should we validate the responses: - ensure that the requested slave id is what is - * in the response - */ - protected boolean validateResponse; + /** + * Should we validate the responses: - ensure that the requested slave id is what is + * in the response + */ + protected boolean validateResponse; - /** - * If connection is established with slave/slaves - */ - protected boolean connected = false; + /** + * If connection is established with slave/slaves + */ + protected boolean connected = false; - protected boolean initialized; + protected boolean initialized; - private int timeout = 500; + private int timeout = 500; - private int retries = 2; + private int retries = 2; - /** - * If the slave equipment only supports multiple write commands, set this to true. - * Otherwise, and combination of single or multiple write commands will be used as - * appropriate. - */ - private boolean multipleWritesOnly; + /** + * If the slave equipment only supports multiple write commands, set this to true. + * Otherwise, and combination of single or multiple write commands will be used as + * appropriate. + */ + private boolean multipleWritesOnly; - private int discardDataDelay = 0; + private int discardDataDelay = 0; - private BaseIOLog ioLog; + private BaseIOLog ioLog; - /** - * An input stream ePoll will use a single thread to read all input streams. If - * multiple serial or TCP modbus connections are to be made, an ePoll can be much more - * efficient. - */ - private InputStreamEPollWrapper ePoll; + /** + * An input stream ePoll will use a single thread to read all input streams. If + * multiple serial or TCP modbus connections are to be made, an ePoll can be much more + * efficient. + */ + private InputStreamEPollWrapper ePoll; - /** - *

- * isConnected. - *

- * @return a boolean. - */ - public boolean isConnected() { - return connected; - } + /** + *

+ * isConnected. + *

+ * + * @return a boolean. + */ + public boolean isConnected() { + return connected; + } - /** - *

- * Setter for the field connected. - *

- * @param connected a boolean. - */ - public void setConnected(boolean connected) { - this.connected = connected; - } + /** + *

+ * Setter for the field connected. + *

+ * + * @param connected a boolean. + */ + public void setConnected(boolean connected) { + this.connected = connected; + } - /** - *

- * init. - *

- * @throws ModbusInitException if any. - */ - abstract public void init() throws ModbusInitException; + /** + *

+ * init. + *

+ * + * @throws ModbusInitException if any. + */ + abstract public void init() throws ModbusInitException; - /** - *

- * isInitialized. - *

- * @return a boolean. - */ - public boolean isInitialized() { - return initialized; - } + /** + *

+ * isInitialized. + *

+ * + * @return a boolean. + */ + public boolean isInitialized() { + return initialized; + } - /** - *

- * destroy. - *

- */ - abstract public void destroy(); + /** + *

+ * destroy. + *

+ */ + abstract public void destroy(); - /** - *

- * send. - *

- * @param request a {@link ModbusRequest} object. - * @return a {@link ModbusResponse} object. - * @throws ModbusTransportException if any. - */ - public final ModbusResponse send(ModbusRequest request) throws ModbusTransportException { - request.validate(this); - ModbusResponse modbusResponse = sendImpl(request); - if (validateResponse) - modbusResponse.validateResponse(request); - return modbusResponse; - } + /** + *

+ * send. + *

+ * + * @param request a {@link ModbusRequest} object. + * @return a {@link ModbusResponse} object. + * @throws ModbusTransportException if any. + */ + public final ModbusResponse send(ModbusRequest request) throws ModbusTransportException { + request.validate(this); + ModbusResponse modbusResponse = sendImpl(request); + if (validateResponse) + modbusResponse.validateResponse(request); + return modbusResponse; + } - /** - *

- * sendImpl. - *

- * @param request a {@link ModbusRequest} object. - * @return a {@link ModbusResponse} object. - * @throws ModbusTransportException if any. - */ - abstract public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException; + /** + *

+ * sendImpl. + *

+ * + * @param request a {@link ModbusRequest} object. + * @return a {@link ModbusResponse} object. + * @throws ModbusTransportException if any. + */ + abstract public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException; - /** - * Returns a value from the modbus network according to the given locator information. - * Various data types are allowed to be requested including multi-word types. The - * determination of the correct request message to send is handled automatically. - * @param locator the information required to locate the value in the modbus network. - * @param a T object. - * @return an object representing the value found. This will be one of Boolean, Short, - * Integer, Long, BigInteger, Float, or Double. See the DataType enumeration for - * details on which type to expect. - * @throws ModbusTransportException if there was an IO error or other technical - * failure while sending the message - * @throws ErrorResponseException if the response returned from the slave was an - * exception. - */ - @SuppressWarnings("unchecked") - public T getValue(BaseLocator locator) throws ModbusTransportException, ErrorResponseException { - BatchRead batch = new BatchRead<>(); - batch.addLocator("", locator); - BatchResults result = send(batch); - return (T) result.getValue(""); - } + /** + * Returns a value from the modbus network according to the given locator information. + * Various data types are allowed to be requested including multi-word types. The + * determination of the correct request message to send is handled automatically. + * + * @param locator the information required to locate the value in the modbus network. + * @param a T object. + * @return an object representing the value found. This will be one of Boolean, Short, + * Integer, Long, BigInteger, Float, or Double. See the DataType enumeration for + * details on which type to expect. + * @throws ModbusTransportException if there was an IO error or other technical + * failure while sending the message + * @throws ErrorResponseException if the response returned from the slave was an + * exception. + */ + @SuppressWarnings("unchecked") + public T getValue(BaseLocator locator) throws ModbusTransportException, ErrorResponseException { + BatchRead batch = new BatchRead<>(); + batch.addLocator("", locator); + BatchResults result = send(batch); + return (T) result.getValue(""); + } - /** - * Sets the given value in the modbus network according to the given locator - * information. Various data types are allowed to be set including including - * multi-word types. The determination of the correct write message to send is handled - * automatically. - * @param locator the information required to locate the value in the modbus network. - * @param value an object representing the value to be set. This will be one of - * Boolean, Short, Integer, Long, BigInteger, Float, or Double. See the DataType - * enumeration for details on which type to expect. - * @param type of locator - * @throws ModbusTransportException if there was an IO error or other technical - * failure while sending the message - * @throws ErrorResponseException if the response returned from the slave was an - * exception. - */ - public void setValue(BaseLocator locator, Object value) - throws ModbusTransportException, ErrorResponseException { - int slaveId = locator.getSlaveId(); - int registerRange = locator.getRange(); - int writeOffset = locator.getOffset(); + /** + * Sets the given value in the modbus network according to the given locator + * information. Various data types are allowed to be set including including + * multi-word types. The determination of the correct write message to send is handled + * automatically. + * + * @param locator the information required to locate the value in the modbus network. + * @param value an object representing the value to be set. This will be one of + * Boolean, Short, Integer, Long, BigInteger, Float, or Double. See the DataType + * enumeration for details on which type to expect. + * @param type of locator + * @throws ModbusTransportException if there was an IO error or other technical + * failure while sending the message + * @throws ErrorResponseException if the response returned from the slave was an + * exception. + */ + public void setValue(BaseLocator locator, Object value) + throws ModbusTransportException, ErrorResponseException { + int slaveId = locator.getSlaveId(); + int registerRange = locator.getRange(); + int writeOffset = locator.getOffset(); - // Determine the request type that we will use - if (registerRange == RegisterRange.INPUT_STATUS || registerRange == RegisterRange.INPUT_REGISTER) - throw new RuntimeException("Cannot write to input status or input register ranges"); + // Determine the request type that we will use + if (registerRange == RegisterRange.INPUT_STATUS || registerRange == RegisterRange.INPUT_REGISTER) + throw new RuntimeException("Cannot write to input status or input register ranges"); - if (registerRange == RegisterRange.COIL_STATUS) { - if (!(value instanceof Boolean)) - throw new InvalidDataConversionException("Only boolean values can be written to coils"); - if (multipleWritesOnly) - setValue(new WriteCoilsRequest(slaveId, writeOffset, - new boolean[] { ((Boolean) value).booleanValue() })); - else - setValue(new WriteCoilRequest(slaveId, writeOffset, ((Boolean) value).booleanValue())); - } - else { - // Writing to holding registers. - if (locator.getDataType() == DataType.BINARY) { - if (!(value instanceof Boolean)) - throw new InvalidDataConversionException("Only boolean values can be written to coils"); - setHoldingRegisterBit(slaveId, writeOffset, ((BinaryLocator) locator).getBit(), - ((Boolean) value).booleanValue()); - } - else { - // Writing some kind of value to a holding register. - @SuppressWarnings("unchecked") - short[] data = locator.valueToShorts((T) value); - if (data.length == 1 && !multipleWritesOnly) - setValue(new WriteRegisterRequest(slaveId, writeOffset, data[0])); - else - setValue(new WriteRegistersRequest(slaveId, writeOffset, data)); - } - } + if (registerRange == RegisterRange.COIL_STATUS) { + if (!(value instanceof Boolean)) + throw new InvalidDataConversionException("Only boolean values can be written to coils"); + if (multipleWritesOnly) + setValue(new WriteCoilsRequest(slaveId, writeOffset, + new boolean[]{((Boolean) value).booleanValue()})); + else + setValue(new WriteCoilRequest(slaveId, writeOffset, ((Boolean) value).booleanValue())); + } else { + // Writing to holding registers. + if (locator.getDataType() == DataType.BINARY) { + if (!(value instanceof Boolean)) + throw new InvalidDataConversionException("Only boolean values can be written to coils"); + setHoldingRegisterBit(slaveId, writeOffset, ((BinaryLocator) locator).getBit(), + ((Boolean) value).booleanValue()); + } else { + // Writing some kind of value to a holding register. + @SuppressWarnings("unchecked") + short[] data = locator.valueToShorts((T) value); + if (data.length == 1 && !multipleWritesOnly) + setValue(new WriteRegisterRequest(slaveId, writeOffset, data[0])); + else + setValue(new WriteRegistersRequest(slaveId, writeOffset, data)); + } + } - } + } - /** - * Node scanning. Returns a list of slave nodes that respond to a read exception - * status request (perhaps with an error, but respond nonetheless). - *

- * Note: a similar scan could be done for registers in nodes, but, for one thing, it - * would take some time to run, and in any case the results would not be meaningful - * since there would be no semantic information accompanying the results. - * @return a {@link List} object. - */ - public List scanForSlaveNodes() { - List result = new ArrayList<>(); - for (int i = 1; i <= 240; i++) { - if (testSlaveNode(i)) - result.add(i); - } - return result; - } + /** + * Node scanning. Returns a list of slave nodes that respond to a read exception + * status request (perhaps with an error, but respond nonetheless). + *

+ * Note: a similar scan could be done for registers in nodes, but, for one thing, it + * would take some time to run, and in any case the results would not be meaningful + * since there would be no semantic information accompanying the results. + * + * @return a {@link List} object. + */ + public List scanForSlaveNodes() { + List result = new ArrayList<>(); + for (int i = 1; i <= 240; i++) { + if (testSlaveNode(i)) + result.add(i); + } + return result; + } - /** - *

- * scanForSlaveNodes. - *

- * @param l a {@link NodeScanListener} object. - * @return a {@link ProgressiveTask} object. - */ - public ProgressiveTask scanForSlaveNodes(final NodeScanListener l) { - l.progressUpdate(0); - ProgressiveTask task = new ProgressiveTask(l) { - private int node = 1; + /** + *

+ * scanForSlaveNodes. + *

+ * + * @param l a {@link NodeScanListener} object. + * @return a {@link ProgressiveTask} object. + */ + public ProgressiveTask scanForSlaveNodes(final NodeScanListener l) { + l.progressUpdate(0); + ProgressiveTask task = new ProgressiveTask(l) { + private int node = 1; - @Override - protected void runImpl() { - if (testSlaveNode(node)) - l.nodeFound(node); + @Override + protected void runImpl() { + if (testSlaveNode(node)) + l.nodeFound(node); - declareProgress(((float) node) / 240); + declareProgress(((float) node) / 240); - node++; - if (node > 240) - completed = true; - } - }; + node++; + if (node > 240) + completed = true; + } + }; - new Thread(task).start(); + new Thread(task).start(); - return task; - } + return task; + } - /** - *

- * testSlaveNode. - *

- * @param node a int. - * @return a boolean. - */ - public boolean testSlaveNode(int node) { - try { - send(new ReadHoldingRegistersRequest(node, 0, 1)); - } - catch (ModbusTransportException e) { - // If there was a transport exception, there's no node there. - return false; - } - return true; - } + /** + *

+ * testSlaveNode. + *

+ * + * @param node a int. + * @return a boolean. + */ + public boolean testSlaveNode(int node) { + try { + send(new ReadHoldingRegistersRequest(node, 0, 1)); + } catch (ModbusTransportException e) { + // If there was a transport exception, there's no node there. + return false; + } + return true; + } - /** - *

- * Getter for the field retries. - *

- * @return a int. - */ - public int getRetries() { - return retries; - } + /** + *

+ * Getter for the field retries. + *

+ * + * @return a int. + */ + public int getRetries() { + return retries; + } - /** - *

- * Setter for the field retries. - *

- * @param retries a int. - */ - public void setRetries(int retries) { - if (retries < 0) - this.retries = 0; - else - this.retries = retries; - } + /** + *

+ * Setter for the field retries. + *

+ * + * @param retries a int. + */ + public void setRetries(int retries) { + if (retries < 0) + this.retries = 0; + else + this.retries = retries; + } - /** - *

- * Getter for the field timeout. - *

- * @return a int. - */ - public int getTimeout() { - return timeout; - } + /** + *

+ * Getter for the field timeout. + *

+ * + * @return a int. + */ + public int getTimeout() { + return timeout; + } - /** - *

- * Setter for the field timeout. - *

- * @param timeout a int. - */ - public void setTimeout(int timeout) { - if (timeout < 1) - this.timeout = 1; - else - this.timeout = timeout; - } + /** + *

+ * Setter for the field timeout. + *

+ * + * @param timeout a int. + */ + public void setTimeout(int timeout) { + if (timeout < 1) + this.timeout = 1; + else + this.timeout = timeout; + } - /** - *

- * isMultipleWritesOnly. - *

- * @return a boolean. - */ - public boolean isMultipleWritesOnly() { - return multipleWritesOnly; - } + /** + *

+ * isMultipleWritesOnly. + *

+ * + * @return a boolean. + */ + public boolean isMultipleWritesOnly() { + return multipleWritesOnly; + } - /** - *

- * Setter for the field multipleWritesOnly. - *

- * @param multipleWritesOnly a boolean. - */ - public void setMultipleWritesOnly(boolean multipleWritesOnly) { - this.multipleWritesOnly = multipleWritesOnly; - } + /** + *

+ * Setter for the field multipleWritesOnly. + *

+ * + * @param multipleWritesOnly a boolean. + */ + public void setMultipleWritesOnly(boolean multipleWritesOnly) { + this.multipleWritesOnly = multipleWritesOnly; + } - /** - *

- * Getter for the field discardDataDelay. - *

- * @return a int. - */ - public int getDiscardDataDelay() { - return discardDataDelay; - } + /** + *

+ * Getter for the field discardDataDelay. + *

+ * + * @return a int. + */ + public int getDiscardDataDelay() { + return discardDataDelay; + } - /** - *

- * Setter for the field discardDataDelay. - *

- * @param discardDataDelay a int. - */ - public void setDiscardDataDelay(int discardDataDelay) { - if (discardDataDelay < 0) - this.discardDataDelay = 0; - else - this.discardDataDelay = discardDataDelay; - } + /** + *

+ * Setter for the field discardDataDelay. + *

+ * + * @param discardDataDelay a int. + */ + public void setDiscardDataDelay(int discardDataDelay) { + if (discardDataDelay < 0) + this.discardDataDelay = 0; + else + this.discardDataDelay = discardDataDelay; + } - /** - *

- * Getter for the field ioLog. - *

- * @return a {@link BaseIOLog} object. - */ - public BaseIOLog getIoLog() { - return ioLog; - } + /** + *

+ * Getter for the field ioLog. + *

+ * + * @return a {@link BaseIOLog} object. + */ + public BaseIOLog getIoLog() { + return ioLog; + } - /** - *

- * Setter for the field ioLog. - *

- * @param ioLog a {@link BaseIOLog} object. - */ - public void setIoLog(BaseIOLog ioLog) { - this.ioLog = ioLog; - } + /** + *

+ * Setter for the field ioLog. + *

+ * + * @param ioLog a {@link BaseIOLog} object. + */ + public void setIoLog(BaseIOLog ioLog) { + this.ioLog = ioLog; + } - /** - *

- * Getter for the field ePoll. - *

- * @return a {@link InputStreamEPollWrapper} object. - */ - public InputStreamEPollWrapper getePoll() { - return ePoll; - } + /** + *

+ * Getter for the field ePoll. + *

+ * + * @return a {@link InputStreamEPollWrapper} object. + */ + public InputStreamEPollWrapper getePoll() { + return ePoll; + } - /** - *

- * Setter for the field ePoll. - *

- * @param ePoll a {@link InputStreamEPollWrapper} object. - */ - public void setePoll(InputStreamEPollWrapper ePoll) { - this.ePoll = ePoll; - } + /** + *

+ * Setter for the field ePoll. + *

+ * + * @param ePoll a {@link InputStreamEPollWrapper} object. + */ + public void setePoll(InputStreamEPollWrapper ePoll) { + this.ePoll = ePoll; + } - /** - * Useful for sending a number of polling commands at once, or at least in as optimal - * a batch as possible. - * @param batch a {@link BatchRead} object. - * @param type of result - * @return a {@link BatchResults} object. - * @throws ModbusTransportException if any. - * @throws ErrorResponseException if any. - */ - public BatchResults send(BatchRead batch) throws ModbusTransportException, ErrorResponseException { - if (!initialized) - throw new ModbusTransportException("not initialized"); + /** + * Useful for sending a number of polling commands at once, or at least in as optimal + * a batch as possible. + * + * @param batch a {@link BatchRead} object. + * @param type of result + * @return a {@link BatchResults} object. + * @throws ModbusTransportException if any. + * @throws ErrorResponseException if any. + */ + public BatchResults send(BatchRead batch) throws ModbusTransportException, ErrorResponseException { + if (!initialized) + throw new ModbusTransportException("not initialized"); - BatchResults results = new BatchResults<>(); - List> functionGroups = batch.getReadFunctionGroups(this); + BatchResults results = new BatchResults<>(); + List> functionGroups = batch.getReadFunctionGroups(this); - // Execute each read function and process the results. - for (ReadFunctionGroup functionGroup : functionGroups) { - sendFunctionGroup(functionGroup, results, batch.isErrorsInResults(), batch.isExceptionsInResults()); - if (batch.isCancel()) - break; - } + // Execute each read function and process the results. + for (ReadFunctionGroup functionGroup : functionGroups) { + sendFunctionGroup(functionGroup, results, batch.isErrorsInResults(), batch.isExceptionsInResults()); + if (batch.isCancel()) + break; + } - return results; - } + return results; + } - // - // - // Protected methods - // + // + // + // Protected methods + // - /** - *

- * getMessageControl. - *

- * @return a {@link MessageControl} object. - */ - protected MessageControl getMessageControl() { - MessageControl conn = new MessageControl(); - conn.setRetries(getRetries()); - conn.setTimeout(getTimeout()); - conn.setDiscardDataDelay(getDiscardDataDelay()); - conn.setExceptionHandler(getExceptionHandler()); - conn.setIoLog(ioLog); - return conn; - } + /** + *

+ * getMessageControl. + *

+ * + * @return a {@link MessageControl} object. + */ + protected MessageControl getMessageControl() { + MessageControl conn = new MessageControl(); + conn.setRetries(getRetries()); + conn.setTimeout(getTimeout()); + conn.setDiscardDataDelay(getDiscardDataDelay()); + conn.setExceptionHandler(getExceptionHandler()); + conn.setIoLog(ioLog); + return conn; + } - /** - *

- * closeMessageControl. - *

- * @param conn a {@link MessageControl} object. - */ - protected void closeMessageControl(MessageControl conn) { - if (conn != null) - conn.close(); - } + /** + *

+ * closeMessageControl. + *

+ * + * @param conn a {@link MessageControl} object. + */ + protected void closeMessageControl(MessageControl conn) { + if (conn != null) + conn.close(); + } - // - // - // Private stuff - // + // + // + // Private stuff + // - /** - * This method assumes that all locators have already been pre-sorted and grouped into - * valid requests, say, by the createRequestGroups method. - */ - private void sendFunctionGroup(ReadFunctionGroup functionGroup, BatchResults results, - boolean errorsInResults, boolean exceptionsInResults) - throws ModbusTransportException, ErrorResponseException { - int slaveId = functionGroup.getSlaveAndRange().getSlaveId(); - int startOffset = functionGroup.getStartOffset(); - int length = functionGroup.getLength(); + /** + * This method assumes that all locators have already been pre-sorted and grouped into + * valid requests, say, by the createRequestGroups method. + */ + private void sendFunctionGroup(ReadFunctionGroup functionGroup, BatchResults results, + boolean errorsInResults, boolean exceptionsInResults) + throws ModbusTransportException, ErrorResponseException { + int slaveId = functionGroup.getSlaveAndRange().getSlaveId(); + int startOffset = functionGroup.getStartOffset(); + int length = functionGroup.getLength(); - // Inspect the function group for data required to create the request. - ModbusRequest request; - if (functionGroup.getFunctionCode() == FunctionCode.READ_COILS) - request = new ReadCoilsRequest(slaveId, startOffset, length); - else if (functionGroup.getFunctionCode() == FunctionCode.READ_DISCRETE_INPUTS) - request = new ReadDiscreteInputsRequest(slaveId, startOffset, length); - else if (functionGroup.getFunctionCode() == FunctionCode.READ_HOLDING_REGISTERS) - request = new ReadHoldingRegistersRequest(slaveId, startOffset, length); - else if (functionGroup.getFunctionCode() == FunctionCode.READ_INPUT_REGISTERS) - request = new ReadInputRegistersRequest(slaveId, startOffset, length); - else - throw new RuntimeException("Unsupported function"); + // Inspect the function group for data required to create the request. + ModbusRequest request; + if (functionGroup.getFunctionCode() == FunctionCode.READ_COILS) + request = new ReadCoilsRequest(slaveId, startOffset, length); + else if (functionGroup.getFunctionCode() == FunctionCode.READ_DISCRETE_INPUTS) + request = new ReadDiscreteInputsRequest(slaveId, startOffset, length); + else if (functionGroup.getFunctionCode() == FunctionCode.READ_HOLDING_REGISTERS) + request = new ReadHoldingRegistersRequest(slaveId, startOffset, length); + else if (functionGroup.getFunctionCode() == FunctionCode.READ_INPUT_REGISTERS) + request = new ReadInputRegistersRequest(slaveId, startOffset, length); + else + throw new RuntimeException("Unsupported function"); - ReadResponse response; - try { - response = (ReadResponse) send(request); - } - catch (ModbusTransportException e) { - if (!exceptionsInResults) - throw e; + ReadResponse response; + try { + response = (ReadResponse) send(request); + } catch (ModbusTransportException e) { + if (!exceptionsInResults) + throw e; - for (KeyedModbusLocator locator : functionGroup.getLocators()) - results.addResult(locator.getKey(), e); + for (KeyedModbusLocator locator : functionGroup.getLocators()) + results.addResult(locator.getKey(), e); - return; - } + return; + } - byte[] data = null; - if (!errorsInResults && response.isException()) - throw new ErrorResponseException(request, response); - else if (!response.isException()) - data = response.getData(); + byte[] data = null; + if (!errorsInResults && response.isException()) + throw new ErrorResponseException(request, response); + else if (!response.isException()) + data = response.getData(); - for (KeyedModbusLocator locator : functionGroup.getLocators()) { - if (errorsInResults && response.isException()) - results.addResult(locator.getKey(), new ExceptionResult(response.getExceptionCode())); - else { - try { - results.addResult(locator.getKey(), locator.bytesToValue(data, startOffset)); - } - catch (RuntimeException e) { - throw new RuntimeException("Result conversion exception. data=" + ArrayUtils.toHexString(data) - + ", startOffset=" + startOffset + ", locator=" + locator + ", functionGroup.functionCode=" - + functionGroup.getFunctionCode() + ", functionGroup.startOffset=" + startOffset - + ", functionGroup.length=" + length, e); - } - } - } - } + for (KeyedModbusLocator locator : functionGroup.getLocators()) { + if (errorsInResults && response.isException()) + results.addResult(locator.getKey(), new ExceptionResult(response.getExceptionCode())); + else { + try { + results.addResult(locator.getKey(), locator.bytesToValue(data, startOffset)); + } catch (RuntimeException e) { + throw new RuntimeException("Result conversion exception. data=" + ArrayUtils.toHexString(data) + + ", startOffset=" + startOffset + ", locator=" + locator + ", functionGroup.functionCode=" + + functionGroup.getFunctionCode() + ", functionGroup.startOffset=" + startOffset + + ", functionGroup.length=" + length, e); + } + } + } + } - private void setValue(ModbusRequest request) throws ModbusTransportException, ErrorResponseException { - ModbusResponse response = send(request); - if (response == null) - // This should only happen if the request was a broadcast - return; - if (response.isException()) - throw new ErrorResponseException(request, response); - } + private void setValue(ModbusRequest request) throws ModbusTransportException, ErrorResponseException { + ModbusResponse response = send(request); + if (response == null) + // This should only happen if the request was a broadcast + return; + if (response.isException()) + throw new ErrorResponseException(request, response); + } - private void setHoldingRegisterBit(int slaveId, int writeOffset, int bit, boolean value) - throws ModbusTransportException, ErrorResponseException { - // Writing a bit in a holding register field. There are two ways to do this. The - // easy way is to - // use a write mask request, but it is not always supported. The hard way is to - // read the value, change - // the appropriate bit, and then write it back again (so as not to overwrite the - // other bits in the - // value). However, since the hard way is not atomic, it is not fail-safe either, - // but it should be - // at least possible. - SlaveProfile sp = getSlaveProfile(slaveId); - if (sp.getWriteMaskRegister()) { - // Give the write mask a try. - WriteMaskRegisterRequest request = new WriteMaskRegisterRequest(slaveId, writeOffset); - request.setBit(bit, value); - ModbusResponse response = send(request); - if (response == null) - // This should only happen if the request was a broadcast - return; - if (!response.isException()) - // Hey, cool, it worked. - return; + private void setHoldingRegisterBit(int slaveId, int writeOffset, int bit, boolean value) + throws ModbusTransportException, ErrorResponseException { + // Writing a bit in a holding register field. There are two ways to do this. The + // easy way is to + // use a write mask request, but it is not always supported. The hard way is to + // read the value, change + // the appropriate bit, and then write it back again (so as not to overwrite the + // other bits in the + // value). However, since the hard way is not atomic, it is not fail-safe either, + // but it should be + // at least possible. + SlaveProfile sp = getSlaveProfile(slaveId); + if (sp.getWriteMaskRegister()) { + // Give the write mask a try. + WriteMaskRegisterRequest request = new WriteMaskRegisterRequest(slaveId, writeOffset); + request.setBit(bit, value); + ModbusResponse response = send(request); + if (response == null) + // This should only happen if the request was a broadcast + return; + if (!response.isException()) + // Hey, cool, it worked. + return; - if (response.getExceptionCode() == ExceptionCode.ILLEGAL_FUNCTION) - // The function is probably not supported. Fail-over to the two step. - sp.setWriteMaskRegister(false); - else - throw new ErrorResponseException(request, response); - } + if (response.getExceptionCode() == ExceptionCode.ILLEGAL_FUNCTION) + // The function is probably not supported. Fail-over to the two step. + sp.setWriteMaskRegister(false); + else + throw new ErrorResponseException(request, response); + } - // Do it the hard way. Get the register's current value. - int regValue = (Integer) getValue(new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, writeOffset, - DataType.TWO_BYTE_INT_UNSIGNED)); + // Do it the hard way. Get the register's current value. + int regValue = (Integer) getValue(new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, writeOffset, + DataType.TWO_BYTE_INT_UNSIGNED)); - // Modify the value according to the given bit and value. - if (value) - regValue = regValue | 1 << bit; - else - regValue = regValue & ~(1 << bit); + // Modify the value according to the given bit and value. + if (value) + regValue = regValue | 1 << bit; + else + regValue = regValue & ~(1 << bit); - // Write the new register value. - setValue(new WriteRegisterRequest(slaveId, writeOffset, regValue)); - } + // Write the new register value. + setValue(new WriteRegisterRequest(slaveId, writeOffset, regValue)); + } - private SlaveProfile getSlaveProfile(int slaveId) { - SlaveProfile sp = slaveProfiles.get(slaveId); - if (sp == null) { - sp = new SlaveProfile(); - slaveProfiles.put(slaveId, sp); - } - return sp; - } + private SlaveProfile getSlaveProfile(int slaveId) { + SlaveProfile sp = slaveProfiles.get(slaveId); + if (sp == null) { + sp = new SlaveProfile(); + slaveProfiles.put(slaveId, sp); + } + return sp; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusSlaveSet.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusSlaveSet.java index 56a0658b3..01836021c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusSlaveSet.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ModbusSlaveSet.java @@ -33,111 +33,112 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; * @version 2025.9.0 */ abstract /** - * Modbus Slave Set - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Slave Set + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusSlaveSet extends Modbus { - private LinkedHashMap processImages = new LinkedHashMap<>(); + private LinkedHashMap processImages = new LinkedHashMap<>(); - private ReadWriteLock lock = new ReentrantReadWriteLock(); + private ReadWriteLock lock = new ReentrantReadWriteLock(); - /** - *

- * addProcessImage. - *

- * @param processImage a {@link ProcessImage} object. - */ - public void addProcessImage(ProcessImage processImage) { - lock.writeLock().lock(); - try { - processImages.put(processImage.getSlaveId(), processImage); - } - finally { - lock.writeLock().unlock(); - } - } + /** + *

+ * addProcessImage. + *

+ * + * @param processImage a {@link ProcessImage} object. + */ + public void addProcessImage(ProcessImage processImage) { + lock.writeLock().lock(); + try { + processImages.put(processImage.getSlaveId(), processImage); + } finally { + lock.writeLock().unlock(); + } + } - /** - *

- * removeProcessImage. - *

- * @param slaveId a int. - * @return a boolean. - */ - public boolean removeProcessImage(int slaveId) { - lock.writeLock().lock(); - try { - return (processImages.remove(slaveId) != null); - } - finally { - lock.writeLock().unlock(); - } - } + /** + *

+ * removeProcessImage. + *

+ * + * @param slaveId a int. + * @return a boolean. + */ + public boolean removeProcessImage(int slaveId) { + lock.writeLock().lock(); + try { + return (processImages.remove(slaveId) != null); + } finally { + lock.writeLock().unlock(); + } + } - /** - *

- * removeProcessImage. - *

- * @param processImage a {@link ProcessImage} object. - * @return a boolean. - */ - public boolean removeProcessImage(ProcessImage processImage) { - lock.writeLock().lock(); - try { - return (processImages.remove(processImage.getSlaveId()) != null); - } - finally { - lock.writeLock().unlock(); - } - } + /** + *

+ * removeProcessImage. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @return a boolean. + */ + public boolean removeProcessImage(ProcessImage processImage) { + lock.writeLock().lock(); + try { + return (processImages.remove(processImage.getSlaveId()) != null); + } finally { + lock.writeLock().unlock(); + } + } - /** - *

- * getProcessImage. - *

- * @param slaveId a int. - * @return a {@link ProcessImage} object. - */ - public ProcessImage getProcessImage(int slaveId) { - lock.readLock().lock(); - try { - return processImages.get(slaveId); - } - finally { - lock.readLock().unlock(); - } - } + /** + *

+ * getProcessImage. + *

+ * + * @param slaveId a int. + * @return a {@link ProcessImage} object. + */ + public ProcessImage getProcessImage(int slaveId) { + lock.readLock().lock(); + try { + return processImages.get(slaveId); + } finally { + lock.readLock().unlock(); + } + } - /** - * Get a copy of the current process images - * @return a {@link Collection} object. - */ - public Collection getProcessImages() { - lock.readLock().lock(); - try { - return new HashSet<>(processImages.values()); - } - finally { - lock.readLock().unlock(); - } - } + /** + * Get a copy of the current process images + * + * @return a {@link Collection} object. + */ + public Collection getProcessImages() { + lock.readLock().lock(); + try { + return new HashSet<>(processImages.values()); + } finally { + lock.readLock().unlock(); + } + } - /** - * Starts the slave. If an exception is not thrown, this method doesn't return, but - * uses the thread to execute the listening. - * @throws ModbusInitException if necessary - */ - abstract public void start() throws ModbusInitException; + /** + * Starts the slave. If an exception is not thrown, this method doesn't return, but + * uses the thread to execute the listening. + * + * @throws ModbusInitException if necessary + */ + abstract public void start() throws ModbusInitException; - /** - *

- * stop. - *

- */ - abstract public void stop(); + /** + *

+ * stop. + *

+ */ + abstract public void stop(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/NodeScanListener.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/NodeScanListener.java index e1878de9e..8ebe4bcbe 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/NodeScanListener.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/NodeScanListener.java @@ -28,12 +28,13 @@ import com.serotonin.modbus4j.sero.util.ProgressiveTaskListener; */ public interface NodeScanListener extends ProgressiveTaskListener { - /** - *

- * nodeFound. - *

- * @param nodeNumber a int. - */ - void nodeFound(int nodeNumber); + /** + *

+ * nodeFound. + *

+ * + * @param nodeNumber a int. + */ + void nodeFound(int nodeNumber); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImage.java index 2503108e0..083b0b67e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImage.java @@ -27,136 +27,149 @@ import com.serotonin.modbus4j.exception.IllegalDataAddressException; */ public interface ProcessImage { - /** - *

- * getSlaveId. - *

- * @return a int. - */ - int getSlaveId(); + /** + *

+ * getSlaveId. + *

+ * + * @return a int. + */ + int getSlaveId(); - // - // / - // / Coils - // / - // + // + // / + // / Coils + // / + // - /** - * Returns the current value of the coil for the given offset. - * @param offset a int. - * @return the value of the coil - * @throws IllegalDataAddressException if any. - */ - boolean getCoil(int offset) throws IllegalDataAddressException; + /** + * Returns the current value of the coil for the given offset. + * + * @param offset a int. + * @return the value of the coil + * @throws IllegalDataAddressException if any. + */ + boolean getCoil(int offset) throws IllegalDataAddressException; - /** - * Used internally for setting the value of the coil. - * @param offset a int. - * @param value a boolean. - */ - void setCoil(int offset, boolean value); + /** + * Used internally for setting the value of the coil. + * + * @param offset a int. + * @param value a boolean. + */ + void setCoil(int offset, boolean value); - /** - * Used to set the coil as a result of a write command from the master. - * @param offset a int. - * @param value a boolean. - * @throws IllegalDataAddressException if any. - */ - void writeCoil(int offset, boolean value) throws IllegalDataAddressException; + /** + * Used to set the coil as a result of a write command from the master. + * + * @param offset a int. + * @param value a boolean. + * @throws IllegalDataAddressException if any. + */ + void writeCoil(int offset, boolean value) throws IllegalDataAddressException; - // - // / - // / Inputs - // / - // + // + // / + // / Inputs + // / + // - /** - * Returns the current value of the input for the given offset. - * @param offset a int. - * @return the value of the input - * @throws IllegalDataAddressException if any. - */ - boolean getInput(int offset) throws IllegalDataAddressException; + /** + * Returns the current value of the input for the given offset. + * + * @param offset a int. + * @return the value of the input + * @throws IllegalDataAddressException if any. + */ + boolean getInput(int offset) throws IllegalDataAddressException; - /** - * Used internally for setting the value of the input. - * @param offset a int. - * @param value a boolean. - */ - void setInput(int offset, boolean value); + /** + * Used internally for setting the value of the input. + * + * @param offset a int. + * @param value a boolean. + */ + void setInput(int offset, boolean value); - // - // / - // / Holding registers - // / - // + // + // / + // / Holding registers + // / + // - /** - * Returns the current value of the holding register for the given offset. - * @param offset a int. - * @return the value of the register - * @throws IllegalDataAddressException if any. - */ - short getHoldingRegister(int offset) throws IllegalDataAddressException; + /** + * Returns the current value of the holding register for the given offset. + * + * @param offset a int. + * @return the value of the register + * @throws IllegalDataAddressException if any. + */ + short getHoldingRegister(int offset) throws IllegalDataAddressException; - /** - * Used internally for setting the value of the holding register. - * @param offset a int. - * @param value a short. - */ - void setHoldingRegister(int offset, short value); + /** + * Used internally for setting the value of the holding register. + * + * @param offset a int. + * @param value a short. + */ + void setHoldingRegister(int offset, short value); - /** - * Used to set the holding register as a result of a write command from the master. - * @param offset a int. - * @param value a short. - * @throws IllegalDataAddressException if any. - */ - void writeHoldingRegister(int offset, short value) throws IllegalDataAddressException; + /** + * Used to set the holding register as a result of a write command from the master. + * + * @param offset a int. + * @param value a short. + * @throws IllegalDataAddressException if any. + */ + void writeHoldingRegister(int offset, short value) throws IllegalDataAddressException; - // - // / - // / Input registers - // / - // + // + // / + // / Input registers + // / + // - /** - * Returns the current value of the input register for the given offset. - * @param offset a int. - * @return the value of the register - * @throws IllegalDataAddressException if any. - */ - short getInputRegister(int offset) throws IllegalDataAddressException; + /** + * Returns the current value of the input register for the given offset. + * + * @param offset a int. + * @return the value of the register + * @throws IllegalDataAddressException if any. + */ + short getInputRegister(int offset) throws IllegalDataAddressException; - /** - * Used internally for setting the value of the input register. - * @param offset a int. - * @param value a short. - */ - void setInputRegister(int offset, short value); + /** + * Used internally for setting the value of the input register. + * + * @param offset a int. + * @param value a short. + */ + void setInputRegister(int offset, short value); - // - // / - // / Exception status - // / - // + // + // / + // / Exception status + // / + // - /** - * Returns the current value of the exception status. - * @return the current value of the exception status. - */ - byte getExceptionStatus(); + /** + * Returns the current value of the exception status. + * + * @return the current value of the exception status. + */ + byte getExceptionStatus(); - // - // / - // / Report slave id - // / - // + // + // / + // / Report slave id + // / + // - /** - * Returns the data for the report slave id command. - * @return the data for the report slave id command. - */ - byte[] getReportSlaveIdData(); + /** + * Returns the data for the report slave id command. + * + * @return the data for the report slave id command. + */ + byte[] getReportSlaveIdData(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImageListener.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImageListener.java index 77898f174..53a641c9d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImageListener.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ProcessImageListener.java @@ -26,24 +26,26 @@ package com.serotonin.modbus4j; */ public interface ProcessImageListener { - /** - *

- * coilWrite. - *

- * @param offset a int. - * @param oldValue a boolean. - * @param newValue a boolean. - */ - public void coilWrite(int offset, boolean oldValue, boolean newValue); + /** + *

+ * coilWrite. + *

+ * + * @param offset a int. + * @param oldValue a boolean. + * @param newValue a boolean. + */ + public void coilWrite(int offset, boolean oldValue, boolean newValue); - /** - *

- * holdingRegisterWrite. - *

- * @param offset a int. - * @param oldValue a short. - * @param newValue a short. - */ - public void holdingRegisterWrite(int offset, short oldValue, short newValue); + /** + *

+ * holdingRegisterWrite. + *

+ * + * @param offset a int. + * @param oldValue a short. + * @param newValue a short. + */ + public void holdingRegisterWrite(int offset, short oldValue, short newValue); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseMessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseMessageParser.java index e869bb678..cec6c559e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseMessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseMessageParser.java @@ -29,45 +29,46 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Base Message Parser - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Base Message Parser + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class BaseMessageParser implements MessageParser { - protected final boolean master; + protected final boolean master; - /** - *

- * Constructor for BaseMessageParser. - *

- * @param master a boolean. - */ - public BaseMessageParser(boolean master) { - this.master = master; - } + /** + *

+ * Constructor for BaseMessageParser. + *

+ * + * @param master a boolean. + */ + public BaseMessageParser(boolean master) { + this.master = master; + } - @Override - public IncomingMessage parseMessage(ByteQueue queue) throws Exception { - try { - return parseMessageImpl(queue); - } - catch (ArrayIndexOutOfBoundsException e) { - // Means that we ran out of data trying to read the message. Just return null. - return null; - } - } + @Override + public IncomingMessage parseMessage(ByteQueue queue) throws Exception { + try { + return parseMessageImpl(queue); + } catch (ArrayIndexOutOfBoundsException e) { + // Means that we ran out of data trying to read the message. Just return null. + return null; + } + } - /** - *

- * parseMessageImpl. - *

- * @param queue a {@link ByteQueue} object. - * @return a {@link IncomingMessage} object. - * @throws Exception if any. - */ - abstract protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception; + /** + *

+ * parseMessageImpl. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a {@link IncomingMessage} object. + * @throws Exception if any. + */ + abstract protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception; } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseRequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseRequestHandler.java index 9647bd24b..581f2f2cb 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseRequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/BaseRequestHandler.java @@ -32,53 +32,55 @@ import com.serotonin.modbus4j.sero.messaging.RequestHandler; * @version 2025.9.0 */ abstract /** - * Base Request Handler - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Base Request Handler + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class BaseRequestHandler implements RequestHandler { - protected ModbusSlaveSet slave; + protected ModbusSlaveSet slave; - /** - *

- * Constructor for BaseRequestHandler. - *

- * @param slave a {@link ModbusSlaveSet} object. - */ - public BaseRequestHandler(ModbusSlaveSet slave) { - this.slave = slave; - } + /** + *

+ * Constructor for BaseRequestHandler. + *

+ * + * @param slave a {@link ModbusSlaveSet} object. + */ + public BaseRequestHandler(ModbusSlaveSet slave) { + this.slave = slave; + } - /** - *

- * handleRequestImpl. - *

- * @param request a {@link ModbusRequest} object. - * @return a {@link ModbusResponse} object. - * @throws ModbusTransportException if any. - */ - protected ModbusResponse handleRequestImpl(ModbusRequest request) throws ModbusTransportException { - request.validate(slave); + /** + *

+ * handleRequestImpl. + *

+ * + * @param request a {@link ModbusRequest} object. + * @return a {@link ModbusResponse} object. + * @throws ModbusTransportException if any. + */ + protected ModbusResponse handleRequestImpl(ModbusRequest request) throws ModbusTransportException { + request.validate(slave); - int slaveId = request.getSlaveId(); + int slaveId = request.getSlaveId(); - // Check the slave id. - if (slaveId == 0) { - // Broadcast message. Send to all process images. - for (ProcessImage processImage : slave.getProcessImages()) - request.handle(processImage); - return null; - } + // Check the slave id. + if (slaveId == 0) { + // Broadcast message. Send to all process images. + for (ProcessImage processImage : slave.getProcessImages()) + request.handle(processImage); + return null; + } - // Find the process image to which to send. - ProcessImage processImage = slave.getProcessImage(slaveId); - if (processImage == null) - return null; + // Find the process image to which to send. + ProcessImage processImage = slave.getProcessImage(slaveId); + if (processImage == null) + return null; - return request.handle(processImage); - } + return request.handle(processImage); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/KeyedModbusLocator.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/KeyedModbusLocator.java index 7040e883e..99524f66d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/KeyedModbusLocator.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/KeyedModbusLocator.java @@ -30,121 +30,129 @@ import com.serotonin.modbus4j.locator.BaseLocator; */ public class KeyedModbusLocator { - private final K key; + private final K key; - private final BaseLocator locator; + private final BaseLocator locator; - /** - *

- * Constructor for KeyedModbusLocator. - *

- * @param key a K object. - * @param locator a {@link BaseLocator} object. - */ - public KeyedModbusLocator(K key, BaseLocator locator) { - this.key = key; - this.locator = locator; - } + /** + *

+ * Constructor for KeyedModbusLocator. + *

+ * + * @param key a K object. + * @param locator a {@link BaseLocator} object. + */ + public KeyedModbusLocator(K key, BaseLocator locator) { + this.key = key; + this.locator = locator; + } - /** - *

- * Getter for the field key. - *

- * @return a K object. - */ - public K getKey() { - return key; - } + /** + *

+ * Getter for the field key. + *

+ * + * @return a K object. + */ + public K getKey() { + return key; + } - /** - *

- * Getter for the field locator. - *

- * @return a {@link BaseLocator} object. - */ - public BaseLocator getLocator() { - return locator; - } + /** + *

+ * Getter for the field locator. + *

+ * + * @return a {@link BaseLocator} object. + */ + public BaseLocator getLocator() { + return locator; + } - @Override - public String toString() { - return "KeyedModbusLocator(key=" + key + ", locator=" + locator + ")"; - } + @Override + public String toString() { + return "KeyedModbusLocator(key=" + key + ", locator=" + locator + ")"; + } - // - /// - /// Delegation. - /// - // + // + /// + /// Delegation. + /// + // - /** - *

- * getDataType. - *

- * @return a int. - */ - public int getDataType() { - return locator.getDataType(); - } + /** + *

+ * getDataType. + *

+ * + * @return a int. + */ + public int getDataType() { + return locator.getDataType(); + } - /** - *

- * getOffset. - *

- * @return a int. - */ - public int getOffset() { - return locator.getOffset(); - } + /** + *

+ * getOffset. + *

+ * + * @return a int. + */ + public int getOffset() { + return locator.getOffset(); + } - /** - *

- * getSlaveAndRange. - *

- * @return a {@link SlaveAndRange} object. - */ - public SlaveAndRange getSlaveAndRange() { - return new SlaveAndRange(locator.getSlaveId(), locator.getRange()); - } + /** + *

+ * getSlaveAndRange. + *

+ * + * @return a {@link SlaveAndRange} object. + */ + public SlaveAndRange getSlaveAndRange() { + return new SlaveAndRange(locator.getSlaveId(), locator.getRange()); + } - /** - *

- * getEndOffset. - *

- * @return a int. - */ - public int getEndOffset() { - return locator.getEndOffset(); - } + /** + *

+ * getEndOffset. + *

+ * + * @return a int. + */ + public int getEndOffset() { + return locator.getEndOffset(); + } - /** - *

- * getRegisterCount. - *

- * @return a int. - */ - public int getRegisterCount() { - return locator.getRegisterCount(); - } + /** + *

+ * getRegisterCount. + *

+ * + * @return a int. + */ + public int getRegisterCount() { + return locator.getRegisterCount(); + } - /** - *

- * bytesToValue. - *

- * @param data an array of {@link byte} objects. - * @param requestOffset a int. - * @return a {@link Object} object. - */ - public Object bytesToValue(byte[] data, int requestOffset) { - try { - return locator.bytesToValue(data, requestOffset); - } - catch (ArrayIndexOutOfBoundsException e) { - // Some equipment will not return data lengths that we expect, which causes - // AIOOBEs. Catch them and convert - // them into illegal data address exceptions. - return new ExceptionResult(ExceptionCode.ILLEGAL_DATA_ADDRESS); - } - } + /** + *

+ * bytesToValue. + *

+ * + * @param data an array of {@link byte} objects. + * @param requestOffset a int. + * @return a {@link Object} object. + */ + public Object bytesToValue(byte[] data, int requestOffset) { + try { + return locator.bytesToValue(data, requestOffset); + } catch (ArrayIndexOutOfBoundsException e) { + // Some equipment will not return data lengths that we expect, which causes + // AIOOBEs. Catch them and convert + // them into illegal data address exceptions. + return new ExceptionResult(ExceptionCode.ILLEGAL_DATA_ADDRESS); + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ModbusUtils.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ModbusUtils.java index 7134ada51..f57c06d84 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ModbusUtils.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ModbusUtils.java @@ -33,246 +33,261 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ModbusUtils { - /** - * Constant TCP_PORT=502 - */ - public static final int TCP_PORT = 502; + /** + * Constant TCP_PORT=502 + */ + public static final int TCP_PORT = 502; - /** - * Constant IP_PROTOCOL_ID=0 - */ - public static final int IP_PROTOCOL_ID = 0; // Modbus protocol + /** + * Constant IP_PROTOCOL_ID=0 + */ + public static final int IP_PROTOCOL_ID = 0; // Modbus protocol - // public static final int MAX_READ_BIT_COUNT = 2000; - // public static final int MAX_READ_REGISTER_COUNT = 125; - // public static final int MAX_WRITE_REGISTER_COUNT = 120; - // Table of CRC values for high-order byte - private final static short[] lookupCRCHi = { 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, - 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, - 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, - 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, - 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 }; + // public static final int MAX_READ_BIT_COUNT = 2000; + // public static final int MAX_READ_REGISTER_COUNT = 125; + // public static final int MAX_WRITE_REGISTER_COUNT = 120; + // Table of CRC values for high-order byte + private final static short[] lookupCRCHi = {0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, + 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, + 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, + 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40}; - // Table of CRC values for low-order byte - private final static short[] lookupCRCLo = { 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, - 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, - 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, - 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, - 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, - 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, - 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, - 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, - 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, - 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, - 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, - 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, - 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, - 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, - 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 }; + // Table of CRC values for low-order byte + private final static short[] lookupCRCLo = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, + 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, + 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, + 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, + 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, + 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, + 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, + 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, + 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, + 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, + 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, + 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, + 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40}; - /** - *

- * pushByte. - *

- * @param queue a {@link ByteQueue} object. - * @param value a int. - */ - public static void pushByte(ByteQueue queue, int value) { - queue.push((byte) value); - } + /** + *

+ * pushByte. + *

+ * + * @param queue a {@link ByteQueue} object. + * @param value a int. + */ + public static void pushByte(ByteQueue queue, int value) { + queue.push((byte) value); + } - /** - *

- * pushShort. - *

- * @param queue a {@link ByteQueue} object. - * @param value a int. - */ - public static void pushShort(ByteQueue queue, int value) { - queue.push((byte) (0xff & (value >> 8))); - queue.push((byte) (0xff & value)); - } + /** + *

+ * pushShort. + *

+ * + * @param queue a {@link ByteQueue} object. + * @param value a int. + */ + public static void pushShort(ByteQueue queue, int value) { + queue.push((byte) (0xff & (value >> 8))); + queue.push((byte) (0xff & value)); + } - /** - *

- * popByte. - *

- * @param queue a {@link ByteQueue} object. - * @return a int. - */ - public static int popByte(ByteQueue queue) { - return queue.pop(); - } + /** + *

+ * popByte. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a int. + */ + public static int popByte(ByteQueue queue) { + return queue.pop(); + } - /** - *

- * popUnsignedByte. - *

- * @param queue a {@link ByteQueue} object. - * @return a int. - */ - public static int popUnsignedByte(ByteQueue queue) { - return queue.pop() & 0xff; - } + /** + *

+ * popUnsignedByte. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a int. + */ + public static int popUnsignedByte(ByteQueue queue) { + return queue.pop() & 0xff; + } - /** - *

- * popShort. - *

- * @param queue a {@link ByteQueue} object. - * @return a int. - */ - public static int popShort(ByteQueue queue) { - return toShort(queue.pop(), queue.pop()); - } + /** + *

+ * popShort. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a int. + */ + public static int popShort(ByteQueue queue) { + return toShort(queue.pop(), queue.pop()); + } - /** - *

- * popUnsignedShort. - *

- * @param queue a {@link ByteQueue} object. - * @return a int. - */ - public static int popUnsignedShort(ByteQueue queue) { - return ((queue.pop() & 0xff) << 8) | (queue.pop() & 0xff); - } + /** + *

+ * popUnsignedShort. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a int. + */ + public static int popUnsignedShort(ByteQueue queue) { + return ((queue.pop() & 0xff) << 8) | (queue.pop() & 0xff); + } - /** - *

- * toShort. - *

- * @param b1 a byte. - * @param b2 a byte. - * @return a short. - */ - public static short toShort(byte b1, byte b2) { - return (short) ((b1 << 8) | (b2 & 0xff)); - } + /** + *

+ * toShort. + *

+ * + * @param b1 a byte. + * @param b2 a byte. + * @return a short. + */ + public static short toShort(byte b1, byte b2) { + return (short) ((b1 << 8) | (b2 & 0xff)); + } - /** - *

- * toByte. - *

- * @param value a short. - * @param first a boolean. - * @return a byte. - */ - public static byte toByte(short value, boolean first) { - if (first) - return (byte) (0xff & (value >> 8)); - return (byte) (0xff & value); - } + /** + *

+ * toByte. + *

+ * + * @param value a short. + * @param first a boolean. + * @return a byte. + */ + public static byte toByte(short value, boolean first) { + if (first) + return (byte) (0xff & (value >> 8)); + return (byte) (0xff & value); + } - /** - *

- * validateRegisterRange. - *

- * @param range a int. - */ - public static void validateRegisterRange(int range) { - if (RegisterRange.getReadFunctionCode(range) == -1) - throw new ModbusIdException("Invalid register range: " + range); - } + /** + *

+ * validateRegisterRange. + *

+ * + * @param range a int. + */ + public static void validateRegisterRange(int range) { + if (RegisterRange.getReadFunctionCode(range) == -1) + throw new ModbusIdException("Invalid register range: " + range); + } - /** - *

- * validateSlaveId. - *

- * @param slaveId a int. - * @param includeBroadcast a boolean. - */ - public static void validateSlaveId(int slaveId, boolean includeBroadcast) { - if (slaveId < (includeBroadcast ? 0 : 1) /* || slaveId > 240 */) - throw new IllegalSlaveIdException("Invalid slave id: " + slaveId); - } + /** + *

+ * validateSlaveId. + *

+ * + * @param slaveId a int. + * @param includeBroadcast a boolean. + */ + public static void validateSlaveId(int slaveId, boolean includeBroadcast) { + if (slaveId < (includeBroadcast ? 0 : 1) /* || slaveId > 240 */) + throw new IllegalSlaveIdException("Invalid slave id: " + slaveId); + } - /** - *

- * validateBit. - *

- * @param bit a int. - */ - public static void validateBit(int bit) { - if (bit < 0 || bit > 15) - throw new ModbusIdException("Invalid bit: " + bit); - } + /** + *

+ * validateBit. + *

+ * + * @param bit a int. + */ + public static void validateBit(int bit) { + if (bit < 0 || bit > 15) + throw new ModbusIdException("Invalid bit: " + bit); + } - /** - *

- * validateOffset. - *

- * @param offset a int. - * @throws ModbusTransportException if any. - */ - public static void validateOffset(int offset) throws ModbusTransportException { - if (offset < 0 || offset > 65535) - throw new ModbusTransportException("Invalid offset: " + offset); - } + /** + *

+ * validateOffset. + *

+ * + * @param offset a int. + * @throws ModbusTransportException if any. + */ + public static void validateOffset(int offset) throws ModbusTransportException { + if (offset < 0 || offset > 65535) + throw new ModbusTransportException("Invalid offset: " + offset); + } - /** - *

- * validateEndOffset. - *

- * @param offset a int. - * @throws ModbusTransportException if any. - */ - public static void validateEndOffset(int offset) throws ModbusTransportException { - if (offset > 65535) - throw new ModbusTransportException("Invalid end offset: " + offset); - } + /** + *

+ * validateEndOffset. + *

+ * + * @param offset a int. + * @throws ModbusTransportException if any. + */ + public static void validateEndOffset(int offset) throws ModbusTransportException { + if (offset > 65535) + throw new ModbusTransportException("Invalid end offset: " + offset); + } - /** - *

- * checkCRC. - *

- * @param modbusMessage a {@link ModbusMessage} object. - * @param queue a {@link ByteQueue} object. - * @throws ModbusTransportException if any. - */ - public static void checkCRC(ModbusMessage modbusMessage, ByteQueue queue) throws ModbusTransportException { - // Check the CRC - int calcCrc = calculateCRC(modbusMessage); - int givenCrc = ModbusUtils.popUnsignedShort(queue); + /** + *

+ * checkCRC. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + * @param queue a {@link ByteQueue} object. + * @throws ModbusTransportException if any. + */ + public static void checkCRC(ModbusMessage modbusMessage, ByteQueue queue) throws ModbusTransportException { + // Check the CRC + int calcCrc = calculateCRC(modbusMessage); + int givenCrc = ModbusUtils.popUnsignedShort(queue); - if (calcCrc != givenCrc) - throw new ModbusTransportException("CRC mismatch: given=" + givenCrc + ", calc=" + calcCrc, - modbusMessage.getSlaveId()); - } + if (calcCrc != givenCrc) + throw new ModbusTransportException("CRC mismatch: given=" + givenCrc + ", calc=" + calcCrc, + modbusMessage.getSlaveId()); + } - /** - *

- * calculateCRC. - *

- * @param modbusMessage a {@link ModbusMessage} object. - * @return a int. - */ - public static int calculateCRC(ModbusMessage modbusMessage) { - ByteQueue queue = new ByteQueue(); - modbusMessage.write(queue); + /** + *

+ * calculateCRC. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + * @return a int. + */ + public static int calculateCRC(ModbusMessage modbusMessage) { + ByteQueue queue = new ByteQueue(); + modbusMessage.write(queue); - int high = 0xff; - int low = 0xff; - int nextByte = 0; - int uIndex; + int high = 0xff; + int low = 0xff; + int nextByte = 0; + int uIndex; - while (queue.size() > 0) { - nextByte = 0xFF & queue.pop(); - uIndex = high ^ nextByte; - high = low ^ lookupCRCHi[uIndex]; - low = lookupCRCLo[uIndex]; - } + while (queue.size() > 0) { + nextByte = 0xFF & queue.pop(); + uIndex = high ^ nextByte; + high = low ^ lookupCRCHi[uIndex]; + low = lookupCRCLo[uIndex]; + } - return (high << 8) | low; - } + return (high << 8) | low; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/RangeAndOffset.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/RangeAndOffset.java index 69d9b6fc3..b6f8c3745 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/RangeAndOffset.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/RangeAndOffset.java @@ -28,64 +28,65 @@ import com.serotonin.modbus4j.code.RegisterRange; */ public class RangeAndOffset { - private int range; + private int range; - private int offset; + private int offset; - /** - *

- * Constructor for RangeAndOffset. - *

- * @param range a int. - * @param offset a int. - */ - public RangeAndOffset(int range, int offset) { - this.range = range; - this.offset = offset; - } + /** + *

+ * Constructor for RangeAndOffset. + *

+ * + * @param range a int. + * @param offset a int. + */ + public RangeAndOffset(int range, int offset) { + this.range = range; + this.offset = offset; + } - /** - * This constructor provides a best guess at the function and offset the user wants, - * with the assumption that the offset will never go over 9999. - * @param registerId a int. - */ - public RangeAndOffset(int registerId) { - if (registerId < 10000) { - this.range = RegisterRange.COIL_STATUS; - this.offset = registerId - 1; - } - else if (registerId < 20000) { - this.range = RegisterRange.INPUT_STATUS; - this.offset = registerId - 10001; - } - else if (registerId < 40000) { - this.range = RegisterRange.INPUT_REGISTER; - this.offset = registerId - 30001; - } - else { - this.range = RegisterRange.HOLDING_REGISTER; - this.offset = registerId - 40001; - } - } + /** + * This constructor provides a best guess at the function and offset the user wants, + * with the assumption that the offset will never go over 9999. + * + * @param registerId a int. + */ + public RangeAndOffset(int registerId) { + if (registerId < 10000) { + this.range = RegisterRange.COIL_STATUS; + this.offset = registerId - 1; + } else if (registerId < 20000) { + this.range = RegisterRange.INPUT_STATUS; + this.offset = registerId - 10001; + } else if (registerId < 40000) { + this.range = RegisterRange.INPUT_REGISTER; + this.offset = registerId - 30001; + } else { + this.range = RegisterRange.HOLDING_REGISTER; + this.offset = registerId - 40001; + } + } - /** - *

- * Getter for the field range. - *

- * @return a int. - */ - public int getRange() { - return range; - } + /** + *

+ * Getter for the field range. + *

+ * + * @return a int. + */ + public int getRange() { + return range; + } - /** - *

- * Getter for the field offset. - *

- * @return a int. - */ - public int getOffset() { - return offset; - } + /** + *

+ * Getter for the field offset. + *

+ * + * @return a int. + */ + public int getOffset() { + return offset; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ReadFunctionGroup.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ReadFunctionGroup.java index b49e05993..1c6397922 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ReadFunctionGroup.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/ReadFunctionGroup.java @@ -31,100 +31,108 @@ import java.util.List; */ public class ReadFunctionGroup { - private final SlaveAndRange slaveAndRange; + private final SlaveAndRange slaveAndRange; - private final int functionCode; + private final int functionCode; - private final List> locators = new ArrayList<>(); + private final List> locators = new ArrayList<>(); - private int startOffset = 65536; + private int startOffset = 65536; - private int length = 0; + private int length = 0; - /** - *

- * Constructor for ReadFunctionGroup. - *

- * @param locator a {@link KeyedModbusLocator} object. - */ - public ReadFunctionGroup(KeyedModbusLocator locator) { - slaveAndRange = locator.getSlaveAndRange(); - functionCode = RegisterRange.getReadFunctionCode(slaveAndRange.getRange()); - add(locator); - } + /** + *

+ * Constructor for ReadFunctionGroup. + *

+ * + * @param locator a {@link KeyedModbusLocator} object. + */ + public ReadFunctionGroup(KeyedModbusLocator locator) { + slaveAndRange = locator.getSlaveAndRange(); + functionCode = RegisterRange.getReadFunctionCode(slaveAndRange.getRange()); + add(locator); + } - /** - *

- * add. - *

- * @param locator a {@link KeyedModbusLocator} object. - */ - public void add(KeyedModbusLocator locator) { - if (startOffset > locator.getOffset()) - startOffset = locator.getOffset(); - if (length < locator.getEndOffset() - startOffset + 1) - length = locator.getEndOffset() - startOffset + 1; - locators.add(locator); - } + /** + *

+ * add. + *

+ * + * @param locator a {@link KeyedModbusLocator} object. + */ + public void add(KeyedModbusLocator locator) { + if (startOffset > locator.getOffset()) + startOffset = locator.getOffset(); + if (length < locator.getEndOffset() - startOffset + 1) + length = locator.getEndOffset() - startOffset + 1; + locators.add(locator); + } - /** - *

- * Getter for the field startOffset. - *

- * @return a int. - */ - public int getStartOffset() { - return startOffset; - } + /** + *

+ * Getter for the field startOffset. + *

+ * + * @return a int. + */ + public int getStartOffset() { + return startOffset; + } - /** - *

- * getEndOffset. - *

- * @return a int. - */ - public int getEndOffset() { - return startOffset + length - 1; - } + /** + *

+ * getEndOffset. + *

+ * + * @return a int. + */ + public int getEndOffset() { + return startOffset + length - 1; + } - /** - *

- * Getter for the field slaveAndRange. - *

- * @return a {@link SlaveAndRange} object. - */ - public SlaveAndRange getSlaveAndRange() { - return slaveAndRange; - } + /** + *

+ * Getter for the field slaveAndRange. + *

+ * + * @return a {@link SlaveAndRange} object. + */ + public SlaveAndRange getSlaveAndRange() { + return slaveAndRange; + } - /** - *

- * Getter for the field length. - *

- * @return a int. - */ - public int getLength() { - return length; - } + /** + *

+ * Getter for the field length. + *

+ * + * @return a int. + */ + public int getLength() { + return length; + } - /** - *

- * Getter for the field functionCode. - *

- * @return a int. - */ - public int getFunctionCode() { - return functionCode; - } + /** + *

+ * Getter for the field functionCode. + *

+ * + * @return a int. + */ + public int getFunctionCode() { + return functionCode; + } - /** - *

- * Getter for the field locators. - *

- * @return a {@link List} object. - */ - public List> getLocators() { - return locators; - } + /** + *

+ * Getter for the field locators. + *

+ * + * @return a {@link List} object. + */ + public List> getLocators() { + return locators; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveAndRange.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveAndRange.java index c4880e582..d9008a0fc 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveAndRange.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveAndRange.java @@ -26,67 +26,70 @@ package com.serotonin.modbus4j.base; */ public class SlaveAndRange { - private final int slaveId; + private final int slaveId; - private final int range; + private final int range; - /** - *

- * Constructor for SlaveAndRange. - *

- * @param slaveId a int. - * @param range a int. - */ - public SlaveAndRange(int slaveId, int range) { - ModbusUtils.validateSlaveId(slaveId, true); + /** + *

+ * Constructor for SlaveAndRange. + *

+ * + * @param slaveId a int. + * @param range a int. + */ + public SlaveAndRange(int slaveId, int range) { + ModbusUtils.validateSlaveId(slaveId, true); - this.slaveId = slaveId; - this.range = range; - } + this.slaveId = slaveId; + this.range = range; + } - /** - *

- * Getter for the field range. - *

- * @return a int. - */ - public int getRange() { - return range; - } + /** + *

+ * Getter for the field range. + *

+ * + * @return a int. + */ + public int getRange() { + return range; + } - /** - *

- * Getter for the field slaveId. - *

- * @return a int. - */ - public int getSlaveId() { - return slaveId; - } + /** + *

+ * Getter for the field slaveId. + *

+ * + * @return a int. + */ + public int getSlaveId() { + return slaveId; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + range; - result = prime * result + slaveId; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + range; + result = prime * result + slaveId; + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final SlaveAndRange other = (SlaveAndRange) obj; - if (range != other.range) - return false; - if (slaveId != other.slaveId) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final SlaveAndRange other = (SlaveAndRange) obj; + if (range != other.range) + return false; + if (slaveId != other.slaveId) + return false; + return true; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveProfile.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveProfile.java index 0a16a0080..87aa748bb 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveProfile.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/base/SlaveProfile.java @@ -26,26 +26,28 @@ package com.serotonin.modbus4j.base; */ public class SlaveProfile { - private boolean writeMaskRegister = true; + private boolean writeMaskRegister = true; - /** - *

- * Getter for the field writeMaskRegister. - *

- * @return a boolean. - */ - public boolean getWriteMaskRegister() { - return writeMaskRegister; - } + /** + *

+ * Getter for the field writeMaskRegister. + *

+ * + * @return a boolean. + */ + public boolean getWriteMaskRegister() { + return writeMaskRegister; + } - /** - *

- * Setter for the field writeMaskRegister. - *

- * @param writeMaskRegister a boolean. - */ - public void setWriteMaskRegister(boolean writeMaskRegister) { - this.writeMaskRegister = writeMaskRegister; - } + /** + *

+ * Setter for the field writeMaskRegister. + *

+ * + * @param writeMaskRegister a boolean. + */ + public void setWriteMaskRegister(boolean writeMaskRegister) { + this.writeMaskRegister = writeMaskRegister; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/DataType.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/DataType.java index 950cbb05c..f38f7a2fc 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/DataType.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/DataType.java @@ -28,287 +28,289 @@ import java.math.BigInteger; */ public class DataType { - /** - * Constant BINARY=1 - */ - public static final int BINARY = 1; + /** + * Constant BINARY=1 + */ + public static final int BINARY = 1; - /** - * Constant TWO_BYTE_INT_UNSIGNED=2 - */ - public static final int TWO_BYTE_INT_UNSIGNED = 2; + /** + * Constant TWO_BYTE_INT_UNSIGNED=2 + */ + public static final int TWO_BYTE_INT_UNSIGNED = 2; - /** - * Constant TWO_BYTE_INT_SIGNED=3 - */ - public static final int TWO_BYTE_INT_SIGNED = 3; + /** + * Constant TWO_BYTE_INT_SIGNED=3 + */ + public static final int TWO_BYTE_INT_SIGNED = 3; - /** - * Constant TWO_BYTE_INT_UNSIGNED_SWAPPED=22 - */ - public static final int TWO_BYTE_INT_UNSIGNED_SWAPPED = 22; + /** + * Constant TWO_BYTE_INT_UNSIGNED_SWAPPED=22 + */ + public static final int TWO_BYTE_INT_UNSIGNED_SWAPPED = 22; - /** - * Constant TWO_BYTE_INT_SIGNED_SWAPPED=23 - */ - public static final int TWO_BYTE_INT_SIGNED_SWAPPED = 23; + /** + * Constant TWO_BYTE_INT_SIGNED_SWAPPED=23 + */ + public static final int TWO_BYTE_INT_SIGNED_SWAPPED = 23; - /** - * Constant FOUR_BYTE_INT_UNSIGNED=4 - */ - public static final int FOUR_BYTE_INT_UNSIGNED = 4; + /** + * Constant FOUR_BYTE_INT_UNSIGNED=4 + */ + public static final int FOUR_BYTE_INT_UNSIGNED = 4; - /** - * Constant FOUR_BYTE_INT_SIGNED=5 - */ - public static final int FOUR_BYTE_INT_SIGNED = 5; + /** + * Constant FOUR_BYTE_INT_SIGNED=5 + */ + public static final int FOUR_BYTE_INT_SIGNED = 5; - /** - * Constant FOUR_BYTE_INT_UNSIGNED_SWAPPED=6 - */ - public static final int FOUR_BYTE_INT_UNSIGNED_SWAPPED = 6; + /** + * Constant FOUR_BYTE_INT_UNSIGNED_SWAPPED=6 + */ + public static final int FOUR_BYTE_INT_UNSIGNED_SWAPPED = 6; - /** - * Constant FOUR_BYTE_INT_SIGNED_SWAPPED=7 - */ - public static final int FOUR_BYTE_INT_SIGNED_SWAPPED = 7; + /** + * Constant FOUR_BYTE_INT_SIGNED_SWAPPED=7 + */ + public static final int FOUR_BYTE_INT_SIGNED_SWAPPED = 7; - /* 0xAABBCCDD is transmitted as 0xDDCCBBAA */ - /** - * Constant FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED=24 - */ - public static final int FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED = 24; + /* 0xAABBCCDD is transmitted as 0xDDCCBBAA */ + /** + * Constant FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED=24 + */ + public static final int FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED = 24; - /** - * Constant FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED=25 - */ - public static final int FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED = 25; + /** + * Constant FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED=25 + */ + public static final int FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED = 25; - /** - * Constant FOUR_BYTE_FLOAT=8 - */ - public static final int FOUR_BYTE_FLOAT = 8; + /** + * Constant FOUR_BYTE_FLOAT=8 + */ + public static final int FOUR_BYTE_FLOAT = 8; - /** - * Constant FOUR_BYTE_FLOAT_SWAPPED=9 - */ - public static final int FOUR_BYTE_FLOAT_SWAPPED = 9; + /** + * Constant FOUR_BYTE_FLOAT_SWAPPED=9 + */ + public static final int FOUR_BYTE_FLOAT_SWAPPED = 9; - /** - * Constant FOUR_BYTE_FLOAT_SWAPPED_INVERTED=21 - */ - public static final int FOUR_BYTE_FLOAT_SWAPPED_INVERTED = 21; + /** + * Constant FOUR_BYTE_FLOAT_SWAPPED_INVERTED=21 + */ + public static final int FOUR_BYTE_FLOAT_SWAPPED_INVERTED = 21; - /** - * Constant EIGHT_BYTE_INT_UNSIGNED=10 - */ - public static final int EIGHT_BYTE_INT_UNSIGNED = 10; + /** + * Constant EIGHT_BYTE_INT_UNSIGNED=10 + */ + public static final int EIGHT_BYTE_INT_UNSIGNED = 10; - /** - * Constant EIGHT_BYTE_INT_SIGNED=11 - */ - public static final int EIGHT_BYTE_INT_SIGNED = 11; + /** + * Constant EIGHT_BYTE_INT_SIGNED=11 + */ + public static final int EIGHT_BYTE_INT_SIGNED = 11; - /** - * Constant EIGHT_BYTE_INT_UNSIGNED_SWAPPED=12 - */ - public static final int EIGHT_BYTE_INT_UNSIGNED_SWAPPED = 12; + /** + * Constant EIGHT_BYTE_INT_UNSIGNED_SWAPPED=12 + */ + public static final int EIGHT_BYTE_INT_UNSIGNED_SWAPPED = 12; - /** - * Constant EIGHT_BYTE_INT_SIGNED_SWAPPED=13 - */ - public static final int EIGHT_BYTE_INT_SIGNED_SWAPPED = 13; + /** + * Constant EIGHT_BYTE_INT_SIGNED_SWAPPED=13 + */ + public static final int EIGHT_BYTE_INT_SIGNED_SWAPPED = 13; - /** - * Constant EIGHT_BYTE_FLOAT=14 - */ - public static final int EIGHT_BYTE_FLOAT = 14; + /** + * Constant EIGHT_BYTE_FLOAT=14 + */ + public static final int EIGHT_BYTE_FLOAT = 14; - /** - * Constant EIGHT_BYTE_FLOAT_SWAPPED=15 - */ - public static final int EIGHT_BYTE_FLOAT_SWAPPED = 15; + /** + * Constant EIGHT_BYTE_FLOAT_SWAPPED=15 + */ + public static final int EIGHT_BYTE_FLOAT_SWAPPED = 15; - /** - * Constant TWO_BYTE_BCD=16 - */ - public static final int TWO_BYTE_BCD = 16; + /** + * Constant TWO_BYTE_BCD=16 + */ + public static final int TWO_BYTE_BCD = 16; - /** - * Constant FOUR_BYTE_BCD=17 - */ - public static final int FOUR_BYTE_BCD = 17; + /** + * Constant FOUR_BYTE_BCD=17 + */ + public static final int FOUR_BYTE_BCD = 17; - /** - * Constant FOUR_BYTE_BCD_SWAPPED=20 - */ - public static final int FOUR_BYTE_BCD_SWAPPED = 20; + /** + * Constant FOUR_BYTE_BCD_SWAPPED=20 + */ + public static final int FOUR_BYTE_BCD_SWAPPED = 20; - /** - * Constant CHAR=18 - */ - public static final int CHAR = 18; + /** + * Constant CHAR=18 + */ + public static final int CHAR = 18; - /** - * Constant VARCHAR=19 - */ - public static final int VARCHAR = 19; + /** + * Constant VARCHAR=19 + */ + public static final int VARCHAR = 19; - // MOD10K two, three and four register types - /** - * Constant FOUR_BYTE_MOD_10K=26 - */ - public static final int FOUR_BYTE_MOD_10K = 26; + // MOD10K two, three and four register types + /** + * Constant FOUR_BYTE_MOD_10K=26 + */ + public static final int FOUR_BYTE_MOD_10K = 26; - /** - * Constant SIX_BYTE_MOD_10K=27 - */ - public static final int SIX_BYTE_MOD_10K = 27; + /** + * Constant SIX_BYTE_MOD_10K=27 + */ + public static final int SIX_BYTE_MOD_10K = 27; - /** - * Constant EIGHT_BYTE_MOD_10K=28 - */ - public static final int EIGHT_BYTE_MOD_10K = 28; + /** + * Constant EIGHT_BYTE_MOD_10K=28 + */ + public static final int EIGHT_BYTE_MOD_10K = 28; - /** - * Constant FOUR_BYTE_MOD_10K_SWAPPED=29 - */ - public static final int FOUR_BYTE_MOD_10K_SWAPPED = 29; + /** + * Constant FOUR_BYTE_MOD_10K_SWAPPED=29 + */ + public static final int FOUR_BYTE_MOD_10K_SWAPPED = 29; - /** - * Constant SIX_BYTE_MOD_10K_SWAPPED=30 - */ - public static final int SIX_BYTE_MOD_10K_SWAPPED = 30; + /** + * Constant SIX_BYTE_MOD_10K_SWAPPED=30 + */ + public static final int SIX_BYTE_MOD_10K_SWAPPED = 30; - /** - * Constant EIGHT_BYTE_MOD_10K_SWAPPED=31 - */ - public static final int EIGHT_BYTE_MOD_10K_SWAPPED = 31; + /** + * Constant EIGHT_BYTE_MOD_10K_SWAPPED=31 + */ + public static final int EIGHT_BYTE_MOD_10K_SWAPPED = 31; - // One byte unsigned integer types - /** - * Constant ONE_BYTE_INT_UNSIGNED_LOWER=32 - */ - public static final int ONE_BYTE_INT_UNSIGNED_LOWER = 32; + // One byte unsigned integer types + /** + * Constant ONE_BYTE_INT_UNSIGNED_LOWER=32 + */ + public static final int ONE_BYTE_INT_UNSIGNED_LOWER = 32; - /** - * Constant ONE_BYTE_INT_UNSIGNED_UPPER=33 - */ - public static final int ONE_BYTE_INT_UNSIGNED_UPPER = 33; + /** + * Constant ONE_BYTE_INT_UNSIGNED_UPPER=33 + */ + public static final int ONE_BYTE_INT_UNSIGNED_UPPER = 33; - /** - *

- * getRegisterCount. - *

- * @param id a int. - * @return a int. - */ - public static int getRegisterCount(int id) { - switch (id) { - case BINARY: - case TWO_BYTE_INT_UNSIGNED: - case TWO_BYTE_INT_SIGNED: - case TWO_BYTE_INT_UNSIGNED_SWAPPED: - case TWO_BYTE_INT_SIGNED_SWAPPED: - case TWO_BYTE_BCD: - case ONE_BYTE_INT_UNSIGNED_LOWER: - case ONE_BYTE_INT_UNSIGNED_UPPER: - return 1; - case FOUR_BYTE_INT_UNSIGNED: - case FOUR_BYTE_INT_SIGNED: - case FOUR_BYTE_INT_UNSIGNED_SWAPPED: - case FOUR_BYTE_INT_SIGNED_SWAPPED: - case FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: - case FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: - case FOUR_BYTE_FLOAT: - case FOUR_BYTE_FLOAT_SWAPPED: - case FOUR_BYTE_FLOAT_SWAPPED_INVERTED: - case FOUR_BYTE_BCD: - case FOUR_BYTE_BCD_SWAPPED: - case FOUR_BYTE_MOD_10K: - case FOUR_BYTE_MOD_10K_SWAPPED: - return 2; - case SIX_BYTE_MOD_10K: - case SIX_BYTE_MOD_10K_SWAPPED: - return 3; - case EIGHT_BYTE_INT_UNSIGNED: - case EIGHT_BYTE_INT_SIGNED: - case EIGHT_BYTE_INT_UNSIGNED_SWAPPED: - case EIGHT_BYTE_INT_SIGNED_SWAPPED: - case EIGHT_BYTE_FLOAT: - case EIGHT_BYTE_FLOAT_SWAPPED: - case EIGHT_BYTE_MOD_10K: - case EIGHT_BYTE_MOD_10K_SWAPPED: - return 4; - } - return 0; - } + /** + *

+ * getRegisterCount. + *

+ * + * @param id a int. + * @return a int. + */ + public static int getRegisterCount(int id) { + switch (id) { + case BINARY: + case TWO_BYTE_INT_UNSIGNED: + case TWO_BYTE_INT_SIGNED: + case TWO_BYTE_INT_UNSIGNED_SWAPPED: + case TWO_BYTE_INT_SIGNED_SWAPPED: + case TWO_BYTE_BCD: + case ONE_BYTE_INT_UNSIGNED_LOWER: + case ONE_BYTE_INT_UNSIGNED_UPPER: + return 1; + case FOUR_BYTE_INT_UNSIGNED: + case FOUR_BYTE_INT_SIGNED: + case FOUR_BYTE_INT_UNSIGNED_SWAPPED: + case FOUR_BYTE_INT_SIGNED_SWAPPED: + case FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: + case FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: + case FOUR_BYTE_FLOAT: + case FOUR_BYTE_FLOAT_SWAPPED: + case FOUR_BYTE_FLOAT_SWAPPED_INVERTED: + case FOUR_BYTE_BCD: + case FOUR_BYTE_BCD_SWAPPED: + case FOUR_BYTE_MOD_10K: + case FOUR_BYTE_MOD_10K_SWAPPED: + return 2; + case SIX_BYTE_MOD_10K: + case SIX_BYTE_MOD_10K_SWAPPED: + return 3; + case EIGHT_BYTE_INT_UNSIGNED: + case EIGHT_BYTE_INT_SIGNED: + case EIGHT_BYTE_INT_UNSIGNED_SWAPPED: + case EIGHT_BYTE_INT_SIGNED_SWAPPED: + case EIGHT_BYTE_FLOAT: + case EIGHT_BYTE_FLOAT_SWAPPED: + case EIGHT_BYTE_MOD_10K: + case EIGHT_BYTE_MOD_10K_SWAPPED: + return 4; + } + return 0; + } - /** - *

- * getJavaType. - *

- * @param id a int. - * @return a {@link Class} object. - */ - public static Class getJavaType(int id) { - switch (id) { - case ONE_BYTE_INT_UNSIGNED_LOWER: - case ONE_BYTE_INT_UNSIGNED_UPPER: - return Integer.class; - case BINARY: - return Boolean.class; - case TWO_BYTE_INT_UNSIGNED: - case TWO_BYTE_INT_UNSIGNED_SWAPPED: - return Integer.class; - case TWO_BYTE_INT_SIGNED: - case TWO_BYTE_INT_SIGNED_SWAPPED: - return Short.class; - case FOUR_BYTE_INT_UNSIGNED: - return Long.class; - case FOUR_BYTE_INT_SIGNED: - return Integer.class; - case FOUR_BYTE_INT_UNSIGNED_SWAPPED: - case FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: - return Long.class; - case FOUR_BYTE_INT_SIGNED_SWAPPED: - case FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: - return Integer.class; - case FOUR_BYTE_FLOAT: - return Float.class; - case FOUR_BYTE_FLOAT_SWAPPED: - return Float.class; - case FOUR_BYTE_FLOAT_SWAPPED_INVERTED: - return Float.class; - case EIGHT_BYTE_INT_UNSIGNED: - return BigInteger.class; - case EIGHT_BYTE_INT_SIGNED: - return Long.class; - case EIGHT_BYTE_INT_UNSIGNED_SWAPPED: - return BigInteger.class; - case EIGHT_BYTE_INT_SIGNED_SWAPPED: - return Long.class; - case EIGHT_BYTE_FLOAT: - return Double.class; - case EIGHT_BYTE_FLOAT_SWAPPED: - return Double.class; - case TWO_BYTE_BCD: - return Short.class; - case FOUR_BYTE_BCD: - case FOUR_BYTE_BCD_SWAPPED: - return Integer.class; - case CHAR: - case VARCHAR: - return String.class; - case FOUR_BYTE_MOD_10K: - case SIX_BYTE_MOD_10K: - case EIGHT_BYTE_MOD_10K: - case FOUR_BYTE_MOD_10K_SWAPPED: - case SIX_BYTE_MOD_10K_SWAPPED: - case EIGHT_BYTE_MOD_10K_SWAPPED: - return BigInteger.class; - } - return null; - } + /** + *

+ * getJavaType. + *

+ * + * @param id a int. + * @return a {@link Class} object. + */ + public static Class getJavaType(int id) { + switch (id) { + case ONE_BYTE_INT_UNSIGNED_LOWER: + case ONE_BYTE_INT_UNSIGNED_UPPER: + return Integer.class; + case BINARY: + return Boolean.class; + case TWO_BYTE_INT_UNSIGNED: + case TWO_BYTE_INT_UNSIGNED_SWAPPED: + return Integer.class; + case TWO_BYTE_INT_SIGNED: + case TWO_BYTE_INT_SIGNED_SWAPPED: + return Short.class; + case FOUR_BYTE_INT_UNSIGNED: + return Long.class; + case FOUR_BYTE_INT_SIGNED: + return Integer.class; + case FOUR_BYTE_INT_UNSIGNED_SWAPPED: + case FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: + return Long.class; + case FOUR_BYTE_INT_SIGNED_SWAPPED: + case FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: + return Integer.class; + case FOUR_BYTE_FLOAT: + return Float.class; + case FOUR_BYTE_FLOAT_SWAPPED: + return Float.class; + case FOUR_BYTE_FLOAT_SWAPPED_INVERTED: + return Float.class; + case EIGHT_BYTE_INT_UNSIGNED: + return BigInteger.class; + case EIGHT_BYTE_INT_SIGNED: + return Long.class; + case EIGHT_BYTE_INT_UNSIGNED_SWAPPED: + return BigInteger.class; + case EIGHT_BYTE_INT_SIGNED_SWAPPED: + return Long.class; + case EIGHT_BYTE_FLOAT: + return Double.class; + case EIGHT_BYTE_FLOAT_SWAPPED: + return Double.class; + case TWO_BYTE_BCD: + return Short.class; + case FOUR_BYTE_BCD: + case FOUR_BYTE_BCD_SWAPPED: + return Integer.class; + case CHAR: + case VARCHAR: + return String.class; + case FOUR_BYTE_MOD_10K: + case SIX_BYTE_MOD_10K: + case EIGHT_BYTE_MOD_10K: + case FOUR_BYTE_MOD_10K_SWAPPED: + case SIX_BYTE_MOD_10K_SWAPPED: + case EIGHT_BYTE_MOD_10K_SWAPPED: + return BigInteger.class; + } + return null; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/ExceptionCode.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/ExceptionCode.java index c7fcc6fad..4e470e13b 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/ExceptionCode.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/ExceptionCode.java @@ -26,80 +26,81 @@ package com.serotonin.modbus4j.code; */ public class ExceptionCode { - /** - * Constant ILLEGAL_FUNCTION=0x1 - */ - public static final byte ILLEGAL_FUNCTION = 0x1; + /** + * Constant ILLEGAL_FUNCTION=0x1 + */ + public static final byte ILLEGAL_FUNCTION = 0x1; - /** - * Constant ILLEGAL_DATA_ADDRESS=0x2 - */ - public static final byte ILLEGAL_DATA_ADDRESS = 0x2; + /** + * Constant ILLEGAL_DATA_ADDRESS=0x2 + */ + public static final byte ILLEGAL_DATA_ADDRESS = 0x2; - /** - * Constant ILLEGAL_DATA_VALUE=0x3 - */ - public static final byte ILLEGAL_DATA_VALUE = 0x3; + /** + * Constant ILLEGAL_DATA_VALUE=0x3 + */ + public static final byte ILLEGAL_DATA_VALUE = 0x3; - /** - * Constant SLAVE_DEVICE_FAILURE=0x4 - */ - public static final byte SLAVE_DEVICE_FAILURE = 0x4; + /** + * Constant SLAVE_DEVICE_FAILURE=0x4 + */ + public static final byte SLAVE_DEVICE_FAILURE = 0x4; - /** - * Constant ACKNOWLEDGE=0x5 - */ - public static final byte ACKNOWLEDGE = 0x5; + /** + * Constant ACKNOWLEDGE=0x5 + */ + public static final byte ACKNOWLEDGE = 0x5; - /** - * Constant SLAVE_DEVICE_BUSY=0x6 - */ - public static final byte SLAVE_DEVICE_BUSY = 0x6; + /** + * Constant SLAVE_DEVICE_BUSY=0x6 + */ + public static final byte SLAVE_DEVICE_BUSY = 0x6; - /** - * Constant MEMORY_PARITY_ERROR=0x8 - */ - public static final byte MEMORY_PARITY_ERROR = 0x8; + /** + * Constant MEMORY_PARITY_ERROR=0x8 + */ + public static final byte MEMORY_PARITY_ERROR = 0x8; - /** - * Constant GATEWAY_PATH_UNAVAILABLE=0xa - */ - public static final byte GATEWAY_PATH_UNAVAILABLE = 0xa; + /** + * Constant GATEWAY_PATH_UNAVAILABLE=0xa + */ + public static final byte GATEWAY_PATH_UNAVAILABLE = 0xa; - /** - * Constant GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND=0xb - */ - public static final byte GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND = 0xb; + /** + * Constant GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND=0xb + */ + public static final byte GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND = 0xb; - /** - *

- * getExceptionMessage. - *

- * @param id a byte. - * @return a {@link String} object. - */ - public static String getExceptionMessage(byte id) { - switch (id) { - case ILLEGAL_FUNCTION: - return "Illegal function"; - case ILLEGAL_DATA_ADDRESS: - return "Illegal data address"; - case ILLEGAL_DATA_VALUE: - return "Illegal data value"; - case SLAVE_DEVICE_FAILURE: - return "Slave device failure"; - case ACKNOWLEDGE: - return "Acknowledge"; - case SLAVE_DEVICE_BUSY: - return "Slave device busy"; - case MEMORY_PARITY_ERROR: - return "Memory parity error"; - case GATEWAY_PATH_UNAVAILABLE: - return "Gateway path unavailable"; - case GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND: - return "Gateway target device failed to respond"; - } - return "Unknown exception code: " + id; - } + /** + *

+ * getExceptionMessage. + *

+ * + * @param id a byte. + * @return a {@link String} object. + */ + public static String getExceptionMessage(byte id) { + switch (id) { + case ILLEGAL_FUNCTION: + return "Illegal function"; + case ILLEGAL_DATA_ADDRESS: + return "Illegal data address"; + case ILLEGAL_DATA_VALUE: + return "Illegal data value"; + case SLAVE_DEVICE_FAILURE: + return "Slave device failure"; + case ACKNOWLEDGE: + return "Acknowledge"; + case SLAVE_DEVICE_BUSY: + return "Slave device busy"; + case MEMORY_PARITY_ERROR: + return "Memory parity error"; + case GATEWAY_PATH_UNAVAILABLE: + return "Gateway path unavailable"; + case GATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND: + return "Gateway target device failed to respond"; + } + return "Unknown exception code: " + id; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/FunctionCode.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/FunctionCode.java index 8d7450b8c..9f835e7d9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/FunctionCode.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/FunctionCode.java @@ -26,70 +26,71 @@ package com.serotonin.modbus4j.code; */ public class FunctionCode { - /** - * Constant READ_COILS=1 - */ - public static final byte READ_COILS = 1; + /** + * Constant READ_COILS=1 + */ + public static final byte READ_COILS = 1; - /** - * Constant READ_DISCRETE_INPUTS=2 - */ - public static final byte READ_DISCRETE_INPUTS = 2; + /** + * Constant READ_DISCRETE_INPUTS=2 + */ + public static final byte READ_DISCRETE_INPUTS = 2; - /** - * Constant READ_HOLDING_REGISTERS=3 - */ - public static final byte READ_HOLDING_REGISTERS = 3; + /** + * Constant READ_HOLDING_REGISTERS=3 + */ + public static final byte READ_HOLDING_REGISTERS = 3; - /** - * Constant READ_INPUT_REGISTERS=4 - */ - public static final byte READ_INPUT_REGISTERS = 4; + /** + * Constant READ_INPUT_REGISTERS=4 + */ + public static final byte READ_INPUT_REGISTERS = 4; - /** - * Constant WRITE_COIL=5 - */ - public static final byte WRITE_COIL = 5; + /** + * Constant WRITE_COIL=5 + */ + public static final byte WRITE_COIL = 5; - /** - * Constant WRITE_REGISTER=6 - */ - public static final byte WRITE_REGISTER = 6; + /** + * Constant WRITE_REGISTER=6 + */ + public static final byte WRITE_REGISTER = 6; - /** - * Constant READ_EXCEPTION_STATUS=7 - */ - public static final byte READ_EXCEPTION_STATUS = 7; + /** + * Constant READ_EXCEPTION_STATUS=7 + */ + public static final byte READ_EXCEPTION_STATUS = 7; - /** - * Constant WRITE_COILS=15 - */ - public static final byte WRITE_COILS = 15; + /** + * Constant WRITE_COILS=15 + */ + public static final byte WRITE_COILS = 15; - /** - * Constant WRITE_REGISTERS=16 - */ - public static final byte WRITE_REGISTERS = 16; + /** + * Constant WRITE_REGISTERS=16 + */ + public static final byte WRITE_REGISTERS = 16; - /** - * Constant REPORT_SLAVE_ID=17 - */ - public static final byte REPORT_SLAVE_ID = 17; + /** + * Constant REPORT_SLAVE_ID=17 + */ + public static final byte REPORT_SLAVE_ID = 17; - /** - * Constant WRITE_MASK_REGISTER=22 - */ - public static final byte WRITE_MASK_REGISTER = 22; + /** + * Constant WRITE_MASK_REGISTER=22 + */ + public static final byte WRITE_MASK_REGISTER = 22; - /** - *

- * toString. - *

- * @param code a byte. - * @return a {@link String} object. - */ - public static String toString(byte code) { - return Integer.toString(code & 0xff); - } + /** + *

+ * toString. + *

+ * + * @param code a byte. + * @return a {@link String} object. + */ + public static String toString(byte code) { + return Integer.toString(code & 0xff); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/RegisterRange.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/RegisterRange.java index 11e27fd18..6be6b3937 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/RegisterRange.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/code/RegisterRange.java @@ -26,87 +26,90 @@ package com.serotonin.modbus4j.code; */ public class RegisterRange { - /** - * Constant COIL_STATUS=1 - */ - public static final int COIL_STATUS = 1; + /** + * Constant COIL_STATUS=1 + */ + public static final int COIL_STATUS = 1; - /** - * Constant INPUT_STATUS=2 - */ - public static final int INPUT_STATUS = 2; + /** + * Constant INPUT_STATUS=2 + */ + public static final int INPUT_STATUS = 2; - /** - * Constant HOLDING_REGISTER=3 - */ - public static final int HOLDING_REGISTER = 3; + /** + * Constant HOLDING_REGISTER=3 + */ + public static final int HOLDING_REGISTER = 3; - /** - * Constant INPUT_REGISTER=4 - */ - public static final int INPUT_REGISTER = 4; + /** + * Constant INPUT_REGISTER=4 + */ + public static final int INPUT_REGISTER = 4; - /** - *

- * getFrom. - *

- * @param id a int. - * @return a int. - */ - public static int getFrom(int id) { - switch (id) { - case COIL_STATUS: - return 0; - case INPUT_STATUS: - return 0x10000; - case HOLDING_REGISTER: - return 0x40000; - case INPUT_REGISTER: - return 0x30000; - } - return -1; - } + /** + *

+ * getFrom. + *

+ * + * @param id a int. + * @return a int. + */ + public static int getFrom(int id) { + switch (id) { + case COIL_STATUS: + return 0; + case INPUT_STATUS: + return 0x10000; + case HOLDING_REGISTER: + return 0x40000; + case INPUT_REGISTER: + return 0x30000; + } + return -1; + } - /** - *

- * getTo. - *

- * @param id a int. - * @return a int. - */ - public static int getTo(int id) { - switch (id) { - case COIL_STATUS: - return 0xffff; - case INPUT_STATUS: - return 0x1ffff; - case HOLDING_REGISTER: - return 0x4ffff; - case INPUT_REGISTER: - return 0x3ffff; - } - return -1; - } + /** + *

+ * getTo. + *

+ * + * @param id a int. + * @return a int. + */ + public static int getTo(int id) { + switch (id) { + case COIL_STATUS: + return 0xffff; + case INPUT_STATUS: + return 0x1ffff; + case HOLDING_REGISTER: + return 0x4ffff; + case INPUT_REGISTER: + return 0x3ffff; + } + return -1; + } - /** - *

- * getReadFunctionCode. - *

- * @param id a int. - * @return a int. - */ - public static int getReadFunctionCode(int id) { - switch (id) { - case COIL_STATUS: - return FunctionCode.READ_COILS; - case INPUT_STATUS: - return FunctionCode.READ_DISCRETE_INPUTS; - case HOLDING_REGISTER: - return FunctionCode.READ_HOLDING_REGISTERS; - case INPUT_REGISTER: - return FunctionCode.READ_INPUT_REGISTERS; - } - return -1; - } + /** + *

+ * getReadFunctionCode. + *

+ * + * @param id a int. + * @return a int. + */ + public static int getReadFunctionCode(int id) { + switch (id) { + case COIL_STATUS: + return FunctionCode.READ_COILS; + case INPUT_STATUS: + return FunctionCode.READ_DISCRETE_INPUTS; + case HOLDING_REGISTER: + return FunctionCode.READ_HOLDING_REGISTERS; + case INPUT_REGISTER: + return FunctionCode.READ_INPUT_REGISTERS; + } + return -1; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ErrorResponseException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ErrorResponseException.java index 305043db1..db82d6389 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ErrorResponseException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ErrorResponseException.java @@ -29,47 +29,50 @@ import com.serotonin.modbus4j.msg.ModbusResponse; */ public class ErrorResponseException extends Exception { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - private final ModbusRequest originalRequest; + private final ModbusRequest originalRequest; - private final ModbusResponse errorResponse; + private final ModbusResponse errorResponse; - /** - *

- * Constructor for ErrorResponseException. - *

- * @param originalRequest a {@link ModbusRequest} object. - * @param errorResponse a {@link ModbusResponse} object. - */ - public ErrorResponseException(ModbusRequest originalRequest, ModbusResponse errorResponse) { - this.originalRequest = originalRequest; - this.errorResponse = errorResponse; - } + /** + *

+ * Constructor for ErrorResponseException. + *

+ * + * @param originalRequest a {@link ModbusRequest} object. + * @param errorResponse a {@link ModbusResponse} object. + */ + public ErrorResponseException(ModbusRequest originalRequest, ModbusResponse errorResponse) { + this.originalRequest = originalRequest; + this.errorResponse = errorResponse; + } - /** - *

- * Getter for the field errorResponse. - *

- * @return a {@link ModbusResponse} object. - */ - public ModbusResponse getErrorResponse() { - return errorResponse; - } + /** + *

+ * Getter for the field errorResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + public ModbusResponse getErrorResponse() { + return errorResponse; + } - /** - *

- * Getter for the field originalRequest. - *

- * @return a {@link ModbusRequest} object. - */ - public ModbusRequest getOriginalRequest() { - return originalRequest; - } + /** + *

+ * Getter for the field originalRequest. + *

+ * + * @return a {@link ModbusRequest} object. + */ + public ModbusRequest getOriginalRequest() { + return originalRequest; + } - @Override - public String getMessage() { - return errorResponse.getExceptionMessage(); - } + @Override + public String getMessage() { + return errorResponse.getExceptionMessage(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataAddressException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataAddressException.java index 5a488a533..b94e176c3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataAddressException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataAddressException.java @@ -26,25 +26,26 @@ package com.serotonin.modbus4j.exception; */ public class IllegalDataAddressException extends ModbusTransportException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for IllegalDataAddressException. - *

- */ - public IllegalDataAddressException() { - super(); - } + /** + *

+ * Constructor for IllegalDataAddressException. + *

+ */ + public IllegalDataAddressException() { + super(); + } - /** - *

- * Constructor for IllegalDataAddressException. - *

- * @param slaveId a int. - */ - public IllegalDataAddressException(int slaveId) { - super(slaveId); - } + /** + *

+ * Constructor for IllegalDataAddressException. + *

+ * + * @param slaveId a int. + */ + public IllegalDataAddressException(int slaveId) { + super(slaveId); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataTypeException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataTypeException.java index 69ad9e6aa..f0802040b 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataTypeException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalDataTypeException.java @@ -26,16 +26,17 @@ package com.serotonin.modbus4j.exception; */ public class IllegalDataTypeException extends ModbusIdException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for IllegalDataTypeException. - *

- * @param message a {@link String} object. - */ - public IllegalDataTypeException(String message) { - super(message); - } + /** + *

+ * Constructor for IllegalDataTypeException. + *

+ * + * @param message a {@link String} object. + */ + public IllegalDataTypeException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalFunctionException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalFunctionException.java index 010dd3d5c..f6fd559d5 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalFunctionException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalFunctionException.java @@ -26,30 +26,32 @@ package com.serotonin.modbus4j.exception; */ public class IllegalFunctionException extends ModbusTransportException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - private final byte functionCode; + private final byte functionCode; - /** - *

- * Constructor for IllegalFunctionException. - *

- * @param functionCode a byte. - * @param slaveId a int. - */ - public IllegalFunctionException(byte functionCode, int slaveId) { - super("Function code: 0x" + Integer.toHexString(functionCode & 0xff), slaveId); - this.functionCode = functionCode; - } + /** + *

+ * Constructor for IllegalFunctionException. + *

+ * + * @param functionCode a byte. + * @param slaveId a int. + */ + public IllegalFunctionException(byte functionCode, int slaveId) { + super("Function code: 0x" + Integer.toHexString(functionCode & 0xff), slaveId); + this.functionCode = functionCode; + } - /** - *

- * Getter for the field functionCode. - *

- * @return a byte. - */ - public byte getFunctionCode() { - return functionCode; - } + /** + *

+ * Getter for the field functionCode. + *

+ * + * @return a byte. + */ + public byte getFunctionCode() { + return functionCode; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalSlaveIdException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalSlaveIdException.java index d44a081b8..105295dab 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalSlaveIdException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/IllegalSlaveIdException.java @@ -26,16 +26,17 @@ package com.serotonin.modbus4j.exception; */ public class IllegalSlaveIdException extends ModbusIdException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for IllegalSlaveIdException. - *

- * @param message a {@link String} object. - */ - public IllegalSlaveIdException(String message) { - super(message); - } + /** + *

+ * Constructor for IllegalSlaveIdException. + *

+ * + * @param message a {@link String} object. + */ + public IllegalSlaveIdException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/InvalidDataConversionException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/InvalidDataConversionException.java index 3c9022a8c..f5b8a8dee 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/InvalidDataConversionException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/InvalidDataConversionException.java @@ -26,16 +26,17 @@ package com.serotonin.modbus4j.exception; */ public class InvalidDataConversionException extends RuntimeException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for InvalidDataConversionException. - *

- * @param message a {@link String} object. - */ - public InvalidDataConversionException(String message) { - super(message); - } + /** + *

+ * Constructor for InvalidDataConversionException. + *

+ * + * @param message a {@link String} object. + */ + public InvalidDataConversionException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusIdException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusIdException.java index 0f6e9266e..9ce885e53 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusIdException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusIdException.java @@ -26,26 +26,28 @@ package com.serotonin.modbus4j.exception; */ public class ModbusIdException extends RuntimeException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for ModbusIdException. - *

- * @param message a {@link String} object. - */ - public ModbusIdException(String message) { - super(message); - } + /** + *

+ * Constructor for ModbusIdException. + *

+ * + * @param message a {@link String} object. + */ + public ModbusIdException(String message) { + super(message); + } - /** - *

- * Constructor for ModbusIdException. - *

- * @param cause a {@link Throwable} object. - */ - public ModbusIdException(Throwable cause) { - super(cause); - } + /** + *

+ * Constructor for ModbusIdException. + *

+ * + * @param cause a {@link Throwable} object. + */ + public ModbusIdException(Throwable cause) { + super(cause); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusInitException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusInitException.java index 74247ada6..70f225d44 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusInitException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusInitException.java @@ -26,46 +26,49 @@ package com.serotonin.modbus4j.exception; */ public class ModbusInitException extends Exception { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for ModbusInitException. - *

- */ - public ModbusInitException() { - super(); - } + /** + *

+ * Constructor for ModbusInitException. + *

+ */ + public ModbusInitException() { + super(); + } - /** - *

- * Constructor for ModbusInitException. - *

- * @param message a {@link String} object. - * @param cause a {@link Throwable} object. - */ - public ModbusInitException(String message, Throwable cause) { - super(message, cause); - } + /** + *

+ * Constructor for ModbusInitException. + *

+ * + * @param message a {@link String} object. + * @param cause a {@link Throwable} object. + */ + public ModbusInitException(String message, Throwable cause) { + super(message, cause); + } - /** - *

- * Constructor for ModbusInitException. - *

- * @param message a {@link String} object. - */ - public ModbusInitException(String message) { - super(message); - } + /** + *

+ * Constructor for ModbusInitException. + *

+ * + * @param message a {@link String} object. + */ + public ModbusInitException(String message) { + super(message); + } - /** - *

- * Constructor for ModbusInitException. - *

- * @param cause a {@link Throwable} object. - */ - public ModbusInitException(Throwable cause) { - super(cause); - } + /** + *

+ * Constructor for ModbusInitException. + *

+ * + * @param cause a {@link Throwable} object. + */ + public ModbusInitException(Throwable cause) { + super(cause); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusTransportException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusTransportException.java index 8896f0ff9..b5c9c8de0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusTransportException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/ModbusTransportException.java @@ -26,96 +26,103 @@ package com.serotonin.modbus4j.exception; */ public class ModbusTransportException extends Exception { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - private final int slaveId; + private final int slaveId; - /** - *

- * Constructor for ModbusTransportException. - *

- */ - public ModbusTransportException() { - this.slaveId = -1; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ */ + public ModbusTransportException() { + this.slaveId = -1; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param slaveId a int. - */ - public ModbusTransportException(int slaveId) { - this.slaveId = slaveId; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param slaveId a int. + */ + public ModbusTransportException(int slaveId) { + this.slaveId = slaveId; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param message a {@link String} object. - * @param cause a {@link Throwable} object. - * @param slaveId a int. - */ - public ModbusTransportException(String message, Throwable cause, int slaveId) { - super(message, cause); - this.slaveId = slaveId; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param message a {@link String} object. + * @param cause a {@link Throwable} object. + * @param slaveId a int. + */ + public ModbusTransportException(String message, Throwable cause, int slaveId) { + super(message, cause); + this.slaveId = slaveId; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param message a {@link String} object. - * @param slaveId a int. - */ - public ModbusTransportException(String message, int slaveId) { - super(message); - this.slaveId = slaveId; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param message a {@link String} object. + * @param slaveId a int. + */ + public ModbusTransportException(String message, int slaveId) { + super(message); + this.slaveId = slaveId; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param message a {@link String} object. - */ - public ModbusTransportException(String message) { - super(message); - this.slaveId = -1; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param message a {@link String} object. + */ + public ModbusTransportException(String message) { + super(message); + this.slaveId = -1; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param cause a {@link Throwable} object. - */ - public ModbusTransportException(Throwable cause) { - super(cause); - this.slaveId = -1; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param cause a {@link Throwable} object. + */ + public ModbusTransportException(Throwable cause) { + super(cause); + this.slaveId = -1; + } - /** - *

- * Constructor for ModbusTransportException. - *

- * @param cause a {@link Throwable} object. - * @param slaveId a int. - */ - public ModbusTransportException(Throwable cause, int slaveId) { - super(cause); - this.slaveId = slaveId; - } + /** + *

+ * Constructor for ModbusTransportException. + *

+ * + * @param cause a {@link Throwable} object. + * @param slaveId a int. + */ + public ModbusTransportException(Throwable cause, int slaveId) { + super(cause); + this.slaveId = slaveId; + } - /** - *

- * Getter for the field slaveId. - *

- * @return a int. - */ - public int getSlaveId() { - return slaveId; - } + /** + *

+ * Getter for the field slaveId. + *

+ * + * @return a int. + */ + public int getSlaveId() { + return slaveId; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/SlaveIdNotEqual.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/SlaveIdNotEqual.java index d5444ec83..32cb928b1 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/SlaveIdNotEqual.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/exception/SlaveIdNotEqual.java @@ -26,15 +26,16 @@ package com.serotonin.modbus4j.exception; public class SlaveIdNotEqual extends ModbusTransportException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - * Exception to show that the requested slave id is not what was received - * @param requestSlaveId - slave id requested - * @param responseSlaveId - slave id of response - */ - public SlaveIdNotEqual(int requestSlaveId, int responseSlaveId) { - super("Response slave id different from requested id", requestSlaveId); - } + /** + * Exception to show that the requested slave id is not what was received + * + * @param requestSlaveId - slave id requested + * @param responseSlaveId - slave id of response + */ + public SlaveIdNotEqual(int requestSlaveId, int responseSlaveId) { + super("Response slave id different from requested id", requestSlaveId); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessage.java index 734042ae8..5c38fa683 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessage.java @@ -27,34 +27,36 @@ import com.serotonin.modbus4j.msg.ModbusMessage; * @version 2025.9.0 */ abstract /** - * Ip Message - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Ip Message + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class IpMessage { - protected final ModbusMessage modbusMessage; + protected final ModbusMessage modbusMessage; - /** - *

- * Constructor for IpMessage. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public IpMessage(ModbusMessage modbusMessage) { - this.modbusMessage = modbusMessage; - } + /** + *

+ * Constructor for IpMessage. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public IpMessage(ModbusMessage modbusMessage) { + this.modbusMessage = modbusMessage; + } - /** - *

- * Getter for the field modbusMessage. - *

- * @return a {@link ModbusMessage} object. - */ - public ModbusMessage getModbusMessage() { - return modbusMessage; - } + /** + *

+ * Getter for the field modbusMessage. + *

+ * + * @return a {@link ModbusMessage} object. + */ + public ModbusMessage getModbusMessage() { + return modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessageResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessageResponse.java index d65ba3f86..2130eef17 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessageResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpMessageResponse.java @@ -30,12 +30,13 @@ import com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage; */ public interface IpMessageResponse extends OutgoingResponseMessage, IncomingResponseMessage { - /** - *

- * getModbusResponse. - *

- * @return a {@link ModbusResponse} object. - */ - ModbusResponse getModbusResponse(); + /** + *

+ * getModbusResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + ModbusResponse getModbusResponse(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpParameters.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpParameters.java index af0b72085..1ae90624c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpParameters.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/IpParameters.java @@ -28,92 +28,100 @@ import com.serotonin.modbus4j.base.ModbusUtils; */ public class IpParameters { - private String host; + private String host; - private int port = ModbusUtils.TCP_PORT; + private int port = ModbusUtils.TCP_PORT; - private boolean encapsulated; + private boolean encapsulated; - private Integer lingerTime = -1; + private Integer lingerTime = -1; - /** - *

- * Getter for the field host. - *

- * @return a {@link String} object. - */ - public String getHost() { - return host; - } + /** + *

+ * Getter for the field host. + *

+ * + * @return a {@link String} object. + */ + public String getHost() { + return host; + } - /** - *

- * Setter for the field host. - *

- * @param host a {@link String} object. - */ - public void setHost(String host) { - this.host = host; - } + /** + *

+ * Setter for the field host. + *

+ * + * @param host a {@link String} object. + */ + public void setHost(String host) { + this.host = host; + } - /** - *

- * Getter for the field port. - *

- * @return a int. - */ - public int getPort() { - return port; - } + /** + *

+ * Getter for the field port. + *

+ * + * @return a int. + */ + public int getPort() { + return port; + } - /** - *

- * Setter for the field port. - *

- * @param port a int. - */ - public void setPort(int port) { - this.port = port; - } + /** + *

+ * Setter for the field port. + *

+ * + * @param port a int. + */ + public void setPort(int port) { + this.port = port; + } - /** - *

- * isEncapsulated. - *

- * @return a boolean. - */ - public boolean isEncapsulated() { - return encapsulated; - } + /** + *

+ * isEncapsulated. + *

+ * + * @return a boolean. + */ + public boolean isEncapsulated() { + return encapsulated; + } - /** - *

- * Setter for the field encapsulated. - *

- * @param encapsulated a boolean. - */ - public void setEncapsulated(boolean encapsulated) { - this.encapsulated = encapsulated; - } + /** + *

+ * Setter for the field encapsulated. + *

+ * + * @param encapsulated a boolean. + */ + public void setEncapsulated(boolean encapsulated) { + this.encapsulated = encapsulated; + } - /** - *

- * Getter for the field linger. - *

- * @return a int. - */ - public Integer getLingerTime() { - return lingerTime; - } + /** + *

+ * Getter for the field linger. + *

+ * + * @return a int. + */ + public Integer getLingerTime() { + return lingerTime; + } - /** - *

- * Setter for the field linger. - *

- * @param lingerTime a int. - */ - public void setLingerTime(Integer lingerTime) { - this.lingerTime = lingerTime; - } + /** + *

+ * Setter for the field linger. + *

+ * + * @param lingerTime a int. + */ + public void setLingerTime(Integer lingerTime) { + this.lingerTime = lingerTime; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessage.java index e3a3b9c40..0902afe24 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessage.java @@ -31,33 +31,35 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class EncapMessage extends IpMessage { - /** - *

- * Constructor for EncapMessage. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public EncapMessage(ModbusMessage modbusMessage) { - super(modbusMessage); - } + /** + *

+ * Constructor for EncapMessage. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public EncapMessage(ModbusMessage modbusMessage) { + super(modbusMessage); + } - /** - *

- * getMessageData. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getMessageData() { - ByteQueue msgQueue = new ByteQueue(); + /** + *

+ * getMessageData. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getMessageData() { + ByteQueue msgQueue = new ByteQueue(); - // Write the particular message. - modbusMessage.write(msgQueue); + // Write the particular message. + modbusMessage.write(msgQueue); - // Write the CRC - ModbusUtils.pushShort(msgQueue, ModbusUtils.calculateCRC(modbusMessage)); + // Write the CRC + ModbusUtils.pushShort(msgQueue, ModbusUtils.calculateCRC(modbusMessage)); - // Return the data. - return msgQueue.popAll(); - } + // Return the data. + return msgQueue.popAll(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageParser.java index 7c897b696..9cec7b57c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageParser.java @@ -30,21 +30,22 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class EncapMessageParser extends BaseMessageParser { - /** - *

- * Constructor for EncapMessageParser. - *

- * @param master a boolean. - */ - public EncapMessageParser(boolean master) { - super(master); - } + /** + *

+ * Constructor for EncapMessageParser. + *

+ * + * @param master a boolean. + */ + public EncapMessageParser(boolean master) { + super(master); + } - @Override - protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { - if (master) - return EncapMessageResponse.createEncapMessageResponse(queue); - return EncapMessageRequest.createEncapMessageRequest(queue); - } + @Override + protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { + if (master) + return EncapMessageResponse.createEncapMessageResponse(queue); + return EncapMessageRequest.createEncapMessageRequest(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageRequest.java index afd1b39b7..fc17b8dcc 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageRequest.java @@ -33,40 +33,42 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class EncapMessageRequest extends EncapMessage implements OutgoingRequestMessage, IncomingRequestMessage { - /** - *

- * Constructor for EncapMessageRequest. - *

- * @param modbusRequest a {@link ModbusRequest} object. - */ - public EncapMessageRequest(ModbusRequest modbusRequest) { - super(modbusRequest); - } + /** + *

+ * Constructor for EncapMessageRequest. + *

+ * + * @param modbusRequest a {@link ModbusRequest} object. + */ + public EncapMessageRequest(ModbusRequest modbusRequest) { + super(modbusRequest); + } - static EncapMessageRequest createEncapMessageRequest(ByteQueue queue) throws ModbusTransportException { - // Create the modbus response. - ModbusRequest request = ModbusRequest.createModbusRequest(queue); - EncapMessageRequest encapRequest = new EncapMessageRequest(request); + static EncapMessageRequest createEncapMessageRequest(ByteQueue queue) throws ModbusTransportException { + // Create the modbus response. + ModbusRequest request = ModbusRequest.createModbusRequest(queue); + EncapMessageRequest encapRequest = new EncapMessageRequest(request); - // Check the CRC - ModbusUtils.checkCRC(encapRequest.modbusMessage, queue); + // Check the CRC + ModbusUtils.checkCRC(encapRequest.modbusMessage, queue); - return encapRequest; - } + return encapRequest; + } - @Override - public boolean expectsResponse() { - return modbusMessage.getSlaveId() != 0; - } + @Override + public boolean expectsResponse() { + return modbusMessage.getSlaveId() != 0; + } - /** - *

- * getModbusRequest. - *

- * @return a {@link ModbusRequest} object. - */ - public ModbusRequest getModbusRequest() { - return (ModbusRequest) modbusMessage; - } + /** + *

+ * getModbusRequest. + *

+ * + * @return a {@link ModbusRequest} object. + */ + public ModbusRequest getModbusRequest() { + return (ModbusRequest) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageResponse.java index 441ba626d..44984cf6e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapMessageResponse.java @@ -32,35 +32,37 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class EncapMessageResponse extends EncapMessage implements IpMessageResponse { - /** - *

- * Constructor for EncapMessageResponse. - *

- * @param modbusResponse a {@link ModbusResponse} object. - */ - public EncapMessageResponse(ModbusResponse modbusResponse) { - super(modbusResponse); - } + /** + *

+ * Constructor for EncapMessageResponse. + *

+ * + * @param modbusResponse a {@link ModbusResponse} object. + */ + public EncapMessageResponse(ModbusResponse modbusResponse) { + super(modbusResponse); + } - static EncapMessageResponse createEncapMessageResponse(ByteQueue queue) throws ModbusTransportException { - // Create the modbus response. - ModbusResponse response = ModbusResponse.createModbusResponse(queue); - EncapMessageResponse encapResponse = new EncapMessageResponse(response); + static EncapMessageResponse createEncapMessageResponse(ByteQueue queue) throws ModbusTransportException { + // Create the modbus response. + ModbusResponse response = ModbusResponse.createModbusResponse(queue); + EncapMessageResponse encapResponse = new EncapMessageResponse(response); - // Check the CRC - ModbusUtils.checkCRC(encapResponse.modbusMessage, queue); + // Check the CRC + ModbusUtils.checkCRC(encapResponse.modbusMessage, queue); - return encapResponse; - } + return encapResponse; + } - /** - *

- * getModbusResponse. - *

- * @return a {@link ModbusResponse} object. - */ - public ModbusResponse getModbusResponse() { - return (ModbusResponse) modbusMessage; - } + /** + *

+ * getModbusResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + public ModbusResponse getModbusResponse() { + return (ModbusResponse) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapRequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapRequestHandler.java index d156ff405..dd1e04cdb 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapRequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapRequestHandler.java @@ -33,23 +33,24 @@ import com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage; */ public class EncapRequestHandler extends BaseRequestHandler { - /** - *

- * Constructor for EncapRequestHandler. - *

- * @param slave a {@link ModbusSlaveSet} object. - */ - public EncapRequestHandler(ModbusSlaveSet slave) { - super(slave); - } + /** + *

+ * Constructor for EncapRequestHandler. + *

+ * + * @param slave a {@link ModbusSlaveSet} object. + */ + public EncapRequestHandler(ModbusSlaveSet slave) { + super(slave); + } - public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { - EncapMessageRequest tcpRequest = (EncapMessageRequest) req; - ModbusRequest request = tcpRequest.getModbusRequest(); - ModbusResponse response = handleRequestImpl(request); - if (response == null) - return null; - return new EncapMessageResponse(response); - } + public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { + EncapMessageRequest tcpRequest = (EncapMessageRequest) req; + ModbusRequest request = tcpRequest.getModbusRequest(); + ModbusResponse response = handleRequestImpl(request); + if (response == null) + return null; + return new EncapMessageResponse(response); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapWaitingRoomKeyFactory.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapWaitingRoomKeyFactory.java index f40150168..961a3c263 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapWaitingRoomKeyFactory.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/encap/EncapWaitingRoomKeyFactory.java @@ -34,63 +34,64 @@ import com.serotonin.modbus4j.sero.messaging.WaitingRoomKeyFactory; */ public class EncapWaitingRoomKeyFactory implements WaitingRoomKeyFactory { - @Override - public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { - return createWaitingRoomKey(((IpMessage) request).getModbusMessage()); - } + @Override + public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { + return createWaitingRoomKey(((IpMessage) request).getModbusMessage()); + } - @Override - public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { - return createWaitingRoomKey(((IpMessage) response).getModbusMessage()); - } + @Override + public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { + return createWaitingRoomKey(((IpMessage) response).getModbusMessage()); + } - /** - *

- * createWaitingRoomKey. - *

- * @param msg a {@link ModbusMessage} object. - * @return a {@link WaitingRoomKey} object. - */ - public WaitingRoomKey createWaitingRoomKey(ModbusMessage msg) { - return new EncapWaitingRoomKey(msg.getSlaveId(), msg.getFunctionCode()); - } + /** + *

+ * createWaitingRoomKey. + *

+ * + * @param msg a {@link ModbusMessage} object. + * @return a {@link WaitingRoomKey} object. + */ + public WaitingRoomKey createWaitingRoomKey(ModbusMessage msg) { + return new EncapWaitingRoomKey(msg.getSlaveId(), msg.getFunctionCode()); + } - class EncapWaitingRoomKey implements WaitingRoomKey { + class EncapWaitingRoomKey implements WaitingRoomKey { - private final int slaveId; + private final int slaveId; - private final byte functionCode; + private final byte functionCode; - public EncapWaitingRoomKey(int slaveId, byte functionCode) { - this.slaveId = slaveId; - this.functionCode = functionCode; - } + public EncapWaitingRoomKey(int slaveId, byte functionCode) { + this.slaveId = slaveId; + this.functionCode = functionCode; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + functionCode; - result = prime * result + slaveId; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + functionCode; + result = prime * result + slaveId; + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - EncapWaitingRoomKey other = (EncapWaitingRoomKey) obj; - if (functionCode != other.functionCode) - return false; - if (slaveId != other.slaveId) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EncapWaitingRoomKey other = (EncapWaitingRoomKey) obj; + if (functionCode != other.functionCode) + return false; + if (slaveId != other.slaveId) + return false; + return true; + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/listener/TcpListener.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/listener/TcpListener.java index fa6db31d7..9a69f0f9e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/listener/TcpListener.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/listener/TcpListener.java @@ -55,334 +55,322 @@ import java.util.concurrent.TimeUnit; */ public class TcpListener extends ModbusMaster { - // Configuration fields. - private final Log LOG = LogFactory.getLog(TcpListener.class); + // Configuration fields. + private final Log LOG = LogFactory.getLog(TcpListener.class); - private final IpParameters ipParameters; + private final IpParameters ipParameters; - private short nextTransactionId = 0; + private short nextTransactionId = 0; - private short retries = 0; + private short retries = 0; - // Runtime fields. - private ServerSocket serverSocket; + // Runtime fields. + private ServerSocket serverSocket; - private Socket socket; + private Socket socket; - private ExecutorService executorService; + private ExecutorService executorService; - private ListenerConnectionHandler handler; + private ListenerConnectionHandler handler; - /** - *

- * Constructor for TcpListener. - *

- *

- * Will validate response to ensure that slaveId == response slaveId if encapsulated - * is true - * @param params a {@link IpParameters} object. - */ - public TcpListener(IpParameters params) { - LOG.debug("Creating TcpListener in port " + params.getPort()); - ipParameters = params; - connected = false; - validateResponse = ipParameters.isEncapsulated(); - if (LOG.isDebugEnabled()) - LOG.debug("TcpListener created! Port: " + ipParameters.getPort()); - } + /** + *

+ * Constructor for TcpListener. + *

+ *

+ * Will validate response to ensure that slaveId == response slaveId if encapsulated + * is true + * + * @param params a {@link IpParameters} object. + */ + public TcpListener(IpParameters params) { + LOG.debug("Creating TcpListener in port " + params.getPort()); + ipParameters = params; + connected = false; + validateResponse = ipParameters.isEncapsulated(); + if (LOG.isDebugEnabled()) + LOG.debug("TcpListener created! Port: " + ipParameters.getPort()); + } - /** - * Control to validate response to ensure that slaveId == response slaveId - * @param params a {@link IpParameters} object. - * @param validateResponse a boolean. - */ - public TcpListener(IpParameters params, boolean validateResponse) { - LOG.debug("Creating TcpListener in port " + params.getPort()); - ipParameters = params; - connected = false; - this.validateResponse = validateResponse; - if (LOG.isDebugEnabled()) - LOG.debug("TcpListener created! Port: " + ipParameters.getPort()); - } + /** + * Control to validate response to ensure that slaveId == response slaveId + * + * @param params a {@link IpParameters} object. + * @param validateResponse a boolean. + */ + public TcpListener(IpParameters params, boolean validateResponse) { + LOG.debug("Creating TcpListener in port " + params.getPort()); + ipParameters = params; + connected = false; + this.validateResponse = validateResponse; + if (LOG.isDebugEnabled()) + LOG.debug("TcpListener created! Port: " + ipParameters.getPort()); + } - /** - *

- * Getter for the field nextTransactionId. - *

- * @return a short. - */ - protected short getNextTransactionId() { - return nextTransactionId++; - } + /** + *

+ * Getter for the field nextTransactionId. + *

+ * + * @return a short. + */ + protected short getNextTransactionId() { + return nextTransactionId++; + } - @Override - synchronized public void init() throws ModbusInitException { - LOG.debug("Init TcpListener Port: " + ipParameters.getPort()); - executorService = Executors.newCachedThreadPool(); - startListener(); - initialized = true; - LOG.warn("Initialized Port: " + ipParameters.getPort()); - } + @Override + synchronized public void init() throws ModbusInitException { + LOG.debug("Init TcpListener Port: " + ipParameters.getPort()); + executorService = Executors.newCachedThreadPool(); + startListener(); + initialized = true; + LOG.warn("Initialized Port: " + ipParameters.getPort()); + } - private void startListener() throws ModbusInitException { - try { - if (handler != null) { - LOG.debug("handler not null!!!"); - } - handler = new ListenerConnectionHandler(socket); - LOG.debug("Init handler thread"); - executorService.execute(handler); - } - catch (Exception e) { - LOG.warn("Error initializing TcpListener ", e); - throw new ModbusInitException(e); - } - } + private void startListener() throws ModbusInitException { + try { + if (handler != null) { + LOG.debug("handler not null!!!"); + } + handler = new ListenerConnectionHandler(socket); + LOG.debug("Init handler thread"); + executorService.execute(handler); + } catch (Exception e) { + LOG.warn("Error initializing TcpListener ", e); + throw new ModbusInitException(e); + } + } - @Override - synchronized public void destroy() { - LOG.debug("Destroy TCPListener Port: " + ipParameters.getPort()); - // Close the serverSocket first to prevent new messages. - try { - if (serverSocket != null) - serverSocket.close(); - } - catch (IOException e) { - LOG.warn("Error closing socket" + e.getLocalizedMessage()); - getExceptionHandler().receivedException(e); - } + @Override + synchronized public void destroy() { + LOG.debug("Destroy TCPListener Port: " + ipParameters.getPort()); + // Close the serverSocket first to prevent new messages. + try { + if (serverSocket != null) + serverSocket.close(); + } catch (IOException e) { + LOG.warn("Error closing socket" + e.getLocalizedMessage()); + getExceptionHandler().receivedException(e); + } - // Close all open connections. - if (handler != null) { - handler.closeConnection(); - } + // Close all open connections. + if (handler != null) { + handler.closeConnection(); + } - // Terminate Listener - terminateListener(); - initialized = false; - LOG.debug("TCPListener destroyed, Port: " + ipParameters.getPort()); - } + // Terminate Listener + terminateListener(); + initialized = false; + LOG.debug("TCPListener destroyed, Port: " + ipParameters.getPort()); + } - private void terminateListener() { - executorService.shutdown(); - try { - executorService.awaitTermination(300, TimeUnit.MILLISECONDS); - LOG.debug("Handler Thread terminated, Port: " + ipParameters.getPort()); - } - catch (InterruptedException e) { - LOG.debug("Error terminating executorService - " + e.getLocalizedMessage()); - getExceptionHandler().receivedException(e); - } - handler = null; - } + private void terminateListener() { + executorService.shutdown(); + try { + executorService.awaitTermination(300, TimeUnit.MILLISECONDS); + LOG.debug("Handler Thread terminated, Port: " + ipParameters.getPort()); + } catch (InterruptedException e) { + LOG.debug("Error terminating executorService - " + e.getLocalizedMessage()); + getExceptionHandler().receivedException(e); + } + handler = null; + } - @Override - synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { + @Override + synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { - if (!connected) { - LOG.debug("No connection in Port: " + ipParameters.getPort()); - throw new ModbusTransportException(new Exception("TCP Listener has no active connection!"), - request.getSlaveId()); - } + if (!connected) { + LOG.debug("No connection in Port: " + ipParameters.getPort()); + throw new ModbusTransportException(new Exception("TCP Listener has no active connection!"), + request.getSlaveId()); + } - if (!initialized) { - LOG.debug("Listener already terminated " + ipParameters.getPort()); - return null; - } + if (!initialized) { + LOG.debug("Listener already terminated " + ipParameters.getPort()); + return null; + } - // Wrap the modbus request in a ip request. - OutgoingRequestMessage ipRequest; - if (ipParameters.isEncapsulated()) { - ipRequest = new EncapMessageRequest(request); - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Encap Request: " + sb.toString()); - } - else { - ipRequest = new XaMessageRequest(request, getNextTransactionId()); - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Xa Request: " + sb.toString()); - } + // Wrap the modbus request in a ip request. + OutgoingRequestMessage ipRequest; + if (ipParameters.isEncapsulated()) { + ipRequest = new EncapMessageRequest(request); + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Encap Request: " + sb.toString()); + } else { + ipRequest = new XaMessageRequest(request, getNextTransactionId()); + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Xa Request: " + sb.toString()); + } - // Send the request to get the response. - IpMessageResponse ipResponse; - try { - // Send data via handler! - handler.conn.DEBUG = true; - ipResponse = (IpMessageResponse) handler.conn.send(ipRequest); - if (ipResponse == null) { - throw new ModbusTransportException(new Exception("No valid response from slave!"), - request.getSlaveId()); - } - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Response: " + sb.toString()); - return ipResponse.getModbusResponse(); - } - catch (Exception e) { - LOG.debug(e.getLocalizedMessage() + ", Port: " + ipParameters.getPort() + ", retries: " + retries); - if (retries < 10 && !e.getLocalizedMessage().contains("Broken")) { - retries++; - } - else { - /* - * To recover from a Broken Pipe, the only way is to restart serverSocket - */ - LOG.debug("Restarting Socket, Port: " + ipParameters.getPort() + ", retries: " + retries); + // Send the request to get the response. + IpMessageResponse ipResponse; + try { + // Send data via handler! + handler.conn.DEBUG = true; + ipResponse = (IpMessageResponse) handler.conn.send(ipRequest); + if (ipResponse == null) { + throw new ModbusTransportException(new Exception("No valid response from slave!"), + request.getSlaveId()); + } + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Response: " + sb.toString()); + return ipResponse.getModbusResponse(); + } catch (Exception e) { + LOG.debug(e.getLocalizedMessage() + ", Port: " + ipParameters.getPort() + ", retries: " + retries); + if (retries < 10 && !e.getLocalizedMessage().contains("Broken")) { + retries++; + } else { + /* + * To recover from a Broken Pipe, the only way is to restart serverSocket + */ + LOG.debug("Restarting Socket, Port: " + ipParameters.getPort() + ", retries: " + retries); - // Close the serverSocket first to prevent new messages. - try { - if (serverSocket != null) - serverSocket.close(); - } - catch (IOException e2) { - LOG.debug("Error closing socket" + e2.getLocalizedMessage(), e); - getExceptionHandler().receivedException(e2); - } + // Close the serverSocket first to prevent new messages. + try { + if (serverSocket != null) + serverSocket.close(); + } catch (IOException e2) { + LOG.debug("Error closing socket" + e2.getLocalizedMessage(), e); + getExceptionHandler().receivedException(e2); + } - // Close all open connections. - if (handler != null) { - handler.closeConnection(); - terminateListener(); - } + // Close all open connections. + if (handler != null) { + handler.closeConnection(); + terminateListener(); + } - if (!initialized) { - LOG.debug("Listener already terminated " + ipParameters.getPort()); - return null; - } + if (!initialized) { + LOG.debug("Listener already terminated " + ipParameters.getPort()); + return null; + } - executorService = Executors.newCachedThreadPool(); - try { - startListener(); - } - catch (Exception e2) { - LOG.warn("Error trying to restart socket" + e2.getLocalizedMessage(), e); - throw new ModbusTransportException(e2, request.getSlaveId()); - } - retries = 0; - } - LOG.warn("Error sending request, Port: " + ipParameters.getPort() + ", msg: " + e.getMessage()); - // Simple send error! - throw new ModbusTransportException(e, request.getSlaveId()); - } - } + executorService = Executors.newCachedThreadPool(); + try { + startListener(); + } catch (Exception e2) { + LOG.warn("Error trying to restart socket" + e2.getLocalizedMessage(), e); + throw new ModbusTransportException(e2, request.getSlaveId()); + } + retries = 0; + } + LOG.warn("Error sending request, Port: " + ipParameters.getPort() + ", msg: " + e.getMessage()); + // Simple send error! + throw new ModbusTransportException(e, request.getSlaveId()); + } + } - class ListenerConnectionHandler implements Runnable { + class ListenerConnectionHandler implements Runnable { - private Socket socket; + private Socket socket; - private Transport transport; + private Transport transport; - private MessageControl conn; + private MessageControl conn; - private BaseMessageParser ipMessageParser; + private BaseMessageParser ipMessageParser; - private WaitingRoomKeyFactory waitingRoomKeyFactory; + private WaitingRoomKeyFactory waitingRoomKeyFactory; - public ListenerConnectionHandler(Socket socket) { - this.socket = socket; - } + public ListenerConnectionHandler(Socket socket) { + this.socket = socket; + } - @Override - public void run() { - LOG.debug(" ListenerConnectionHandler::run() "); + @Override + public void run() { + LOG.debug(" ListenerConnectionHandler::run() "); - if (ipParameters.isEncapsulated()) { - ipMessageParser = new EncapMessageParser(true); - waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory(); - } - else { - ipMessageParser = new XaMessageParser(true); - waitingRoomKeyFactory = new XaWaitingRoomKeyFactory(); - } + if (ipParameters.isEncapsulated()) { + ipMessageParser = new EncapMessageParser(true); + waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory(); + } else { + ipMessageParser = new XaMessageParser(true); + waitingRoomKeyFactory = new XaWaitingRoomKeyFactory(); + } - try { - acceptConnection(); - } - catch (IOException e) { - LOG.debug("Error in TCP Listener! - " + e.getLocalizedMessage(), e); - conn.close(); - closeConnection(); - getExceptionHandler().receivedException(new ModbusInitException(e)); - } - } + try { + acceptConnection(); + } catch (IOException e) { + LOG.debug("Error in TCP Listener! - " + e.getLocalizedMessage(), e); + conn.close(); + closeConnection(); + getExceptionHandler().receivedException(new ModbusInitException(e)); + } + } - private void acceptConnection() throws IOException, BindException { - while (true) { - try { - Thread.sleep(500); - } - catch (InterruptedException e) { - e.printStackTrace(); - } + private void acceptConnection() throws IOException, BindException { + while (true) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + e.printStackTrace(); + } - if (!connected) { - try { - serverSocket = new ServerSocket(ipParameters.getPort()); - LOG.debug("Start Accept on port: " + ipParameters.getPort()); - socket = serverSocket.accept(); - LOG.info("Connected: " + socket.getInetAddress() + ":" + ipParameters.getPort()); + if (!connected) { + try { + serverSocket = new ServerSocket(ipParameters.getPort()); + LOG.debug("Start Accept on port: " + ipParameters.getPort()); + socket = serverSocket.accept(); + LOG.info("Connected: " + socket.getInetAddress() + ":" + ipParameters.getPort()); - if (getePoll() != null) - transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(), - getePoll()); - else - transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream()); - break; - } - catch (Exception e) { - LOG.warn("Open connection failed on port " + ipParameters.getPort() + ", caused by " - + e.getLocalizedMessage(), e); - if (e instanceof SocketTimeoutException) { - continue; - } - else if (e.getLocalizedMessage().contains("closed")) { - return; - } - else if (e instanceof BindException) { - closeConnection(); - throw (BindException) e; - } - } - } - } + if (getePoll() != null) + transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(), + getePoll()); + else + transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream()); + break; + } catch (Exception e) { + LOG.warn("Open connection failed on port " + ipParameters.getPort() + ", caused by " + + e.getLocalizedMessage(), e); + if (e instanceof SocketTimeoutException) { + continue; + } else if (e.getLocalizedMessage().contains("closed")) { + return; + } else if (e instanceof BindException) { + closeConnection(); + throw (BindException) e; + } + } + } + } - conn = getMessageControl(); - conn.setExceptionHandler(getExceptionHandler()); - conn.DEBUG = true; - conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory); - if (getePoll() == null) - ((StreamTransport) transport).start("Modbus4J TcpMaster"); - connected = true; - } + conn = getMessageControl(); + conn.setExceptionHandler(getExceptionHandler()); + conn.DEBUG = true; + conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory); + if (getePoll() == null) + ((StreamTransport) transport).start("Modbus4J TcpMaster"); + connected = true; + } - void closeConnection() { - if (conn != null) { - LOG.debug("Closing Message Control on port: " + ipParameters.getPort()); - closeMessageControl(conn); - } + void closeConnection() { + if (conn != null) { + LOG.debug("Closing Message Control on port: " + ipParameters.getPort()); + closeMessageControl(conn); + } - try { - if (socket != null) { - socket.close(); - } - } - catch (IOException e) { - LOG.debug("Error closing socket on port " + ipParameters.getPort() + ". " + e.getLocalizedMessage()); - getExceptionHandler().receivedException(new ModbusInitException(e)); - } - connected = false; - conn = null; - socket = null; - } + try { + if (socket != null) { + socket.close(); + } + } catch (IOException e) { + LOG.debug("Error closing socket on port " + ipParameters.getPort() + ". " + e.getLocalizedMessage()); + getExceptionHandler().receivedException(new ModbusInitException(e)); + } + connected = false; + conn = null; + socket = null; + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpMaster.java index 480679e5e..e36eca01d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpMaster.java @@ -49,307 +49,308 @@ import java.util.Arrays; */ public class TcpMaster extends ModbusMaster { - // Configuration fields. - private final Log LOG = LogFactory.getLog(TcpMaster.class); + // Configuration fields. + private final Log LOG = LogFactory.getLog(TcpMaster.class); - private final IpParameters ipParameters; + private final IpParameters ipParameters; - private final boolean keepAlive; + private final boolean keepAlive; - private final boolean autoIncrementTransactionId; + private final boolean autoIncrementTransactionId; - private final Integer lingerTime; + private final Integer lingerTime; - private short nextTransactionId = 0; + private short nextTransactionId = 0; - // Runtime fields. - private Socket socket; + // Runtime fields. + private Socket socket; - private Transport transport; + private Transport transport; - private MessageControl conn; + private MessageControl conn; - /** - *

- * Constructor for TcpMaster. - *

- * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @param autoIncrementTransactionId a boolean. - * @param validateResponse - confirm that requested slave id is the same in the - * response - * @param lingerTime The setting only affects socket close. - */ - public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId, - boolean validateResponse, Integer lingerTime) { - this.ipParameters = params; - this.keepAlive = keepAlive; - this.autoIncrementTransactionId = autoIncrementTransactionId; - this.lingerTime = lingerTime; - } + /** + *

+ * Constructor for TcpMaster. + *

+ * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @param autoIncrementTransactionId a boolean. + * @param validateResponse - confirm that requested slave id is the same in the + * response + * @param lingerTime The setting only affects socket close. + */ + public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId, + boolean validateResponse, Integer lingerTime) { + this.ipParameters = params; + this.keepAlive = keepAlive; + this.autoIncrementTransactionId = autoIncrementTransactionId; + this.lingerTime = lingerTime; + } - /** - *

- * Constructor for TcpMaster. - *

- *

- * Default to lingerTime disabled - * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @param autoIncrementTransactionId a boolean. - * @param validateResponse - confirm that requested slave id is the same in the - * response - */ - public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId, - boolean validateResponse) { - this(params, keepAlive, autoIncrementTransactionId, validateResponse, -1); - // this.ipParameters = params; - // this.keepAlive = keepAlive; - // this.autoIncrementTransactionId = autoIncrementTransactionId; - } + /** + *

+ * Constructor for TcpMaster. + *

+ *

+ * Default to lingerTime disabled + * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @param autoIncrementTransactionId a boolean. + * @param validateResponse - confirm that requested slave id is the same in the + * response + */ + public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId, + boolean validateResponse) { + this(params, keepAlive, autoIncrementTransactionId, validateResponse, -1); + // this.ipParameters = params; + // this.keepAlive = keepAlive; + // this.autoIncrementTransactionId = autoIncrementTransactionId; + } - /** - *

- * Constructor for TcpMaster. - *

- * Default to not validating the slave id in responses Default to lingerTime disabled - * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @param autoIncrementTransactionId a boolean. - */ - public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId) { - this(params, keepAlive, autoIncrementTransactionId, false, -1); - } + /** + *

+ * Constructor for TcpMaster. + *

+ * Default to not validating the slave id in responses Default to lingerTime disabled + * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @param autoIncrementTransactionId a boolean. + */ + public TcpMaster(IpParameters params, boolean keepAlive, boolean autoIncrementTransactionId) { + this(params, keepAlive, autoIncrementTransactionId, false, -1); + } - /** - *

- * Constructor for TcpMaster. - *

- *

- * Default to auto increment transaction id Default to not validating the slave id in - * responses Default to lingerTime disabled - * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - * @param lingerTime an Integer. The setting only affects socket close. - */ - public TcpMaster(IpParameters params, boolean keepAlive, Integer lingerTime) { - this(params, keepAlive, true, false, lingerTime); - } + /** + *

+ * Constructor for TcpMaster. + *

+ *

+ * Default to auto increment transaction id Default to not validating the slave id in + * responses Default to lingerTime disabled + * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + * @param lingerTime an Integer. The setting only affects socket close. + */ + public TcpMaster(IpParameters params, boolean keepAlive, Integer lingerTime) { + this(params, keepAlive, true, false, lingerTime); + } - /** - *

- * Constructor for TcpMaster. - *

- *

- * Default to auto increment transaction id Default to not validating the slave id in - * responses Default to lingerTime disabled - * @param params a {@link IpParameters} object. - * @param keepAlive a boolean. - */ - public TcpMaster(IpParameters params, boolean keepAlive) { - this(params, keepAlive, true, false, -1); - } + /** + *

+ * Constructor for TcpMaster. + *

+ *

+ * Default to auto increment transaction id Default to not validating the slave id in + * responses Default to lingerTime disabled + * + * @param params a {@link IpParameters} object. + * @param keepAlive a boolean. + */ + public TcpMaster(IpParameters params, boolean keepAlive) { + this(params, keepAlive, true, false, -1); + } - /** - *

- * Getter for the field nextTransactionId. - *

- * @return a short. - */ - protected short getNextTransactionId() { - return nextTransactionId; - } + /** + *

+ * Getter for the field nextTransactionId. + *

+ * + * @return a short. + */ + protected short getNextTransactionId() { + return nextTransactionId; + } - /** - *

- * Setter for the field nextTransactionId. - *

- * @param id a short. - */ - public void setNextTransactionId(short id) { - this.nextTransactionId = id; - } + /** + *

+ * Setter for the field nextTransactionId. + *

+ * + * @param id a short. + */ + public void setNextTransactionId(short id) { + this.nextTransactionId = id; + } - @Override - synchronized public void init() throws ModbusInitException { - try { - if (keepAlive) - openConnection(); - } - catch (Exception e) { - throw new ModbusInitException(e); - } - initialized = true; - } + @Override + synchronized public void init() throws ModbusInitException { + try { + if (keepAlive) + openConnection(); + } catch (Exception e) { + throw new ModbusInitException(e); + } + initialized = true; + } - @Override - synchronized public void destroy() { - closeConnection(); - initialized = false; - } + @Override + synchronized public void destroy() { + closeConnection(); + initialized = false; + } - @Override - synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { - try { - // Check if we need to open the connection. - if (!keepAlive) - openConnection(); + @Override + synchronized public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { + try { + // Check if we need to open the connection. + if (!keepAlive) + openConnection(); - if (conn == null) { - LOG.debug("Connection null: " + ipParameters.getPort()); - } + if (conn == null) { + LOG.debug("Connection null: " + ipParameters.getPort()); + } - } - catch (Exception e) { - closeConnection(); - throw new ModbusTransportException(e, request.getSlaveId()); - } + } catch (Exception e) { + closeConnection(); + throw new ModbusTransportException(e, request.getSlaveId()); + } - // Wrap the modbus request in a ip request. - OutgoingRequestMessage ipRequest; - if (ipParameters.isEncapsulated()) - ipRequest = new EncapMessageRequest(request); - else { - if (autoIncrementTransactionId) - this.nextTransactionId++; - ipRequest = new XaMessageRequest(request, getNextTransactionId()); - } + // Wrap the modbus request in a ip request. + OutgoingRequestMessage ipRequest; + if (ipParameters.isEncapsulated()) + ipRequest = new EncapMessageRequest(request); + else { + if (autoIncrementTransactionId) + this.nextTransactionId++; + ipRequest = new XaMessageRequest(request, getNextTransactionId()); + } - if (LOG.isDebugEnabled()) { - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Encap Request: " + sb.toString()); - } + if (LOG.isDebugEnabled()) { + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipRequest.getMessageData(), 0, ipRequest.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Encap Request: " + sb.toString()); + } - // Send the request to get the response. - IpMessageResponse ipResponse; - if (LOG.isDebugEnabled()) { - LOG.debug("Sending on port: " + ipParameters.getPort()); - } - try { - if (conn == null) { - if (LOG.isDebugEnabled()) - LOG.debug("Connection null: " + ipParameters.getPort()); - } - ipResponse = (IpMessageResponse) conn.send(ipRequest); - if (ipResponse == null) - return null; + // Send the request to get the response. + IpMessageResponse ipResponse; + if (LOG.isDebugEnabled()) { + LOG.debug("Sending on port: " + ipParameters.getPort()); + } + try { + if (conn == null) { + if (LOG.isDebugEnabled()) + LOG.debug("Connection null: " + ipParameters.getPort()); + } + ipResponse = (IpMessageResponse) conn.send(ipRequest); + if (ipResponse == null) + return null; - if (LOG.isDebugEnabled()) { - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Response: " + sb.toString()); - } - return ipResponse.getModbusResponse(); - } - catch (Exception e) { - if (LOG.isDebugEnabled()) - LOG.debug("Exception sending message", e); - if (keepAlive) { - if (LOG.isDebugEnabled()) - LOG.debug("KeepAlive - reconnect!"); - // The connection may have been reset, so try to reopen it and attempt the - // message again. - try { - if (LOG.isDebugEnabled()) - LOG.debug("Modbus4J: Keep-alive connection may have been reset. Attempting to re-open."); - openConnection(); - ipResponse = (IpMessageResponse) conn.send(ipRequest); - if (ipResponse == null) - return null; - if (LOG.isDebugEnabled()) { - StringBuilder sb = new StringBuilder(); - for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, - ipResponse.getMessageData().length)) { - sb.append(String.format("%02X ", b)); - } - LOG.debug("Response: " + sb.toString()); - } - return ipResponse.getModbusResponse(); - } - catch (Exception e2) { - closeConnection(); - if (LOG.isDebugEnabled()) - LOG.debug("Exception re-sending message", e); - throw new ModbusTransportException(e2, request.getSlaveId()); - } - } + if (LOG.isDebugEnabled()) { + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, ipResponse.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Response: " + sb.toString()); + } + return ipResponse.getModbusResponse(); + } catch (Exception e) { + if (LOG.isDebugEnabled()) + LOG.debug("Exception sending message", e); + if (keepAlive) { + if (LOG.isDebugEnabled()) + LOG.debug("KeepAlive - reconnect!"); + // The connection may have been reset, so try to reopen it and attempt the + // message again. + try { + if (LOG.isDebugEnabled()) + LOG.debug("Modbus4J: Keep-alive connection may have been reset. Attempting to re-open."); + openConnection(); + ipResponse = (IpMessageResponse) conn.send(ipRequest); + if (ipResponse == null) + return null; + if (LOG.isDebugEnabled()) { + StringBuilder sb = new StringBuilder(); + for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(), 0, + ipResponse.getMessageData().length)) { + sb.append(String.format("%02X ", b)); + } + LOG.debug("Response: " + sb.toString()); + } + return ipResponse.getModbusResponse(); + } catch (Exception e2) { + closeConnection(); + if (LOG.isDebugEnabled()) + LOG.debug("Exception re-sending message", e); + throw new ModbusTransportException(e2, request.getSlaveId()); + } + } - throw new ModbusTransportException(e, request.getSlaveId()); - } - finally { - // Check if we should close the connection. - if (!keepAlive) - closeConnection(); - } - } + throw new ModbusTransportException(e, request.getSlaveId()); + } finally { + // Check if we should close the connection. + if (!keepAlive) + closeConnection(); + } + } - // - // - // Private methods - // - private void openConnection() throws IOException { - // Make sure any existing connection is closed. - closeConnection(); + // + // + // Private methods + // + private void openConnection() throws IOException { + // Make sure any existing connection is closed. + closeConnection(); - Integer soLinger = getLingerTime(); + Integer soLinger = getLingerTime(); - socket = new Socket(); - socket.setSoTimeout(getTimeout()); - if (soLinger == null || soLinger < 0)// any null or negative will disable - // SO_Linger - socket.setSoLinger(false, 0); - else - socket.setSoLinger(true, soLinger); - socket.connect(new InetSocketAddress(ipParameters.getHost(), ipParameters.getPort()), getTimeout()); - if (getePoll() != null) - transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(), getePoll()); - else - transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream()); + socket = new Socket(); + socket.setSoTimeout(getTimeout()); + if (soLinger == null || soLinger < 0)// any null or negative will disable + // SO_Linger + socket.setSoLinger(false, 0); + else + socket.setSoLinger(true, soLinger); + socket.connect(new InetSocketAddress(ipParameters.getHost(), ipParameters.getPort()), getTimeout()); + if (getePoll() != null) + transport = new EpollStreamTransport(socket.getInputStream(), socket.getOutputStream(), getePoll()); + else + transport = new StreamTransport(socket.getInputStream(), socket.getOutputStream()); - BaseMessageParser ipMessageParser; - WaitingRoomKeyFactory waitingRoomKeyFactory; - if (ipParameters.isEncapsulated()) { - ipMessageParser = new EncapMessageParser(true); - waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory(); - } - else { - ipMessageParser = new XaMessageParser(true); - waitingRoomKeyFactory = new XaWaitingRoomKeyFactory(); - } + BaseMessageParser ipMessageParser; + WaitingRoomKeyFactory waitingRoomKeyFactory; + if (ipParameters.isEncapsulated()) { + ipMessageParser = new EncapMessageParser(true); + waitingRoomKeyFactory = new EncapWaitingRoomKeyFactory(); + } else { + ipMessageParser = new XaMessageParser(true); + waitingRoomKeyFactory = new XaWaitingRoomKeyFactory(); + } - conn = getMessageControl(); - conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory); - if (getePoll() == null) - ((StreamTransport) transport).start("Modbus4J TcpMaster"); - } + conn = getMessageControl(); + conn.start(transport, ipMessageParser, null, waitingRoomKeyFactory); + if (getePoll() == null) + ((StreamTransport) transport).start("Modbus4J TcpMaster"); + } - private void closeConnection() { - closeMessageControl(conn); - try { - if (socket != null) - socket.close(); - } - catch (IOException e) { - getExceptionHandler().receivedException(e); - } + private void closeConnection() { + closeMessageControl(conn); + try { + if (socket != null) + socket.close(); + } catch (IOException e) { + getExceptionHandler().receivedException(e); + } - conn = null; - socket = null; - } + conn = null; + socket = null; + } - /** - *

- * Getter for the field lingerTime. - *

- * @return an Integer. - */ - public Integer getLingerTime() { - return lingerTime; - } + /** + *

+ * Getter for the field lingerTime. + *

+ * + * @return an Integer. + */ + public Integer getLingerTime() { + return lingerTime; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpSlave.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpSlave.java index ebfc7c523..3a848a62a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpSlave.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/tcp/TcpSlave.java @@ -47,164 +47,157 @@ import java.util.concurrent.TimeUnit; */ public class TcpSlave extends ModbusSlaveSet { - final boolean encapsulated; + final boolean encapsulated; - final ExecutorService executorService; + final ExecutorService executorService; - final List listConnections = new ArrayList<>(); + final List listConnections = new ArrayList<>(); - // Configuration fields - private final int port; + // Configuration fields + private final int port; - // Runtime fields. - private ServerSocket serverSocket; + // Runtime fields. + private ServerSocket serverSocket; - /** - *

- * Constructor for TcpSlave. - *

- * @param encapsulated a boolean. - */ - public TcpSlave(boolean encapsulated) { - this(ModbusUtils.TCP_PORT, encapsulated); - } + /** + *

+ * Constructor for TcpSlave. + *

+ * + * @param encapsulated a boolean. + */ + public TcpSlave(boolean encapsulated) { + this(ModbusUtils.TCP_PORT, encapsulated); + } - /** - *

- * Constructor for TcpSlave. - *

- * @param port a int. - * @param encapsulated a boolean. - */ - public TcpSlave(int port, boolean encapsulated) { - this.port = port; - this.encapsulated = encapsulated; - executorService = Executors.newCachedThreadPool(); - } + /** + *

+ * Constructor for TcpSlave. + *

+ * + * @param port a int. + * @param encapsulated a boolean. + */ + public TcpSlave(int port, boolean encapsulated) { + this.port = port; + this.encapsulated = encapsulated; + executorService = Executors.newCachedThreadPool(); + } - @Override - public void start() throws ModbusInitException { - try { - serverSocket = new ServerSocket(port); + @Override + public void start() throws ModbusInitException { + try { + serverSocket = new ServerSocket(port); - Socket socket; - while (true) { - socket = serverSocket.accept(); - TcpConnectionHandler handler = new TcpConnectionHandler(socket); - executorService.execute(handler); - synchronized (listConnections) { - listConnections.add(handler); - } - } - } - catch (IOException e) { - throw new ModbusInitException(e); - } - } + Socket socket; + while (true) { + socket = serverSocket.accept(); + TcpConnectionHandler handler = new TcpConnectionHandler(socket); + executorService.execute(handler); + synchronized (listConnections) { + listConnections.add(handler); + } + } + } catch (IOException e) { + throw new ModbusInitException(e); + } + } - @Override - public void stop() { - // Close the socket first to prevent new messages. - try { - serverSocket.close(); - } - catch (IOException e) { - getExceptionHandler().receivedException(e); - } + @Override + public void stop() { + // Close the socket first to prevent new messages. + try { + serverSocket.close(); + } catch (IOException e) { + getExceptionHandler().receivedException(e); + } - // Close all open connections. - synchronized (listConnections) { - for (TcpConnectionHandler tch : listConnections) - tch.kill(); - listConnections.clear(); - } + // Close all open connections. + synchronized (listConnections) { + for (TcpConnectionHandler tch : listConnections) + tch.kill(); + listConnections.clear(); + } - // Now close the executor service. - executorService.shutdown(); - try { - executorService.awaitTermination(3, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - getExceptionHandler().receivedException(e); - } - } + // Now close the executor service. + executorService.shutdown(); + try { + executorService.awaitTermination(3, TimeUnit.SECONDS); + } catch (InterruptedException e) { + getExceptionHandler().receivedException(e); + } + } - class TcpConnectionHandler implements Runnable { + class TcpConnectionHandler implements Runnable { - private final Socket socket; + private final Socket socket; - private TestableTransport transport; + private TestableTransport transport; - private MessageControl conn; + private MessageControl conn; - TcpConnectionHandler(Socket socket) throws ModbusInitException { - this.socket = socket; - try { - transport = new TestableTransport(socket.getInputStream(), socket.getOutputStream()); - } - catch (IOException e) { - throw new ModbusInitException(e); - } - } + TcpConnectionHandler(Socket socket) throws ModbusInitException { + this.socket = socket; + try { + transport = new TestableTransport(socket.getInputStream(), socket.getOutputStream()); + } catch (IOException e) { + throw new ModbusInitException(e); + } + } - @Override - public void run() { - BaseMessageParser messageParser; - BaseRequestHandler requestHandler; + @Override + public void run() { + BaseMessageParser messageParser; + BaseRequestHandler requestHandler; - if (encapsulated) { - messageParser = new EncapMessageParser(false); - requestHandler = new EncapRequestHandler(TcpSlave.this); - } - else { - messageParser = new XaMessageParser(false); - requestHandler = new XaRequestHandler(TcpSlave.this); - } + if (encapsulated) { + messageParser = new EncapMessageParser(false); + requestHandler = new EncapRequestHandler(TcpSlave.this); + } else { + messageParser = new XaMessageParser(false); + requestHandler = new XaRequestHandler(TcpSlave.this); + } - conn = new MessageControl(); - conn.setExceptionHandler(getExceptionHandler()); + conn = new MessageControl(); + conn.setExceptionHandler(getExceptionHandler()); - try { - conn.start(transport, messageParser, requestHandler, null); - executorService.execute(transport); - } - catch (IOException e) { - getExceptionHandler().receivedException(new ModbusInitException(e)); - } + try { + conn.start(transport, messageParser, requestHandler, null); + executorService.execute(transport); + } catch (IOException e) { + getExceptionHandler().receivedException(new ModbusInitException(e)); + } - // Monitor the socket to detect when it gets closed. - while (true) { - try { - transport.testInputStream(); - } - catch (IOException e) { - break; - } + // Monitor the socket to detect when it gets closed. + while (true) { + try { + transport.testInputStream(); + } catch (IOException e) { + break; + } - try { - Thread.sleep(500); - } - catch (InterruptedException e) { - // no op - } - } + try { + Thread.sleep(500); + } catch (InterruptedException e) { + // no op + } + } - conn.close(); - kill(); - synchronized (listConnections) { - listConnections.remove(this); - } - } + conn.close(); + kill(); + synchronized (listConnections) { + listConnections.remove(this); + } + } - void kill() { - try { - socket.close(); - } - catch (IOException e) { - getExceptionHandler().receivedException(new ModbusInitException(e)); - } - } + void kill() { + try { + socket.close(); + } catch (IOException e) { + getExceptionHandler().receivedException(new ModbusInitException(e)); + } + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpMaster.java index 4bd224a3d..5d434a0f3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpMaster.java @@ -44,148 +44,147 @@ import java.net.*; */ public class UdpMaster extends ModbusMaster { - private static final int MESSAGE_LENGTH = 1024; + private static final int MESSAGE_LENGTH = 1024; - private final IpParameters ipParameters; + private final IpParameters ipParameters; - private short nextTransactionId = 0; + private short nextTransactionId = 0; - // Runtime fields. - private BaseMessageParser messageParser; + // Runtime fields. + private BaseMessageParser messageParser; - private DatagramSocket socket; + private DatagramSocket socket; - /** - *

- * Constructor for UdpMaster. - *

- *

- * Default to not validating the slave id in responses - * @param params a {@link IpParameters} object. - */ - public UdpMaster(IpParameters params) { - this(params, false); - } + /** + *

+ * Constructor for UdpMaster. + *

+ *

+ * Default to not validating the slave id in responses + * + * @param params a {@link IpParameters} object. + */ + public UdpMaster(IpParameters params) { + this(params, false); + } - /** - *

- * Constructor for UdpMaster. - *

- * @param params - * @param validateResponse - confirm that requested slave id is the same in the - * response - */ - public UdpMaster(IpParameters params, boolean validateResponse) { - ipParameters = params; - this.validateResponse = validateResponse; - } + /** + *

+ * Constructor for UdpMaster. + *

+ * + * @param params + * @param validateResponse - confirm that requested slave id is the same in the + * response + */ + public UdpMaster(IpParameters params, boolean validateResponse) { + ipParameters = params; + this.validateResponse = validateResponse; + } - /** - *

- * Getter for the field nextTransactionId. - *

- * @return a short. - */ - protected short getNextTransactionId() { - return nextTransactionId++; - } + /** + *

+ * Getter for the field nextTransactionId. + *

+ * + * @return a short. + */ + protected short getNextTransactionId() { + return nextTransactionId++; + } - @Override - public void init() throws ModbusInitException { - if (ipParameters.isEncapsulated()) - messageParser = new EncapMessageParser(true); - else - messageParser = new XaMessageParser(true); + @Override + public void init() throws ModbusInitException { + if (ipParameters.isEncapsulated()) + messageParser = new EncapMessageParser(true); + else + messageParser = new XaMessageParser(true); - try { - socket = new DatagramSocket(); - socket.setSoTimeout(getTimeout()); - } - catch (SocketException e) { - throw new ModbusInitException(e); - } - initialized = true; - } + try { + socket = new DatagramSocket(); + socket.setSoTimeout(getTimeout()); + } catch (SocketException e) { + throw new ModbusInitException(e); + } + initialized = true; + } - @Override - public void destroy() { - socket.close(); - initialized = false; - } + @Override + public void destroy() { + socket.close(); + initialized = false; + } - @Override - public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { - // Wrap the modbus request in an ip request. - OutgoingRequestMessage ipRequest; - if (ipParameters.isEncapsulated()) - ipRequest = new EncapMessageRequest(request); - else - ipRequest = new XaMessageRequest(request, getNextTransactionId()); + @Override + public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { + // Wrap the modbus request in an ip request. + OutgoingRequestMessage ipRequest; + if (ipParameters.isEncapsulated()) + ipRequest = new EncapMessageRequest(request); + else + ipRequest = new XaMessageRequest(request, getNextTransactionId()); - IpMessageResponse ipResponse; + IpMessageResponse ipResponse; - try { - int attempts = getRetries() + 1; + try { + int attempts = getRetries() + 1; - while (true) { - // Send the request. - sendImpl(ipRequest); + while (true) { + // Send the request. + sendImpl(ipRequest); - if (!ipRequest.expectsResponse()) - return null; + if (!ipRequest.expectsResponse()) + return null; - // Receive the response. - try { - ipResponse = receiveImpl(); - } - catch (SocketTimeoutException e) { - attempts--; - if (attempts > 0) - // Try again. - continue; + // Receive the response. + try { + ipResponse = receiveImpl(); + } catch (SocketTimeoutException e) { + attempts--; + if (attempts > 0) + // Try again. + continue; - throw new ModbusTransportException(e, request.getSlaveId()); - } + throw new ModbusTransportException(e, request.getSlaveId()); + } - // We got the response - break; - } + // We got the response + break; + } - return ipResponse.getModbusResponse(); - } - catch (IOException e) { - throw new ModbusTransportException(e, request.getSlaveId()); - } - } + return ipResponse.getModbusResponse(); + } catch (IOException e) { + throw new ModbusTransportException(e, request.getSlaveId()); + } + } - private void sendImpl(OutgoingRequestMessage request) throws IOException { - byte[] data = request.getMessageData(); - DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipParameters.getHost()), - ipParameters.getPort()); - socket.send(packet); - } + private void sendImpl(OutgoingRequestMessage request) throws IOException { + byte[] data = request.getMessageData(); + DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ipParameters.getHost()), + ipParameters.getPort()); + socket.send(packet); + } - private IpMessageResponse receiveImpl() throws IOException, ModbusTransportException { - DatagramPacket packet = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH); - socket.receive(packet); + private IpMessageResponse receiveImpl() throws IOException, ModbusTransportException { + DatagramPacket packet = new DatagramPacket(new byte[MESSAGE_LENGTH], MESSAGE_LENGTH); + socket.receive(packet); - // We could verify that the packet was received from the same address to which the - // request was sent, - // but let's not bother with that yet. + // We could verify that the packet was received from the same address to which the + // request was sent, + // but let's not bother with that yet. - ByteQueue queue = new ByteQueue(packet.getData(), 0, packet.getLength()); - IpMessageResponse response; - try { - response = (IpMessageResponse) messageParser.parseMessage(queue); - } - catch (Exception e) { - throw new ModbusTransportException(e); - } + ByteQueue queue = new ByteQueue(packet.getData(), 0, packet.getLength()); + IpMessageResponse response; + try { + response = (IpMessageResponse) messageParser.parseMessage(queue); + } catch (Exception e) { + throw new ModbusTransportException(e); + } - if (response == null) - throw new ModbusTransportException("Invalid response received"); + if (response == null) + throw new ModbusTransportException("Invalid response received"); - return response; - } + return response; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpSlave.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpSlave.java index 67902af4e..970f1a173 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpSlave.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/udp/UdpSlave.java @@ -47,124 +47,122 @@ import java.util.concurrent.TimeUnit; */ public class UdpSlave extends ModbusSlaveSet { - final BaseMessageParser messageParser; + final BaseMessageParser messageParser; - final BaseRequestHandler requestHandler; + final BaseRequestHandler requestHandler; - // Configuration fields - private final int port; + // Configuration fields + private final int port; - private final ExecutorService executorService; + private final ExecutorService executorService; - // Runtime fields. - DatagramSocket datagramSocket; + // Runtime fields. + DatagramSocket datagramSocket; - /** - *

- * Constructor for UdpSlave. - *

- * @param encapsulated a boolean. - */ - public UdpSlave(boolean encapsulated) { - this(ModbusUtils.TCP_PORT, encapsulated); - } + /** + *

+ * Constructor for UdpSlave. + *

+ * + * @param encapsulated a boolean. + */ + public UdpSlave(boolean encapsulated) { + this(ModbusUtils.TCP_PORT, encapsulated); + } - /** - *

- * Constructor for UdpSlave. - *

- * @param port a int. - * @param encapsulated a boolean. - */ - public UdpSlave(int port, boolean encapsulated) { - this.port = port; + /** + *

+ * Constructor for UdpSlave. + *

+ * + * @param port a int. + * @param encapsulated a boolean. + */ + public UdpSlave(int port, boolean encapsulated) { + this.port = port; - if (encapsulated) { - messageParser = new EncapMessageParser(false); - requestHandler = new EncapRequestHandler(this); - } - else { - messageParser = new XaMessageParser(false); - requestHandler = new XaRequestHandler(this); - } + if (encapsulated) { + messageParser = new EncapMessageParser(false); + requestHandler = new EncapRequestHandler(this); + } else { + messageParser = new XaMessageParser(false); + requestHandler = new XaRequestHandler(this); + } - executorService = Executors.newCachedThreadPool(); - } + executorService = Executors.newCachedThreadPool(); + } - @Override - public void start() throws ModbusInitException { - try { - datagramSocket = new DatagramSocket(port); + @Override + public void start() throws ModbusInitException { + try { + datagramSocket = new DatagramSocket(port); - DatagramPacket datagramPacket; - while (true) { - datagramPacket = new DatagramPacket(new byte[1028], 1028); - datagramSocket.receive(datagramPacket); + DatagramPacket datagramPacket; + while (true) { + datagramPacket = new DatagramPacket(new byte[1028], 1028); + datagramSocket.receive(datagramPacket); - UdpConnectionHandler handler = new UdpConnectionHandler(datagramPacket); - executorService.execute(handler); - } - } - catch (IOException e) { - throw new ModbusInitException(e); - } - } + UdpConnectionHandler handler = new UdpConnectionHandler(datagramPacket); + executorService.execute(handler); + } + } catch (IOException e) { + throw new ModbusInitException(e); + } + } - @Override - public void stop() { - // Close the socket first to prevent new messages. - datagramSocket.close(); + @Override + public void stop() { + // Close the socket first to prevent new messages. + datagramSocket.close(); - // Close the executor service. - executorService.shutdown(); - try { - executorService.awaitTermination(3, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - getExceptionHandler().receivedException(e); - } - } + // Close the executor service. + executorService.shutdown(); + try { + executorService.awaitTermination(3, TimeUnit.SECONDS); + } catch (InterruptedException e) { + getExceptionHandler().receivedException(e); + } + } - // int getSlaveId() { - // return slaveId; - // } - // - // ProcessImage getProcessImage() { - // return processImage; - // } + // int getSlaveId() { + // return slaveId; + // } + // + // ProcessImage getProcessImage() { + // return processImage; + // } - class UdpConnectionHandler implements Runnable { + class UdpConnectionHandler implements Runnable { - private final DatagramPacket requestPacket; + private final DatagramPacket requestPacket; - UdpConnectionHandler(DatagramPacket requestPacket) { - this.requestPacket = requestPacket; - } + UdpConnectionHandler(DatagramPacket requestPacket) { + this.requestPacket = requestPacket; + } - public void run() { - try { - ByteQueue requestQueue = new ByteQueue(requestPacket.getData(), 0, requestPacket.getLength()); + public void run() { + try { + ByteQueue requestQueue = new ByteQueue(requestPacket.getData(), 0, requestPacket.getLength()); - // Parse the request data and get the response. - IncomingMessage request = messageParser.parseMessage(requestQueue); - OutgoingResponseMessage response = requestHandler.handleRequest((IncomingRequestMessage) request); + // Parse the request data and get the response. + IncomingMessage request = messageParser.parseMessage(requestQueue); + OutgoingResponseMessage response = requestHandler.handleRequest((IncomingRequestMessage) request); - if (response == null) - return; + if (response == null) + return; - // Create a response packet. - byte[] responseData = response.getMessageData(); - DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, - requestPacket.getAddress(), requestPacket.getPort()); + // Create a response packet. + byte[] responseData = response.getMessageData(); + DatagramPacket responsePacket = new DatagramPacket(responseData, responseData.length, + requestPacket.getAddress(), requestPacket.getPort()); - // Send the response back. - datagramSocket.send(responsePacket); - } - catch (Exception e) { - getExceptionHandler().receivedException(e); - } - } + // Send the response back. + datagramSocket.send(responsePacket); + } catch (Exception e) { + getExceptionHandler().receivedException(e); + } + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessage.java index 4da4f349c..48eecf9cd 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessage.java @@ -31,61 +31,64 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class XaMessage extends IpMessage { - protected final int transactionId; + protected final int transactionId; - /** - *

- * Constructor for XaMessage. - *

- * @param modbusMessage a {@link ModbusMessage} object. - * @param transactionId a int. - */ - public XaMessage(ModbusMessage modbusMessage, int transactionId) { - super(modbusMessage); - this.transactionId = transactionId; - } + /** + *

+ * Constructor for XaMessage. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + * @param transactionId a int. + */ + public XaMessage(ModbusMessage modbusMessage, int transactionId) { + super(modbusMessage); + this.transactionId = transactionId; + } - /** - *

- * getMessageData. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getMessageData() { - ByteQueue msgQueue = new ByteQueue(); + /** + *

+ * getMessageData. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getMessageData() { + ByteQueue msgQueue = new ByteQueue(); - // Write the particular message. - modbusMessage.write(msgQueue); + // Write the particular message. + modbusMessage.write(msgQueue); - // Create the XA message - ByteQueue xaQueue = new ByteQueue(); - ModbusUtils.pushShort(xaQueue, transactionId); - ModbusUtils.pushShort(xaQueue, ModbusUtils.IP_PROTOCOL_ID); - ModbusUtils.pushShort(xaQueue, msgQueue.size()); - xaQueue.push(msgQueue); + // Create the XA message + ByteQueue xaQueue = new ByteQueue(); + ModbusUtils.pushShort(xaQueue, transactionId); + ModbusUtils.pushShort(xaQueue, ModbusUtils.IP_PROTOCOL_ID); + ModbusUtils.pushShort(xaQueue, msgQueue.size()); + xaQueue.push(msgQueue); - // Return the data. - return xaQueue.popAll(); - } + // Return the data. + return xaQueue.popAll(); + } - /** - *

- * Getter for the field transactionId. - *

- * @return a int. - */ - public int getTransactionId() { - return transactionId; - } + /** + *

+ * Getter for the field transactionId. + *

+ * + * @return a int. + */ + public int getTransactionId() { + return transactionId; + } - @Override - public ModbusMessage getModbusMessage() { - return modbusMessage; - } + @Override + public ModbusMessage getModbusMessage() { + return modbusMessage; + } - @Override - public String toString() { - return "XaMessage [transactionId=" + transactionId + ", message=" + modbusMessage + "]"; - } + @Override + public String toString() { + return "XaMessage [transactionId=" + transactionId + ", message=" + modbusMessage + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageParser.java index ab79981b6..3e4098cf3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageParser.java @@ -30,21 +30,22 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class XaMessageParser extends BaseMessageParser { - /** - *

- * Constructor for XaMessageParser. - *

- * @param master a boolean. - */ - public XaMessageParser(boolean master) { - super(master); - } + /** + *

+ * Constructor for XaMessageParser. + *

+ * + * @param master a boolean. + */ + public XaMessageParser(boolean master) { + super(master); + } - @Override - protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { - if (master) - return XaMessageResponse.createXaMessageResponse(queue); - return XaMessageRequest.createXaMessageRequest(queue); - } + @Override + protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { + if (master) + return XaMessageResponse.createXaMessageResponse(queue); + return XaMessageRequest.createXaMessageRequest(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageRequest.java index 1a3d903ae..e19f7b75a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageRequest.java @@ -33,43 +33,45 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class XaMessageRequest extends XaMessage implements OutgoingRequestMessage, IncomingRequestMessage { - /** - *

- * Constructor for XaMessageRequest. - *

- * @param modbusRequest a {@link ModbusRequest} object. - * @param transactionId a int. - */ - public XaMessageRequest(ModbusRequest modbusRequest, int transactionId) { - super(modbusRequest, transactionId); - } + /** + *

+ * Constructor for XaMessageRequest. + *

+ * + * @param modbusRequest a {@link ModbusRequest} object. + * @param transactionId a int. + */ + public XaMessageRequest(ModbusRequest modbusRequest, int transactionId) { + super(modbusRequest, transactionId); + } - static XaMessageRequest createXaMessageRequest(ByteQueue queue) throws ModbusTransportException { - // Remove the XA header - int transactionId = ModbusUtils.popShort(queue); - int protocolId = ModbusUtils.popShort(queue); - if (protocolId != ModbusUtils.IP_PROTOCOL_ID) - throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId); - ModbusUtils.popShort(queue); // Length, which we don't care about. + static XaMessageRequest createXaMessageRequest(ByteQueue queue) throws ModbusTransportException { + // Remove the XA header + int transactionId = ModbusUtils.popShort(queue); + int protocolId = ModbusUtils.popShort(queue); + if (protocolId != ModbusUtils.IP_PROTOCOL_ID) + throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId); + ModbusUtils.popShort(queue); // Length, which we don't care about. - // Create the modbus response. - ModbusRequest request = ModbusRequest.createModbusRequest(queue); - return new XaMessageRequest(request, transactionId); - } + // Create the modbus response. + ModbusRequest request = ModbusRequest.createModbusRequest(queue); + return new XaMessageRequest(request, transactionId); + } - @Override - public boolean expectsResponse() { - return modbusMessage.getSlaveId() != 0; - } + @Override + public boolean expectsResponse() { + return modbusMessage.getSlaveId() != 0; + } - /** - *

- * getModbusRequest. - *

- * @return a {@link ModbusRequest} object. - */ - public ModbusRequest getModbusRequest() { - return (ModbusRequest) modbusMessage; - } + /** + *

+ * getModbusRequest. + *

+ * + * @return a {@link ModbusRequest} object. + */ + public ModbusRequest getModbusRequest() { + return (ModbusRequest) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageResponse.java index 7ef8088a8..ea4655670 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaMessageResponse.java @@ -32,38 +32,40 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class XaMessageResponse extends XaMessage implements IpMessageResponse { - /** - *

- * Constructor for XaMessageResponse. - *

- * @param modbusResponse a {@link ModbusResponse} object. - * @param transactionId a int. - */ - public XaMessageResponse(ModbusResponse modbusResponse, int transactionId) { - super(modbusResponse, transactionId); - } + /** + *

+ * Constructor for XaMessageResponse. + *

+ * + * @param modbusResponse a {@link ModbusResponse} object. + * @param transactionId a int. + */ + public XaMessageResponse(ModbusResponse modbusResponse, int transactionId) { + super(modbusResponse, transactionId); + } - static XaMessageResponse createXaMessageResponse(ByteQueue queue) throws ModbusTransportException { - // Remove the XA header - int transactionId = ModbusUtils.popShort(queue); - int protocolId = ModbusUtils.popShort(queue); - if (protocolId != ModbusUtils.IP_PROTOCOL_ID) - throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId); - ModbusUtils.popShort(queue); // Length, which we don't care about. + static XaMessageResponse createXaMessageResponse(ByteQueue queue) throws ModbusTransportException { + // Remove the XA header + int transactionId = ModbusUtils.popShort(queue); + int protocolId = ModbusUtils.popShort(queue); + if (protocolId != ModbusUtils.IP_PROTOCOL_ID) + throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId); + ModbusUtils.popShort(queue); // Length, which we don't care about. - // Create the modbus response. - ModbusResponse response = ModbusResponse.createModbusResponse(queue); - return new XaMessageResponse(response, transactionId); - } + // Create the modbus response. + ModbusResponse response = ModbusResponse.createModbusResponse(queue); + return new XaMessageResponse(response, transactionId); + } - /** - *

- * getModbusResponse. - *

- * @return a {@link ModbusResponse} object. - */ - public ModbusResponse getModbusResponse() { - return (ModbusResponse) modbusMessage; - } + /** + *

+ * getModbusResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + public ModbusResponse getModbusResponse() { + return (ModbusResponse) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaRequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaRequestHandler.java index 979e1520a..2d1b53e06 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaRequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaRequestHandler.java @@ -33,23 +33,24 @@ import com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage; */ public class XaRequestHandler extends BaseRequestHandler { - /** - *

- * Constructor for XaRequestHandler. - *

- * @param slave a {@link ModbusSlaveSet} object. - */ - public XaRequestHandler(ModbusSlaveSet slave) { - super(slave); - } + /** + *

+ * Constructor for XaRequestHandler. + *

+ * + * @param slave a {@link ModbusSlaveSet} object. + */ + public XaRequestHandler(ModbusSlaveSet slave) { + super(slave); + } - public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { - XaMessageRequest tcpRequest = (XaMessageRequest) req; - ModbusRequest request = tcpRequest.getModbusRequest(); - ModbusResponse response = handleRequestImpl(request); - if (response == null) - return null; - return new XaMessageResponse(response, tcpRequest.transactionId); - } + public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { + XaMessageRequest tcpRequest = (XaMessageRequest) req; + ModbusRequest request = tcpRequest.getModbusRequest(); + ModbusResponse response = handleRequestImpl(request); + if (response == null) + return null; + return new XaMessageResponse(response, tcpRequest.transactionId); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaWaitingRoomKeyFactory.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaWaitingRoomKeyFactory.java index 0ff2a61c1..a1ac6d652 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaWaitingRoomKeyFactory.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/ip/xa/XaWaitingRoomKeyFactory.java @@ -33,69 +33,70 @@ import com.serotonin.modbus4j.sero.messaging.WaitingRoomKeyFactory; */ public class XaWaitingRoomKeyFactory implements WaitingRoomKeyFactory { - @Override - public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { - return createWaitingRoomKey((XaMessage) request); - } + @Override + public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { + return createWaitingRoomKey((XaMessage) request); + } - @Override - public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { - return createWaitingRoomKey((XaMessage) response); - } + @Override + public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { + return createWaitingRoomKey((XaMessage) response); + } - /** - *

- * createWaitingRoomKey. - *

- * @param msg a {@link XaMessage} object. - * @return a {@link WaitingRoomKey} object. - */ - public WaitingRoomKey createWaitingRoomKey(XaMessage msg) { - return new XaWaitingRoomKey(msg.getTransactionId(), msg.getModbusMessage()); - } + /** + *

+ * createWaitingRoomKey. + *

+ * + * @param msg a {@link XaMessage} object. + * @return a {@link WaitingRoomKey} object. + */ + public WaitingRoomKey createWaitingRoomKey(XaMessage msg) { + return new XaWaitingRoomKey(msg.getTransactionId(), msg.getModbusMessage()); + } - class XaWaitingRoomKey implements WaitingRoomKey { + class XaWaitingRoomKey implements WaitingRoomKey { - private final int transactionId; + private final int transactionId; - private final int slaveId; + private final int slaveId; - private final byte functionCode; + private final byte functionCode; - public XaWaitingRoomKey(int transactionId, ModbusMessage msg) { - this.transactionId = transactionId; - this.slaveId = msg.getSlaveId(); - this.functionCode = msg.getFunctionCode(); - } + public XaWaitingRoomKey(int transactionId, ModbusMessage msg) { + this.transactionId = transactionId; + this.slaveId = msg.getSlaveId(); + this.functionCode = msg.getFunctionCode(); + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + functionCode; - result = prime * result + slaveId; - result = prime * result + transactionId; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + functionCode; + result = prime * result + slaveId; + result = prime * result + transactionId; + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - XaWaitingRoomKey other = (XaWaitingRoomKey) obj; - if (functionCode != other.functionCode) - return false; - if (slaveId != other.slaveId) - return false; - if (transactionId != other.transactionId) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + XaWaitingRoomKey other = (XaWaitingRoomKey) obj; + if (functionCode != other.functionCode) + return false; + if (slaveId != other.slaveId) + return false; + if (transactionId != other.transactionId) + return false; + return true; + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BaseLocator.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BaseLocator.java index c37b85ce3..ae1932119 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BaseLocator.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BaseLocator.java @@ -35,298 +35,318 @@ import java.nio.charset.Charset; * @version 2025.9.0 */ abstract /** - * Base Locator - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Base Locator + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class BaseLocator { - // - // - // Factory methods - // + // + // + // Factory methods + // - protected final int range; + protected final int range; - protected final int offset; + protected final int offset; - private final int slaveId; + private final int slaveId; - /** - *

- * Constructor for BaseLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - */ - public BaseLocator(int slaveId, int range, int offset) { - this.slaveId = slaveId; - this.range = range; - this.offset = offset; - } + /** + *

+ * Constructor for BaseLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + */ + public BaseLocator(int slaveId, int range, int offset) { + this.slaveId = slaveId; + this.range = range; + this.offset = offset; + } - /** - *

- * coilStatus. - *

- * @param slaveId a int. - * @param offset a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator coilStatus(int slaveId, int offset) { - return new BinaryLocator(slaveId, RegisterRange.COIL_STATUS, offset); - } + /** + *

+ * coilStatus. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator coilStatus(int slaveId, int offset) { + return new BinaryLocator(slaveId, RegisterRange.COIL_STATUS, offset); + } - /** - *

- * inputStatus. - *

- * @param slaveId a int. - * @param offset a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator inputStatus(int slaveId, int offset) { - return new BinaryLocator(slaveId, RegisterRange.INPUT_STATUS, offset); - } + /** + *

+ * inputStatus. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator inputStatus(int slaveId, int offset) { + return new BinaryLocator(slaveId, RegisterRange.INPUT_STATUS, offset); + } - /** - *

- * inputRegister. - *

- * @param slaveId a int. - * @param offset a int. - * @param dataType a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator inputRegister(int slaveId, int offset, int dataType) { - return new NumericLocator(slaveId, RegisterRange.INPUT_REGISTER, offset, dataType); - } + /** + *

+ * inputRegister. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @param dataType a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator inputRegister(int slaveId, int offset, int dataType) { + return new NumericLocator(slaveId, RegisterRange.INPUT_REGISTER, offset, dataType); + } - /** - *

- * inputRegisterBit. - *

- * @param slaveId a int. - * @param offset a int. - * @param bit a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator inputRegisterBit(int slaveId, int offset, int bit) { - return new BinaryLocator(slaveId, RegisterRange.INPUT_REGISTER, offset, bit); - } + /** + *

+ * inputRegisterBit. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @param bit a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator inputRegisterBit(int slaveId, int offset, int bit) { + return new BinaryLocator(slaveId, RegisterRange.INPUT_REGISTER, offset, bit); + } - /** - *

- * holdingRegister. - *

- * @param slaveId a int. - * @param offset a int. - * @param dataType a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator holdingRegister(int slaveId, int offset, int dataType) { - return new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, offset, dataType); - } + /** + *

+ * holdingRegister. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @param dataType a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator holdingRegister(int slaveId, int offset, int dataType) { + return new NumericLocator(slaveId, RegisterRange.HOLDING_REGISTER, offset, dataType); + } - /** - *

- * holdingRegisterBit. - *

- * @param slaveId a int. - * @param offset a int. - * @param bit a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator holdingRegisterBit(int slaveId, int offset, int bit) { - return new BinaryLocator(slaveId, RegisterRange.HOLDING_REGISTER, offset, bit); - } + /** + *

+ * holdingRegisterBit. + *

+ * + * @param slaveId a int. + * @param offset a int. + * @param bit a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator holdingRegisterBit(int slaveId, int offset, int bit) { + return new BinaryLocator(slaveId, RegisterRange.HOLDING_REGISTER, offset, bit); + } - /** - *

- * createLocator. - *

- * @param slaveId a int. - * @param registerId a int. - * @param dataType a int. - * @param bit a int. - * @param registerCount a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator createLocator(int slaveId, int registerId, int dataType, int bit, int registerCount) { - RangeAndOffset rao = new RangeAndOffset(registerId); - return createLocator(slaveId, rao.getRange(), rao.getOffset(), dataType, bit, registerCount, - StringLocator.ASCII); - } + /** + *

+ * createLocator. + *

+ * + * @param slaveId a int. + * @param registerId a int. + * @param dataType a int. + * @param bit a int. + * @param registerCount a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator createLocator(int slaveId, int registerId, int dataType, int bit, int registerCount) { + RangeAndOffset rao = new RangeAndOffset(registerId); + return createLocator(slaveId, rao.getRange(), rao.getOffset(), dataType, bit, registerCount, + StringLocator.ASCII); + } - /** - *

- * createLocator. - *

- * @param slaveId a int. - * @param registerId a int. - * @param dataType a int. - * @param bit a int. - * @param registerCount a int. - * @param charset a {@link Charset} object. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator createLocator(int slaveId, int registerId, int dataType, int bit, int registerCount, - Charset charset) { - RangeAndOffset rao = new RangeAndOffset(registerId); - return createLocator(slaveId, rao.getRange(), rao.getOffset(), dataType, bit, registerCount, charset); - } + /** + *

+ * createLocator. + *

+ * + * @param slaveId a int. + * @param registerId a int. + * @param dataType a int. + * @param bit a int. + * @param registerCount a int. + * @param charset a {@link Charset} object. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator createLocator(int slaveId, int registerId, int dataType, int bit, int registerCount, + Charset charset) { + RangeAndOffset rao = new RangeAndOffset(registerId); + return createLocator(slaveId, rao.getRange(), rao.getOffset(), dataType, bit, registerCount, charset); + } - /** - *

- * createLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param bit a int. - * @param registerCount a int. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator createLocator(int slaveId, int range, int offset, int dataType, int bit, - int registerCount) { - return createLocator(slaveId, range, offset, dataType, bit, registerCount, StringLocator.ASCII); - } + /** + *

+ * createLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param bit a int. + * @param registerCount a int. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator createLocator(int slaveId, int range, int offset, int dataType, int bit, + int registerCount) { + return createLocator(slaveId, range, offset, dataType, bit, registerCount, StringLocator.ASCII); + } - /** - *

- * createLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param bit a int. - * @param registerCount a int. - * @param charset a {@link Charset} object. - * @return a {@link BaseLocator} object. - */ - public static BaseLocator createLocator(int slaveId, int range, int offset, int dataType, int bit, - int registerCount, Charset charset) { - if (dataType == DataType.BINARY) { - if (BinaryLocator.isBinaryRange(range)) - return new BinaryLocator(slaveId, range, offset); - return new BinaryLocator(slaveId, range, offset, bit); - } - if (dataType == DataType.CHAR || dataType == DataType.VARCHAR) - return new StringLocator(slaveId, range, offset, dataType, registerCount, charset); - return new NumericLocator(slaveId, range, offset, dataType); - } + /** + *

+ * createLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param bit a int. + * @param registerCount a int. + * @param charset a {@link Charset} object. + * @return a {@link BaseLocator} object. + */ + public static BaseLocator createLocator(int slaveId, int range, int offset, int dataType, int bit, + int registerCount, Charset charset) { + if (dataType == DataType.BINARY) { + if (BinaryLocator.isBinaryRange(range)) + return new BinaryLocator(slaveId, range, offset); + return new BinaryLocator(slaveId, range, offset, bit); + } + if (dataType == DataType.CHAR || dataType == DataType.VARCHAR) + return new StringLocator(slaveId, range, offset, dataType, registerCount, charset); + return new NumericLocator(slaveId, range, offset, dataType); + } - /** - *

- * validate. - *

- * @param registerCount a int. - */ - protected void validate(int registerCount) { - try { - ModbusUtils.validateOffset(offset); - ModbusUtils.validateEndOffset(offset + registerCount - 1); - } - catch (ModbusTransportException e) { - throw new ModbusIdException(e); - } - } + /** + *

+ * validate. + *

+ * + * @param registerCount a int. + */ + protected void validate(int registerCount) { + try { + ModbusUtils.validateOffset(offset); + ModbusUtils.validateEndOffset(offset + registerCount - 1); + } catch (ModbusTransportException e) { + throw new ModbusIdException(e); + } + } - /** - *

- * getDataType. - *

- * @return a int. - */ - abstract public int getDataType(); + /** + *

+ * getDataType. + *

+ * + * @return a int. + */ + abstract public int getDataType(); - /** - *

- * getRegisterCount. - *

- * @return a int. - */ - abstract public int getRegisterCount(); + /** + *

+ * getRegisterCount. + *

+ * + * @return a int. + */ + abstract public int getRegisterCount(); - /** - *

- * Getter for the field slaveId. - *

- * @return a int. - */ - public int getSlaveId() { - return slaveId; - } + /** + *

+ * Getter for the field slaveId. + *

+ * + * @return a int. + */ + public int getSlaveId() { + return slaveId; + } - /** - *

- * Getter for the field range. - *

- * @return a int. - */ - public int getRange() { - return range; - } + /** + *

+ * Getter for the field range. + *

+ * + * @return a int. + */ + public int getRange() { + return range; + } - /** - *

- * Getter for the field offset. - *

- * @return a int. - */ - public int getOffset() { - return offset; - } + /** + *

+ * Getter for the field offset. + *

+ * + * @return a int. + */ + public int getOffset() { + return offset; + } - // public SlaveAndRange getSlaveAndRange() { - // return slaveAndRange; - // } + // public SlaveAndRange getSlaveAndRange() { + // return slaveAndRange; + // } - /** - *

- * getEndOffset. - *

- * @return a int. - */ - public int getEndOffset() { - return offset + getRegisterCount() - 1; - } + /** + *

+ * getEndOffset. + *

+ * + * @return a int. + */ + public int getEndOffset() { + return offset + getRegisterCount() - 1; + } - /** - *

- * bytesToValue. - *

- * @param data an array of {@link byte} objects. - * @param requestOffset a int. - * @return a T object. - */ - public T bytesToValue(byte[] data, int requestOffset) { - // Determined the offset normalized to the response data. - return bytesToValueRealOffset(data, offset - requestOffset); - } + /** + *

+ * bytesToValue. + *

+ * + * @param data an array of {@link byte} objects. + * @param requestOffset a int. + * @return a T object. + */ + public T bytesToValue(byte[] data, int requestOffset) { + // Determined the offset normalized to the response data. + return bytesToValueRealOffset(data, offset - requestOffset); + } - /** - *

- * bytesToValueRealOffset. - *

- * @param data an array of {@link byte} objects. - * @param offset a int. - * @return a T object. - */ - abstract public T bytesToValueRealOffset(byte[] data, int offset); + /** + *

+ * bytesToValueRealOffset. + *

+ * + * @param data an array of {@link byte} objects. + * @param offset a int. + * @return a T object. + */ + abstract public T bytesToValueRealOffset(byte[] data, int offset); - /** - *

- * valueToShorts. - *

- * @param value a T object. - * @return an array of {@link short} objects. - */ - abstract public short[] valueToShorts(T value); + /** + *

+ * valueToShorts. + *

+ * + * @param value a T object. + * @return an array of {@link short} objects. + */ + abstract public short[] valueToShorts(T value); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BinaryLocator.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BinaryLocator.java index a0c1ce4b0..13fd5386f 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BinaryLocator.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/BinaryLocator.java @@ -33,106 +33,110 @@ import com.serotonin.modbus4j.sero.NotImplementedException; */ public class BinaryLocator extends BaseLocator { - private int bit = -1; + private int bit = -1; - /** - *

- * Constructor for BinaryLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - */ - public BinaryLocator(int slaveId, int range, int offset) { - super(slaveId, range, offset); - if (!isBinaryRange(range)) - throw new ModbusIdException("Non-bit requests can only be made from coil status and input status ranges"); - validate(); - } + /** + *

+ * Constructor for BinaryLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + */ + public BinaryLocator(int slaveId, int range, int offset) { + super(slaveId, range, offset); + if (!isBinaryRange(range)) + throw new ModbusIdException("Non-bit requests can only be made from coil status and input status ranges"); + validate(); + } - /** - *

- * Constructor for BinaryLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param bit a int. - */ - public BinaryLocator(int slaveId, int range, int offset, int bit) { - super(slaveId, range, offset); - if (isBinaryRange(range)) - throw new ModbusIdException("Bit requests can only be made from holding registers and input registers"); - this.bit = bit; - validate(); - } + /** + *

+ * Constructor for BinaryLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param bit a int. + */ + public BinaryLocator(int slaveId, int range, int offset, int bit) { + super(slaveId, range, offset); + if (isBinaryRange(range)) + throw new ModbusIdException("Bit requests can only be made from holding registers and input registers"); + this.bit = bit; + validate(); + } - /** - *

- * isBinaryRange. - *

- * @param range a int. - * @return a boolean. - */ - public static boolean isBinaryRange(int range) { - return range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS; - } + /** + *

+ * isBinaryRange. + *

+ * + * @param range a int. + * @return a boolean. + */ + public static boolean isBinaryRange(int range) { + return range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS; + } - /** - *

- * validate. - *

- */ - protected void validate() { - super.validate(1); + /** + *

+ * validate. + *

+ */ + protected void validate() { + super.validate(1); - if (!isBinaryRange(range)) - ModbusUtils.validateBit(bit); - } + if (!isBinaryRange(range)) + ModbusUtils.validateBit(bit); + } - /** - *

- * Getter for the field bit. - *

- * @return a int. - */ - public int getBit() { - return bit; - } + /** + *

+ * Getter for the field bit. + *

+ * + * @return a int. + */ + public int getBit() { + return bit; + } - @Override - public int getDataType() { - return DataType.BINARY; - } + @Override + public int getDataType() { + return DataType.BINARY; + } - @Override - public int getRegisterCount() { - return 1; - } + @Override + public int getRegisterCount() { + return 1; + } - @Override - public String toString() { - return "BinaryLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", bit=" + bit - + ")"; - } + @Override + public String toString() { + return "BinaryLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", bit=" + bit + + ")"; + } - @Override - public Boolean bytesToValueRealOffset(byte[] data, int offset) { - // If this is a coil or input, convert to boolean. - if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) - return (((data[offset / 8] & 0xff) >> (offset % 8)) & 0x1) == 1; + @Override + public Boolean bytesToValueRealOffset(byte[] data, int offset) { + // If this is a coil or input, convert to boolean. + if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) + return (((data[offset / 8] & 0xff) >> (offset % 8)) & 0x1) == 1; - // For the rest of the types, we double the normalized offset to account for short - // to byte. - offset *= 2; + // For the rest of the types, we double the normalized offset to account for short + // to byte. + offset *= 2; - // We could still be asking for a binary if it's a bit in a register. - return (((data[offset + 1 - bit / 8] & 0xff) >> (bit % 8)) & 0x1) == 1; - } + // We could still be asking for a binary if it's a bit in a register. + return (((data[offset + 1 - bit / 8] & 0xff) >> (bit % 8)) & 0x1) == 1; + } - @Override - public short[] valueToShorts(Boolean value) { - throw new NotImplementedException(); - } + @Override + public short[] valueToShorts(Boolean value) { + throw new NotImplementedException(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/NumericLocator.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/NumericLocator.java index 52abd0ab2..4fa3f860a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/NumericLocator.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/NumericLocator.java @@ -36,449 +36,452 @@ import java.util.Arrays; */ public class NumericLocator extends BaseLocator { - private static final int[] DATA_TYPES = { // - DataType.TWO_BYTE_INT_UNSIGNED, // - DataType.TWO_BYTE_INT_SIGNED, // - DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED, // - DataType.TWO_BYTE_INT_SIGNED_SWAPPED, // - DataType.FOUR_BYTE_INT_UNSIGNED, // - DataType.FOUR_BYTE_INT_SIGNED, // - DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED, // - DataType.FOUR_BYTE_INT_SIGNED_SWAPPED, // - DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED, // - DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED, // - DataType.FOUR_BYTE_FLOAT, // - DataType.FOUR_BYTE_FLOAT_SWAPPED, // - DataType.EIGHT_BYTE_INT_UNSIGNED, // - DataType.EIGHT_BYTE_INT_SIGNED, // - DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED, // - DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED, // - DataType.EIGHT_BYTE_FLOAT, // - DataType.EIGHT_BYTE_FLOAT_SWAPPED, // - DataType.TWO_BYTE_BCD, // - DataType.FOUR_BYTE_BCD, // - DataType.FOUR_BYTE_BCD_SWAPPED, // - DataType.FOUR_BYTE_MOD_10K, // - DataType.FOUR_BYTE_MOD_10K_SWAPPED, // - DataType.SIX_BYTE_MOD_10K, DataType.SIX_BYTE_MOD_10K_SWAPPED, DataType.EIGHT_BYTE_MOD_10K, // - DataType.EIGHT_BYTE_MOD_10K_SWAPPED, // - DataType.ONE_BYTE_INT_UNSIGNED_LOWER, // - DataType.ONE_BYTE_INT_UNSIGNED_UPPER }; + private static final int[] DATA_TYPES = { // + DataType.TWO_BYTE_INT_UNSIGNED, // + DataType.TWO_BYTE_INT_SIGNED, // + DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED, // + DataType.TWO_BYTE_INT_SIGNED_SWAPPED, // + DataType.FOUR_BYTE_INT_UNSIGNED, // + DataType.FOUR_BYTE_INT_SIGNED, // + DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED, // + DataType.FOUR_BYTE_INT_SIGNED_SWAPPED, // + DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED, // + DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED, // + DataType.FOUR_BYTE_FLOAT, // + DataType.FOUR_BYTE_FLOAT_SWAPPED, // + DataType.EIGHT_BYTE_INT_UNSIGNED, // + DataType.EIGHT_BYTE_INT_SIGNED, // + DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED, // + DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED, // + DataType.EIGHT_BYTE_FLOAT, // + DataType.EIGHT_BYTE_FLOAT_SWAPPED, // + DataType.TWO_BYTE_BCD, // + DataType.FOUR_BYTE_BCD, // + DataType.FOUR_BYTE_BCD_SWAPPED, // + DataType.FOUR_BYTE_MOD_10K, // + DataType.FOUR_BYTE_MOD_10K_SWAPPED, // + DataType.SIX_BYTE_MOD_10K, DataType.SIX_BYTE_MOD_10K_SWAPPED, DataType.EIGHT_BYTE_MOD_10K, // + DataType.EIGHT_BYTE_MOD_10K_SWAPPED, // + DataType.ONE_BYTE_INT_UNSIGNED_LOWER, // + DataType.ONE_BYTE_INT_UNSIGNED_UPPER}; - private final int dataType; + private final int dataType; - private RoundingMode roundingMode = RoundingMode.HALF_UP; + private RoundingMode roundingMode = RoundingMode.HALF_UP; - /** - *

- * Constructor for NumericLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param dataType a int. - */ - public NumericLocator(int slaveId, int range, int offset, int dataType) { - super(slaveId, range, offset); - this.dataType = dataType; - validate(); - } + /** + *

+ * Constructor for NumericLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param dataType a int. + */ + public NumericLocator(int slaveId, int range, int offset, int dataType) { + super(slaveId, range, offset); + this.dataType = dataType; + validate(); + } - private static void appendBCD(StringBuilder sb, byte b) { - sb.append(bcdNibbleToInt(b, true)); - sb.append(bcdNibbleToInt(b, false)); - } + private static void appendBCD(StringBuilder sb, byte b) { + sb.append(bcdNibbleToInt(b, true)); + sb.append(bcdNibbleToInt(b, false)); + } - private static int bcdNibbleToInt(byte b, boolean high) { - int n; - if (high) - n = (b >> 4) & 0xf; - else - n = b & 0xf; - if (n > 9) - n = 0; - return n; - } + private static int bcdNibbleToInt(byte b, boolean high) { + int n; + if (high) + n = (b >> 4) & 0xf; + else + n = b & 0xf; + if (n > 9) + n = 0; + return n; + } - private void validate() { - super.validate(getRegisterCount()); + private void validate() { + super.validate(getRegisterCount()); - if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) - throw new IllegalDataTypeException("Only binary values can be read from Coil and Input ranges"); - boolean b = Arrays.stream(DATA_TYPES).anyMatch(dt -> dt == dataType); - if (!b) - throw new IllegalDataTypeException("Invalid data type"); - } + if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) + throw new IllegalDataTypeException("Only binary values can be read from Coil and Input ranges"); + boolean b = Arrays.stream(DATA_TYPES).anyMatch(dt -> dt == dataType); + if (!b) + throw new IllegalDataTypeException("Invalid data type"); + } - @Override - public int getDataType() { - return dataType; - } + @Override + public int getDataType() { + return dataType; + } - /** - *

- * Getter for the field roundingMode. - *

- * @return a {@link RoundingMode} object. - */ - public RoundingMode getRoundingMode() { - return roundingMode; - } + /** + *

+ * Getter for the field roundingMode. + *

+ * + * @return a {@link RoundingMode} object. + */ + public RoundingMode getRoundingMode() { + return roundingMode; + } - /** - *

- * Setter for the field roundingMode. - *

- * @param roundingMode a {@link RoundingMode} object. - */ - public void setRoundingMode(RoundingMode roundingMode) { - this.roundingMode = roundingMode; - } + /** + *

+ * Setter for the field roundingMode. + *

+ * + * @param roundingMode a {@link RoundingMode} object. + */ + public void setRoundingMode(RoundingMode roundingMode) { + this.roundingMode = roundingMode; + } - @Override - public String toString() { - return "NumericLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", dataType=" - + dataType + ")"; - } + @Override + public String toString() { + return "NumericLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", dataType=" + + dataType + ")"; + } - @Override - public int getRegisterCount() { - switch (dataType) { - case DataType.TWO_BYTE_INT_UNSIGNED: - case DataType.TWO_BYTE_INT_SIGNED: - case DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED: - case DataType.TWO_BYTE_INT_SIGNED_SWAPPED: - case DataType.TWO_BYTE_BCD: - case DataType.ONE_BYTE_INT_UNSIGNED_LOWER: - case DataType.ONE_BYTE_INT_UNSIGNED_UPPER: - return 1; - case DataType.FOUR_BYTE_INT_UNSIGNED: - case DataType.FOUR_BYTE_INT_SIGNED: - case DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED: - case DataType.FOUR_BYTE_INT_SIGNED_SWAPPED: - case DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: - case DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: - case DataType.FOUR_BYTE_FLOAT: - case DataType.FOUR_BYTE_FLOAT_SWAPPED: - case DataType.FOUR_BYTE_BCD: - case DataType.FOUR_BYTE_BCD_SWAPPED: - case DataType.FOUR_BYTE_MOD_10K: - case DataType.FOUR_BYTE_MOD_10K_SWAPPED: - return 2; - case DataType.SIX_BYTE_MOD_10K: - case DataType.SIX_BYTE_MOD_10K_SWAPPED: - return 3; - case DataType.EIGHT_BYTE_INT_UNSIGNED: - case DataType.EIGHT_BYTE_INT_SIGNED: - case DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED: - case DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED: - case DataType.EIGHT_BYTE_FLOAT: - case DataType.EIGHT_BYTE_FLOAT_SWAPPED: - case DataType.EIGHT_BYTE_MOD_10K: - case DataType.EIGHT_BYTE_MOD_10K_SWAPPED: - return 4; - } + @Override + public int getRegisterCount() { + switch (dataType) { + case DataType.TWO_BYTE_INT_UNSIGNED: + case DataType.TWO_BYTE_INT_SIGNED: + case DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED: + case DataType.TWO_BYTE_INT_SIGNED_SWAPPED: + case DataType.TWO_BYTE_BCD: + case DataType.ONE_BYTE_INT_UNSIGNED_LOWER: + case DataType.ONE_BYTE_INT_UNSIGNED_UPPER: + return 1; + case DataType.FOUR_BYTE_INT_UNSIGNED: + case DataType.FOUR_BYTE_INT_SIGNED: + case DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED: + case DataType.FOUR_BYTE_INT_SIGNED_SWAPPED: + case DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED: + case DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED: + case DataType.FOUR_BYTE_FLOAT: + case DataType.FOUR_BYTE_FLOAT_SWAPPED: + case DataType.FOUR_BYTE_BCD: + case DataType.FOUR_BYTE_BCD_SWAPPED: + case DataType.FOUR_BYTE_MOD_10K: + case DataType.FOUR_BYTE_MOD_10K_SWAPPED: + return 2; + case DataType.SIX_BYTE_MOD_10K: + case DataType.SIX_BYTE_MOD_10K_SWAPPED: + return 3; + case DataType.EIGHT_BYTE_INT_UNSIGNED: + case DataType.EIGHT_BYTE_INT_SIGNED: + case DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED: + case DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED: + case DataType.EIGHT_BYTE_FLOAT: + case DataType.EIGHT_BYTE_FLOAT_SWAPPED: + case DataType.EIGHT_BYTE_MOD_10K: + case DataType.EIGHT_BYTE_MOD_10K_SWAPPED: + return 4; + } - throw new RuntimeException("Unsupported data type: " + dataType); - } + throw new RuntimeException("Unsupported data type: " + dataType); + } - @Override - public Number bytesToValueRealOffset(byte[] data, int offset) { - offset *= 2; + @Override + public Number bytesToValueRealOffset(byte[] data, int offset) { + offset *= 2; - // 2 bytes - if (dataType == DataType.TWO_BYTE_INT_UNSIGNED) - return ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff); + // 2 bytes + if (dataType == DataType.TWO_BYTE_INT_UNSIGNED) + return ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff); - if (dataType == DataType.TWO_BYTE_INT_SIGNED) - return (short) (((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff)); + if (dataType == DataType.TWO_BYTE_INT_SIGNED) + return (short) (((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff)); - if (dataType == DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED) - return ((data[offset + 1] & 0xff) << 8) | (data[offset] & 0xff); + if (dataType == DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED) + return ((data[offset + 1] & 0xff) << 8) | (data[offset] & 0xff); - if (dataType == DataType.TWO_BYTE_INT_SIGNED_SWAPPED) - return (short) (((data[offset + 1] & 0xff) << 8) | (data[offset] & 0xff)); + if (dataType == DataType.TWO_BYTE_INT_SIGNED_SWAPPED) + return (short) (((data[offset + 1] & 0xff) << 8) | (data[offset] & 0xff)); - if (dataType == DataType.TWO_BYTE_BCD) { - StringBuilder sb = new StringBuilder(); - appendBCD(sb, data[offset]); - appendBCD(sb, data[offset + 1]); - return Short.parseShort(sb.toString()); - } + if (dataType == DataType.TWO_BYTE_BCD) { + StringBuilder sb = new StringBuilder(); + appendBCD(sb, data[offset]); + appendBCD(sb, data[offset + 1]); + return Short.parseShort(sb.toString()); + } - // 1 byte - if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_LOWER) - return data[offset + 1] & 0xff; - if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_UPPER) - return data[offset] & 0xff; + // 1 byte + if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_LOWER) + return data[offset + 1] & 0xff; + if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_UPPER) + return data[offset] & 0xff; - // 4 bytes - if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED) - return (long) ((data[offset] & 0xff)) << 24 | ((long) ((data[offset + 1] & 0xff)) << 16) - | ((long) ((data[offset + 2] & 0xff)) << 8) | ((data[offset + 3] & 0xff)); + // 4 bytes + if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED) + return (long) ((data[offset] & 0xff)) << 24 | ((long) ((data[offset + 1] & 0xff)) << 16) + | ((long) ((data[offset + 2] & 0xff)) << 8) | ((data[offset + 3] & 0xff)); - if (dataType == DataType.FOUR_BYTE_INT_SIGNED) - return ((data[offset] & 0xff) << 24) | ((data[offset + 1] & 0xff) << 16) | ((data[offset + 2] & 0xff) << 8) - | (data[offset + 3] & 0xff); + if (dataType == DataType.FOUR_BYTE_INT_SIGNED) + return ((data[offset] & 0xff) << 24) | ((data[offset + 1] & 0xff) << 16) | ((data[offset + 2] & 0xff) << 8) + | (data[offset + 3] & 0xff); - if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED) - return ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) - | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff)); + if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED) + return ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) + | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff)); - if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED) - return ((data[offset + 2] & 0xff) << 24) | ((data[offset + 3] & 0xff) << 16) | ((data[offset] & 0xff) << 8) - | (data[offset + 1] & 0xff); + if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED) + return ((data[offset + 2] & 0xff) << 24) | ((data[offset + 3] & 0xff) << 16) | ((data[offset] & 0xff) << 8) + | (data[offset + 1] & 0xff); - if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED) - return ((long) ((data[offset + 3] & 0xff)) << 24) | (((data[offset + 2] & 0xff) << 16)) - | ((long) ((data[offset + 1] & 0xff)) << 8) | (data[offset] & 0xff); + if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED) + return ((long) ((data[offset + 3] & 0xff)) << 24) | (((data[offset + 2] & 0xff) << 16)) + | ((long) ((data[offset + 1] & 0xff)) << 8) | (data[offset] & 0xff); - if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED) - return ((data[offset + 3] & 0xff) << 24) | ((data[offset + 2] & 0xff) << 16) - | ((data[offset + 1] & 0xff) << 8) | ((data[offset] & 0xff)); + if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED) + return ((data[offset + 3] & 0xff) << 24) | ((data[offset + 2] & 0xff) << 16) + | ((data[offset + 1] & 0xff) << 8) | ((data[offset] & 0xff)); - if (dataType == DataType.FOUR_BYTE_FLOAT) - return Float.intBitsToFloat(((data[offset] & 0xff) << 24) | ((data[offset + 1] & 0xff) << 16) - | ((data[offset + 2] & 0xff) << 8) | (data[offset + 3] & 0xff)); + if (dataType == DataType.FOUR_BYTE_FLOAT) + return Float.intBitsToFloat(((data[offset] & 0xff) << 24) | ((data[offset + 1] & 0xff) << 16) + | ((data[offset + 2] & 0xff) << 8) | (data[offset + 3] & 0xff)); - if (dataType == DataType.FOUR_BYTE_FLOAT_SWAPPED) - return Float.intBitsToFloat(((data[offset + 2] & 0xff) << 24) | ((data[offset + 3] & 0xff) << 16) - | ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff)); + if (dataType == DataType.FOUR_BYTE_FLOAT_SWAPPED) + return Float.intBitsToFloat(((data[offset + 2] & 0xff) << 24) | ((data[offset + 3] & 0xff) << 16) + | ((data[offset] & 0xff) << 8) | (data[offset + 1] & 0xff)); - if (dataType == DataType.FOUR_BYTE_BCD) { - StringBuilder sb = new StringBuilder(); - appendBCD(sb, data[offset]); - appendBCD(sb, data[offset + 1]); - appendBCD(sb, data[offset + 2]); - appendBCD(sb, data[offset + 3]); - return Integer.parseInt(sb.toString()); - } + if (dataType == DataType.FOUR_BYTE_BCD) { + StringBuilder sb = new StringBuilder(); + appendBCD(sb, data[offset]); + appendBCD(sb, data[offset + 1]); + appendBCD(sb, data[offset + 2]); + appendBCD(sb, data[offset + 3]); + return Integer.parseInt(sb.toString()); + } - if (dataType == DataType.FOUR_BYTE_BCD_SWAPPED) { - StringBuilder sb = new StringBuilder(); - appendBCD(sb, data[offset + 2]); - appendBCD(sb, data[offset + 3]); - appendBCD(sb, data[offset]); - appendBCD(sb, data[offset + 1]); - return Integer.parseInt(sb.toString()); - } + if (dataType == DataType.FOUR_BYTE_BCD_SWAPPED) { + StringBuilder sb = new StringBuilder(); + appendBCD(sb, data[offset + 2]); + appendBCD(sb, data[offset + 3]); + appendBCD(sb, data[offset]); + appendBCD(sb, data[offset + 1]); + return Integer.parseInt(sb.toString()); + } - // MOD10K types - if (dataType == DataType.FOUR_BYTE_MOD_10K_SWAPPED) - return BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) - .multiply(BigInteger.valueOf(10000L)) - .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); - if (dataType == DataType.FOUR_BYTE_MOD_10K) - return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) - .multiply(BigInteger.valueOf(10000L)) - .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff)))); - if (dataType == DataType.SIX_BYTE_MOD_10K_SWAPPED) - return BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) - .multiply(BigInteger.valueOf(100000000L)) - .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) - .multiply(BigInteger.valueOf(10000L))) - .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); - if (dataType == DataType.SIX_BYTE_MOD_10K) - return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) - .multiply(BigInteger.valueOf(100000000L)) - .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) - .multiply(BigInteger.valueOf(10000L))) - .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff)))); - if (dataType == DataType.EIGHT_BYTE_MOD_10K_SWAPPED) - return BigInteger.valueOf((((data[offset + 6] & 0xff) << 8) + (data[offset + 7] & 0xff))) - .multiply(BigInteger.valueOf(1000000000000L)) - .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) - .multiply(BigInteger.valueOf(100000000L))) - .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) - .multiply(BigInteger.valueOf(10000L))) - .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); - if (dataType == DataType.EIGHT_BYTE_MOD_10K) - return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) - .multiply(BigInteger.valueOf(1000000000000L)) - .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) - .multiply(BigInteger.valueOf(100000000L))) - .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) - .multiply(BigInteger.valueOf(10000L))) - .add(BigInteger.valueOf((((data[offset + 6] & 0xff) << 8) + (data[offset + 7] & 0xff)))); + // MOD10K types + if (dataType == DataType.FOUR_BYTE_MOD_10K_SWAPPED) + return BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) + .multiply(BigInteger.valueOf(10000L)) + .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); + if (dataType == DataType.FOUR_BYTE_MOD_10K) + return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) + .multiply(BigInteger.valueOf(10000L)) + .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff)))); + if (dataType == DataType.SIX_BYTE_MOD_10K_SWAPPED) + return BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) + .multiply(BigInteger.valueOf(100000000L)) + .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) + .multiply(BigInteger.valueOf(10000L))) + .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); + if (dataType == DataType.SIX_BYTE_MOD_10K) + return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) + .multiply(BigInteger.valueOf(100000000L)) + .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) + .multiply(BigInteger.valueOf(10000L))) + .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff)))); + if (dataType == DataType.EIGHT_BYTE_MOD_10K_SWAPPED) + return BigInteger.valueOf((((data[offset + 6] & 0xff) << 8) + (data[offset + 7] & 0xff))) + .multiply(BigInteger.valueOf(1000000000000L)) + .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) + .multiply(BigInteger.valueOf(100000000L))) + .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) + .multiply(BigInteger.valueOf(10000L))) + .add(BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff)))); + if (dataType == DataType.EIGHT_BYTE_MOD_10K) + return BigInteger.valueOf((((data[offset] & 0xff) << 8) + (data[offset + 1] & 0xff))) + .multiply(BigInteger.valueOf(1000000000000L)) + .add(BigInteger.valueOf((((data[offset + 2] & 0xff) << 8) + (data[offset + 3] & 0xff))) + .multiply(BigInteger.valueOf(100000000L))) + .add(BigInteger.valueOf((((data[offset + 4] & 0xff) << 8) + (data[offset + 5] & 0xff))) + .multiply(BigInteger.valueOf(10000L))) + .add(BigInteger.valueOf((((data[offset + 6] & 0xff) << 8) + (data[offset + 7] & 0xff)))); - // 8 bytes - if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED) { - byte[] b9 = new byte[9]; - System.arraycopy(data, offset, b9, 1, 8); - return new BigInteger(b9); - } + // 8 bytes + if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED) { + byte[] b9 = new byte[9]; + System.arraycopy(data, offset, b9, 1, 8); + return new BigInteger(b9); + } - if (dataType == DataType.EIGHT_BYTE_INT_SIGNED) - return ((long) ((data[offset] & 0xff)) << 56) | ((long) ((data[offset + 1] & 0xff)) << 48) - | ((long) ((data[offset + 2] & 0xff)) << 40) | ((long) ((data[offset + 3] & 0xff)) << 32) - | ((long) ((data[offset + 4] & 0xff)) << 24) | ((long) ((data[offset + 5] & 0xff)) << 16) - | ((long) ((data[offset + 6] & 0xff)) << 8) | ((data[offset + 7] & 0xff)); + if (dataType == DataType.EIGHT_BYTE_INT_SIGNED) + return ((long) ((data[offset] & 0xff)) << 56) | ((long) ((data[offset + 1] & 0xff)) << 48) + | ((long) ((data[offset + 2] & 0xff)) << 40) | ((long) ((data[offset + 3] & 0xff)) << 32) + | ((long) ((data[offset + 4] & 0xff)) << 24) | ((long) ((data[offset + 5] & 0xff)) << 16) + | ((long) ((data[offset + 6] & 0xff)) << 8) | ((data[offset + 7] & 0xff)); - if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED) { - byte[] b9 = new byte[9]; - b9[1] = data[offset + 6]; - b9[2] = data[offset + 7]; - b9[3] = data[offset + 4]; - b9[4] = data[offset + 5]; - b9[5] = data[offset + 2]; - b9[6] = data[offset + 3]; - b9[7] = data[offset]; - b9[8] = data[offset + 1]; - return new BigInteger(b9); - } + if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED) { + byte[] b9 = new byte[9]; + b9[1] = data[offset + 6]; + b9[2] = data[offset + 7]; + b9[3] = data[offset + 4]; + b9[4] = data[offset + 5]; + b9[5] = data[offset + 2]; + b9[6] = data[offset + 3]; + b9[7] = data[offset]; + b9[8] = data[offset + 1]; + return new BigInteger(b9); + } - if (dataType == DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED) - return ((long) ((data[offset + 6] & 0xff)) << 56) | ((long) ((data[offset + 7] & 0xff)) << 48) - | ((long) ((data[offset + 4] & 0xff)) << 40) | ((long) ((data[offset + 5] & 0xff)) << 32) - | ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) - | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff)); + if (dataType == DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED) + return ((long) ((data[offset + 6] & 0xff)) << 56) | ((long) ((data[offset + 7] & 0xff)) << 48) + | ((long) ((data[offset + 4] & 0xff)) << 40) | ((long) ((data[offset + 5] & 0xff)) << 32) + | ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) + | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff)); - if (dataType == DataType.EIGHT_BYTE_FLOAT) - return Double - .longBitsToDouble(((long) ((data[offset] & 0xff)) << 56) | ((long) ((data[offset + 1] & 0xff)) << 48) - | ((long) ((data[offset + 2] & 0xff)) << 40) | ((long) ((data[offset + 3] & 0xff)) << 32) - | ((long) ((data[offset + 4] & 0xff)) << 24) | ((long) ((data[offset + 5] & 0xff)) << 16) - | ((long) ((data[offset + 6] & 0xff)) << 8) | ((data[offset + 7] & 0xff))); + if (dataType == DataType.EIGHT_BYTE_FLOAT) + return Double + .longBitsToDouble(((long) ((data[offset] & 0xff)) << 56) | ((long) ((data[offset + 1] & 0xff)) << 48) + | ((long) ((data[offset + 2] & 0xff)) << 40) | ((long) ((data[offset + 3] & 0xff)) << 32) + | ((long) ((data[offset + 4] & 0xff)) << 24) | ((long) ((data[offset + 5] & 0xff)) << 16) + | ((long) ((data[offset + 6] & 0xff)) << 8) | ((data[offset + 7] & 0xff))); - if (dataType == DataType.EIGHT_BYTE_FLOAT_SWAPPED) - return Double.longBitsToDouble( - ((long) ((data[offset + 6] & 0xff)) << 56) | ((long) ((data[offset + 7] & 0xff)) << 48) - | ((long) ((data[offset + 4] & 0xff)) << 40) | ((long) ((data[offset + 5] & 0xff)) << 32) - | ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) - | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff))); + if (dataType == DataType.EIGHT_BYTE_FLOAT_SWAPPED) + return Double.longBitsToDouble( + ((long) ((data[offset + 6] & 0xff)) << 56) | ((long) ((data[offset + 7] & 0xff)) << 48) + | ((long) ((data[offset + 4] & 0xff)) << 40) | ((long) ((data[offset + 5] & 0xff)) << 32) + | ((long) ((data[offset + 2] & 0xff)) << 24) | ((long) ((data[offset + 3] & 0xff)) << 16) + | ((long) ((data[offset] & 0xff)) << 8) | ((data[offset + 1] & 0xff))); - throw new RuntimeException("Unsupported data type: " + dataType); - } + throw new RuntimeException("Unsupported data type: " + dataType); + } - @Override - public short[] valueToShorts(Number value) { - // 2 bytes - if (dataType == DataType.TWO_BYTE_INT_UNSIGNED || dataType == DataType.TWO_BYTE_INT_SIGNED) - return new short[] { toShort(value) }; + @Override + public short[] valueToShorts(Number value) { + // 2 bytes + if (dataType == DataType.TWO_BYTE_INT_UNSIGNED || dataType == DataType.TWO_BYTE_INT_SIGNED) + return new short[]{toShort(value)}; - if (dataType == DataType.TWO_BYTE_INT_SIGNED_SWAPPED || dataType == DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED) { - short sval = toShort(value); - // 0x1100 - return new short[] { (short) (((sval & 0xFF00) >> 8) | ((sval & 0x00FF) << 8)) }; - } + if (dataType == DataType.TWO_BYTE_INT_SIGNED_SWAPPED || dataType == DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED) { + short sval = toShort(value); + // 0x1100 + return new short[]{(short) (((sval & 0xFF00) >> 8) | ((sval & 0x00FF) << 8))}; + } - if (dataType == DataType.TWO_BYTE_BCD) { - short s = toShort(value); - return new short[] { - (short) ((((s / 1000) % 10) << 12) | (((s / 100) % 10) << 8) | (((s / 10) % 10) << 4) | (s % 10)) }; - } + if (dataType == DataType.TWO_BYTE_BCD) { + short s = toShort(value); + return new short[]{ + (short) ((((s / 1000) % 10) << 12) | (((s / 100) % 10) << 8) | (((s / 10) % 10) << 4) | (s % 10))}; + } - if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_LOWER) { - return new short[] { (short) (toShort(value) & 0x00FF) }; - } - if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_UPPER) { - return new short[] { (short) ((toShort(value) << 8) & 0xFF00) }; - } + if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_LOWER) { + return new short[]{(short) (toShort(value) & 0x00FF)}; + } + if (dataType == DataType.ONE_BYTE_INT_UNSIGNED_UPPER) { + return new short[]{(short) ((toShort(value) << 8) & 0xFF00)}; + } - // 4 bytes - if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED || dataType == DataType.FOUR_BYTE_INT_SIGNED) { - int i = toInt(value); - return new short[] { (short) (i >> 16), (short) i }; - } + // 4 bytes + if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED || dataType == DataType.FOUR_BYTE_INT_SIGNED) { + int i = toInt(value); + return new short[]{(short) (i >> 16), (short) i}; + } - if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED || dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED) { - int i = toInt(value); - return new short[] { (short) i, (short) (i >> 16) }; - } + if (dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED || dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED) { + int i = toInt(value); + return new short[]{(short) i, (short) (i >> 16)}; + } - if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED - || dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED) { - int i = toInt(value); - short topWord = (short) (((i & 0xFF) << 8) | ((i >> 8) & 0xFF)); - short bottomWord = (short) (((i >> 24) & 0x000000FF) | ((i >> 8) & 0x0000FF00)); - return new short[] { topWord, bottomWord }; - } + if (dataType == DataType.FOUR_BYTE_INT_SIGNED_SWAPPED_SWAPPED + || dataType == DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED_SWAPPED) { + int i = toInt(value); + short topWord = (short) (((i & 0xFF) << 8) | ((i >> 8) & 0xFF)); + short bottomWord = (short) (((i >> 24) & 0x000000FF) | ((i >> 8) & 0x0000FF00)); + return new short[]{topWord, bottomWord}; + } - if (dataType == DataType.FOUR_BYTE_FLOAT) { - int i = Float.floatToIntBits(value.floatValue()); - return new short[] { (short) (i >> 16), (short) i }; - } + if (dataType == DataType.FOUR_BYTE_FLOAT) { + int i = Float.floatToIntBits(value.floatValue()); + return new short[]{(short) (i >> 16), (short) i}; + } - if (dataType == DataType.FOUR_BYTE_FLOAT_SWAPPED) { - int i = Float.floatToIntBits(value.floatValue()); - return new short[] { (short) i, (short) (i >> 16) }; - } + if (dataType == DataType.FOUR_BYTE_FLOAT_SWAPPED) { + int i = Float.floatToIntBits(value.floatValue()); + return new short[]{(short) i, (short) (i >> 16)}; + } - if (dataType == DataType.FOUR_BYTE_BCD) { - int i = toInt(value); - return new short[] { - (short) ((((i / 10000000) % 10) << 12) | (((i / 1000000) % 10) << 8) | (((i / 100000) % 10) << 4) - | ((i / 10000) % 10)), - (short) ((((i / 1000) % 10) << 12) | (((i / 100) % 10) << 8) | (((i / 10) % 10) << 4) | (i % 10)) }; - } + if (dataType == DataType.FOUR_BYTE_BCD) { + int i = toInt(value); + return new short[]{ + (short) ((((i / 10000000) % 10) << 12) | (((i / 1000000) % 10) << 8) | (((i / 100000) % 10) << 4) + | ((i / 10000) % 10)), + (short) ((((i / 1000) % 10) << 12) | (((i / 100) % 10) << 8) | (((i / 10) % 10) << 4) | (i % 10))}; + } - // MOD10K - if (dataType == DataType.FOUR_BYTE_MOD_10K) { - long l = value.longValue(); - return new short[] { (short) ((l / 10000) % 10000), (short) (l % 10000) }; - } - if (dataType == DataType.FOUR_BYTE_MOD_10K_SWAPPED) { - long l = value.longValue(); - return new short[] { (short) (l % 10000), (short) ((l / 10000) % 10000) }; - } - if (dataType == DataType.SIX_BYTE_MOD_10K) { - long l = value.longValue(); - return new short[] { (short) ((l / 100000000L) % 10000), (short) ((l / 10000) % 10000), - (short) (l % 10000) }; - } - if (dataType == DataType.SIX_BYTE_MOD_10K_SWAPPED) { - long l = value.longValue(); - return new short[] { (short) (l % 10000), (short) ((l / 10000) % 10000), - (short) ((l / 100000000L) % 10000) }; - } - if (dataType == DataType.EIGHT_BYTE_MOD_10K) { - long l = value.longValue(); - return new short[] { (short) ((l / 1000000000000L) % 10000), (short) ((l / 100000000L) % 10000), - (short) ((l / 10000) % 10000), (short) (l % 10000) }; - } - if (dataType == DataType.EIGHT_BYTE_MOD_10K_SWAPPED) { - long l = value.longValue(); - return new short[] { (short) (l % 10000), (short) ((l / 10000) % 10000), (short) ((l / 100000000L) % 10000), - (short) ((l / 1000000000000L) % 10000) }; - } + // MOD10K + if (dataType == DataType.FOUR_BYTE_MOD_10K) { + long l = value.longValue(); + return new short[]{(short) ((l / 10000) % 10000), (short) (l % 10000)}; + } + if (dataType == DataType.FOUR_BYTE_MOD_10K_SWAPPED) { + long l = value.longValue(); + return new short[]{(short) (l % 10000), (short) ((l / 10000) % 10000)}; + } + if (dataType == DataType.SIX_BYTE_MOD_10K) { + long l = value.longValue(); + return new short[]{(short) ((l / 100000000L) % 10000), (short) ((l / 10000) % 10000), + (short) (l % 10000)}; + } + if (dataType == DataType.SIX_BYTE_MOD_10K_SWAPPED) { + long l = value.longValue(); + return new short[]{(short) (l % 10000), (short) ((l / 10000) % 10000), + (short) ((l / 100000000L) % 10000)}; + } + if (dataType == DataType.EIGHT_BYTE_MOD_10K) { + long l = value.longValue(); + return new short[]{(short) ((l / 1000000000000L) % 10000), (short) ((l / 100000000L) % 10000), + (short) ((l / 10000) % 10000), (short) (l % 10000)}; + } + if (dataType == DataType.EIGHT_BYTE_MOD_10K_SWAPPED) { + long l = value.longValue(); + return new short[]{(short) (l % 10000), (short) ((l / 10000) % 10000), (short) ((l / 100000000L) % 10000), + (short) ((l / 1000000000000L) % 10000)}; + } - // 8 bytes - if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED || dataType == DataType.EIGHT_BYTE_INT_SIGNED) { - long l = value.longValue(); - return new short[] { (short) (l >> 48), (short) (l >> 32), (short) (l >> 16), (short) l }; - } + // 8 bytes + if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED || dataType == DataType.EIGHT_BYTE_INT_SIGNED) { + long l = value.longValue(); + return new short[]{(short) (l >> 48), (short) (l >> 32), (short) (l >> 16), (short) l}; + } - if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED - || dataType == DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED) { - long l = value.longValue(); - return new short[] { (short) l, (short) (l >> 16), (short) (l >> 32), (short) (l >> 48) }; - } + if (dataType == DataType.EIGHT_BYTE_INT_UNSIGNED_SWAPPED + || dataType == DataType.EIGHT_BYTE_INT_SIGNED_SWAPPED) { + long l = value.longValue(); + return new short[]{(short) l, (short) (l >> 16), (short) (l >> 32), (short) (l >> 48)}; + } - if (dataType == DataType.EIGHT_BYTE_FLOAT) { - long l = Double.doubleToLongBits(value.doubleValue()); - return new short[] { (short) (l >> 48), (short) (l >> 32), (short) (l >> 16), (short) l }; - } + if (dataType == DataType.EIGHT_BYTE_FLOAT) { + long l = Double.doubleToLongBits(value.doubleValue()); + return new short[]{(short) (l >> 48), (short) (l >> 32), (short) (l >> 16), (short) l}; + } - if (dataType == DataType.EIGHT_BYTE_FLOAT_SWAPPED) { - long l = Double.doubleToLongBits(value.doubleValue()); - return new short[] { (short) l, (short) (l >> 16), (short) (l >> 32), (short) (l >> 48) }; - } + if (dataType == DataType.EIGHT_BYTE_FLOAT_SWAPPED) { + long l = Double.doubleToLongBits(value.doubleValue()); + return new short[]{(short) l, (short) (l >> 16), (short) (l >> 32), (short) (l >> 48)}; + } - throw new RuntimeException("Unsupported data type: " + dataType); - } + throw new RuntimeException("Unsupported data type: " + dataType); + } - private short toShort(Number value) { - return (short) toInt(value); - } + private short toShort(Number value) { + return (short) toInt(value); + } - private int toInt(Number value) { - if (value instanceof Double) - return new BigDecimal(value.doubleValue()).setScale(0, roundingMode).intValue(); - if (value instanceof Float) - return new BigDecimal(value.floatValue()).setScale(0, roundingMode).intValue(); - if (value instanceof BigDecimal) - return ((BigDecimal) value).setScale(0, roundingMode).intValue(); - return value.intValue(); - } + private int toInt(Number value) { + if (value instanceof Double) + return new BigDecimal(value.doubleValue()).setScale(0, roundingMode).intValue(); + if (value instanceof Float) + return new BigDecimal(value.floatValue()).setScale(0, roundingMode).intValue(); + if (value instanceof BigDecimal) + return ((BigDecimal) value).setScale(0, roundingMode).intValue(); + return value.intValue(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/StringLocator.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/StringLocator.java index 8637ed0d5..194ff1be4 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/StringLocator.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/locator/StringLocator.java @@ -33,185 +33,184 @@ import java.nio.charset.Charset; */ public class StringLocator extends BaseLocator { - /** - * Constant ASCII - */ - public static final Charset ASCII = Charset.forName("ASCII"); + /** + * Constant ASCII + */ + public static final Charset ASCII = Charset.forName("ASCII"); - private final int dataType; + private final int dataType; - private final int registerCount; + private final int registerCount; - private final Charset charset; + private final Charset charset; - /** - *

- * Constructor for StringLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - */ - public StringLocator(int slaveId, int range, int offset, int dataType, int registerCount) { - this(slaveId, range, offset, dataType, registerCount, ASCII); - } + /** + *

+ * Constructor for StringLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + */ + public StringLocator(int slaveId, int range, int offset, int dataType, int registerCount) { + this(slaveId, range, offset, dataType, registerCount, ASCII); + } - /** - *

- * Constructor for StringLocator. - *

- * @param slaveId a int. - * @param range a int. - * @param offset a int. - * @param dataType a int. - * @param registerCount a int. - * @param charset a {@link Charset} object. - */ - public StringLocator(int slaveId, int range, int offset, int dataType, int registerCount, Charset charset) { - super(slaveId, range, offset); - this.dataType = dataType; - this.registerCount = registerCount; - this.charset = charset; - validate(); - } + /** + *

+ * Constructor for StringLocator. + *

+ * + * @param slaveId a int. + * @param range a int. + * @param offset a int. + * @param dataType a int. + * @param registerCount a int. + * @param charset a {@link Charset} object. + */ + public StringLocator(int slaveId, int range, int offset, int dataType, int registerCount, Charset charset) { + super(slaveId, range, offset); + this.dataType = dataType; + this.registerCount = registerCount; + this.charset = charset; + validate(); + } - private void validate() { - super.validate(registerCount); + private void validate() { + super.validate(registerCount); - if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) - throw new IllegalDataTypeException("Only binary values can be read from Coil and Input ranges"); + if (range == RegisterRange.COIL_STATUS || range == RegisterRange.INPUT_STATUS) + throw new IllegalDataTypeException("Only binary values can be read from Coil and Input ranges"); - if (dataType != DataType.CHAR && dataType != DataType.VARCHAR) - throw new IllegalDataTypeException("Invalid data type"); - } + if (dataType != DataType.CHAR && dataType != DataType.VARCHAR) + throw new IllegalDataTypeException("Invalid data type"); + } - @Override - public int getDataType() { - return dataType; - } + @Override + public int getDataType() { + return dataType; + } - @Override - public int getRegisterCount() { - return registerCount; - } + @Override + public int getRegisterCount() { + return registerCount; + } - @Override - public String toString() { - return "StringLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", dataType=" - + dataType + ", registerCount=" + registerCount + ", charset=" + charset + ")"; - } + @Override + public String toString() { + return "StringLocator(slaveId=" + getSlaveId() + ", range=" + range + ", offset=" + offset + ", dataType=" + + dataType + ", registerCount=" + registerCount + ", charset=" + charset + ")"; + } - @Override - public String bytesToValueRealOffset(byte[] data, int offset) { - offset *= 2; - int length = registerCount * 2; + @Override + public String bytesToValueRealOffset(byte[] data, int offset) { + offset *= 2; + int length = registerCount * 2; - if (dataType == DataType.CHAR) - return new String(data, offset, length, charset); + if (dataType == DataType.CHAR) + return new String(data, offset, length, charset); - if (dataType == DataType.VARCHAR) { - int nullPos = -1; - for (int i = offset; i < offset + length; i++) { - if (data[i] == 0) { - nullPos = i; - break; - } - } + if (dataType == DataType.VARCHAR) { + int nullPos = -1; + for (int i = offset; i < offset + length; i++) { + if (data[i] == 0) { + nullPos = i; + break; + } + } - if (nullPos == -1) - return new String(data, offset, length, charset); - return new String(data, offset, nullPos, charset); - } + if (nullPos == -1) + return new String(data, offset, length, charset); + return new String(data, offset, nullPos, charset); + } - throw new RuntimeException("Unsupported data type: " + dataType); - } + throw new RuntimeException("Unsupported data type: " + dataType); + } - @Override - public short[] valueToShorts(String value) { - short[] result = new short[registerCount]; - int resultByteLen = registerCount * 2; + @Override + public short[] valueToShorts(String value) { + short[] result = new short[registerCount]; + int resultByteLen = registerCount * 2; - int length; - if (value != null) { - byte[] bytes = value.getBytes(charset); + int length; + if (value != null) { + byte[] bytes = value.getBytes(charset); - length = resultByteLen; - if (length > bytes.length) - length = bytes.length; + length = resultByteLen; + if (length > bytes.length) + length = bytes.length; - for (int i = 0; i < length; i++) - setByte(result, i, bytes[i] & 0xff); - } - else - length = 0; + for (int i = 0; i < length; i++) + setByte(result, i, bytes[i] & 0xff); + } else + length = 0; - if (dataType == DataType.CHAR) { - // Pad the rest with spaces - for (int i = length; i < resultByteLen; i++) - setByte(result, i, 0x20); - } - else if (dataType == DataType.VARCHAR) { - if (length >= resultByteLen) - // Ensure the last byte is a null terminator. - result[registerCount - 1] &= 0xff00; - else { - // Pad the rest with null. - for (int i = length; i < resultByteLen; i++) - setByte(result, i, 0); - } - } - else - throw new RuntimeException("Unsupported data type: " + dataType); + if (dataType == DataType.CHAR) { + // Pad the rest with spaces + for (int i = length; i < resultByteLen; i++) + setByte(result, i, 0x20); + } else if (dataType == DataType.VARCHAR) { + if (length >= resultByteLen) + // Ensure the last byte is a null terminator. + result[registerCount - 1] &= 0xff00; + else { + // Pad the rest with null. + for (int i = length; i < resultByteLen; i++) + setByte(result, i, 0); + } + } else + throw new RuntimeException("Unsupported data type: " + dataType); - return result; - } + return result; + } - private void setByte(short[] s, int byteIndex, int value) { - if (byteIndex % 2 == 0) - s[byteIndex / 2] |= value << 8; - else - s[byteIndex / 2] |= value; - } - // - // public static void main(String[] args) { - // StringLocator l1 = new StringLocator(1, RegisterRange.HOLDING_REGISTER, 0, - // DataType.CHAR, 4); - // StringLocator l2 = new StringLocator(1, RegisterRange.HOLDING_REGISTER, 0, - // DataType.VARCHAR, 4); - // - // short[] s; - // - // s = l1.valueToShorts("abcdefg"); - // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); - // - // s = l1.valueToShorts("abcdefgh"); - // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); - // - // s = l1.valueToShorts("abcdefghi"); - // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); - // - // s = l2.valueToShorts("abcdef"); - // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); - // - // s = l2.valueToShorts("abcdefg"); - // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); - // - // s = l2.valueToShorts("abcdefgh"); - // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); - // - // s = l2.valueToShorts("abcdefghi"); - // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); - // } - // - // private static byte[] toBytes(short[] s) { - // byte[] b = new byte[s.length * 2]; - // for (int i = 0; i < s.length; i++) { - // b[i * 2] = (byte) ((s[i] >> 8) & 0xff); - // b[i * 2 + 1] = (byte) (s[i] & 0xff); - // } - // return b; - // } + private void setByte(short[] s, int byteIndex, int value) { + if (byteIndex % 2 == 0) + s[byteIndex / 2] |= value << 8; + else + s[byteIndex / 2] |= value; + } + // + // public static void main(String[] args) { + // StringLocator l1 = new StringLocator(1, RegisterRange.HOLDING_REGISTER, 0, + // DataType.CHAR, 4); + // StringLocator l2 = new StringLocator(1, RegisterRange.HOLDING_REGISTER, 0, + // DataType.VARCHAR, 4); + // + // short[] s; + // + // s = l1.valueToShorts("abcdefg"); + // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); + // + // s = l1.valueToShorts("abcdefgh"); + // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); + // + // s = l1.valueToShorts("abcdefghi"); + // System.out.println(new String(l1.bytesToValue(toBytes(s), 0))); + // + // s = l2.valueToShorts("abcdef"); + // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); + // + // s = l2.valueToShorts("abcdefg"); + // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); + // + // s = l2.valueToShorts("abcdefgh"); + // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); + // + // s = l2.valueToShorts("abcdefghi"); + // System.out.println(new String(l2.bytesToValue(toBytes(s), 0))); + // } + // + // private static byte[] toBytes(short[] s) { + // byte[] b = new byte[s.length * 2]; + // for (int i = 0; i < s.length; i++) { + // b[i * 2] = (byte) ((s[i] >> 8) & 0xff); + // b[i * 2 + 1] = (byte) (s[i] & 0xff); + // } + // return b; + // } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionRequest.java index 05e2c2a39..9b1347a7f 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionRequest.java @@ -32,63 +32,65 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ExceptionRequest extends ModbusRequest { - private final byte functionCode; + private final byte functionCode; - private final byte exceptionCode; + private final byte exceptionCode; - /** - *

- * Constructor for ExceptionRequest. - *

- * @param slaveId a int. - * @param functionCode a byte. - * @param exceptionCode a byte. - * @throws ModbusTransportException if any. - */ - public ExceptionRequest(int slaveId, byte functionCode, byte exceptionCode) throws ModbusTransportException { - super(slaveId); - this.functionCode = functionCode; - this.exceptionCode = exceptionCode; - } + /** + *

+ * Constructor for ExceptionRequest. + *

+ * + * @param slaveId a int. + * @param functionCode a byte. + * @param exceptionCode a byte. + * @throws ModbusTransportException if any. + */ + public ExceptionRequest(int slaveId, byte functionCode, byte exceptionCode) throws ModbusTransportException { + super(slaveId); + this.functionCode = functionCode; + this.exceptionCode = exceptionCode; + } - @Override - public void validate(Modbus modbus) { - // no op - } + @Override + public void validate(Modbus modbus) { + // no op + } - @Override - protected void writeRequest(ByteQueue queue) { - throw new ShouldNeverHappenException("wha"); - } + @Override + protected void writeRequest(ByteQueue queue) { + throw new ShouldNeverHappenException("wha"); + } - @Override - protected void readRequest(ByteQueue queue) { - queue.clear(); - } + @Override + protected void readRequest(ByteQueue queue) { + queue.clear(); + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ExceptionResponse(slaveId, functionCode, exceptionCode); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ExceptionResponse(slaveId, functionCode, exceptionCode); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return getResponseInstance(slaveId); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return getResponseInstance(slaveId); + } - @Override - public byte getFunctionCode() { - return functionCode; - } + @Override + public byte getFunctionCode() { + return functionCode; + } - /** - *

- * Getter for the field exceptionCode. - *

- * @return a byte. - */ - public byte getExceptionCode() { - return exceptionCode; - } + /** + *

+ * Getter for the field exceptionCode. + *

+ * + * @return a byte. + */ + public byte getExceptionCode() { + return exceptionCode; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionResponse.java index fbb7b3d36..1e13a360d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ExceptionResponse.java @@ -29,36 +29,37 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ExceptionResponse extends ModbusResponse { - private final byte functionCode; + private final byte functionCode; - /** - *

- * Constructor for ExceptionResponse. - *

- * @param slaveId a int. - * @param functionCode a byte. - * @param exceptionCode a byte. - * @throws ModbusTransportException if any. - */ - public ExceptionResponse(int slaveId, byte functionCode, byte exceptionCode) throws ModbusTransportException { - super(slaveId); - this.functionCode = functionCode; - setException(exceptionCode); - } + /** + *

+ * Constructor for ExceptionResponse. + *

+ * + * @param slaveId a int. + * @param functionCode a byte. + * @param exceptionCode a byte. + * @throws ModbusTransportException if any. + */ + public ExceptionResponse(int slaveId, byte functionCode, byte exceptionCode) throws ModbusTransportException { + super(slaveId); + this.functionCode = functionCode; + setException(exceptionCode); + } - @Override - public byte getFunctionCode() { - return functionCode; - } + @Override + public byte getFunctionCode() { + return functionCode; + } - @Override - protected void readResponse(ByteQueue queue) { - // no op - } + @Override + protected void readResponse(ByteQueue queue) { + // no op + } - @Override - protected void writeResponse(ByteQueue queue) { - // no op - } + @Override + protected void writeResponse(ByteQueue queue) { + // no op + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusMessage.java index cd57fec1c..ef961ef95 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusMessage.java @@ -29,126 +29,135 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Modbus Message - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Message + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusMessage { - protected int slaveId; + protected int slaveId; - /** - *

- * Constructor for ModbusMessage. - *

- * @param slaveId a int. - * @throws ModbusTransportException if any. - */ - public ModbusMessage(int slaveId) throws ModbusTransportException { - // Validate the node id. Note that a 0 slave id is a broadcast message. - if (slaveId < 0 /* || slaveId > 247 */) - throw new ModbusTransportException("Invalid slave id", slaveId); + /** + *

+ * Constructor for ModbusMessage. + *

+ * + * @param slaveId a int. + * @throws ModbusTransportException if any. + */ + public ModbusMessage(int slaveId) throws ModbusTransportException { + // Validate the node id. Note that a 0 slave id is a broadcast message. + if (slaveId < 0 /* || slaveId > 247 */) + throw new ModbusTransportException("Invalid slave id", slaveId); - this.slaveId = slaveId; - } + this.slaveId = slaveId; + } - /** - *

- * Getter for the field slaveId. - *

- * @return a int. - */ - public int getSlaveId() { - return slaveId; - } + /** + *

+ * Getter for the field slaveId. + *

+ * + * @return a int. + */ + public int getSlaveId() { + return slaveId; + } - /** - *

- * getFunctionCode. - *

- * @return a byte. - */ - abstract public byte getFunctionCode(); + /** + *

+ * getFunctionCode. + *

+ * + * @return a byte. + */ + abstract public byte getFunctionCode(); - /** - *

- * write. - *

- * @param queue a {@link ByteQueue} object. - */ - final public void write(ByteQueue queue) { - ModbusUtils.pushByte(queue, slaveId); - writeImpl(queue); - } + /** + *

+ * write. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + final public void write(ByteQueue queue) { + ModbusUtils.pushByte(queue, slaveId); + writeImpl(queue); + } - /** - *

- * writeImpl. - *

- * @param queue a {@link ByteQueue} object. - */ - abstract protected void writeImpl(ByteQueue queue); + /** + *

+ * writeImpl. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + abstract protected void writeImpl(ByteQueue queue); - /** - *

- * convertToBytes. - *

- * @param bdata an array of {@link boolean} objects. - * @return an array of {@link byte} objects. - */ - protected byte[] convertToBytes(boolean[] bdata) { - int byteCount = (bdata.length + 7) / 8; - byte[] data = new byte[byteCount]; - for (int i = 0; i < bdata.length; i++) - data[i / 8] |= (bdata[i] ? 1 : 0) << (i % 8); - return data; - } + /** + *

+ * convertToBytes. + *

+ * + * @param bdata an array of {@link boolean} objects. + * @return an array of {@link byte} objects. + */ + protected byte[] convertToBytes(boolean[] bdata) { + int byteCount = (bdata.length + 7) / 8; + byte[] data = new byte[byteCount]; + for (int i = 0; i < bdata.length; i++) + data[i / 8] |= (bdata[i] ? 1 : 0) << (i % 8); + return data; + } - /** - *

- * convertToBytes. - *

- * @param sdata an array of {@link short} objects. - * @return an array of {@link byte} objects. - */ - protected byte[] convertToBytes(short[] sdata) { - int byteCount = sdata.length * 2; - byte[] data = new byte[byteCount]; - for (int i = 0; i < sdata.length; i++) { - data[i * 2] = (byte) (0xff & (sdata[i] >> 8)); - data[i * 2 + 1] = (byte) (0xff & sdata[i]); - } - return data; - } + /** + *

+ * convertToBytes. + *

+ * + * @param sdata an array of {@link short} objects. + * @return an array of {@link byte} objects. + */ + protected byte[] convertToBytes(short[] sdata) { + int byteCount = sdata.length * 2; + byte[] data = new byte[byteCount]; + for (int i = 0; i < sdata.length; i++) { + data[i * 2] = (byte) (0xff & (sdata[i] >> 8)); + data[i * 2 + 1] = (byte) (0xff & sdata[i]); + } + return data; + } - /** - *

- * convertToBooleans. - *

- * @param data an array of {@link byte} objects. - * @return an array of {@link boolean} objects. - */ - protected boolean[] convertToBooleans(byte[] data) { - boolean[] bdata = new boolean[data.length * 8]; - for (int i = 0; i < bdata.length; i++) - bdata[i] = ((data[i / 8] >> (i % 8)) & 0x1) == 1; - return bdata; - } + /** + *

+ * convertToBooleans. + *

+ * + * @param data an array of {@link byte} objects. + * @return an array of {@link boolean} objects. + */ + protected boolean[] convertToBooleans(byte[] data) { + boolean[] bdata = new boolean[data.length * 8]; + for (int i = 0; i < bdata.length; i++) + bdata[i] = ((data[i / 8] >> (i % 8)) & 0x1) == 1; + return bdata; + } - /** - *

- * convertToShorts. - *

- * @param data an array of {@link byte} objects. - * @return an array of {@link short} objects. - */ - protected short[] convertToShorts(byte[] data) { - short[] sdata = new short[data.length / 2]; - for (int i = 0; i < sdata.length; i++) - sdata[i] = ModbusUtils.toShort(data[i * 2], data[i * 2 + 1]); - return sdata; - } + /** + *

+ * convertToShorts. + *

+ * + * @param data an array of {@link byte} objects. + * @return an array of {@link short} objects. + */ + protected short[] convertToShorts(byte[] data) { + short[] sdata = new short[data.length / 2]; + for (int i = 0; i < sdata.length; i++) + sdata[i] = ModbusUtils.toShort(data[i * 2], data[i * 2 + 1]); + return sdata; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusRequest.java index 783d0c324..1f1b8b758 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusRequest.java @@ -34,122 +34,125 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Modbus Request - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Request + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusRequest extends ModbusMessage { - ModbusRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ModbusRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - /** - *

- * createModbusRequest. - *

- * @param queue a {@link ByteQueue} object. - * @return a {@link ModbusRequest} object. - * @throws ModbusTransportException if any. - */ - public static ModbusRequest createModbusRequest(ByteQueue queue) throws ModbusTransportException { - int slaveId = ModbusUtils.popUnsignedByte(queue); - byte functionCode = queue.pop(); + /** + *

+ * createModbusRequest. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a {@link ModbusRequest} object. + * @throws ModbusTransportException if any. + */ + public static ModbusRequest createModbusRequest(ByteQueue queue) throws ModbusTransportException { + int slaveId = ModbusUtils.popUnsignedByte(queue); + byte functionCode = queue.pop(); - ModbusRequest request = null; - if (functionCode == FunctionCode.READ_COILS) - request = new ReadCoilsRequest(slaveId); - else if (functionCode == FunctionCode.READ_DISCRETE_INPUTS) - request = new ReadDiscreteInputsRequest(slaveId); - else if (functionCode == FunctionCode.READ_HOLDING_REGISTERS) - request = new ReadHoldingRegistersRequest(slaveId); - else if (functionCode == FunctionCode.READ_INPUT_REGISTERS) - request = new ReadInputRegistersRequest(slaveId); - else if (functionCode == FunctionCode.WRITE_COIL) - request = new WriteCoilRequest(slaveId); - else if (functionCode == FunctionCode.WRITE_REGISTER) - request = new WriteRegisterRequest(slaveId); - else if (functionCode == FunctionCode.READ_EXCEPTION_STATUS) - request = new ReadExceptionStatusRequest(slaveId); - else if (functionCode == FunctionCode.WRITE_COILS) - request = new WriteCoilsRequest(slaveId); - else if (functionCode == FunctionCode.WRITE_REGISTERS) - request = new WriteRegistersRequest(slaveId); - else if (functionCode == FunctionCode.REPORT_SLAVE_ID) - request = new ReportSlaveIdRequest(slaveId); - // else if (functionCode == FunctionCode.WRITE_MASK_REGISTER) - // request = new WriteMaskRegisterRequest(slaveId); - else - request = new ExceptionRequest(slaveId, functionCode, ExceptionCode.ILLEGAL_FUNCTION); + ModbusRequest request = null; + if (functionCode == FunctionCode.READ_COILS) + request = new ReadCoilsRequest(slaveId); + else if (functionCode == FunctionCode.READ_DISCRETE_INPUTS) + request = new ReadDiscreteInputsRequest(slaveId); + else if (functionCode == FunctionCode.READ_HOLDING_REGISTERS) + request = new ReadHoldingRegistersRequest(slaveId); + else if (functionCode == FunctionCode.READ_INPUT_REGISTERS) + request = new ReadInputRegistersRequest(slaveId); + else if (functionCode == FunctionCode.WRITE_COIL) + request = new WriteCoilRequest(slaveId); + else if (functionCode == FunctionCode.WRITE_REGISTER) + request = new WriteRegisterRequest(slaveId); + else if (functionCode == FunctionCode.READ_EXCEPTION_STATUS) + request = new ReadExceptionStatusRequest(slaveId); + else if (functionCode == FunctionCode.WRITE_COILS) + request = new WriteCoilsRequest(slaveId); + else if (functionCode == FunctionCode.WRITE_REGISTERS) + request = new WriteRegistersRequest(slaveId); + else if (functionCode == FunctionCode.REPORT_SLAVE_ID) + request = new ReportSlaveIdRequest(slaveId); + // else if (functionCode == FunctionCode.WRITE_MASK_REGISTER) + // request = new WriteMaskRegisterRequest(slaveId); + else + request = new ExceptionRequest(slaveId, functionCode, ExceptionCode.ILLEGAL_FUNCTION); - request.readRequest(queue); + request.readRequest(queue); - return request; - } + return request; + } - /** - *

- * validate. - *

- * @param modbus a {@link Modbus} object. - * @throws ModbusTransportException if any. - */ - abstract public void validate(Modbus modbus) throws ModbusTransportException; + /** + *

+ * validate. + *

+ * + * @param modbus a {@link Modbus} object. + * @throws ModbusTransportException if any. + */ + abstract public void validate(Modbus modbus) throws ModbusTransportException; - /** - *

- * handle. - *

- * @param processImage a {@link ProcessImage} object. - * @return a {@link ModbusResponse} object. - * @throws ModbusTransportException if any. - */ - public ModbusResponse handle(ProcessImage processImage) throws ModbusTransportException { - try { - try { - return handleImpl(processImage); - } - catch (IllegalDataAddressException e) { - return handleException(ExceptionCode.ILLEGAL_DATA_ADDRESS); - } - } - catch (Exception e) { - return handleException(ExceptionCode.SLAVE_DEVICE_FAILURE); - } - } + /** + *

+ * handle. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @return a {@link ModbusResponse} object. + * @throws ModbusTransportException if any. + */ + public ModbusResponse handle(ProcessImage processImage) throws ModbusTransportException { + try { + try { + return handleImpl(processImage); + } catch (IllegalDataAddressException e) { + return handleException(ExceptionCode.ILLEGAL_DATA_ADDRESS); + } + } catch (Exception e) { + return handleException(ExceptionCode.SLAVE_DEVICE_FAILURE); + } + } - abstract ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException; + abstract ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException; - /** - *

- * readRequest. - *

- * @param queue a {@link ByteQueue} object. - */ - abstract protected void readRequest(ByteQueue queue); + /** + *

+ * readRequest. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + abstract protected void readRequest(ByteQueue queue); - ModbusResponse handleException(byte exceptionCode) throws ModbusTransportException { - ModbusResponse response = getResponseInstance(slaveId); - response.setException(exceptionCode); - return response; - } + ModbusResponse handleException(byte exceptionCode) throws ModbusTransportException { + ModbusResponse response = getResponseInstance(slaveId); + response.setException(exceptionCode); + return response; + } - abstract ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException; + abstract ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException; - @Override - final protected void writeImpl(ByteQueue queue) { - queue.push(getFunctionCode()); - writeRequest(queue); - } + @Override + final protected void writeImpl(ByteQueue queue) { + queue.push(getFunctionCode()); + writeRequest(queue); + } - /** - *

- * writeRequest. - *

- * @param queue a {@link ByteQueue} object. - */ - abstract protected void writeRequest(ByteQueue queue); + /** + *

+ * writeRequest. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + abstract protected void writeRequest(ByteQueue queue); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusResponse.java index 6b9381f87..d3f228c41 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ModbusResponse.java @@ -33,170 +33,177 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Modbus Response - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Response + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusResponse extends ModbusMessage { - /** - * Constant MAX_FUNCTION_CODE=(byte) 0x80 - */ - protected static final byte MAX_FUNCTION_CODE = (byte) 0x80; + /** + * Constant MAX_FUNCTION_CODE=(byte) 0x80 + */ + protected static final byte MAX_FUNCTION_CODE = (byte) 0x80; - protected byte exceptionCode = -1; + protected byte exceptionCode = -1; - ModbusResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ModbusResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - /** - *

- * createModbusResponse. - *

- * @param queue a {@link ByteQueue} object. - * @return a {@link ModbusResponse} object. - * @throws ModbusTransportException if any. - */ - public static ModbusResponse createModbusResponse(ByteQueue queue) throws ModbusTransportException { - int slaveId = ModbusUtils.popUnsignedByte(queue); - byte functionCode = queue.pop(); - boolean isException = false; + /** + *

+ * createModbusResponse. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a {@link ModbusResponse} object. + * @throws ModbusTransportException if any. + */ + public static ModbusResponse createModbusResponse(ByteQueue queue) throws ModbusTransportException { + int slaveId = ModbusUtils.popUnsignedByte(queue); + byte functionCode = queue.pop(); + boolean isException = false; - if (greaterThan(functionCode, MAX_FUNCTION_CODE)) { - isException = true; - functionCode -= MAX_FUNCTION_CODE; - } + if (greaterThan(functionCode, MAX_FUNCTION_CODE)) { + isException = true; + functionCode -= MAX_FUNCTION_CODE; + } - ModbusResponse response = null; - if (functionCode == FunctionCode.READ_COILS) - response = new ReadCoilsResponse(slaveId); - else if (functionCode == FunctionCode.READ_DISCRETE_INPUTS) - response = new ReadDiscreteInputsResponse(slaveId); - else if (functionCode == FunctionCode.READ_HOLDING_REGISTERS) - response = new ReadHoldingRegistersResponse(slaveId); - else if (functionCode == FunctionCode.READ_INPUT_REGISTERS) - response = new ReadInputRegistersResponse(slaveId); - else if (functionCode == FunctionCode.WRITE_COIL) - response = new WriteCoilResponse(slaveId); - else if (functionCode == FunctionCode.WRITE_REGISTER) - response = new WriteRegisterResponse(slaveId); - else if (functionCode == FunctionCode.READ_EXCEPTION_STATUS) - response = new ReadExceptionStatusResponse(slaveId); - else if (functionCode == FunctionCode.WRITE_COILS) - response = new WriteCoilsResponse(slaveId); - else if (functionCode == FunctionCode.WRITE_REGISTERS) - response = new WriteRegistersResponse(slaveId); - else if (functionCode == FunctionCode.REPORT_SLAVE_ID) - response = new ReportSlaveIdResponse(slaveId); - else if (functionCode == FunctionCode.WRITE_MASK_REGISTER) - response = new WriteMaskRegisterResponse(slaveId); - else - throw new IllegalFunctionException(functionCode, slaveId); + ModbusResponse response = null; + if (functionCode == FunctionCode.READ_COILS) + response = new ReadCoilsResponse(slaveId); + else if (functionCode == FunctionCode.READ_DISCRETE_INPUTS) + response = new ReadDiscreteInputsResponse(slaveId); + else if (functionCode == FunctionCode.READ_HOLDING_REGISTERS) + response = new ReadHoldingRegistersResponse(slaveId); + else if (functionCode == FunctionCode.READ_INPUT_REGISTERS) + response = new ReadInputRegistersResponse(slaveId); + else if (functionCode == FunctionCode.WRITE_COIL) + response = new WriteCoilResponse(slaveId); + else if (functionCode == FunctionCode.WRITE_REGISTER) + response = new WriteRegisterResponse(slaveId); + else if (functionCode == FunctionCode.READ_EXCEPTION_STATUS) + response = new ReadExceptionStatusResponse(slaveId); + else if (functionCode == FunctionCode.WRITE_COILS) + response = new WriteCoilsResponse(slaveId); + else if (functionCode == FunctionCode.WRITE_REGISTERS) + response = new WriteRegistersResponse(slaveId); + else if (functionCode == FunctionCode.REPORT_SLAVE_ID) + response = new ReportSlaveIdResponse(slaveId); + else if (functionCode == FunctionCode.WRITE_MASK_REGISTER) + response = new WriteMaskRegisterResponse(slaveId); + else + throw new IllegalFunctionException(functionCode, slaveId); - response.read(queue, isException); + response.read(queue, isException); - return response; - } + return response; + } - private static boolean greaterThan(byte b1, byte b2) { - int i1 = b1 & 0xff; - int i2 = b2 & 0xff; - return i1 > i2; - } + private static boolean greaterThan(byte b1, byte b2) { + int i1 = b1 & 0xff; + int i2 = b2 & 0xff; + return i1 > i2; + } - /** - *

- * main. - *

- * @param args an array of {@link String} objects. - * @throws Exception if any. - */ - public static void main(String[] args) throws Exception { - ByteQueue queue = new ByteQueue(new byte[] { 3, 2 }); - ModbusResponse r = createModbusResponse(queue); - System.out.println(r); - } + /** + *

+ * main. + *

+ * + * @param args an array of {@link String} objects. + * @throws Exception if any. + */ + public static void main(String[] args) throws Exception { + ByteQueue queue = new ByteQueue(new byte[]{3, 2}); + ModbusResponse r = createModbusResponse(queue); + System.out.println(r); + } - /** - *

- * isException. - *

- * @return a boolean. - */ - public boolean isException() { - return exceptionCode != -1; - } + /** + *

+ * isException. + *

+ * + * @return a boolean. + */ + public boolean isException() { + return exceptionCode != -1; + } - void setException(byte exceptionCode) { - this.exceptionCode = exceptionCode; - } + void setException(byte exceptionCode) { + this.exceptionCode = exceptionCode; + } - /** - *

- * getExceptionMessage. - *

- * @return a {@link String} object. - */ - public String getExceptionMessage() { - return ExceptionCode.getExceptionMessage(exceptionCode); - } + /** + *

+ * getExceptionMessage. + *

+ * + * @return a {@link String} object. + */ + public String getExceptionMessage() { + return ExceptionCode.getExceptionMessage(exceptionCode); + } - /** - *

- * Getter for the field exceptionCode. - *

- * @return a byte. - */ - public byte getExceptionCode() { - return exceptionCode; - } + /** + *

+ * Getter for the field exceptionCode. + *

+ * + * @return a byte. + */ + public byte getExceptionCode() { + return exceptionCode; + } - @Override - final protected void writeImpl(ByteQueue queue) { - if (isException()) { - queue.push((byte) (getFunctionCode() + MAX_FUNCTION_CODE)); - queue.push(exceptionCode); - } - else { - queue.push(getFunctionCode()); - writeResponse(queue); - } - } + @Override + final protected void writeImpl(ByteQueue queue) { + if (isException()) { + queue.push((byte) (getFunctionCode() + MAX_FUNCTION_CODE)); + queue.push(exceptionCode); + } else { + queue.push(getFunctionCode()); + writeResponse(queue); + } + } - /** - *

- * writeResponse. - *

- * @param queue a {@link ByteQueue} object. - */ - abstract protected void writeResponse(ByteQueue queue); + /** + *

+ * writeResponse. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + abstract protected void writeResponse(ByteQueue queue); - void read(ByteQueue queue, boolean isException) { - if (isException) - exceptionCode = queue.pop(); - else - readResponse(queue); - } + void read(ByteQueue queue, boolean isException) { + if (isException) + exceptionCode = queue.pop(); + else + readResponse(queue); + } - /** - *

- * readResponse. - *

- * @param queue a {@link ByteQueue} object. - */ - abstract protected void readResponse(ByteQueue queue); + /** + *

+ * readResponse. + *

+ * + * @param queue a {@link ByteQueue} object. + */ + abstract protected void readResponse(ByteQueue queue); - /** - * Ensure that the Response slave id is equal to the requested slave id - * @param request - * @throws ModbusTransportException - */ - public void validateResponse(ModbusRequest request) throws ModbusTransportException { - if (getSlaveId() != request.slaveId) - throw new SlaveIdNotEqual(request.slaveId, getSlaveId()); - } + /** + * Ensure that the Response slave id is equal to the requested slave id + * + * @param request + * @throws ModbusTransportException + */ + public void validateResponse(ModbusRequest request) throws ModbusTransportException { + if (getSlaveId() != request.slaveId) + throw new SlaveIdNotEqual(request.slaveId, getSlaveId()); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadBinaryRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadBinaryRequest.java index 6345a5ef3..a651c323d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadBinaryRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadBinaryRequest.java @@ -31,89 +31,92 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Read Binary Request - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Read Binary Request + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ReadBinaryRequest extends ModbusRequest { - private int startOffset; + private int startOffset; - private int numberOfBits; + private int numberOfBits; - /** - *

- * Constructor for ReadBinaryRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfBits a int. - * @throws ModbusTransportException if any. - */ - public ReadBinaryRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - this.numberOfBits = numberOfBits; - } + /** + *

+ * Constructor for ReadBinaryRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfBits a int. + * @throws ModbusTransportException if any. + */ + public ReadBinaryRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + this.numberOfBits = numberOfBits; + } - ReadBinaryRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadBinaryRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(startOffset); - modbus.validateNumberOfBits(numberOfBits); - ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(startOffset); + modbus.validateNumberOfBits(numberOfBits); + ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, numberOfBits); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, numberOfBits); + } - @Override - protected void readRequest(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - numberOfBits = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readRequest(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + numberOfBits = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * getData. - *

- * @param processImage a {@link ProcessImage} object. - * @return an array of {@link byte} objects. - * @throws ModbusTransportException if any. - */ - protected byte[] getData(ProcessImage processImage) throws ModbusTransportException { - boolean[] data = new boolean[numberOfBits]; + /** + *

+ * getData. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @return an array of {@link byte} objects. + * @throws ModbusTransportException if any. + */ + protected byte[] getData(ProcessImage processImage) throws ModbusTransportException { + boolean[] data = new boolean[numberOfBits]; - // Get the data from the process image. - for (int i = 0; i < numberOfBits; i++) - data[i] = getBinary(processImage, i + startOffset); + // Get the data from the process image. + for (int i = 0; i < numberOfBits; i++) + data[i] = getBinary(processImage, i + startOffset); - // Convert the boolean array into an array of bytes. - return convertToBytes(data); - } + // Convert the boolean array into an array of bytes. + return convertToBytes(data); + } - /** - *

- * getBinary. - *

- * @param processImage a {@link ProcessImage} object. - * @param index a int. - * @return a boolean. - * @throws ModbusTransportException if any. - */ - abstract protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException; + /** + *

+ * getBinary. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @param index a int. + * @return a boolean. + * @throws ModbusTransportException if any. + */ + abstract protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException; - @Override - public String toString() { - return "ReadBinaryRequest [startOffset=" + startOffset + ", numberOfBits=" + numberOfBits + "]"; - } + @Override + public String toString() { + return "ReadBinaryRequest [startOffset=" + startOffset + ", numberOfBits=" + numberOfBits + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsRequest.java index 54c6ed35e..27f60a034 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsRequest.java @@ -30,47 +30,48 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadCoilsRequest extends ReadBinaryRequest { - /** - *

- * Constructor for ReadCoilsRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfBits a int. - * @throws ModbusTransportException if any. - */ - public ReadCoilsRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { - super(slaveId, startOffset, numberOfBits); - } + /** + *

+ * Constructor for ReadCoilsRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfBits a int. + * @throws ModbusTransportException if any. + */ + public ReadCoilsRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { + super(slaveId, startOffset, numberOfBits); + } - ReadCoilsRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadCoilsRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_COILS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_COILS; + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReadCoilsResponse(slaveId, getData(processImage)); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReadCoilsResponse(slaveId, getData(processImage)); + } - @Override - protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException { - return processImage.getCoil(index); - } + @Override + protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException { + return processImage.getCoil(index); + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReadCoilsResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReadCoilsResponse(slaveId); + } - @Override - public String toString() { - return "ReadCoilsRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() + ", toString()=" - + super.toString() + "]"; - } + @Override + public String toString() { + return "ReadCoilsRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() + ", toString()=" + + super.toString() + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsResponse.java index c5f074172..b202b90a9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadCoilsResponse.java @@ -29,25 +29,25 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadCoilsResponse extends ReadResponse { - ReadCoilsResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId, data); - } + ReadCoilsResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId, data); + } - ReadCoilsResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadCoilsResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_COILS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_COILS; + } - @Override - public String toString() { - return "ReadCoilsResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId + ", getFunctionCode()=" - + getFunctionCode() + ", isException()=" + isException() + ", getExceptionMessage()=" - + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() + ", toString()=" - + super.toString(false) + "]"; - } + @Override + public String toString() { + return "ReadCoilsResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId + ", getFunctionCode()=" + + getFunctionCode() + ", isException()=" + isException() + ", getExceptionMessage()=" + + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() + ", toString()=" + + super.toString(false) + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsRequest.java index 53ac73b8f..4092deb34 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsRequest.java @@ -30,41 +30,42 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadDiscreteInputsRequest extends ReadBinaryRequest { - /** - *

- * Constructor for ReadDiscreteInputsRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfBits a int. - * @throws ModbusTransportException if any. - */ - public ReadDiscreteInputsRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { - super(slaveId, startOffset, numberOfBits); - } + /** + *

+ * Constructor for ReadDiscreteInputsRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfBits a int. + * @throws ModbusTransportException if any. + */ + public ReadDiscreteInputsRequest(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { + super(slaveId, startOffset, numberOfBits); + } - ReadDiscreteInputsRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadDiscreteInputsRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_DISCRETE_INPUTS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_DISCRETE_INPUTS; + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReadDiscreteInputsResponse(slaveId, getData(processImage)); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReadDiscreteInputsResponse(slaveId, getData(processImage)); + } - @Override - protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException { - return processImage.getInput(index); - } + @Override + protected boolean getBinary(ProcessImage processImage, int index) throws ModbusTransportException { + return processImage.getInput(index); + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReadDiscreteInputsResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReadDiscreteInputsResponse(slaveId); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsResponse.java index 458cb7d7b..f60d85bee 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadDiscreteInputsResponse.java @@ -29,25 +29,25 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadDiscreteInputsResponse extends ReadResponse { - ReadDiscreteInputsResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId, data); - } + ReadDiscreteInputsResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId, data); + } - ReadDiscreteInputsResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadDiscreteInputsResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_DISCRETE_INPUTS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_DISCRETE_INPUTS; + } - @Override - public String toString() { - return "ReadDiscreteInputsResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId - + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() - + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() - + super.toString(false) + "]"; - } + @Override + public String toString() { + return "ReadDiscreteInputsResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId + + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() + + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() + + super.toString(false) + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusRequest.java index 3d207ebe8..02ae4c6cc 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusRequest.java @@ -32,45 +32,46 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ReadExceptionStatusRequest extends ModbusRequest { - /** - *

- * Constructor for ReadExceptionStatusRequest. - *

- * @param slaveId a int. - * @throws ModbusTransportException if any. - */ - public ReadExceptionStatusRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + /** + *

+ * Constructor for ReadExceptionStatusRequest. + *

+ * + * @param slaveId a int. + * @throws ModbusTransportException if any. + */ + public ReadExceptionStatusRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) { - // no op - } + @Override + public void validate(Modbus modbus) { + // no op + } - @Override - protected void writeRequest(ByteQueue queue) { - // no op - } + @Override + protected void writeRequest(ByteQueue queue) { + // no op + } - @Override - protected void readRequest(ByteQueue queue) { - // no op - } + @Override + protected void readRequest(ByteQueue queue) { + // no op + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReadExceptionStatusResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReadExceptionStatusResponse(slaveId); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReadExceptionStatusResponse(slaveId, processImage.getExceptionStatus()); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReadExceptionStatusResponse(slaveId, processImage.getExceptionStatus()); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_EXCEPTION_STATUS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_EXCEPTION_STATUS; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusResponse.java index c2f695a18..da68e62ea 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadExceptionStatusResponse.java @@ -30,40 +30,41 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ReadExceptionStatusResponse extends ModbusResponse { - private byte exceptionStatus; + private byte exceptionStatus; - ReadExceptionStatusResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadExceptionStatusResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - ReadExceptionStatusResponse(int slaveId, byte exceptionStatus) throws ModbusTransportException { - super(slaveId); - this.exceptionStatus = exceptionStatus; - } + ReadExceptionStatusResponse(int slaveId, byte exceptionStatus) throws ModbusTransportException { + super(slaveId); + this.exceptionStatus = exceptionStatus; + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_EXCEPTION_STATUS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_EXCEPTION_STATUS; + } - @Override - protected void readResponse(ByteQueue queue) { - exceptionStatus = queue.pop(); - } + @Override + protected void readResponse(ByteQueue queue) { + exceptionStatus = queue.pop(); + } - @Override - protected void writeResponse(ByteQueue queue) { - queue.push(exceptionStatus); - } + @Override + protected void writeResponse(ByteQueue queue) { + queue.push(exceptionStatus); + } - /** - *

- * Getter for the field exceptionStatus. - *

- * @return a byte. - */ - public byte getExceptionStatus() { - return exceptionStatus; - } + /** + *

+ * Getter for the field exceptionStatus. + *

+ * + * @return a byte. + */ + public byte getExceptionStatus() { + return exceptionStatus; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersRequest.java index 83862f3cc..4e895dfed 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersRequest.java @@ -30,48 +30,49 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadHoldingRegistersRequest extends ReadNumericRequest { - /** - *

- * Constructor for ReadHoldingRegistersRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfRegisters a int. - * @throws ModbusTransportException if any. - */ - public ReadHoldingRegistersRequest(int slaveId, int startOffset, int numberOfRegisters) - throws ModbusTransportException { - super(slaveId, startOffset, numberOfRegisters); - } + /** + *

+ * Constructor for ReadHoldingRegistersRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfRegisters a int. + * @throws ModbusTransportException if any. + */ + public ReadHoldingRegistersRequest(int slaveId, int startOffset, int numberOfRegisters) + throws ModbusTransportException { + super(slaveId, startOffset, numberOfRegisters); + } - ReadHoldingRegistersRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadHoldingRegistersRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_HOLDING_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_HOLDING_REGISTERS; + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReadHoldingRegistersResponse(slaveId, getData(processImage)); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReadHoldingRegistersResponse(slaveId, getData(processImage)); + } - @Override - protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException { - return processImage.getHoldingRegister(index); - } + @Override + protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException { + return processImage.getHoldingRegister(index); + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReadHoldingRegistersResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReadHoldingRegistersResponse(slaveId); + } - @Override - public String toString() { - return "ReadHoldingRegistersRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() - + ", toString()=" + super.toString() + "]"; - } + @Override + public String toString() { + return "ReadHoldingRegistersRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() + + ", toString()=" + super.toString() + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersResponse.java index 32c87bc79..a179d3222 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadHoldingRegistersResponse.java @@ -29,25 +29,25 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadHoldingRegistersResponse extends ReadResponse { - ReadHoldingRegistersResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId, data); - } + ReadHoldingRegistersResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId, data); + } - ReadHoldingRegistersResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadHoldingRegistersResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_HOLDING_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_HOLDING_REGISTERS; + } - @Override - public String toString() { - return "ReadHoldingRegistersResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId - + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() - + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() - + ", toString()=" + super.toString(true) + "]"; - } + @Override + public String toString() { + return "ReadHoldingRegistersResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId + + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() + + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() + + ", toString()=" + super.toString(true) + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersRequest.java index 36a8f3994..2f3b8e882 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersRequest.java @@ -30,48 +30,49 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadInputRegistersRequest extends ReadNumericRequest { - /** - *

- * Constructor for ReadInputRegistersRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfRegisters a int. - * @throws ModbusTransportException if any. - */ - public ReadInputRegistersRequest(int slaveId, int startOffset, int numberOfRegisters) - throws ModbusTransportException { - super(slaveId, startOffset, numberOfRegisters); - } + /** + *

+ * Constructor for ReadInputRegistersRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfRegisters a int. + * @throws ModbusTransportException if any. + */ + public ReadInputRegistersRequest(int slaveId, int startOffset, int numberOfRegisters) + throws ModbusTransportException { + super(slaveId, startOffset, numberOfRegisters); + } - ReadInputRegistersRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadInputRegistersRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_INPUT_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_INPUT_REGISTERS; + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReadInputRegistersResponse(slaveId, getData(processImage)); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReadInputRegistersResponse(slaveId, getData(processImage)); + } - @Override - protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException { - return processImage.getInputRegister(index); - } + @Override + protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException { + return processImage.getInputRegister(index); + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReadInputRegistersResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReadInputRegistersResponse(slaveId); + } - @Override - public String toString() { - return "ReadInputRegistersRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() - + ", toString()=" + super.toString() + "]"; - } + @Override + public String toString() { + return "ReadInputRegistersRequest [slaveId=" + slaveId + ", getFunctionCode()=" + getFunctionCode() + + ", toString()=" + super.toString() + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersResponse.java index e0be4eb5a..a36140846 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadInputRegistersResponse.java @@ -29,25 +29,25 @@ import com.serotonin.modbus4j.exception.ModbusTransportException; */ public class ReadInputRegistersResponse extends ReadResponse { - ReadInputRegistersResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId, data); - } + ReadInputRegistersResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId, data); + } - ReadInputRegistersResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadInputRegistersResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public byte getFunctionCode() { - return FunctionCode.READ_INPUT_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.READ_INPUT_REGISTERS; + } - @Override - public String toString() { - return "ReadInputRegistersResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId - + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() - + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() - + ", toString()=" + super.toString(true) + "]"; - } + @Override + public String toString() { + return "ReadInputRegistersResponse [exceptionCode=" + exceptionCode + ", slaveId=" + slaveId + + ", getFunctionCode()=" + getFunctionCode() + ", isException()=" + isException() + + ", getExceptionMessage()=" + getExceptionMessage() + ", getExceptionCode()=" + getExceptionCode() + + ", toString()=" + super.toString(true) + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadNumericRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadNumericRequest.java index 7ed5fe72b..16a118ab7 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadNumericRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadNumericRequest.java @@ -31,88 +31,91 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Read Numeric Request - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Read Numeric Request + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ReadNumericRequest extends ModbusRequest { - private int startOffset; + private int startOffset; - private int numberOfRegisters; + private int numberOfRegisters; - /** - *

- * Constructor for ReadNumericRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param numberOfRegisters a int. - * @throws ModbusTransportException if any. - */ - public ReadNumericRequest(int slaveId, int startOffset, int numberOfRegisters) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - this.numberOfRegisters = numberOfRegisters; - } + /** + *

+ * Constructor for ReadNumericRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param numberOfRegisters a int. + * @throws ModbusTransportException if any. + */ + public ReadNumericRequest(int slaveId, int startOffset, int numberOfRegisters) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + this.numberOfRegisters = numberOfRegisters; + } - ReadNumericRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadNumericRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(startOffset); - modbus.validateNumberOfRegisters(numberOfRegisters); - ModbusUtils.validateEndOffset(startOffset + numberOfRegisters - 1); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(startOffset); + modbus.validateNumberOfRegisters(numberOfRegisters); + ModbusUtils.validateEndOffset(startOffset + numberOfRegisters - 1); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, numberOfRegisters); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, numberOfRegisters); + } - @Override - protected void readRequest(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - numberOfRegisters = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readRequest(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + numberOfRegisters = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * getData. - *

- * @param processImage a {@link ProcessImage} object. - * @return an array of {@link byte} objects. - * @throws ModbusTransportException if any. - */ - protected byte[] getData(ProcessImage processImage) throws ModbusTransportException { - short[] data = new short[numberOfRegisters]; + /** + *

+ * getData. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @return an array of {@link byte} objects. + * @throws ModbusTransportException if any. + */ + protected byte[] getData(ProcessImage processImage) throws ModbusTransportException { + short[] data = new short[numberOfRegisters]; - // Get the data from the process image. - for (int i = 0; i < numberOfRegisters; i++) - data[i] = getNumeric(processImage, i + startOffset); + // Get the data from the process image. + for (int i = 0; i < numberOfRegisters; i++) + data[i] = getNumeric(processImage, i + startOffset); - return convertToBytes(data); - } + return convertToBytes(data); + } - /** - *

- * getNumeric. - *

- * @param processImage a {@link ProcessImage} object. - * @param index a int. - * @return a short. - * @throws ModbusTransportException if any. - */ - abstract protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException; + /** + *

+ * getNumeric. + *

+ * + * @param processImage a {@link ProcessImage} object. + * @param index a int. + * @return a short. + * @throws ModbusTransportException if any. + */ + abstract protected short getNumeric(ProcessImage processImage, int index) throws ModbusTransportException; - @Override - public String toString() { - return "ReadNumericRequest [startOffset=" + startOffset + ", numberOfRegisters=" + numberOfRegisters + "]"; - } + @Override + public String toString() { + return "ReadNumericRequest [startOffset=" + startOffset + ", numberOfRegisters=" + numberOfRegisters + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadResponse.java index be680880f..685372166 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReadResponse.java @@ -30,83 +30,87 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Read Response - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Read Response + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ReadResponse extends ModbusResponse { - private byte[] data; + private byte[] data; - ReadResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReadResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - ReadResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId); - this.data = data; - } + ReadResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId); + this.data = data; + } - @Override - protected void readResponse(ByteQueue queue) { - int numberOfBytes = ModbusUtils.popUnsignedByte(queue); - if (queue.size() < numberOfBytes) - throw new ArrayIndexOutOfBoundsException(); + @Override + protected void readResponse(ByteQueue queue) { + int numberOfBytes = ModbusUtils.popUnsignedByte(queue); + if (queue.size() < numberOfBytes) + throw new ArrayIndexOutOfBoundsException(); - data = new byte[numberOfBytes]; - queue.pop(data); - } + data = new byte[numberOfBytes]; + queue.pop(data); + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushByte(queue, data.length); - queue.push(data); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushByte(queue, data.length); + queue.push(data); + } - /** - *

- * Getter for the field data. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getData() { - return data; - } + /** + *

+ * Getter for the field data. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getData() { + return data; + } - /** - *

- * getShortData. - *

- * @return an array of {@link short} objects. - */ - public short[] getShortData() { - return convertToShorts(data); - } + /** + *

+ * getShortData. + *

+ * + * @return an array of {@link short} objects. + */ + public short[] getShortData() { + return convertToShorts(data); + } - /** - *

- * getBooleanData. - *

- * @return an array of {@link boolean} objects. - */ - public boolean[] getBooleanData() { - return convertToBooleans(data); - } + /** + *

+ * getBooleanData. + *

+ * + * @return an array of {@link boolean} objects. + */ + public boolean[] getBooleanData() { + return convertToBooleans(data); + } - /** - *

- * toString. - *

- * @param numeric a boolean. - * @return a {@link String} object. - */ - public String toString(boolean numeric) { - if (data == null) - return "ReadResponse [null]"; - return "ReadResponse [len=" + (numeric ? data.length / 2 : data.length * 8) + ", " + StreamUtils.dumpHex(data) - + "]"; - } + /** + *

+ * toString. + *

+ * + * @param numeric a boolean. + * @return a {@link String} object. + */ + public String toString(boolean numeric) { + if (data == null) + return "ReadResponse [null]"; + return "ReadResponse [len=" + (numeric ? data.length / 2 : data.length * 8) + ", " + StreamUtils.dumpHex(data) + + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdRequest.java index 94e832f73..bedf232d0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdRequest.java @@ -32,45 +32,46 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ReportSlaveIdRequest extends ModbusRequest { - /** - *

- * Constructor for ReportSlaveIdRequest. - *

- * @param slaveId a int. - * @throws ModbusTransportException if any. - */ - public ReportSlaveIdRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + /** + *

+ * Constructor for ReportSlaveIdRequest. + *

+ * + * @param slaveId a int. + * @throws ModbusTransportException if any. + */ + public ReportSlaveIdRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) { - // no op - } + @Override + public void validate(Modbus modbus) { + // no op + } - @Override - protected void writeRequest(ByteQueue queue) { - // no op - } + @Override + protected void writeRequest(ByteQueue queue) { + // no op + } - @Override - protected void readRequest(ByteQueue queue) { - // no op - } + @Override + protected void readRequest(ByteQueue queue) { + // no op + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new ReportSlaveIdResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new ReportSlaveIdResponse(slaveId); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - return new ReportSlaveIdResponse(slaveId, processImage.getReportSlaveIdData()); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + return new ReportSlaveIdResponse(slaveId, processImage.getReportSlaveIdData()); + } - @Override - public byte getFunctionCode() { - return FunctionCode.REPORT_SLAVE_ID; - } + @Override + public byte getFunctionCode() { + return FunctionCode.REPORT_SLAVE_ID; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdResponse.java index c488336fb..8dd76bc65 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/ReportSlaveIdResponse.java @@ -31,46 +31,47 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class ReportSlaveIdResponse extends ModbusResponse { - private byte[] data; + private byte[] data; - ReportSlaveIdResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + ReportSlaveIdResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - ReportSlaveIdResponse(int slaveId, byte[] data) throws ModbusTransportException { - super(slaveId); - this.data = data; - } + ReportSlaveIdResponse(int slaveId, byte[] data) throws ModbusTransportException { + super(slaveId); + this.data = data; + } - @Override - public byte getFunctionCode() { - return FunctionCode.REPORT_SLAVE_ID; - } + @Override + public byte getFunctionCode() { + return FunctionCode.REPORT_SLAVE_ID; + } - @Override - protected void readResponse(ByteQueue queue) { - int numberOfBytes = ModbusUtils.popUnsignedByte(queue); - if (queue.size() < numberOfBytes) - throw new ArrayIndexOutOfBoundsException(); + @Override + protected void readResponse(ByteQueue queue) { + int numberOfBytes = ModbusUtils.popUnsignedByte(queue); + if (queue.size() < numberOfBytes) + throw new ArrayIndexOutOfBoundsException(); - data = new byte[numberOfBytes]; - queue.pop(data); - } + data = new byte[numberOfBytes]; + queue.pop(data); + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushByte(queue, data.length); - queue.push(data); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushByte(queue, data.length); + queue.push(data); + } - /** - *

- * Getter for the field data. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getData() { - return data; - } + /** + *

+ * Getter for the field data. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getData() { + return data; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilRequest.java index 2a21ec75c..66814e426 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilRequest.java @@ -33,60 +33,61 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteCoilRequest extends ModbusRequest { - private int writeOffset; + private int writeOffset; - private boolean writeValue; + private boolean writeValue; - /** - *

- * Constructor for WriteCoilRequest. - *

- * @param slaveId a int. - * @param writeOffset a int. - * @param writeValue a boolean. - * @throws ModbusTransportException if any. - */ - public WriteCoilRequest(int slaveId, int writeOffset, boolean writeValue) throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.writeValue = writeValue; - } + /** + *

+ * Constructor for WriteCoilRequest. + *

+ * + * @param slaveId a int. + * @param writeOffset a int. + * @param writeValue a boolean. + * @throws ModbusTransportException if any. + */ + public WriteCoilRequest(int slaveId, int writeOffset, boolean writeValue) throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.writeValue = writeValue; + } - WriteCoilRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteCoilRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(writeOffset); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(writeOffset); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, writeValue ? 0xff00 : 0); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, writeValue ? 0xff00 : 0); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - processImage.writeCoil(writeOffset, writeValue); - return new WriteCoilResponse(slaveId, writeOffset, writeValue); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + processImage.writeCoil(writeOffset, writeValue); + return new WriteCoilResponse(slaveId, writeOffset, writeValue); + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_COIL; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_COIL; + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new WriteCoilResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new WriteCoilResponse(slaveId); + } - @Override - protected void readRequest(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - writeValue = ModbusUtils.popUnsignedShort(queue) == 0xff00; - } + @Override + protected void readRequest(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + writeValue = ModbusUtils.popUnsignedShort(queue) == 0xff00; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilResponse.java index 8a6d19ec3..981f60ba3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilResponse.java @@ -31,55 +31,57 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteCoilResponse extends ModbusResponse { - private int writeOffset; + private int writeOffset; - private boolean writeValue; + private boolean writeValue; - WriteCoilResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteCoilResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - WriteCoilResponse(int slaveId, int writeOffset, boolean writeValue) throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.writeValue = writeValue; - } + WriteCoilResponse(int slaveId, int writeOffset, boolean writeValue) throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.writeValue = writeValue; + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_COIL; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_COIL; + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, writeValue ? 0xff00 : 0); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, writeValue ? 0xff00 : 0); + } - @Override - protected void readResponse(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - writeValue = ModbusUtils.popUnsignedShort(queue) == 0xff00; - } + @Override + protected void readResponse(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + writeValue = ModbusUtils.popUnsignedShort(queue) == 0xff00; + } - /** - *

- * Getter for the field writeOffset. - *

- * @return a int. - */ - public int getWriteOffset() { - return writeOffset; - } + /** + *

+ * Getter for the field writeOffset. + *

+ * + * @return a int. + */ + public int getWriteOffset() { + return writeOffset; + } - /** - *

- * isWriteValue. - *

- * @return a boolean. - */ - public boolean isWriteValue() { - return writeValue; - } + /** + *

+ * isWriteValue. + *

+ * + * @return a boolean. + */ + public boolean isWriteValue() { + return writeValue; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsRequest.java index 667ddf150..56817cf2e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsRequest.java @@ -33,71 +33,72 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteCoilsRequest extends ModbusRequest { - private int startOffset; + private int startOffset; - private int numberOfBits; + private int numberOfBits; - private byte[] data; + private byte[] data; - /** - *

- * Constructor for WriteCoilsRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param bdata an array of {@link boolean} objects. - * @throws ModbusTransportException if any. - */ - public WriteCoilsRequest(int slaveId, int startOffset, boolean[] bdata) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - numberOfBits = bdata.length; - data = convertToBytes(bdata); - } + /** + *

+ * Constructor for WriteCoilsRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param bdata an array of {@link boolean} objects. + * @throws ModbusTransportException if any. + */ + public WriteCoilsRequest(int slaveId, int startOffset, boolean[] bdata) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + numberOfBits = bdata.length; + data = convertToBytes(bdata); + } - WriteCoilsRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteCoilsRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(startOffset); - modbus.validateNumberOfBits(numberOfBits); - ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(startOffset); + modbus.validateNumberOfBits(numberOfBits); + ModbusUtils.validateEndOffset(startOffset + numberOfBits - 1); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, numberOfBits); - ModbusUtils.pushByte(queue, data.length); - queue.push(data); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, numberOfBits); + ModbusUtils.pushByte(queue, data.length); + queue.push(data); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - boolean[] bdata = convertToBooleans(data); - for (int i = 0; i < numberOfBits; i++) - processImage.writeCoil(startOffset + i, bdata[i]); - return new WriteCoilsResponse(slaveId, startOffset, numberOfBits); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + boolean[] bdata = convertToBooleans(data); + for (int i = 0; i < numberOfBits; i++) + processImage.writeCoil(startOffset + i, bdata[i]); + return new WriteCoilsResponse(slaveId, startOffset, numberOfBits); + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_COILS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_COILS; + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new WriteCoilsResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new WriteCoilsResponse(slaveId); + } - @Override - protected void readRequest(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - numberOfBits = ModbusUtils.popUnsignedShort(queue); - data = new byte[ModbusUtils.popUnsignedByte(queue)]; - queue.pop(data); - } + @Override + protected void readRequest(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + numberOfBits = ModbusUtils.popUnsignedShort(queue); + data = new byte[ModbusUtils.popUnsignedByte(queue)]; + queue.pop(data); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsResponse.java index b31833d40..23475942a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteCoilsResponse.java @@ -31,55 +31,57 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteCoilsResponse extends ModbusResponse { - private int startOffset; + private int startOffset; - private int numberOfBits; + private int numberOfBits; - WriteCoilsResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteCoilsResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - WriteCoilsResponse(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - this.numberOfBits = numberOfBits; - } + WriteCoilsResponse(int slaveId, int startOffset, int numberOfBits) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + this.numberOfBits = numberOfBits; + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_COILS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_COILS; + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, numberOfBits); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, numberOfBits); + } - @Override - protected void readResponse(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - numberOfBits = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readResponse(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + numberOfBits = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * Getter for the field startOffset. - *

- * @return a int. - */ - public int getStartOffset() { - return startOffset; - } + /** + *

+ * Getter for the field startOffset. + *

+ * + * @return a int. + */ + public int getStartOffset() { + return startOffset; + } - /** - *

- * Getter for the field numberOfBits. - *

- * @return a int. - */ - public int getNumberOfBits() { - return numberOfBits; - } + /** + *

+ * Getter for the field numberOfBits. + *

+ * + * @return a int. + */ + public int getNumberOfBits() { + return numberOfBits; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterRequest.java index 92a57d994..1e4dde4b6 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterRequest.java @@ -34,111 +34,114 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteMaskRegisterRequest extends ModbusRequest { - private int writeOffset; + private int writeOffset; - /** - * The andMask determines which bits we want to change. If a bit in the andMask is 1, - * it indicates that the value should not be changed. If it is zero, it should be - * changed according to the orMask value for that bit. - */ - private int andMask; + /** + * The andMask determines which bits we want to change. If a bit in the andMask is 1, + * it indicates that the value should not be changed. If it is zero, it should be + * changed according to the orMask value for that bit. + */ + private int andMask; - /** - * The orMask determines what value a bit will have after writing if the andMask - * allows that bit to be changed. If a changable bit in the orMask is 0, the bit in - * the result will be zero. Ditto for 1. - */ - private int orMask; + /** + * The orMask determines what value a bit will have after writing if the andMask + * allows that bit to be changed. If a changable bit in the orMask is 0, the bit in + * the result will be zero. Ditto for 1. + */ + private int orMask; - /** - * Constructor that defaults the masks to have no effect on the register. Use the - * setBit function to modify mask values. - * @param slaveId a int. - * @param writeOffset a int. - * @throws ModbusTransportException when necessary - */ - public WriteMaskRegisterRequest(int slaveId, int writeOffset) throws ModbusTransportException { - this(slaveId, writeOffset, 0xffff, 0); - } + /** + * Constructor that defaults the masks to have no effect on the register. Use the + * setBit function to modify mask values. + * + * @param slaveId a int. + * @param writeOffset a int. + * @throws ModbusTransportException when necessary + */ + public WriteMaskRegisterRequest(int slaveId, int writeOffset) throws ModbusTransportException { + this(slaveId, writeOffset, 0xffff, 0); + } - /** - *

- * Constructor for WriteMaskRegisterRequest. - *

- * @param slaveId a int. - * @param writeOffset a int. - * @param andMask a int. - * @param orMask a int. - * @throws ModbusTransportException if any. - */ - public WriteMaskRegisterRequest(int slaveId, int writeOffset, int andMask, int orMask) - throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.andMask = andMask; - this.orMask = orMask; - } + /** + *

+ * Constructor for WriteMaskRegisterRequest. + *

+ * + * @param slaveId a int. + * @param writeOffset a int. + * @param andMask a int. + * @param orMask a int. + * @throws ModbusTransportException if any. + */ + public WriteMaskRegisterRequest(int slaveId, int writeOffset, int andMask, int orMask) + throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.andMask = andMask; + this.orMask = orMask; + } - WriteMaskRegisterRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteMaskRegisterRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(writeOffset); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(writeOffset); + } - /** - *

- * setBit. - *

- * @param bit a int. - * @param value a boolean. - */ - public void setBit(int bit, boolean value) { - if (bit < 0 || bit > 15) - throw new ModbusIdException("Bit must be between 0 and 15 inclusive"); + /** + *

+ * setBit. + *

+ * + * @param bit a int. + * @param value a boolean. + */ + public void setBit(int bit, boolean value) { + if (bit < 0 || bit > 15) + throw new ModbusIdException("Bit must be between 0 and 15 inclusive"); - // Set the bit in the andMask to 0 to allow writing. - andMask = andMask & ~(1 << bit); + // Set the bit in the andMask to 0 to allow writing. + andMask = andMask & ~(1 << bit); - // Set the bit in the orMask to write the correct value. - if (value) - orMask = orMask | 1 << bit; - else - orMask = orMask & ~(1 << bit); - } + // Set the bit in the orMask to write the correct value. + if (value) + orMask = orMask | 1 << bit; + else + orMask = orMask & ~(1 << bit); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, andMask); - ModbusUtils.pushShort(queue, orMask); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, andMask); + ModbusUtils.pushShort(queue, orMask); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - short value = processImage.getHoldingRegister(writeOffset); - value = (short) ((value & andMask) | (orMask & (~andMask))); - processImage.writeHoldingRegister(writeOffset, value); - return new WriteMaskRegisterResponse(slaveId, writeOffset, andMask, orMask); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + short value = processImage.getHoldingRegister(writeOffset); + value = (short) ((value & andMask) | (orMask & (~andMask))); + processImage.writeHoldingRegister(writeOffset, value); + return new WriteMaskRegisterResponse(slaveId, writeOffset, andMask, orMask); + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_MASK_REGISTER; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_MASK_REGISTER; + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new WriteMaskRegisterResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new WriteMaskRegisterResponse(slaveId); + } - @Override - protected void readRequest(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - andMask = ModbusUtils.popUnsignedShort(queue); - orMask = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readRequest(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + andMask = ModbusUtils.popUnsignedShort(queue); + orMask = ModbusUtils.popUnsignedShort(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterResponse.java index fecadc50e..3d30b858e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteMaskRegisterResponse.java @@ -31,70 +31,73 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteMaskRegisterResponse extends ModbusResponse { - private int writeOffset; + private int writeOffset; - private int andMask; + private int andMask; - private int orMask; + private int orMask; - WriteMaskRegisterResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteMaskRegisterResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - WriteMaskRegisterResponse(int slaveId, int writeOffset, int andMask, int orMask) throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.andMask = andMask; - this.orMask = orMask; - } + WriteMaskRegisterResponse(int slaveId, int writeOffset, int andMask, int orMask) throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.andMask = andMask; + this.orMask = orMask; + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_MASK_REGISTER; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_MASK_REGISTER; + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, andMask); - ModbusUtils.pushShort(queue, orMask); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, andMask); + ModbusUtils.pushShort(queue, orMask); + } - @Override - protected void readResponse(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - andMask = ModbusUtils.popUnsignedShort(queue); - orMask = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readResponse(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + andMask = ModbusUtils.popUnsignedShort(queue); + orMask = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * Getter for the field writeOffset. - *

- * @return a int. - */ - public int getWriteOffset() { - return writeOffset; - } + /** + *

+ * Getter for the field writeOffset. + *

+ * + * @return a int. + */ + public int getWriteOffset() { + return writeOffset; + } - /** - *

- * Getter for the field andMask. - *

- * @return a int. - */ - public int getAndMask() { - return andMask; - } + /** + *

+ * Getter for the field andMask. + *

+ * + * @return a int. + */ + public int getAndMask() { + return andMask; + } - /** - *

- * Getter for the field orMask. - *

- * @return a int. - */ - public int getOrMask() { - return orMask; - } + /** + *

+ * Getter for the field orMask. + *

+ * + * @return a int. + */ + public int getOrMask() { + return orMask; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterRequest.java index 36554b27e..f846f9c96 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterRequest.java @@ -33,60 +33,61 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteRegisterRequest extends ModbusRequest { - private int writeOffset; + private int writeOffset; - private int writeValue; + private int writeValue; - /** - *

- * Constructor for WriteRegisterRequest. - *

- * @param slaveId a int. - * @param writeOffset a int. - * @param writeValue a int. - * @throws ModbusTransportException if any. - */ - public WriteRegisterRequest(int slaveId, int writeOffset, int writeValue) throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.writeValue = writeValue; - } + /** + *

+ * Constructor for WriteRegisterRequest. + *

+ * + * @param slaveId a int. + * @param writeOffset a int. + * @param writeValue a int. + * @throws ModbusTransportException if any. + */ + public WriteRegisterRequest(int slaveId, int writeOffset, int writeValue) throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.writeValue = writeValue; + } - WriteRegisterRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteRegisterRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(writeOffset); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(writeOffset); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, writeValue); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, writeValue); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - processImage.writeHoldingRegister(writeOffset, (short) writeValue); - return new WriteRegisterResponse(slaveId, writeOffset, writeValue); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + processImage.writeHoldingRegister(writeOffset, (short) writeValue); + return new WriteRegisterResponse(slaveId, writeOffset, writeValue); + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_REGISTER; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_REGISTER; + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new WriteRegisterResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new WriteRegisterResponse(slaveId); + } - @Override - protected void readRequest(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - writeValue = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readRequest(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + writeValue = ModbusUtils.popUnsignedShort(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterResponse.java index fb2130ec2..fc98fb7c0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegisterResponse.java @@ -31,55 +31,57 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteRegisterResponse extends ModbusResponse { - private int writeOffset; + private int writeOffset; - private int writeValue; + private int writeValue; - WriteRegisterResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteRegisterResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - WriteRegisterResponse(int slaveId, int writeOffset, int writeValue) throws ModbusTransportException { - super(slaveId); - this.writeOffset = writeOffset; - this.writeValue = writeValue; - } + WriteRegisterResponse(int slaveId, int writeOffset, int writeValue) throws ModbusTransportException { + super(slaveId); + this.writeOffset = writeOffset; + this.writeValue = writeValue; + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_REGISTER; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_REGISTER; + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushShort(queue, writeOffset); - ModbusUtils.pushShort(queue, writeValue); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushShort(queue, writeOffset); + ModbusUtils.pushShort(queue, writeValue); + } - @Override - protected void readResponse(ByteQueue queue) { - writeOffset = ModbusUtils.popUnsignedShort(queue); - writeValue = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readResponse(ByteQueue queue) { + writeOffset = ModbusUtils.popUnsignedShort(queue); + writeValue = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * Getter for the field writeOffset. - *

- * @return a int. - */ - public int getWriteOffset() { - return writeOffset; - } + /** + *

+ * Getter for the field writeOffset. + *

+ * + * @return a int. + */ + public int getWriteOffset() { + return writeOffset; + } - /** - *

- * Getter for the field writeValue. - *

- * @return a int. - */ - public int getWriteValue() { - return writeValue; - } + /** + *

+ * Getter for the field writeValue. + *

+ * + * @return a int. + */ + public int getWriteValue() { + return writeValue; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersRequest.java index 6840d5a67..cf4da9567 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersRequest.java @@ -33,70 +33,71 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteRegistersRequest extends ModbusRequest { - private int startOffset; + private int startOffset; - private byte[] data; + private byte[] data; - /** - *

- * Constructor for WriteRegistersRequest. - *

- * @param slaveId a int. - * @param startOffset a int. - * @param sdata an array of {@link short} objects. - * @throws ModbusTransportException if any. - */ - public WriteRegistersRequest(int slaveId, int startOffset, short[] sdata) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - data = convertToBytes(sdata); - } + /** + *

+ * Constructor for WriteRegistersRequest. + *

+ * + * @param slaveId a int. + * @param startOffset a int. + * @param sdata an array of {@link short} objects. + * @throws ModbusTransportException if any. + */ + public WriteRegistersRequest(int slaveId, int startOffset, short[] sdata) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + data = convertToBytes(sdata); + } - WriteRegistersRequest(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteRegistersRequest(int slaveId) throws ModbusTransportException { + super(slaveId); + } - @Override - public void validate(Modbus modbus) throws ModbusTransportException { - ModbusUtils.validateOffset(startOffset); - int registerCount = data.length / 2; - if (registerCount < 1 || registerCount > modbus.getMaxWriteRegisterCount()) - throw new ModbusTransportException("Invalid number of registers: " + registerCount, slaveId); - ModbusUtils.validateEndOffset(startOffset + registerCount - 1); - } + @Override + public void validate(Modbus modbus) throws ModbusTransportException { + ModbusUtils.validateOffset(startOffset); + int registerCount = data.length / 2; + if (registerCount < 1 || registerCount > modbus.getMaxWriteRegisterCount()) + throw new ModbusTransportException("Invalid number of registers: " + registerCount, slaveId); + ModbusUtils.validateEndOffset(startOffset + registerCount - 1); + } - @Override - protected void writeRequest(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, data.length / 2); - ModbusUtils.pushByte(queue, data.length); - queue.push(data); - } + @Override + protected void writeRequest(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, data.length / 2); + ModbusUtils.pushByte(queue, data.length); + queue.push(data); + } - @Override - ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { - short[] sdata = convertToShorts(data); - for (int i = 0; i < sdata.length; i++) - processImage.writeHoldingRegister(startOffset + i, sdata[i]); - return new WriteRegistersResponse(slaveId, startOffset, sdata.length); - } + @Override + ModbusResponse handleImpl(ProcessImage processImage) throws ModbusTransportException { + short[] sdata = convertToShorts(data); + for (int i = 0; i < sdata.length; i++) + processImage.writeHoldingRegister(startOffset + i, sdata[i]); + return new WriteRegistersResponse(slaveId, startOffset, sdata.length); + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_REGISTERS; + } - @Override - ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { - return new WriteRegistersResponse(slaveId); - } + @Override + ModbusResponse getResponseInstance(int slaveId) throws ModbusTransportException { + return new WriteRegistersResponse(slaveId); + } - @Override - protected void readRequest(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - ModbusUtils.popUnsignedShort(queue); // register count not needed. - data = new byte[ModbusUtils.popUnsignedByte(queue)]; - queue.pop(data); - } + @Override + protected void readRequest(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + ModbusUtils.popUnsignedShort(queue); // register count not needed. + data = new byte[ModbusUtils.popUnsignedByte(queue)]; + queue.pop(data); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersResponse.java index bff4924db..92e3d6c6b 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/msg/WriteRegistersResponse.java @@ -31,55 +31,57 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class WriteRegistersResponse extends ModbusResponse { - private int startOffset; + private int startOffset; - private int numberOfRegisters; + private int numberOfRegisters; - WriteRegistersResponse(int slaveId) throws ModbusTransportException { - super(slaveId); - } + WriteRegistersResponse(int slaveId) throws ModbusTransportException { + super(slaveId); + } - WriteRegistersResponse(int slaveId, int startOffset, int numberOfRegisters) throws ModbusTransportException { - super(slaveId); - this.startOffset = startOffset; - this.numberOfRegisters = numberOfRegisters; - } + WriteRegistersResponse(int slaveId, int startOffset, int numberOfRegisters) throws ModbusTransportException { + super(slaveId); + this.startOffset = startOffset; + this.numberOfRegisters = numberOfRegisters; + } - @Override - public byte getFunctionCode() { - return FunctionCode.WRITE_REGISTERS; - } + @Override + public byte getFunctionCode() { + return FunctionCode.WRITE_REGISTERS; + } - @Override - protected void writeResponse(ByteQueue queue) { - ModbusUtils.pushShort(queue, startOffset); - ModbusUtils.pushShort(queue, numberOfRegisters); - } + @Override + protected void writeResponse(ByteQueue queue) { + ModbusUtils.pushShort(queue, startOffset); + ModbusUtils.pushShort(queue, numberOfRegisters); + } - @Override - protected void readResponse(ByteQueue queue) { - startOffset = ModbusUtils.popUnsignedShort(queue); - numberOfRegisters = ModbusUtils.popUnsignedShort(queue); - } + @Override + protected void readResponse(ByteQueue queue) { + startOffset = ModbusUtils.popUnsignedShort(queue); + numberOfRegisters = ModbusUtils.popUnsignedShort(queue); + } - /** - *

- * Getter for the field startOffset. - *

- * @return a int. - */ - public int getStartOffset() { - return startOffset; - } + /** + *

+ * Getter for the field startOffset. + *

+ * + * @return a int. + */ + public int getStartOffset() { + return startOffset; + } - /** - *

- * Getter for the field numberOfRegisters. - *

- * @return a int. - */ - public int getNumberOfRegisters() { - return numberOfRegisters; - } + /** + *

+ * Getter for the field numberOfRegisters. + *

+ * + * @return a int. + */ + public int getNumberOfRegisters() { + return numberOfRegisters; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMaster.java index ee526227e..020a3880d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMaster.java @@ -34,142 +34,140 @@ import org.apache.commons.logging.LogFactory; * @version 2025.9.0 */ abstract /** - * Serial Master - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Serial Master + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class SerialMaster extends ModbusMaster { - private static final int RETRY_PAUSE_START = 50; + private static final int RETRY_PAUSE_START = 50; - private static final int RETRY_PAUSE_MAX = 1000; + private static final int RETRY_PAUSE_MAX = 1000; - private final Log LOG = LogFactory.getLog(SerialMaster.class); + private final Log LOG = LogFactory.getLog(SerialMaster.class); - // Runtime fields. - protected boolean serialPortOpen; + // Runtime fields. + protected boolean serialPortOpen; - protected SerialPortWrapper wrapper; + protected SerialPortWrapper wrapper; - protected Transport transport; + protected Transport transport; - /** - *

- * Constructor for SerialMaster. - *

- *

- * Default to validating the slave id in responses - * @param wrapper a {@link SerialPortWrapper} object. - */ - public SerialMaster(SerialPortWrapper wrapper) { - this(wrapper, true); - } + /** + *

+ * Constructor for SerialMaster. + *

+ *

+ * Default to validating the slave id in responses + * + * @param wrapper a {@link SerialPortWrapper} object. + */ + public SerialMaster(SerialPortWrapper wrapper) { + this(wrapper, true); + } - /** - *

- * Constructor for SerialMaster. - *

- * @param wrapper a {@link SerialPortWrapper} object. - * @param validateResponse - confirm that requested slave id is the same in the - * response - */ - public SerialMaster(SerialPortWrapper wrapper, boolean validateResponse) { - this.wrapper = wrapper; - this.validateResponse = validateResponse; - } + /** + *

+ * Constructor for SerialMaster. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + * @param validateResponse - confirm that requested slave id is the same in the + * response + */ + public SerialMaster(SerialPortWrapper wrapper, boolean validateResponse) { + this.wrapper = wrapper; + this.validateResponse = validateResponse; + } - @Override - public void init() throws ModbusInitException { - try { - this.openConnection(null); - } - catch (Exception e) { - throw new ModbusInitException(e); - } - } + @Override + public void init() throws ModbusInitException { + try { + this.openConnection(null); + } catch (Exception e) { + throw new ModbusInitException(e); + } + } - /** - * Open the serial port and initialize the transport, ensure connection is closed - * first - * @param conn - * @throws Exception - */ - protected void openConnection(MessageControl toClose) throws Exception { - // Make sure any existing connection is closed. - closeConnection(toClose); + /** + * Open the serial port and initialize the transport, ensure connection is closed + * first + * + * @param conn + * @throws Exception + */ + protected void openConnection(MessageControl toClose) throws Exception { + // Make sure any existing connection is closed. + closeConnection(toClose); - // Try 'retries' times to get the socket open. - int retries = getRetries(); - int retryPause = RETRY_PAUSE_START; - while (true) { - try { - this.wrapper.open(); - this.serialPortOpen = true; - if (getePoll() != null) { - transport = new EpollStreamTransport(wrapper.getInputStream(), wrapper.getOutputStream(), - getePoll()); - } - else { - transport = new StreamTransport(wrapper.getInputStream(), wrapper.getOutputStream()); - } - break; - } - catch (Exception e) { - // Ensure port is closed before we try to reopen or bail out - close(); + // Try 'retries' times to get the socket open. + int retries = getRetries(); + int retryPause = RETRY_PAUSE_START; + while (true) { + try { + this.wrapper.open(); + this.serialPortOpen = true; + if (getePoll() != null) { + transport = new EpollStreamTransport(wrapper.getInputStream(), wrapper.getOutputStream(), + getePoll()); + } else { + transport = new StreamTransport(wrapper.getInputStream(), wrapper.getOutputStream()); + } + break; + } catch (Exception e) { + // Ensure port is closed before we try to reopen or bail out + close(); - if (retries <= 0) - throw e; + if (retries <= 0) + throw e; - retries--; + retries--; - // Pause for a bit. - try { - Thread.sleep(retryPause); - } - catch (InterruptedException e1) { - // ignore - } - retryPause *= 2; - if (retryPause > RETRY_PAUSE_MAX) - retryPause = RETRY_PAUSE_MAX; - } - } - } + // Pause for a bit. + try { + Thread.sleep(retryPause); + } catch (InterruptedException e1) { + // ignore + } + retryPause *= 2; + if (retryPause > RETRY_PAUSE_MAX) + retryPause = RETRY_PAUSE_MAX; + } + } + } - /** - * Close serial port - * @param conn - */ - protected void closeConnection(MessageControl conn) { - closeMessageControl(conn); - try { - if (serialPortOpen) { - wrapper.close(); - serialPortOpen = false; - } - } - catch (Exception e) { - getExceptionHandler().receivedException(e); - } + /** + * Close serial port + * + * @param conn + */ + protected void closeConnection(MessageControl conn) { + closeMessageControl(conn); + try { + if (serialPortOpen) { + wrapper.close(); + serialPortOpen = false; + } + } catch (Exception e) { + getExceptionHandler().receivedException(e); + } - transport = null; - } + transport = null; + } - /** - *

- * close. - *

- */ - public void close() { - try { - wrapper.close(); - } - catch (Exception e) { - LOG.error(e.getMessage(), e); - } - } + /** + *

+ * close. + *

+ */ + public void close() { + try { + wrapper.close(); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMessage.java index d4705bac8..c69d1c86e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialMessage.java @@ -28,39 +28,41 @@ import com.serotonin.modbus4j.msg.ModbusMessage; * @version 2025.9.0 */ abstract /** - * Serial Message - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Serial Message + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class SerialMessage { - protected final ModbusMessage modbusMessage; + protected final ModbusMessage modbusMessage; - /** - *

- * Constructor for SerialMessage. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public SerialMessage(ModbusMessage modbusMessage) { - this.modbusMessage = modbusMessage; - } + /** + *

+ * Constructor for SerialMessage. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public SerialMessage(ModbusMessage modbusMessage) { + this.modbusMessage = modbusMessage; + } - /** - *

- * Getter for the field modbusMessage. - *

- * @return a {@link ModbusMessage} object. - */ - public ModbusMessage getModbusMessage() { - return modbusMessage; - } + /** + *

+ * Getter for the field modbusMessage. + *

+ * + * @return a {@link ModbusMessage} object. + */ + public ModbusMessage getModbusMessage() { + return modbusMessage; + } - @Override - public String toString() { - return "SerialMessage [modbusMessage=" + modbusMessage + "]"; - } + @Override + public String toString() { + return "SerialMessage [modbusMessage=" + modbusMessage + "]"; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialPortWrapper.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialPortWrapper.java index 35ec890fa..c6e002c31 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialPortWrapper.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialPortWrapper.java @@ -27,62 +27,70 @@ import java.io.OutputStream; */ public interface SerialPortWrapper { - /** - * Close the Serial Port - * @throws Exception if any. - */ - void close() throws Exception; + /** + * Close the Serial Port + * + * @throws Exception if any. + */ + void close() throws Exception; - /** - *

- * open. - *

- * @throws Exception if any. - */ - void open() throws Exception; + /** + *

+ * open. + *

+ * + * @throws Exception if any. + */ + void open() throws Exception; - /** - * Return the input stream for an open port - * @return a {@link InputStream} object. - */ - InputStream getInputStream(); + /** + * Return the input stream for an open port + * + * @return a {@link InputStream} object. + */ + InputStream getInputStream(); - /** - * Return the output stream for an open port - * @return a {@link OutputStream} object. - */ - OutputStream getOutputStream(); + /** + * Return the output stream for an open port + * + * @return a {@link OutputStream} object. + */ + OutputStream getOutputStream(); - /** - *

- * getBaudRate. - *

- * @return a int. - */ - int getBaudRate(); + /** + *

+ * getBaudRate. + *

+ * + * @return a int. + */ + int getBaudRate(); - /** - *

- * getDataBits. - *

- * @return a int. - */ - int getDataBits(); + /** + *

+ * getDataBits. + *

+ * + * @return a int. + */ + int getDataBits(); - /** - *

- * getStopBits. - *

- * @return a int. - */ - int getStopBits(); + /** + *

+ * getStopBits. + *

+ * + * @return a int. + */ + int getStopBits(); - /** - *

- * getParity. - *

- * @return a int. - */ - int getParity(); + /** + *

+ * getParity. + *

+ * + * @return a int. + */ + int getParity(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialSlave.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialSlave.java index f404fa45b..2fe7e0828 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialSlave.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialSlave.java @@ -31,52 +31,51 @@ import org.apache.commons.logging.LogFactory; * @version 2025.9.0 */ abstract /** - * Serial Slave - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Serial Slave + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class SerialSlave extends ModbusSlaveSet { - private final Log LOG = LogFactory.getLog(SerialSlave.class); + private final Log LOG = LogFactory.getLog(SerialSlave.class); - protected StreamTransport transport; + protected StreamTransport transport; - // Runtime fields - private SerialPortWrapper wrapper; + // Runtime fields + private SerialPortWrapper wrapper; - /** - *

- * Constructor for SerialSlave. - *

- * @param wrapper a {@link SerialPortWrapper} object. - */ - public SerialSlave(SerialPortWrapper wrapper) { - this.wrapper = wrapper; - } + /** + *

+ * Constructor for SerialSlave. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + */ + public SerialSlave(SerialPortWrapper wrapper) { + this.wrapper = wrapper; + } - @Override - public void start() throws ModbusInitException { - try { + @Override + public void start() throws ModbusInitException { + try { - wrapper.open(); + wrapper.open(); - transport = new StreamTransport(wrapper.getInputStream(), wrapper.getOutputStream()); - } - catch (Exception e) { - throw new ModbusInitException(e); - } - } + transport = new StreamTransport(wrapper.getInputStream(), wrapper.getOutputStream()); + } catch (Exception e) { + throw new ModbusInitException(e); + } + } - @Override - public void stop() { - try { - wrapper.close(); - } - catch (Exception e) { - LOG.error(e.getMessage(), e); - } - } + @Override + public void stop() { + try { + wrapper.close(); + } catch (Exception e) { + LOG.error(e.getMessage(), e); + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialWaitingRoomKeyFactory.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialWaitingRoomKeyFactory.java index 8ef69b774..50e327d59 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialWaitingRoomKeyFactory.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/SerialWaitingRoomKeyFactory.java @@ -32,36 +32,36 @@ import com.serotonin.modbus4j.sero.messaging.WaitingRoomKeyFactory; */ public class SerialWaitingRoomKeyFactory implements WaitingRoomKeyFactory { - private static final Sync sync = new Sync(); + private static final Sync sync = new Sync(); - @Override - public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { - return sync; - } + @Override + public WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request) { + return sync; + } - @Override - public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { - return sync; - } + @Override + public WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response) { + return sync; + } - static class Sync implements WaitingRoomKey { + static class Sync implements WaitingRoomKey { - @Override - public int hashCode() { - return 1; - } + @Override + public int hashCode() { + return 1; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + return true; + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMaster.java index d01208d5f..efa365613 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMaster.java @@ -38,88 +38,86 @@ import org.apache.commons.logging.LogFactory; */ public class AsciiMaster extends SerialMaster { - private final Log LOG = LogFactory.getLog(SerialMaster.class); + private final Log LOG = LogFactory.getLog(SerialMaster.class); - private MessageControl conn; + private MessageControl conn; - /** - *

- * Constructor for AsciiMaster. - *

- *

- * Default to validating the slave id in responses - * @param wrapper a {@link SerialPortWrapper} object. - */ - public AsciiMaster(SerialPortWrapper wrapper) { - super(wrapper, true); - } + /** + *

+ * Constructor for AsciiMaster. + *

+ *

+ * Default to validating the slave id in responses + * + * @param wrapper a {@link SerialPortWrapper} object. + */ + public AsciiMaster(SerialPortWrapper wrapper) { + super(wrapper, true); + } - /** - * @param wrapper a {@link SerialPortWrapper} object. - * @param validateResponse - confirm that requested slave id is the same in the - * response - */ - public AsciiMaster(SerialPortWrapper wrapper, boolean validateResponse) { - super(wrapper, validateResponse); - } + /** + * @param wrapper a {@link SerialPortWrapper} object. + * @param validateResponse - confirm that requested slave id is the same in the + * response + */ + public AsciiMaster(SerialPortWrapper wrapper, boolean validateResponse) { + super(wrapper, validateResponse); + } - @Override - public void init() throws ModbusInitException { - try { - openConnection(null); - } - catch (Exception e) { - throw new ModbusInitException(e); - } - initialized = true; - } + @Override + public void init() throws ModbusInitException { + try { + openConnection(null); + } catch (Exception e) { + throw new ModbusInitException(e); + } + initialized = true; + } - @Override - protected void openConnection(MessageControl toClose) throws Exception { - super.openConnection(toClose); - AsciiMessageParser asciiMessageParser = new AsciiMessageParser(true); - this.conn = getMessageControl(); - this.conn.start(transport, asciiMessageParser, null, new SerialWaitingRoomKeyFactory()); - if (getePoll() == null) { - ((StreamTransport) transport).start("Modbus ASCII master"); - } - } + @Override + protected void openConnection(MessageControl toClose) throws Exception { + super.openConnection(toClose); + AsciiMessageParser asciiMessageParser = new AsciiMessageParser(true); + this.conn = getMessageControl(); + this.conn.start(transport, asciiMessageParser, null, new SerialWaitingRoomKeyFactory()); + if (getePoll() == null) { + ((StreamTransport) transport).start("Modbus ASCII master"); + } + } - @Override - public void destroy() { - closeMessageControl(conn); - super.close(); - initialized = false; - } + @Override + public void destroy() { + closeMessageControl(conn); + super.close(); + initialized = false; + } - @Override - public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { - // Wrap the modbus request in an ascii request. - AsciiMessageRequest asciiRequest = new AsciiMessageRequest(request); + @Override + public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { + // Wrap the modbus request in an ascii request. + AsciiMessageRequest asciiRequest = new AsciiMessageRequest(request); - // Send the request to get the response. - AsciiMessageResponse asciiResponse; - try { - asciiResponse = (AsciiMessageResponse) conn.send(asciiRequest); - if (asciiResponse == null) - return null; - return asciiResponse.getModbusResponse(); - } - catch (Exception e) { - try { - LOG.debug("Connection may have been reset. Attempting to re-open."); - openConnection(conn); - asciiResponse = (AsciiMessageResponse) conn.send(asciiRequest); - if (asciiResponse == null) - return null; - return asciiResponse.getModbusResponse(); - } - catch (Exception e2) { - closeConnection(conn); - LOG.debug("Failed to re-connect", e); - throw new ModbusTransportException(e2, request.getSlaveId()); - } - } - } + // Send the request to get the response. + AsciiMessageResponse asciiResponse; + try { + asciiResponse = (AsciiMessageResponse) conn.send(asciiRequest); + if (asciiResponse == null) + return null; + return asciiResponse.getModbusResponse(); + } catch (Exception e) { + try { + LOG.debug("Connection may have been reset. Attempting to re-open."); + openConnection(conn); + asciiResponse = (AsciiMessageResponse) conn.send(asciiRequest); + if (asciiResponse == null) + return null; + return asciiResponse.getModbusResponse(); + } catch (Exception e2) { + closeConnection(conn); + LOG.debug("Failed to re-connect", e); + throw new ModbusTransportException(e2, request.getSlaveId()); + } + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessage.java index ac506ba8a..862b45936 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessage.java @@ -30,154 +30,157 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; * @version 2025.9.0 */ abstract /** - * Ascii Message - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Ascii Message + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class AsciiMessage extends SerialMessage { - private static final byte START = ':'; + private static final byte START = ':'; - private static final byte[] END = { '\r', '\n' }; + private static final byte[] END = {'\r', '\n'}; - private static byte[] lookupAscii = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, - 0x44, 0x45, 0x46, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; + private static byte[] lookupAscii = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, + 0x44, 0x45, 0x46, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}; - private static byte[] lookupUnascii = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, - 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; + private static byte[] lookupUnascii = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, + 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,}; - AsciiMessage(ModbusMessage modbusMessage) { - super(modbusMessage); - } + AsciiMessage(ModbusMessage modbusMessage) { + super(modbusMessage); + } - /** - *

- * getUnasciiMessage. - *

- * @param queue a {@link ByteQueue} object. - * @return a {@link ByteQueue} object. - * @throws ModbusTransportException if any. - */ - protected static ByteQueue getUnasciiMessage(ByteQueue queue) throws ModbusTransportException { - // Validate that the message starts with the required indicator - byte b = queue.pop(); - if (b != START) - throw new ModbusTransportException("Invalid message start: " + b); + /** + *

+ * getUnasciiMessage. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return a {@link ByteQueue} object. + * @throws ModbusTransportException if any. + */ + protected static ByteQueue getUnasciiMessage(ByteQueue queue) throws ModbusTransportException { + // Validate that the message starts with the required indicator + byte b = queue.pop(); + if (b != START) + throw new ModbusTransportException("Invalid message start: " + b); - // Find the end indicator - int end = queue.indexOf(END); - if (end == -1) - throw new ArrayIndexOutOfBoundsException(); + // Find the end indicator + int end = queue.indexOf(END); + if (end == -1) + throw new ArrayIndexOutOfBoundsException(); - // Remove the message from the queue, leaving the LRC there - byte[] asciiBytes = new byte[end - 2]; - queue.pop(asciiBytes); - ByteQueue msgQueue = new ByteQueue(asciiBytes); + // Remove the message from the queue, leaving the LRC there + byte[] asciiBytes = new byte[end - 2]; + queue.pop(asciiBytes); + ByteQueue msgQueue = new ByteQueue(asciiBytes); - // Pop off the LRC - byte givenLrc = readAscii(queue); + // Pop off the LRC + byte givenLrc = readAscii(queue); - // Pop the end indicator off of the queue - queue.pop(END.length); + // Pop the end indicator off of the queue + queue.pop(END.length); - // Convert to unascii - fromAscii(msgQueue, msgQueue.size()); + // Convert to unascii + fromAscii(msgQueue, msgQueue.size()); - // Check the LRC - int calcLrc = calculateLRC(msgQueue, 0, msgQueue.size()); - if (calcLrc != givenLrc) - throw new ModbusTransportException( - "LRC mismatch: given=" + (givenLrc & 0xff) + ", calc=" + (calcLrc & 0xff)); + // Check the LRC + int calcLrc = calculateLRC(msgQueue, 0, msgQueue.size()); + if (calcLrc != givenLrc) + throw new ModbusTransportException( + "LRC mismatch: given=" + (givenLrc & 0xff) + ", calc=" + (calcLrc & 0xff)); - return msgQueue; - } + return msgQueue; + } - private static byte calculateLRC(ByteQueue queue, int start, int len) { - int lrc = 0; - for (int i = 0; i < len; i++) - lrc -= queue.peek(i + start); - return (byte) (lrc & 0xff); - } + private static byte calculateLRC(ByteQueue queue, int start, int len) { + int lrc = 0; + for (int i = 0; i < len; i++) + lrc -= queue.peek(i + start); + return (byte) (lrc & 0xff); + } - private static void toAscii(ByteQueue queue, int unasciiLen) { - for (int i = 0; i < unasciiLen; i++) - writeAscii(queue, queue.pop()); - } + private static void toAscii(ByteQueue queue, int unasciiLen) { + for (int i = 0; i < unasciiLen; i++) + writeAscii(queue, queue.pop()); + } - private static void writeAscii(ByteQueue to, byte b) { - to.push(lookupAscii[b & 0xf0]); - to.push(lookupAscii[b & 0x0f]); - } + private static void writeAscii(ByteQueue to, byte b) { + to.push(lookupAscii[b & 0xf0]); + to.push(lookupAscii[b & 0x0f]); + } - private static void fromAscii(ByteQueue queue, int asciiLen) { - int len = asciiLen / 2; - for (int i = 0; i < len; i++) - queue.push(readAscii(queue)); - } + private static void fromAscii(ByteQueue queue, int asciiLen) { + int len = asciiLen / 2; + for (int i = 0; i < len; i++) + queue.push(readAscii(queue)); + } - private static byte readAscii(ByteQueue from) { - return (byte) ((lookupUnascii[from.pop()] << 4) | lookupUnascii[from.pop()]); - } + private static byte readAscii(ByteQueue from) { + return (byte) ((lookupUnascii[from.pop()] << 4) | lookupUnascii[from.pop()]); + } - /** - *

- * getAsciiData. - *

- * @param queue a {@link ByteQueue} object. - * @return an array of {@link byte} objects. - */ - protected byte[] getAsciiData(ByteQueue queue) { - int unasciiLen = queue.size(); + /** + *

+ * getAsciiData. + *

+ * + * @param queue a {@link ByteQueue} object. + * @return an array of {@link byte} objects. + */ + protected byte[] getAsciiData(ByteQueue queue) { + int unasciiLen = queue.size(); - // Convert the message to ascii - queue.push(START); - byte lrc = calculateLRC(queue, 0, unasciiLen); - toAscii(queue, unasciiLen); - writeAscii(queue, lrc); - queue.push(END); + // Convert the message to ascii + queue.push(START); + byte lrc = calculateLRC(queue, 0, unasciiLen); + toAscii(queue, unasciiLen); + writeAscii(queue, lrc); + queue.push(END); - // Return the data. - return queue.popAll(); - } + // Return the data. + return queue.popAll(); + } - /** - *

- * getMessageData. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getMessageData() { - ByteQueue queue = new ByteQueue(); - modbusMessage.write(queue); - return getAsciiData(queue); - } + /** + *

+ * getMessageData. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getMessageData() { + ByteQueue queue = new ByteQueue(); + modbusMessage.write(queue); + return getAsciiData(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageParser.java index 2d3dbcf01..16fd03df7 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageParser.java @@ -30,21 +30,22 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class AsciiMessageParser extends BaseMessageParser { - /** - *

- * Constructor for AsciiMessageParser. - *

- * @param master a boolean. - */ - public AsciiMessageParser(boolean master) { - super(master); - } + /** + *

+ * Constructor for AsciiMessageParser. + *

+ * + * @param master a boolean. + */ + public AsciiMessageParser(boolean master) { + super(master); + } - @Override - protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { - if (master) - return AsciiMessageResponse.createAsciiMessageResponse(queue); - return AsciiMessageRequest.createAsciiMessageRequest(queue); - } + @Override + protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { + if (master) + return AsciiMessageResponse.createAsciiMessageResponse(queue); + return AsciiMessageRequest.createAsciiMessageRequest(queue); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageRequest.java index 16513b31d..6d6e8d155 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageRequest.java @@ -33,38 +33,40 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class AsciiMessageRequest extends AsciiMessage implements OutgoingRequestMessage, IncomingRequestMessage { - /** - *

- * Constructor for AsciiMessageRequest. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public AsciiMessageRequest(ModbusMessage modbusMessage) { - super(modbusMessage); - } + /** + *

+ * Constructor for AsciiMessageRequest. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public AsciiMessageRequest(ModbusMessage modbusMessage) { + super(modbusMessage); + } - static AsciiMessageRequest createAsciiMessageRequest(ByteQueue queue) throws ModbusTransportException { - ByteQueue msgQueue = getUnasciiMessage(queue); - ModbusRequest request = ModbusRequest.createModbusRequest(msgQueue); - AsciiMessageRequest asciiRequest = new AsciiMessageRequest(request); + static AsciiMessageRequest createAsciiMessageRequest(ByteQueue queue) throws ModbusTransportException { + ByteQueue msgQueue = getUnasciiMessage(queue); + ModbusRequest request = ModbusRequest.createModbusRequest(msgQueue); + AsciiMessageRequest asciiRequest = new AsciiMessageRequest(request); - // Return the data. - return asciiRequest; - } + // Return the data. + return asciiRequest; + } - @Override - public boolean expectsResponse() { - return modbusMessage.getSlaveId() != 0; - } + @Override + public boolean expectsResponse() { + return modbusMessage.getSlaveId() != 0; + } - /** - *

- * getModbusRequest. - *

- * @return a {@link ModbusRequest} object. - */ - public ModbusRequest getModbusRequest() { - return (ModbusRequest) modbusMessage; - } + /** + *

+ * getModbusRequest. + *

+ * + * @return a {@link ModbusRequest} object. + */ + public ModbusRequest getModbusRequest() { + return (ModbusRequest) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageResponse.java index cea92b249..8bacd90d9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiMessageResponse.java @@ -33,33 +33,35 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class AsciiMessageResponse extends AsciiMessage implements OutgoingResponseMessage, IncomingResponseMessage { - /** - *

- * Constructor for AsciiMessageResponse. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public AsciiMessageResponse(ModbusMessage modbusMessage) { - super(modbusMessage); - } + /** + *

+ * Constructor for AsciiMessageResponse. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public AsciiMessageResponse(ModbusMessage modbusMessage) { + super(modbusMessage); + } - static AsciiMessageResponse createAsciiMessageResponse(ByteQueue queue) throws ModbusTransportException { - ByteQueue msgQueue = getUnasciiMessage(queue); - ModbusResponse response = ModbusResponse.createModbusResponse(msgQueue); - AsciiMessageResponse asciiResponse = new AsciiMessageResponse(response); + static AsciiMessageResponse createAsciiMessageResponse(ByteQueue queue) throws ModbusTransportException { + ByteQueue msgQueue = getUnasciiMessage(queue); + ModbusResponse response = ModbusResponse.createModbusResponse(msgQueue); + AsciiMessageResponse asciiResponse = new AsciiMessageResponse(response); - // Return the data. - return asciiResponse; - } + // Return the data. + return asciiResponse; + } - /** - *

- * getModbusResponse. - *

- * @return a {@link ModbusResponse} object. - */ - public ModbusResponse getModbusResponse() { - return (ModbusResponse) modbusMessage; - } + /** + *

+ * getModbusResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + public ModbusResponse getModbusResponse() { + return (ModbusResponse) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiRequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiRequestHandler.java index 5f8c84435..a07cc9a6e 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiRequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiRequestHandler.java @@ -33,23 +33,24 @@ import com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage; */ public class AsciiRequestHandler extends BaseRequestHandler { - /** - *

- * Constructor for AsciiRequestHandler. - *

- * @param slave a {@link ModbusSlaveSet} object. - */ - public AsciiRequestHandler(ModbusSlaveSet slave) { - super(slave); - } + /** + *

+ * Constructor for AsciiRequestHandler. + *

+ * + * @param slave a {@link ModbusSlaveSet} object. + */ + public AsciiRequestHandler(ModbusSlaveSet slave) { + super(slave); + } - public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { - AsciiMessageRequest asciiRequest = (AsciiMessageRequest) req; - ModbusRequest request = asciiRequest.getModbusRequest(); - ModbusResponse response = handleRequestImpl(request); - if (response == null) - return null; - return new AsciiMessageResponse(response); - } + public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { + AsciiMessageRequest asciiRequest = (AsciiMessageRequest) req; + ModbusRequest request = asciiRequest.getModbusRequest(); + ModbusResponse response = handleRequestImpl(request); + if (response == null) + return null; + return new AsciiMessageResponse(response); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiSlave.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiSlave.java index 3ec66e0a0..a2e776dbc 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiSlave.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/ascii/AsciiSlave.java @@ -33,41 +33,41 @@ import java.io.IOException; */ public class AsciiSlave extends SerialSlave { - private MessageControl conn; + private MessageControl conn; - /** - *

- * Constructor for AsciiSlave. - *

- * @param wrapper a {@link SerialPortWrapper} object. - */ - public AsciiSlave(SerialPortWrapper wrapper) { - super(wrapper); - } + /** + *

+ * Constructor for AsciiSlave. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + */ + public AsciiSlave(SerialPortWrapper wrapper) { + super(wrapper); + } - @Override - public void start() throws ModbusInitException { - super.start(); + @Override + public void start() throws ModbusInitException { + super.start(); - AsciiMessageParser asciiMessageParser = new AsciiMessageParser(false); - AsciiRequestHandler asciiRequestHandler = new AsciiRequestHandler(this); + AsciiMessageParser asciiMessageParser = new AsciiMessageParser(false); + AsciiRequestHandler asciiRequestHandler = new AsciiRequestHandler(this); - conn = new MessageControl(); - conn.setExceptionHandler(getExceptionHandler()); + conn = new MessageControl(); + conn.setExceptionHandler(getExceptionHandler()); - try { - conn.start(transport, asciiMessageParser, asciiRequestHandler, null); - transport.start("Modbus ASCII slave"); - } - catch (IOException e) { - throw new ModbusInitException(e); - } - } + try { + conn.start(transport, asciiMessageParser, asciiRequestHandler, null); + transport.start("Modbus ASCII slave"); + } catch (IOException e) { + throw new ModbusInitException(e); + } + } - @Override - public void stop() { - conn.close(); - super.stop(); - } + @Override + public void stop() { + conn.close(); + super.stop(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMaster.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMaster.java index 8e403a0c4..ab0a7e1f4 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMaster.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMaster.java @@ -39,178 +39,178 @@ import org.apache.commons.logging.LogFactory; */ public class RtuMaster extends SerialMaster { - private final Log LOG = LogFactory.getLog(RtuMaster.class); + private final Log LOG = LogFactory.getLog(RtuMaster.class); - // Runtime fields. - private MessageControl conn; + // Runtime fields. + private MessageControl conn; - /** - *

- * Constructor for RtuMaster. - *

- *

- * Default to validating the slave id in responses - * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. - */ - public RtuMaster(SerialPortWrapper wrapper) { - super(wrapper, true); - } + /** + *

+ * Constructor for RtuMaster. + *

+ *

+ * Default to validating the slave id in responses + * + * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. + */ + public RtuMaster(SerialPortWrapper wrapper) { + super(wrapper, true); + } - /** - *

- * Constructor for RtuMaster. - *

- * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. - * @param validateResponse - confirm that requested slave id is the same in the - * response - */ - public RtuMaster(SerialPortWrapper wrapper, boolean validateResponse) { - super(wrapper, validateResponse); - } + /** + *

+ * Constructor for RtuMaster. + *

+ * + * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. + * @param validateResponse - confirm that requested slave id is the same in the + * response + */ + public RtuMaster(SerialPortWrapper wrapper, boolean validateResponse) { + super(wrapper, validateResponse); + } - /** - * RTU Spec: For baud greater than 19200 Message Spacing: 1.750uS - *

- * For baud less than 19200 Message Spacing: 3.5 * char time - * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. - * @return a long. - */ - public static long computeMessageFrameSpacing(SerialPortWrapper wrapper) { - // For Modbus Serial Spec, Message Framing rates at 19200 Baud are fixed - if (wrapper.getBaudRate() > 19200) { - return 1750000l; // Nanoseconds - } - else { - float charTime = computeCharacterTime(wrapper); - return (long) (charTime * 3.5f); - } - } + /** + * RTU Spec: For baud greater than 19200 Message Spacing: 1.750uS + *

+ * For baud less than 19200 Message Spacing: 3.5 * char time + * + * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. + * @return a long. + */ + public static long computeMessageFrameSpacing(SerialPortWrapper wrapper) { + // For Modbus Serial Spec, Message Framing rates at 19200 Baud are fixed + if (wrapper.getBaudRate() > 19200) { + return 1750000l; // Nanoseconds + } else { + float charTime = computeCharacterTime(wrapper); + return (long) (charTime * 3.5f); + } + } - /** - * RTU Spec: For baud greater than 19200 Char Spacing: 750uS - *

- * For baud less than 19200 Char Spacing: 1.5 * char time - * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. - * @return a long. - */ - public static long computeCharacterSpacing(SerialPortWrapper wrapper) { - // For Modbus Serial Spec, Message Framing rates at 19200 Baud are fixed - if (wrapper.getBaudRate() > 19200) { - return 750000l; // Nanoseconds - } - else { - float charTime = computeCharacterTime(wrapper); - return (long) (charTime * 1.5f); - } - } + /** + * RTU Spec: For baud greater than 19200 Char Spacing: 750uS + *

+ * For baud less than 19200 Char Spacing: 1.5 * char time + * + * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. + * @return a long. + */ + public static long computeCharacterSpacing(SerialPortWrapper wrapper) { + // For Modbus Serial Spec, Message Framing rates at 19200 Baud are fixed + if (wrapper.getBaudRate() > 19200) { + return 750000l; // Nanoseconds + } else { + float charTime = computeCharacterTime(wrapper); + return (long) (charTime * 1.5f); + } + } - /** - * Compute the time it takes to transmit 1 character with the provided Serial - * Parameters. - *

- * RTU Spec: For baud greater than 19200 Char Spacing: 750uS Message Spacing: 1.750uS - *

- * For baud less than 19200 Char Spacing: 1.5 * char time Message Spacing: 3.5 * char - * time - * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. - * @return time in nanoseconds - */ - public static float computeCharacterTime(SerialPortWrapper wrapper) { - // Compute the char size - float charBits = wrapper.getDataBits(); - switch (wrapper.getStopBits()) { - case 1: - // Strangely this results in 0 stop bits.. in JSSC code - break; - case 2: - charBits += 2f; - break; - case 3: - // 1.5 stop bits - charBits += 1.5f; - break; - default: - throw new ShouldNeverHappenException("Unknown stop bit size: " + wrapper.getStopBits()); - } + /** + * Compute the time it takes to transmit 1 character with the provided Serial + * Parameters. + *

+ * RTU Spec: For baud greater than 19200 Char Spacing: 750uS Message Spacing: 1.750uS + *

+ * For baud less than 19200 Char Spacing: 1.5 * char time Message Spacing: 3.5 * char + * time + * + * @param wrapper a {@link com.serotonin.modbus4j.serial.SerialPortWrapper} object. + * @return time in nanoseconds + */ + public static float computeCharacterTime(SerialPortWrapper wrapper) { + // Compute the char size + float charBits = wrapper.getDataBits(); + switch (wrapper.getStopBits()) { + case 1: + // Strangely this results in 0 stop bits.. in JSSC code + break; + case 2: + charBits += 2f; + break; + case 3: + // 1.5 stop bits + charBits += 1.5f; + break; + default: + throw new ShouldNeverHappenException("Unknown stop bit size: " + wrapper.getStopBits()); + } - if (wrapper.getParity() > 0) - charBits += 1; // Add another if using parity + if (wrapper.getParity() > 0) + charBits += 1; // Add another if using parity - // Compute ns it takes to send one char - // ((charSize/symbols per second) ) * ns per second - return (charBits / wrapper.getBaudRate()) * 1000000000f; - } + // Compute ns it takes to send one char + // ((charSize/symbols per second) ) * ns per second + return (charBits / wrapper.getBaudRate()) * 1000000000f; + } - /** - * {@inheritDoc} - */ - @Override - public void init() throws ModbusInitException { - try { - openConnection(null); - } - catch (Exception e) { - throw new ModbusInitException(e); - } - initialized = true; - } + /** + * {@inheritDoc} + */ + @Override + public void init() throws ModbusInitException { + try { + openConnection(null); + } catch (Exception e) { + throw new ModbusInitException(e); + } + initialized = true; + } - /** - * {@inheritDoc} - */ - @Override - protected void openConnection(MessageControl toClose) throws Exception { - super.openConnection(toClose); + /** + * {@inheritDoc} + */ + @Override + protected void openConnection(MessageControl toClose) throws Exception { + super.openConnection(toClose); - RtuMessageParser rtuMessageParser = new RtuMessageParser(true); - this.conn = getMessageControl(); - this.conn.start(transport, rtuMessageParser, null, new SerialWaitingRoomKeyFactory()); - if (getePoll() == null) { - ((StreamTransport) transport).start("Modbus RTU master"); - } - } + RtuMessageParser rtuMessageParser = new RtuMessageParser(true); + this.conn = getMessageControl(); + this.conn.start(transport, rtuMessageParser, null, new SerialWaitingRoomKeyFactory()); + if (getePoll() == null) { + ((StreamTransport) transport).start("Modbus RTU master"); + } + } - /** - * {@inheritDoc} - */ - @Override - public void destroy() { - closeMessageControl(conn); - super.close(); - initialized = false; - } + /** + * {@inheritDoc} + */ + @Override + public void destroy() { + closeMessageControl(conn); + super.close(); + initialized = false; + } - /** - * {@inheritDoc} - */ - @Override - public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { - // Wrap the modbus request in an rtu request. - RtuMessageRequest rtuRequest = new RtuMessageRequest(request); + /** + * {@inheritDoc} + */ + @Override + public ModbusResponse sendImpl(ModbusRequest request) throws ModbusTransportException { + // Wrap the modbus request in an rtu request. + RtuMessageRequest rtuRequest = new RtuMessageRequest(request); - // Send the request to get the response. - RtuMessageResponse rtuResponse; - try { - rtuResponse = (RtuMessageResponse) conn.send(rtuRequest); - if (rtuResponse == null) - return null; - return rtuResponse.getModbusResponse(); - } - catch (Exception e) { - try { - LOG.debug("Connection may have been reset. Attempting to re-open.", e); - openConnection(conn); - rtuResponse = (RtuMessageResponse) conn.send(rtuRequest); - if (rtuResponse == null) - return null; - return rtuResponse.getModbusResponse(); - } - catch (Exception e2) { - closeConnection(conn); - LOG.debug("Failed to re-connect", e2); - throw new ModbusTransportException(e2, request.getSlaveId()); - } - } - } + // Send the request to get the response. + RtuMessageResponse rtuResponse; + try { + rtuResponse = (RtuMessageResponse) conn.send(rtuRequest); + if (rtuResponse == null) + return null; + return rtuResponse.getModbusResponse(); + } catch (Exception e) { + try { + LOG.debug("Connection may have been reset. Attempting to re-open.", e); + openConnection(conn); + rtuResponse = (RtuMessageResponse) conn.send(rtuRequest); + if (rtuResponse == null) + return null; + return rtuResponse.getModbusResponse(); + } catch (Exception e2) { + closeConnection(conn); + LOG.debug("Failed to re-connect", e2); + throw new ModbusTransportException(e2, request.getSlaveId()); + } + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessage.java index 77230b03e..26f76019c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessage.java @@ -29,33 +29,35 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class RtuMessage extends SerialMessage { - /** - *

- * Constructor for RtuMessage. - *

- * @param modbusMessage a {@link ModbusMessage} object. - */ - public RtuMessage(ModbusMessage modbusMessage) { - super(modbusMessage); - } + /** + *

+ * Constructor for RtuMessage. + *

+ * + * @param modbusMessage a {@link ModbusMessage} object. + */ + public RtuMessage(ModbusMessage modbusMessage) { + super(modbusMessage); + } - /** - *

- * getMessageData. - *

- * @return an array of {@link byte} objects. - */ - public byte[] getMessageData() { - ByteQueue queue = new ByteQueue(); + /** + *

+ * getMessageData. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] getMessageData() { + ByteQueue queue = new ByteQueue(); - // Write the particular message. - modbusMessage.write(queue); + // Write the particular message. + modbusMessage.write(queue); - // Write the CRC - ModbusUtils.pushShort(queue, ModbusUtils.calculateCRC(modbusMessage)); + // Write the CRC + ModbusUtils.pushShort(queue, ModbusUtils.calculateCRC(modbusMessage)); - // Return the data. - return queue.popAll(); - } + // Return the data. + return queue.popAll(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageParser.java index 03d4773eb..a8a065a15 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageParser.java @@ -29,28 +29,29 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class RtuMessageParser extends BaseMessageParser { - /** - *

- * Constructor for RtuMessageParser. - *

- * @param master a boolean. - */ - public RtuMessageParser(boolean master) { - super(master); - } + /** + *

+ * Constructor for RtuMessageParser. + *

+ * + * @param master a boolean. + */ + public RtuMessageParser(boolean master) { + super(master); + } - @Override - protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { - if (master) - return RtuMessageResponse.createRtuMessageResponse(queue); - return RtuMessageRequest.createRtuMessageRequest(queue); - } - // - // public static void main(String[] args) throws Exception { - // ByteQueue queue = new ByteQueue(new byte[] { 5, 3, 2, 0, (byte) 0xdc, (byte) 0x48, - // (byte) 0x1d, 0 }); - // RtuMessageParser p = new RtuMessageParser(false); - // System.out.println(p.parseResponse(queue)); - // } + @Override + protected IncomingMessage parseMessageImpl(ByteQueue queue) throws Exception { + if (master) + return RtuMessageResponse.createRtuMessageResponse(queue); + return RtuMessageRequest.createRtuMessageRequest(queue); + } + // + // public static void main(String[] args) throws Exception { + // ByteQueue queue = new ByteQueue(new byte[] { 5, 3, 2, 0, (byte) 0xdc, (byte) 0x48, + // (byte) 0x1d, 0 }); + // RtuMessageParser p = new RtuMessageParser(false); + // System.out.println(p.parseResponse(queue)); + // } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageRequest.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageRequest.java index 4949ace65..79a02ba10 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageRequest.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageRequest.java @@ -31,40 +31,42 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class RtuMessageRequest extends RtuMessage implements OutgoingRequestMessage, IncomingRequestMessage { - /** - *

- * Constructor for RtuMessageRequest. - *

- * @param modbusRequest a {@link ModbusRequest} object. - */ - public RtuMessageRequest(ModbusRequest modbusRequest) { - super(modbusRequest); - } + /** + *

+ * Constructor for RtuMessageRequest. + *

+ * + * @param modbusRequest a {@link ModbusRequest} object. + */ + public RtuMessageRequest(ModbusRequest modbusRequest) { + super(modbusRequest); + } - static RtuMessageRequest createRtuMessageRequest(ByteQueue queue) throws ModbusTransportException { - ModbusRequest request = ModbusRequest.createModbusRequest(queue); - RtuMessageRequest rtuRequest = new RtuMessageRequest(request); + static RtuMessageRequest createRtuMessageRequest(ByteQueue queue) throws ModbusTransportException { + ModbusRequest request = ModbusRequest.createModbusRequest(queue); + RtuMessageRequest rtuRequest = new RtuMessageRequest(request); - // Check the CRC - ModbusUtils.checkCRC(rtuRequest.modbusMessage, queue); + // Check the CRC + ModbusUtils.checkCRC(rtuRequest.modbusMessage, queue); - // Return the data. - return rtuRequest; - } + // Return the data. + return rtuRequest; + } - @Override - public boolean expectsResponse() { - return modbusMessage.getSlaveId() != 0; - } + @Override + public boolean expectsResponse() { + return modbusMessage.getSlaveId() != 0; + } - /** - *

- * getModbusRequest. - *

- * @return a {@link ModbusRequest} object. - */ - public ModbusRequest getModbusRequest() { - return (ModbusRequest) modbusMessage; - } + /** + *

+ * getModbusRequest. + *

+ * + * @return a {@link ModbusRequest} object. + */ + public ModbusRequest getModbusRequest() { + return (ModbusRequest) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageResponse.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageResponse.java index ddca5500d..5d6d512a2 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageResponse.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuMessageResponse.java @@ -31,35 +31,37 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public class RtuMessageResponse extends RtuMessage implements OutgoingResponseMessage, IncomingResponseMessage { - /** - *

- * Constructor for RtuMessageResponse. - *

- * @param modbusResponse a {@link ModbusResponse} object. - */ - public RtuMessageResponse(ModbusResponse modbusResponse) { - super(modbusResponse); - } + /** + *

+ * Constructor for RtuMessageResponse. + *

+ * + * @param modbusResponse a {@link ModbusResponse} object. + */ + public RtuMessageResponse(ModbusResponse modbusResponse) { + super(modbusResponse); + } - static RtuMessageResponse createRtuMessageResponse(ByteQueue queue) throws ModbusTransportException { - ModbusResponse response = ModbusResponse.createModbusResponse(queue); - RtuMessageResponse rtuResponse = new RtuMessageResponse(response); + static RtuMessageResponse createRtuMessageResponse(ByteQueue queue) throws ModbusTransportException { + ModbusResponse response = ModbusResponse.createModbusResponse(queue); + RtuMessageResponse rtuResponse = new RtuMessageResponse(response); - // Check the CRC - ModbusUtils.checkCRC(rtuResponse.modbusMessage, queue); + // Check the CRC + ModbusUtils.checkCRC(rtuResponse.modbusMessage, queue); - // Return the data. - return rtuResponse; - } + // Return the data. + return rtuResponse; + } - /** - *

- * getModbusResponse. - *

- * @return a {@link ModbusResponse} object. - */ - public ModbusResponse getModbusResponse() { - return (ModbusResponse) modbusMessage; - } + /** + *

+ * getModbusResponse. + *

+ * + * @return a {@link ModbusResponse} object. + */ + public ModbusResponse getModbusResponse() { + return (ModbusResponse) modbusMessage; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuRequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuRequestHandler.java index 3f6fa7617..23eebc4be 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuRequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuRequestHandler.java @@ -33,23 +33,24 @@ import com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage; */ public class RtuRequestHandler extends BaseRequestHandler { - /** - *

- * Constructor for RtuRequestHandler. - *

- * @param slave a {@link ModbusSlaveSet} object. - */ - public RtuRequestHandler(ModbusSlaveSet slave) { - super(slave); - } + /** + *

+ * Constructor for RtuRequestHandler. + *

+ * + * @param slave a {@link ModbusSlaveSet} object. + */ + public RtuRequestHandler(ModbusSlaveSet slave) { + super(slave); + } - public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { - RtuMessageRequest rtuRequest = (RtuMessageRequest) req; - ModbusRequest request = rtuRequest.getModbusRequest(); - ModbusResponse response = handleRequestImpl(request); - if (response == null) - return null; - return new RtuMessageResponse(response); - } + public OutgoingResponseMessage handleRequest(IncomingRequestMessage req) throws Exception { + RtuMessageRequest rtuRequest = (RtuMessageRequest) req; + ModbusRequest request = rtuRequest.getModbusRequest(); + ModbusResponse response = handleRequestImpl(request); + if (response == null) + return null; + return new RtuMessageResponse(response); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuSlave.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuSlave.java index ab1dc61c6..601c113a0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuSlave.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/serial/rtu/RtuSlave.java @@ -33,42 +33,42 @@ import java.io.IOException; */ public class RtuSlave extends SerialSlave { - // Runtime fields - private MessageControl conn; + // Runtime fields + private MessageControl conn; - /** - *

- * Constructor for RtuSlave. - *

- * @param wrapper a {@link SerialPortWrapper} object. - */ - public RtuSlave(SerialPortWrapper wrapper) { - super(wrapper); - } + /** + *

+ * Constructor for RtuSlave. + *

+ * + * @param wrapper a {@link SerialPortWrapper} object. + */ + public RtuSlave(SerialPortWrapper wrapper) { + super(wrapper); + } - @Override - public void start() throws ModbusInitException { - super.start(); + @Override + public void start() throws ModbusInitException { + super.start(); - RtuMessageParser rtuMessageParser = new RtuMessageParser(false); - RtuRequestHandler rtuRequestHandler = new RtuRequestHandler(this); + RtuMessageParser rtuMessageParser = new RtuMessageParser(false); + RtuRequestHandler rtuRequestHandler = new RtuRequestHandler(this); - conn = new MessageControl(); - conn.setExceptionHandler(getExceptionHandler()); + conn = new MessageControl(); + conn.setExceptionHandler(getExceptionHandler()); - try { - conn.start(transport, rtuMessageParser, rtuRequestHandler, null); - transport.start("Modbus RTU slave"); - } - catch (IOException e) { - throw new ModbusInitException(e); - } - } + try { + conn.start(transport, rtuMessageParser, rtuRequestHandler, null); + transport.start("Modbus RTU slave"); + } catch (IOException e) { + throw new ModbusInitException(e); + } + } - @Override - public void stop() { - conn.close(); - super.stop(); - } + @Override + public void stop() { + conn.close(); + super.stop(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/NotImplementedException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/NotImplementedException.java index 5fd46a534..a429e4d35 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/NotImplementedException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/NotImplementedException.java @@ -26,25 +26,26 @@ package com.serotonin.modbus4j.sero; */ public class NotImplementedException extends RuntimeException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for NotImplementedException. - *

- */ - public NotImplementedException() { - super(); - } + /** + *

+ * Constructor for NotImplementedException. + *

+ */ + public NotImplementedException() { + super(); + } - /** - *

- * Constructor for NotImplementedException. - *

- * @param message a {@link String} object. - */ - public NotImplementedException(String message) { - super(message); - } + /** + *

+ * Constructor for NotImplementedException. + *

+ * + * @param message a {@link String} object. + */ + public NotImplementedException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/ShouldNeverHappenException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/ShouldNeverHappenException.java index 56b57db52..d8b6d3716 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/ShouldNeverHappenException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/ShouldNeverHappenException.java @@ -26,26 +26,28 @@ package com.serotonin.modbus4j.sero; */ public class ShouldNeverHappenException extends RuntimeException { - private static final long serialVersionUID = -1; + private static final long serialVersionUID = -1; - /** - *

- * Constructor for ShouldNeverHappenException. - *

- * @param message a {@link String} object. - */ - public ShouldNeverHappenException(String message) { - super(message); - } + /** + *

+ * Constructor for ShouldNeverHappenException. + *

+ * + * @param message a {@link String} object. + */ + public ShouldNeverHappenException(String message) { + super(message); + } - /** - *

- * Constructor for ShouldNeverHappenException. - *

- * @param cause a {@link Throwable} object. - */ - public ShouldNeverHappenException(Throwable cause) { - super(cause); - } + /** + *

+ * Constructor for ShouldNeverHappenException. + *

+ * + * @param cause a {@link Throwable} object. + */ + public ShouldNeverHappenException(Throwable cause) { + super(cause); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/InputStreamEPollWrapper.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/InputStreamEPollWrapper.java index f23eb1939..f46e70b58 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/InputStreamEPollWrapper.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/InputStreamEPollWrapper.java @@ -28,21 +28,23 @@ import java.io.InputStream; */ public interface InputStreamEPollWrapper { - /** - *

- * add. - *

- * @param in a {@link InputStream} object. - * @param inputStreamCallback a {@link Modbus4JInputStreamCallback} object. - */ - void add(InputStream in, Modbus4JInputStreamCallback inputStreamCallback); + /** + *

+ * add. + *

+ * + * @param in a {@link InputStream} object. + * @param inputStreamCallback a {@link Modbus4JInputStreamCallback} object. + */ + void add(InputStream in, Modbus4JInputStreamCallback inputStreamCallback); - /** - *

- * remove. - *

- * @param in a {@link InputStream} object. - */ - void remove(InputStream in); + /** + *

+ * remove. + *

+ * + * @param in a {@link InputStream} object. + */ + void remove(InputStream in); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/Modbus4JInputStreamCallback.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/Modbus4JInputStreamCallback.java index 6d3a1fae3..287a0d21d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/Modbus4JInputStreamCallback.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/epoll/Modbus4JInputStreamCallback.java @@ -30,30 +30,32 @@ import java.io.IOException; */ public interface Modbus4JInputStreamCallback { - /** - * Called when content is read from the input stream. - * @param buf the content that was read. This is a shared byte array. Contents can be - * manipulated within this call, but the array itself should not be stored beyond the - * call since the contents will be changed. - * @param len the length of content that was read. - */ - void input(byte[] buf, int len); + /** + * Called when content is read from the input stream. + * + * @param buf the content that was read. This is a shared byte array. Contents can be + * manipulated within this call, but the array itself should not be stored beyond the + * call since the contents will be changed. + * @param len the length of content that was read. + */ + void input(byte[] buf, int len); - /** - * Called when the closure of the input stream is detected. - */ - void closed(); + /** + * Called when the closure of the input stream is detected. + */ + void closed(); - /** - * Called if there is an {@link IOException} while reading input stream. - * @param e the exception that was received - */ - void ioException(IOException e); + /** + * Called if there is an {@link IOException} while reading input stream. + * + * @param e the exception that was received + */ + void ioException(IOException e); - /** - * Called if the InputStreamEPoll instance was terminated while the input stream was - * still registered. - */ - void terminated(); + /** + * Called if the InputStreamEPoll instance was terminated while the input stream was + * still registered. + */ + void terminated(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/LineHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/LineHandler.java index 43cf980a2..bba2ce307 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/LineHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/LineHandler.java @@ -26,19 +26,20 @@ package com.serotonin.modbus4j.sero.io; */ public interface LineHandler { - /** - *

- * handleLine. - *

- * @param line a {@link String} object. - */ - public void handleLine(String line); + /** + *

+ * handleLine. + *

+ * + * @param line a {@link String} object. + */ + public void handleLine(String line); - /** - *

- * done. - *

- */ - public void done(); + /** + *

+ * done. + *

+ */ + public void done(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/NullWriter.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/NullWriter.java index b01ff9c9f..7b03f292c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/NullWriter.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/NullWriter.java @@ -30,19 +30,19 @@ import java.io.Writer; */ public class NullWriter extends Writer { - @Override - public void write(char[] cbuf, int off, int len) throws IOException { - // no op - } + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + // no op + } - @Override - public void flush() throws IOException { - // no op - } + @Override + public void flush() throws IOException { + // no op + } - @Override - public void close() throws IOException { - // no op - } + @Override + public void close() throws IOException { + // no op + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/StreamUtils.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/StreamUtils.java index 76aadf22a..5cd014eb3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/StreamUtils.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/io/StreamUtils.java @@ -38,646 +38,684 @@ import java.util.List; */ public class StreamUtils { - /** - *

- * transfer. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - * @throws IOException if any. - */ - public static void transfer(InputStream in, OutputStream out) throws IOException { - transfer(in, out, -1); - } + /** + *

+ * transfer. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + * @throws IOException if any. + */ + public static void transfer(InputStream in, OutputStream out) throws IOException { + transfer(in, out, -1); + } - /** - *

- * transfer. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - * @param limit a long. - * @throws IOException if any. - */ - public static void transfer(InputStream in, OutputStream out, long limit) throws IOException { - byte[] buf = new byte[1024]; - int readcount; - long total = 0; - while ((readcount = in.read(buf)) != -1) { - if (limit != -1) { - if (total + readcount > limit) - readcount = (int) (limit - total); - } + /** + *

+ * transfer. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + * @param limit a long. + * @throws IOException if any. + */ + public static void transfer(InputStream in, OutputStream out, long limit) throws IOException { + byte[] buf = new byte[1024]; + int readcount; + long total = 0; + while ((readcount = in.read(buf)) != -1) { + if (limit != -1) { + if (total + readcount > limit) + readcount = (int) (limit - total); + } - if (readcount > 0) - out.write(buf, 0, readcount); + if (readcount > 0) + out.write(buf, 0, readcount); - total += readcount; - if (limit != -1 && total >= limit) - break; - } - out.flush(); - } + total += readcount; + if (limit != -1 && total >= limit) + break; + } + out.flush(); + } - /** - *

- * transfer. - *

- * @param in a {@link InputStream} object. - * @param out a {@link SocketChannel} object. - * @throws IOException if any. - */ - public static void transfer(InputStream in, SocketChannel out) throws IOException { - byte[] buf = new byte[1024]; - ByteBuffer bbuf = ByteBuffer.allocate(1024); - int len; - while ((len = in.read(buf)) != -1) { - bbuf.put(buf, 0, len); - bbuf.flip(); - while (bbuf.remaining() > 0) - out.write(bbuf); - bbuf.clear(); - } - } + /** + *

+ * transfer. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link SocketChannel} object. + * @throws IOException if any. + */ + public static void transfer(InputStream in, SocketChannel out) throws IOException { + byte[] buf = new byte[1024]; + ByteBuffer bbuf = ByteBuffer.allocate(1024); + int len; + while ((len = in.read(buf)) != -1) { + bbuf.put(buf, 0, len); + bbuf.flip(); + while (bbuf.remaining() > 0) + out.write(bbuf); + bbuf.clear(); + } + } - /** - *

- * transfer. - *

- * @param reader a {@link Reader} object. - * @param writer a {@link Writer} object. - * @throws IOException if any. - */ - public static void transfer(Reader reader, Writer writer) throws IOException { - transfer(reader, writer, -1); - } + /** + *

+ * transfer. + *

+ * + * @param reader a {@link Reader} object. + * @param writer a {@link Writer} object. + * @throws IOException if any. + */ + public static void transfer(Reader reader, Writer writer) throws IOException { + transfer(reader, writer, -1); + } - /** - *

- * transfer. - *

- * @param reader a {@link Reader} object. - * @param writer a {@link Writer} object. - * @param limit a long. - * @throws IOException if any. - */ - public static void transfer(Reader reader, Writer writer, long limit) throws IOException { - char[] buf = new char[1024]; - int readcount; - long total = 0; - while ((readcount = reader.read(buf)) != -1) { - if (limit != -1) { - if (total + readcount > limit) - readcount = (int) (limit - total); - } + /** + *

+ * transfer. + *

+ * + * @param reader a {@link Reader} object. + * @param writer a {@link Writer} object. + * @param limit a long. + * @throws IOException if any. + */ + public static void transfer(Reader reader, Writer writer, long limit) throws IOException { + char[] buf = new char[1024]; + int readcount; + long total = 0; + while ((readcount = reader.read(buf)) != -1) { + if (limit != -1) { + if (total + readcount > limit) + readcount = (int) (limit - total); + } - if (readcount > 0) - writer.write(buf, 0, readcount); + if (readcount > 0) + writer.write(buf, 0, readcount); - total += readcount; - if (limit != -1 && total >= limit) - break; - } - writer.flush(); - } + total += readcount; + if (limit != -1 && total >= limit) + break; + } + writer.flush(); + } - /** - *

- * read. - *

- * @param in a {@link InputStream} object. - * @return an array of {@link byte} objects. - * @throws IOException if any. - */ - public static byte[] read(InputStream in) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(in.available()); - transfer(in, out); - return out.toByteArray(); - } + /** + *

+ * read. + *

+ * + * @param in a {@link InputStream} object. + * @return an array of {@link byte} objects. + * @throws IOException if any. + */ + public static byte[] read(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(in.available()); + transfer(in, out); + return out.toByteArray(); + } - /** - *

- * read. - *

- * @param reader a {@link Reader} object. - * @return an array of {@link char} objects. - * @throws IOException if any. - */ - public static char[] read(Reader reader) throws IOException { - CharArrayWriter writer = new CharArrayWriter(); - transfer(reader, writer); - return writer.toCharArray(); - } + /** + *

+ * read. + *

+ * + * @param reader a {@link Reader} object. + * @return an array of {@link char} objects. + * @throws IOException if any. + */ + public static char[] read(Reader reader) throws IOException { + CharArrayWriter writer = new CharArrayWriter(); + transfer(reader, writer); + return writer.toCharArray(); + } - /** - *

- * readChar. - *

- * @param in a {@link InputStream} object. - * @return a char. - * @throws IOException if any. - */ - public static char readChar(InputStream in) throws IOException { - return (char) in.read(); - } + /** + *

+ * readChar. + *

+ * + * @param in a {@link InputStream} object. + * @return a char. + * @throws IOException if any. + */ + public static char readChar(InputStream in) throws IOException { + return (char) in.read(); + } - /** - *

- * readString. - *

- * @param in a {@link InputStream} object. - * @param length a int. - * @return a {@link String} object. - * @throws IOException if any. - */ - public static String readString(InputStream in, int length) throws IOException { - StringBuilder sb = new StringBuilder(length); - for (int i = 0; i < length; i++) - sb.append(readChar(in)); - return sb.toString(); - } + /** + *

+ * readString. + *

+ * + * @param in a {@link InputStream} object. + * @param length a int. + * @return a {@link String} object. + * @throws IOException if any. + */ + public static String readString(InputStream in, int length) throws IOException { + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) + sb.append(readChar(in)); + return sb.toString(); + } - /** - *

- * readByte. - *

- * @param in a {@link InputStream} object. - * @return a byte. - * @throws IOException if any. - */ - public static byte readByte(InputStream in) throws IOException { - return (byte) in.read(); - } + /** + *

+ * readByte. + *

+ * + * @param in a {@link InputStream} object. + * @return a byte. + * @throws IOException if any. + */ + public static byte readByte(InputStream in) throws IOException { + return (byte) in.read(); + } - /** - *

- * read4ByteSigned. - *

- * @param in a {@link InputStream} object. - * @return a int. - * @throws IOException if any. - */ - public static int read4ByteSigned(InputStream in) throws IOException { - return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); - } + /** + *

+ * read4ByteSigned. + *

+ * + * @param in a {@link InputStream} object. + * @return a int. + * @throws IOException if any. + */ + public static int read4ByteSigned(InputStream in) throws IOException { + return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); + } - /** - *

- * read4ByteUnsigned. - *

- * @param in a {@link InputStream} object. - * @return a long. - * @throws IOException if any. - */ - public static long read4ByteUnsigned(InputStream in) throws IOException { - return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); - } + /** + *

+ * read4ByteUnsigned. + *

+ * + * @param in a {@link InputStream} object. + * @return a long. + * @throws IOException if any. + */ + public static long read4ByteUnsigned(InputStream in) throws IOException { + return in.read() | (in.read() << 8) | (in.read() << 16) | (in.read() << 24); + } - /** - *

- * read2ByteUnsigned. - *

- * @param in a {@link InputStream} object. - * @return a int. - * @throws IOException if any. - */ - public static int read2ByteUnsigned(InputStream in) throws IOException { - return in.read() | (in.read() << 8); - } + /** + *

+ * read2ByteUnsigned. + *

+ * + * @param in a {@link InputStream} object. + * @return a int. + * @throws IOException if any. + */ + public static int read2ByteUnsigned(InputStream in) throws IOException { + return in.read() | (in.read() << 8); + } - /** - *

- * read2ByteSigned. - *

- * @param in a {@link InputStream} object. - * @return a short. - * @throws IOException if any. - */ - public static short read2ByteSigned(InputStream in) throws IOException { - return (short) (in.read() | (in.read() << 8)); - } + /** + *

+ * read2ByteSigned. + *

+ * + * @param in a {@link InputStream} object. + * @return a short. + * @throws IOException if any. + */ + public static short read2ByteSigned(InputStream in) throws IOException { + return (short) (in.read() | (in.read() << 8)); + } - /** - *

- * writeByte. - *

- * @param out a {@link OutputStream} object. - * @param b a byte. - * @throws IOException if any. - */ - public static void writeByte(OutputStream out, byte b) throws IOException { - out.write(b); - } + /** + *

+ * writeByte. + *

+ * + * @param out a {@link OutputStream} object. + * @param b a byte. + * @throws IOException if any. + */ + public static void writeByte(OutputStream out, byte b) throws IOException { + out.write(b); + } - /** - *

- * writeChar. - *

- * @param out a {@link OutputStream} object. - * @param c a char. - * @throws IOException if any. - */ - public static void writeChar(OutputStream out, char c) throws IOException { - out.write((byte) c); - } + /** + *

+ * writeChar. + *

+ * + * @param out a {@link OutputStream} object. + * @param c a char. + * @throws IOException if any. + */ + public static void writeChar(OutputStream out, char c) throws IOException { + out.write((byte) c); + } - /** - *

- * writeString. - *

- * @param out a {@link OutputStream} object. - * @param s a {@link String} object. - * @throws IOException if any. - */ - public static void writeString(OutputStream out, String s) throws IOException { - for (int i = 0; i < s.length(); i++) - writeChar(out, s.charAt(i)); - } + /** + *

+ * writeString. + *

+ * + * @param out a {@link OutputStream} object. + * @param s a {@link String} object. + * @throws IOException if any. + */ + public static void writeString(OutputStream out, String s) throws IOException { + for (int i = 0; i < s.length(); i++) + writeChar(out, s.charAt(i)); + } - /** - *

- * write4ByteSigned. - *

- * @param out a {@link OutputStream} object. - * @param i a int. - * @throws IOException if any. - */ - public static void write4ByteSigned(OutputStream out, int i) throws IOException { - out.write((byte) (i & 0xFF)); - out.write((byte) ((i >> 8) & 0xFF)); - out.write((byte) ((i >> 16) & 0xFF)); - out.write((byte) ((i >> 24) & 0xFF)); - } + /** + *

+ * write4ByteSigned. + *

+ * + * @param out a {@link OutputStream} object. + * @param i a int. + * @throws IOException if any. + */ + public static void write4ByteSigned(OutputStream out, int i) throws IOException { + out.write((byte) (i & 0xFF)); + out.write((byte) ((i >> 8) & 0xFF)); + out.write((byte) ((i >> 16) & 0xFF)); + out.write((byte) ((i >> 24) & 0xFF)); + } - /** - *

- * write4ByteUnsigned. - *

- * @param out a {@link OutputStream} object. - * @param l a long. - * @throws IOException if any. - */ - public static void write4ByteUnsigned(OutputStream out, long l) throws IOException { - out.write((byte) (l & 0xFF)); - out.write((byte) ((l >> 8) & 0xFF)); - out.write((byte) ((l >> 16) & 0xFF)); - out.write((byte) ((l >> 24) & 0xFF)); - } + /** + *

+ * write4ByteUnsigned. + *

+ * + * @param out a {@link OutputStream} object. + * @param l a long. + * @throws IOException if any. + */ + public static void write4ByteUnsigned(OutputStream out, long l) throws IOException { + out.write((byte) (l & 0xFF)); + out.write((byte) ((l >> 8) & 0xFF)); + out.write((byte) ((l >> 16) & 0xFF)); + out.write((byte) ((l >> 24) & 0xFF)); + } - /** - *

- * write2ByteUnsigned. - *

- * @param out a {@link OutputStream} object. - * @param i a int. - * @throws IOException if any. - */ - public static void write2ByteUnsigned(OutputStream out, int i) throws IOException { - out.write((byte) (i & 0xFF)); - out.write((byte) ((i >> 8) & 0xFF)); - } + /** + *

+ * write2ByteUnsigned. + *

+ * + * @param out a {@link OutputStream} object. + * @param i a int. + * @throws IOException if any. + */ + public static void write2ByteUnsigned(OutputStream out, int i) throws IOException { + out.write((byte) (i & 0xFF)); + out.write((byte) ((i >> 8) & 0xFF)); + } - /** - *

- * write2ByteSigned. - *

- * @param out a {@link OutputStream} object. - * @param s a short. - * @throws IOException if any. - */ - public static void write2ByteSigned(OutputStream out, short s) throws IOException { - out.write((byte) (s & 0xFF)); - out.write((byte) ((s >> 8) & 0xFF)); - } + /** + *

+ * write2ByteSigned. + *

+ * + * @param out a {@link OutputStream} object. + * @param s a short. + * @throws IOException if any. + */ + public static void write2ByteSigned(OutputStream out, short s) throws IOException { + out.write((byte) (s & 0xFF)); + out.write((byte) ((s >> 8) & 0xFF)); + } - /** - *

- * dumpArray. - *

- * @param b an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String dumpArray(byte[] b) { - return dumpArray(b, 0, b.length); - } + /** + *

+ * dumpArray. + *

+ * + * @param b an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String dumpArray(byte[] b) { + return dumpArray(b, 0, b.length); + } - /** - *

- * dumpArray. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String dumpArray(byte[] b, int pos, int len) { - StringBuilder sb = new StringBuilder(); - sb.append('['); - for (int i = pos; i < len; i++) { - if (i > 0) - sb.append(","); - sb.append(b[i]); - } - sb.append(']'); - return sb.toString(); - } + /** + *

+ * dumpArray. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String dumpArray(byte[] b, int pos, int len) { + StringBuilder sb = new StringBuilder(); + sb.append('['); + for (int i = pos; i < len; i++) { + if (i > 0) + sb.append(","); + sb.append(b[i]); + } + sb.append(']'); + return sb.toString(); + } - /** - *

- * dumpMessage. - *

- * @param b an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String dumpMessage(byte[] b) { - return dumpMessage(b, 0, b.length); - } + /** + *

+ * dumpMessage. + *

+ * + * @param b an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String dumpMessage(byte[] b) { + return dumpMessage(b, 0, b.length); + } - /** - *

- * dumpMessage. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String dumpMessage(byte[] b, int pos, int len) { - StringBuilder sb = new StringBuilder(); - sb.append('['); - for (int i = pos; i < len; i++) { - switch (b[i]) { - case 2: - sb.append("&STX;"); - break; - case 3: - sb.append("&ETX;"); - break; - case 27: - sb.append("&ESC;"); - break; - default: - sb.append((char) b[i]); - } - } - sb.append(']'); - return sb.toString(); - } + /** + *

+ * dumpMessage. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String dumpMessage(byte[] b, int pos, int len) { + StringBuilder sb = new StringBuilder(); + sb.append('['); + for (int i = pos; i < len; i++) { + switch (b[i]) { + case 2: + sb.append("&STX;"); + break; + case 3: + sb.append("&ETX;"); + break; + case 27: + sb.append("&ESC;"); + break; + default: + sb.append((char) b[i]); + } + } + sb.append(']'); + return sb.toString(); + } - /** - *

- * dumpArrayHex. - *

- * @param b an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String dumpArrayHex(byte[] b) { - return dumpArrayHex(b, 0, b.length); - } + /** + *

+ * dumpArrayHex. + *

+ * + * @param b an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String dumpArrayHex(byte[] b) { + return dumpArrayHex(b, 0, b.length); + } - /** - *

- * dumpArrayHex. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String dumpArrayHex(byte[] b, int pos, int len) { - StringBuilder sb = new StringBuilder(); - sb.append('['); - for (int i = pos; i < len; i++) { - if (i > 0) - sb.append(","); - sb.append(Integer.toHexString(b[i] & 0xff)); - } - sb.append(']'); - return sb.toString(); - } + /** + *

+ * dumpArrayHex. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String dumpArrayHex(byte[] b, int pos, int len) { + StringBuilder sb = new StringBuilder(); + sb.append('['); + for (int i = pos; i < len; i++) { + if (i > 0) + sb.append(","); + sb.append(Integer.toHexString(b[i] & 0xff)); + } + sb.append(']'); + return sb.toString(); + } - /** - *

- * dumpHex. - *

- * @param b an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String dumpHex(byte[] b) { - return dumpHex(b, 0, b.length); - } + /** + *

+ * dumpHex. + *

+ * + * @param b an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String dumpHex(byte[] b) { + return dumpHex(b, 0, b.length); + } - /** - *

- * dumpHex. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String dumpHex(byte[] b, int pos, int len) { - StringBuilder sb = new StringBuilder(); - for (int i = pos; i < len; i++) - sb.append(StringUtils.leftPad(Integer.toHexString(b[i] & 0xff), 2, '0')); - return sb.toString(); - } + /** + *

+ * dumpHex. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String dumpHex(byte[] b, int pos, int len) { + StringBuilder sb = new StringBuilder(); + for (int i = pos; i < len; i++) + sb.append(StringUtils.leftPad(Integer.toHexString(b[i] & 0xff), 2, '0')); + return sb.toString(); + } - /** - *

- * readFile. - *

- * @param filename a {@link String} object. - * @return a {@link String} object. - * @throws IOException if any. - */ - public static String readFile(String filename) throws IOException { - return readFile(new File(filename)); - } + /** + *

+ * readFile. + *

+ * + * @param filename a {@link String} object. + * @return a {@link String} object. + * @throws IOException if any. + */ + public static String readFile(String filename) throws IOException { + return readFile(new File(filename)); + } - /** - *

- * readFile. - *

- * @param file a {@link File} object. - * @return a {@link String} object. - * @throws IOException if any. - */ - public static String readFile(File file) throws IOException { - FileReader in = null; - try { - in = new FileReader(file); - StringWriter out = new StringWriter(); - transfer(in, out); - return out.toString(); - } - finally { - if (in != null) - in.close(); - } - } + /** + *

+ * readFile. + *

+ * + * @param file a {@link File} object. + * @return a {@link String} object. + * @throws IOException if any. + */ + public static String readFile(File file) throws IOException { + FileReader in = null; + try { + in = new FileReader(file); + StringWriter out = new StringWriter(); + transfer(in, out); + return out.toString(); + } finally { + if (in != null) + in.close(); + } + } - /** - *

- * readLines. - *

- * @param filename a {@link String} object. - * @return a {@link List} object. - * @throws IOException if any. - */ - public static List readLines(String filename) throws IOException { - return readLines(new File(filename)); - } + /** + *

+ * readLines. + *

+ * + * @param filename a {@link String} object. + * @return a {@link List} object. + * @throws IOException if any. + */ + public static List readLines(String filename) throws IOException { + return readLines(new File(filename)); + } - /** - *

- * readLines. - *

- * @param file a {@link File} object. - * @return a {@link List} object. - * @throws IOException if any. - */ - public static List readLines(File file) throws IOException { - List lines = new ArrayList(); - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(file)); - String line; - while ((line = in.readLine()) != null) - lines.add(line); - return lines; - } - finally { - if (in != null) - in.close(); - } - } + /** + *

+ * readLines. + *

+ * + * @param file a {@link File} object. + * @return a {@link List} object. + * @throws IOException if any. + */ + public static List readLines(File file) throws IOException { + List lines = new ArrayList(); + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + String line; + while ((line = in.readLine()) != null) + lines.add(line); + return lines; + } finally { + if (in != null) + in.close(); + } + } - /** - *

- * writeFile. - *

- * @param filename a {@link String} object. - * @param content a {@link String} object. - * @throws IOException if any. - */ - public static void writeFile(String filename, String content) throws IOException { - writeFile(new File(filename), content); - } + /** + *

+ * writeFile. + *

+ * + * @param filename a {@link String} object. + * @param content a {@link String} object. + * @throws IOException if any. + */ + public static void writeFile(String filename, String content) throws IOException { + writeFile(new File(filename), content); + } - /** - *

- * writeFile. - *

- * @param file a {@link File} object. - * @param content a {@link String} object. - * @throws IOException if any. - */ - public static void writeFile(File file, String content) throws IOException { - FileWriter out = null; - try { - out = new FileWriter(file); - out.write(content); - } - finally { - if (out != null) - out.close(); - } - } + /** + *

+ * writeFile. + *

+ * + * @param file a {@link File} object. + * @param content a {@link String} object. + * @throws IOException if any. + */ + public static void writeFile(File file, String content) throws IOException { + FileWriter out = null; + try { + out = new FileWriter(file); + out.write(content); + } finally { + if (out != null) + out.close(); + } + } - /** - *

- * readLines. - *

- * @param filename a {@link String} object. - * @param lineHandler a {@link LineHandler} object. - * @throws IOException if any. - */ - public static void readLines(String filename, LineHandler lineHandler) throws IOException { - BufferedReader in = null; - try { - in = new BufferedReader(new FileReader(filename)); - String line; - while ((line = in.readLine()) != null) - lineHandler.handleLine(line); - lineHandler.done(); - } - finally { - if (in != null) - in.close(); - } - } + /** + *

+ * readLines. + *

+ * + * @param filename a {@link String} object. + * @param lineHandler a {@link LineHandler} object. + * @throws IOException if any. + */ + public static void readLines(String filename, LineHandler lineHandler) throws IOException { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(filename)); + String line; + while ((line = in.readLine()) != null) + lineHandler.handleLine(line); + lineHandler.done(); + } finally { + if (in != null) + in.close(); + } + } - /** - *

- * toHex. - *

- * @param bs an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String toHex(byte[] bs) { - StringBuilder sb = new StringBuilder(bs.length * 2); - for (byte b : bs) - sb.append(StringUtils.leftPad(Integer.toHexString(b & 0xff), 2, '0')); - return sb.toString(); - } + /** + *

+ * toHex. + *

+ * + * @param bs an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String toHex(byte[] bs) { + StringBuilder sb = new StringBuilder(bs.length * 2); + for (byte b : bs) + sb.append(StringUtils.leftPad(Integer.toHexString(b & 0xff), 2, '0')); + return sb.toString(); + } - /** - *

- * toHex. - *

- * @param b a byte. - * @return a {@link String} object. - */ - public static String toHex(byte b) { - return StringUtils.leftPad(Integer.toHexString(b & 0xff), 2, '0'); - } + /** + *

+ * toHex. + *

+ * + * @param b a byte. + * @return a {@link String} object. + */ + public static String toHex(byte b) { + return StringUtils.leftPad(Integer.toHexString(b & 0xff), 2, '0'); + } - /** - *

- * toHex. - *

- * @param s a short. - * @return a {@link String} object. - */ - public static String toHex(short s) { - return StringUtils.leftPad(Integer.toHexString(s & 0xffff), 4, '0'); - } + /** + *

+ * toHex. + *

+ * + * @param s a short. + * @return a {@link String} object. + */ + public static String toHex(short s) { + return StringUtils.leftPad(Integer.toHexString(s & 0xffff), 4, '0'); + } - /** - *

- * toHex. - *

- * @param i a int. - * @return a {@link String} object. - */ - public static String toHex(int i) { - return StringUtils.leftPad(Integer.toHexString(i), 8, '0'); - } + /** + *

+ * toHex. + *

+ * + * @param i a int. + * @return a {@link String} object. + */ + public static String toHex(int i) { + return StringUtils.leftPad(Integer.toHexString(i), 8, '0'); + } - /** - *

- * toHex. - *

- * @param l a long. - * @return a {@link String} object. - */ - public static String toHex(long l) { - return StringUtils.leftPad(Long.toHexString(l), 16, '0'); - } + /** + *

+ * toHex. + *

+ * + * @param l a long. + * @return a {@link String} object. + */ + public static String toHex(long l) { + return StringUtils.leftPad(Long.toHexString(l), 16, '0'); + } - /** - *

- * fromHex. - *

- * @param s a {@link String} object. - * @return an array of {@link byte} objects. - */ - public static byte[] fromHex(String s) { - byte[] bs = new byte[s.length() / 2]; - for (int i = 0; i < bs.length; i++) - bs[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16); - return bs; - } + /** + *

+ * fromHex. + *

+ * + * @param s a {@link String} object. + * @return an array of {@link byte} objects. + */ + public static byte[] fromHex(String s) { + byte[] bs = new byte[s.length() / 2]; + for (int i = 0; i < bs.length; i++) + bs[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16); + return bs; + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/BaseIOLog.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/BaseIOLog.java index 2f907d0aa..058bbf1db 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/BaseIOLog.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/BaseIOLog.java @@ -38,152 +38,159 @@ import java.util.Date; */ public abstract class BaseIOLog { - /** - * Constant DATE_FORMAT="yyyy/MM/dd-HH:mm:ss,SSS" - */ - protected static final String DATE_FORMAT = "yyyy/MM/dd-HH:mm:ss,SSS"; + /** + * Constant DATE_FORMAT="yyyy/MM/dd-HH:mm:ss,SSS" + */ + protected static final String DATE_FORMAT = "yyyy/MM/dd-HH:mm:ss,SSS"; - private static final Log LOG = LogFactory.getLog(BaseIOLog.class); + private static final Log LOG = LogFactory.getLog(BaseIOLog.class); - protected final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); + protected final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); - protected final File file; + protected final File file; - protected final StringBuilder sb = new StringBuilder(); + protected final StringBuilder sb = new StringBuilder(); - protected final Date date = new Date(); + protected final Date date = new Date(); - protected PrintWriter out; + protected PrintWriter out; - /** - *

- * Constructor for BaseIOLog. - *

- * @param logFile a {@link File} object. - */ - public BaseIOLog(File logFile) { - this.file = logFile; - createOut(); - } + /** + *

+ * Constructor for BaseIOLog. + *

+ * + * @param logFile a {@link File} object. + */ + public BaseIOLog(File logFile) { + this.file = logFile; + createOut(); + } - /** - * Create the Print Writer output - */ - protected void createOut() { - try { - out = new PrintWriter(new FileWriter(file, true)); - } - catch (IOException e) { - out = new PrintWriter(new NullWriter()); - LOG.error("Error while creating process log", e); - } - } + /** + * Create the Print Writer output + */ + protected void createOut() { + try { + out = new PrintWriter(new FileWriter(file, true)); + } catch (IOException e) { + out = new PrintWriter(new NullWriter()); + LOG.error("Error while creating process log", e); + } + } - /** - *

- * close. - *

- */ - public void close() { - out.close(); - } + /** + *

+ * close. + *

+ */ + public void close() { + out.close(); + } - /** - *

- * input. - *

- * @param b an array of {@link byte} objects. - */ - public void input(byte[] b) { - log(true, b, 0, b.length); - } + /** + *

+ * input. + *

+ * + * @param b an array of {@link byte} objects. + */ + public void input(byte[] b) { + log(true, b, 0, b.length); + } - /** - *

- * input. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - */ - public void input(byte[] b, int pos, int len) { - log(true, b, pos, len); - } + /** + *

+ * input. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + */ + public void input(byte[] b, int pos, int len) { + log(true, b, pos, len); + } - /** - *

- * output. - *

- * @param b an array of {@link byte} objects. - */ - public void output(byte[] b) { - log(false, b, 0, b.length); - } + /** + *

+ * output. + *

+ * + * @param b an array of {@link byte} objects. + */ + public void output(byte[] b) { + log(false, b, 0, b.length); + } - /** - *

- * output. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - */ - public void output(byte[] b, int pos, int len) { - log(false, b, pos, len); - } + /** + *

+ * output. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + */ + public void output(byte[] b, int pos, int len) { + log(false, b, pos, len); + } - /** - *

- * log. - *

- * @param input a boolean. - * @param b an array of {@link byte} objects. - */ - public void log(boolean input, byte[] b) { - log(input, b, 0, b.length); - } + /** + *

+ * log. + *

+ * + * @param input a boolean. + * @param b an array of {@link byte} objects. + */ + public void log(boolean input, byte[] b) { + log(input, b, 0, b.length); + } - /** - *

- * log. - *

- * @param input a boolean. - * @param b an array of {@link byte} objects. - * @param pos a int. - * @param len a int. - */ - public synchronized void log(boolean input, byte[] b, int pos, int len) { - sizeCheck(); + /** + *

+ * log. + *

+ * + * @param input a boolean. + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param len a int. + */ + public synchronized void log(boolean input, byte[] b, int pos, int len) { + sizeCheck(); - sb.delete(0, sb.length()); - date.setTime(System.currentTimeMillis()); - sb.append(sdf.format(date)).append(" "); - sb.append(input ? "I" : "O").append(" "); - sb.append(StreamUtils.dumpHex(b, pos, len)); - out.println(sb.toString()); - out.flush(); - } + sb.delete(0, sb.length()); + date.setTime(System.currentTimeMillis()); + sb.append(sdf.format(date)).append(" "); + sb.append(input ? "I" : "O").append(" "); + sb.append(StreamUtils.dumpHex(b, pos, len)); + out.println(sb.toString()); + out.flush(); + } - /** - *

- * log. - *

- * @param message a {@link String} object. - */ - public synchronized void log(String message) { - sizeCheck(); + /** + *

+ * log. + *

+ * + * @param message a {@link String} object. + */ + public synchronized void log(String message) { + sizeCheck(); - sb.delete(0, sb.length()); - date.setTime(System.currentTimeMillis()); - sb.append(sdf.format(date)).append(" "); - sb.append(message); - out.println(sb.toString()); - out.flush(); - } + sb.delete(0, sb.length()); + date.setTime(System.currentTimeMillis()); + sb.append(sdf.format(date)).append(" "); + sb.append(message); + out.println(sb.toString()); + out.flush(); + } - /** - * Check the size of the logfile and perform adjustments as necessary - */ - protected abstract void sizeCheck(); + /** + * Check the size of the logfile and perform adjustments as necessary + */ + protected abstract void sizeCheck(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/IOLog.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/IOLog.java index b69038b0e..22e72039b 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/IOLog.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/IOLog.java @@ -28,69 +28,70 @@ import java.io.File; */ public class IOLog extends BaseIOLog { - // private static final Log LOG = LogFactory.getLog(IOLog.class); - private static final int MAX_FILESIZE = 1000000; + // private static final Log LOG = LogFactory.getLog(IOLog.class); + private static final int MAX_FILESIZE = 1000000; - // private static final int MAX_FILESIZE = 1000; - private final File backupFile; + // private static final int MAX_FILESIZE = 1000; + private final File backupFile; - /** - *

- * Constructor for IOLog. - *

- * @param filename a {@link String} object. - */ - public IOLog(String filename) { - super(new File(filename)); - backupFile = new File(filename + ".1"); - } + /** + *

+ * Constructor for IOLog. + *

+ * + * @param filename a {@link String} object. + */ + public IOLog(String filename) { + super(new File(filename)); + backupFile = new File(filename + ".1"); + } - @Override - protected void sizeCheck() { - // Check if the file should be rolled. - if (file.length() > MAX_FILESIZE) { - out.close(); + @Override + protected void sizeCheck() { + // Check if the file should be rolled. + if (file.length() > MAX_FILESIZE) { + out.close(); - if (backupFile.exists()) - backupFile.delete(); - file.renameTo(backupFile); - createOut(); - } - } - // - // public static void main(String[] args) { - // byte[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - // - // IOLog log = new IOLog("iotest"); - // log.log("test"); - // log.log("testtest"); - // - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // log.input(b); - // log.output(b); - // - // log.log("testtesttesttesttesttesttesttesttesttest"); - // } + if (backupFile.exists()) + backupFile.delete(); + file.renameTo(backupFile); + createOut(); + } + } + // + // public static void main(String[] args) { + // byte[] b = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + // + // IOLog log = new IOLog("iotest"); + // log.log("test"); + // log.log("testtest"); + // + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // log.input(b); + // log.output(b); + // + // log.log("testtesttesttesttesttesttesttesttesttest"); + // } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/RollingIOLog.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/RollingIOLog.java index f64339bbf..d0a1e9c78 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/RollingIOLog.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/RollingIOLog.java @@ -35,93 +35,93 @@ import java.nio.file.StandardCopyOption; */ public class RollingIOLog extends BaseIOLog { - private static final Log LOG = LogFactory.getLog(RollingIOLog.class); + private static final Log LOG = LogFactory.getLog(RollingIOLog.class); - // New Members - protected int fileSize; + // New Members + protected int fileSize; - protected int maxFiles; + protected int maxFiles; - protected int currentFileNumber; + protected int currentFileNumber; - /** - *

- * Constructor for RollingIOLog. - *

- * @param baseFilename - The base filename for all logfiles ie. dataLog.log - * @param logDirectory a {@link File} object. - * @param fileSize - in bytes of file before rolling over - * @param maxFiles - max number to keep in addition to the current log file - */ - public RollingIOLog(final String baseFilename, File logDirectory, int fileSize, int maxFiles) { - super(new File(logDirectory, baseFilename)); // Ignoring this - createOut(); + /** + *

+ * Constructor for RollingIOLog. + *

+ * + * @param baseFilename - The base filename for all logfiles ie. dataLog.log + * @param logDirectory a {@link File} object. + * @param fileSize - in bytes of file before rolling over + * @param maxFiles - max number to keep in addition to the current log file + */ + public RollingIOLog(final String baseFilename, File logDirectory, int fileSize, int maxFiles) { + super(new File(logDirectory, baseFilename)); // Ignoring this + createOut(); - // Detect the current file number - File[] files = logDirectory.listFiles(new LogFilenameFilter(baseFilename)); + // Detect the current file number + File[] files = logDirectory.listFiles(new LogFilenameFilter(baseFilename)); - // files will contain baseFilename.log, baseFilename.log.1 ... baseFilename.log.n - // where n is our currentFileNumber - this.currentFileNumber = files.length - 1; - if (this.currentFileNumber > maxFiles) - this.currentFileNumber = maxFiles; + // files will contain baseFilename.log, baseFilename.log.1 ... baseFilename.log.n + // where n is our currentFileNumber + this.currentFileNumber = files.length - 1; + if (this.currentFileNumber > maxFiles) + this.currentFileNumber = maxFiles; - this.fileSize = fileSize; - this.maxFiles = maxFiles; + this.fileSize = fileSize; + this.maxFiles = maxFiles; - } + } - @Override - protected void sizeCheck() { - // Check if the file should be rolled. - if (file.length() > this.fileSize) { - out.close(); + @Override + protected void sizeCheck() { + // Check if the file should be rolled. + if (file.length() > this.fileSize) { + out.close(); - try { - // Do rollover + try { + // Do rollover - for (int i = this.currentFileNumber; i > 0; i--) { - Path source = Paths.get(this.file.getAbsolutePath() + "." + i); - Path target = Paths.get(this.file.getAbsolutePath() + "." + (i + 1)); - Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); - } + for (int i = this.currentFileNumber; i > 0; i--) { + Path source = Paths.get(this.file.getAbsolutePath() + "." + i); + Path target = Paths.get(this.file.getAbsolutePath() + "." + (i + 1)); + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + } - Path source = Paths.get(this.file.toURI()); - Path target = Paths.get(this.file.getAbsolutePath() + "." + 1); - Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); + Path source = Paths.get(this.file.toURI()); + Path target = Paths.get(this.file.getAbsolutePath() + "." + 1); + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); - if (this.currentFileNumber < this.maxFiles - 1) { - // Use file number - this.currentFileNumber++; - } + if (this.currentFileNumber < this.maxFiles - 1) { + // Use file number + this.currentFileNumber++; + } - } - catch (IOException e) { - LOG.error(e); - } + } catch (IOException e) { + LOG.error(e); + } - createOut(); - } - } + createOut(); + } + } - /** - * Class to filter log filenames from a directory listing - * - * @author Terry Packer - */ - class LogFilenameFilter implements FilenameFilter { + /** + * Class to filter log filenames from a directory listing + * + * @author Terry Packer + */ + class LogFilenameFilter implements FilenameFilter { - private String nameToMatch; + private String nameToMatch; - public LogFilenameFilter(String nameToMatch) { - this.nameToMatch = nameToMatch; - } + public LogFilenameFilter(String nameToMatch) { + this.nameToMatch = nameToMatch; + } - @Override - public boolean accept(File dir, String name) { - return name.contains(this.nameToMatch); - } + @Override + public boolean accept(File dir, String name) { + return name.contains(this.nameToMatch); + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/SimpleLog.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/SimpleLog.java index 55ca590a0..bc990d818 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/SimpleLog.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/log/SimpleLog.java @@ -31,99 +31,103 @@ import java.util.Date; */ public class SimpleLog { - private final PrintWriter out; + private final PrintWriter out; - private final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd HH:mm:ss.SSS"); + private final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd HH:mm:ss.SSS"); - private final StringBuilder sb = new StringBuilder(); + private final StringBuilder sb = new StringBuilder(); - private final Date date = new Date(); + private final Date date = new Date(); - /** - *

- * Constructor for SimpleLog. - *

- */ - public SimpleLog() { - this(new PrintWriter(System.out)); - } + /** + *

+ * Constructor for SimpleLog. + *

+ */ + public SimpleLog() { + this(new PrintWriter(System.out)); + } - /** - *

- * Constructor for SimpleLog. - *

- * @param out a {@link PrintWriter} object. - */ - public SimpleLog(PrintWriter out) { - this.out = out; - } + /** + *

+ * Constructor for SimpleLog. + *

+ * + * @param out a {@link PrintWriter} object. + */ + public SimpleLog(PrintWriter out) { + this.out = out; + } - /** - *

- * out. - *

- * @param message a {@link String} object. - */ - public void out(String message) { - out(message, null); - } + /** + *

+ * out. + *

+ * + * @param message a {@link String} object. + */ + public void out(String message) { + out(message, null); + } - /** - *

- * out. - *

- * @param t a {@link Throwable} object. - */ - public void out(Throwable t) { - out(null, t); - } + /** + *

+ * out. + *

+ * + * @param t a {@link Throwable} object. + */ + public void out(Throwable t) { + out(null, t); + } - /** - *

- * out. - *

- * @param o a {@link Object} object. - */ - public void out(Object o) { - if (o instanceof Throwable) - out(null, (Throwable) o); - else if (o == null) - out(null, null); - else - out(o.toString(), null); - } + /** + *

+ * out. + *

+ * + * @param o a {@link Object} object. + */ + public void out(Object o) { + if (o instanceof Throwable) + out(null, (Throwable) o); + else if (o == null) + out(null, null); + else + out(o.toString(), null); + } - /** - *

- * close. - *

- */ - public void close() { - out.close(); - } + /** + *

+ * close. + *

+ */ + public void close() { + out.close(); + } - /** - *

- * out. - *

- * @param message a {@link String} object. - * @param t a {@link Throwable} object. - */ - public synchronized void out(String message, Throwable t) { - sb.delete(0, sb.length()); - date.setTime(System.currentTimeMillis()); - sb.append(sdf.format(date)).append(" "); - if (message != null) - sb.append(message); - if (t != null) { - if (t.getMessage() != null) - sb.append(" - ").append(t.getMessage()); - out.println(sb.toString()); - t.printStackTrace(out); - } - else - out.println(sb.toString()); - out.flush(); - } + /** + *

+ * out. + *

+ * + * @param message a {@link String} object. + * @param t a {@link Throwable} object. + */ + public synchronized void out(String message, Throwable t) { + sb.delete(0, sb.length()); + date.setTime(System.currentTimeMillis()); + sb.append(sdf.format(date)).append(" "); + if (message != null) + sb.append(message); + if (t != null) { + if (t.getMessage() != null) + sb.append(" - ").append(t.getMessage()); + out.println(sb.toString()); + t.printStackTrace(out); + } else + out.println(sb.toString()); + out.flush(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DataConsumer.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DataConsumer.java index ca58d73d8..24292b722 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DataConsumer.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DataConsumer.java @@ -29,19 +29,21 @@ import java.io.IOException; */ public interface DataConsumer { - /** - * Notifies the consumer that new data is available - * @param b array of bytes representing the incoming information - * @param len length of the data - */ - public void data(byte[] b, int len); + /** + * Notifies the consumer that new data is available + * + * @param b array of bytes representing the incoming information + * @param len length of the data + */ + public void data(byte[] b, int len); - /** - *

- * handleIOException. - *

- * @param e a {@link IOException} object. - */ - public void handleIOException(IOException e); + /** + *

+ * handleIOException. + *

+ * + * @param e a {@link IOException} object. + */ + public void handleIOException(IOException e); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DefaultMessagingExceptionHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DefaultMessagingExceptionHandler.java index 63c728c73..24db9f52d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DefaultMessagingExceptionHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/DefaultMessagingExceptionHandler.java @@ -27,8 +27,8 @@ package com.serotonin.modbus4j.sero.messaging; */ public class DefaultMessagingExceptionHandler implements MessagingExceptionHandler { - public void receivedException(Exception e) { - e.printStackTrace(); - } + public void receivedException(Exception e) { + e.printStackTrace(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransport.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransport.java index 39e779505..0014d11e9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransport.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransport.java @@ -34,78 +34,80 @@ import java.io.OutputStream; */ public class EpollStreamTransport implements Transport { - private final OutputStream out; + private final OutputStream out; - private final InputStream in; + private final InputStream in; - private final InputStreamEPollWrapper epoll; + private final InputStreamEPollWrapper epoll; - /** - *

- * Constructor for EpollStreamTransport. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - * @param epoll a {@link InputStreamEPollWrapper} object. - */ - public EpollStreamTransport(InputStream in, OutputStream out, InputStreamEPollWrapper epoll) { - this.out = out; - this.in = in; - this.epoll = epoll; - } + /** + *

+ * Constructor for EpollStreamTransport. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + * @param epoll a {@link InputStreamEPollWrapper} object. + */ + public EpollStreamTransport(InputStream in, OutputStream out, InputStreamEPollWrapper epoll) { + this.out = out; + this.in = in; + this.epoll = epoll; + } - @Override - public void setConsumer(final DataConsumer consumer) { - epoll.add(in, new Modbus4JInputStreamCallback() { - @Override - public void terminated() { - removeConsumer(); - } + @Override + public void setConsumer(final DataConsumer consumer) { + epoll.add(in, new Modbus4JInputStreamCallback() { + @Override + public void terminated() { + removeConsumer(); + } - @Override - public void ioException(IOException e) { - consumer.handleIOException(e); - } + @Override + public void ioException(IOException e) { + consumer.handleIOException(e); + } - @Override - public void input(byte[] buf, int len) { - consumer.data(buf, len); - } + @Override + public void input(byte[] buf, int len) { + consumer.data(buf, len); + } - @Override - public void closed() { - removeConsumer(); - } - }); - } + @Override + public void closed() { + removeConsumer(); + } + }); + } - /** - *

- * removeConsumer. - *

- */ - @Override - public void removeConsumer() { - epoll.remove(in); - } + /** + *

+ * removeConsumer. + *

+ */ + @Override + public void removeConsumer() { + epoll.remove(in); + } - /** - *

- * write. - *

- * @param data an array of {@link byte} objects. - * @throws IOException if any. - */ - @Override - public void write(byte[] data) throws IOException { - out.write(data); - out.flush(); - } + /** + *

+ * write. + *

+ * + * @param data an array of {@link byte} objects. + * @throws IOException if any. + */ + @Override + public void write(byte[] data) throws IOException { + out.write(data); + out.flush(); + } - @Override - public void write(byte[] data, int len) throws IOException { - out.write(data, 0, len); - out.flush(); - } + @Override + public void write(byte[] data, int len) throws IOException { + out.write(data, 0, len); + out.flush(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransportCharSpaced.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransportCharSpaced.java index 2fc7ff122..f9e0b5798 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransportCharSpaced.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/EpollStreamTransportCharSpaced.java @@ -32,73 +32,72 @@ import java.io.OutputStream; */ public class EpollStreamTransportCharSpaced extends EpollStreamTransport { - private final long charSpacing; // Spacing for chars in nanoseconds + private final long charSpacing; // Spacing for chars in nanoseconds - private final OutputStream out; // Since the subclass has private members + private final OutputStream out; // Since the subclass has private members - /** - *

- * Constructor for EpollStreamTransportCharSpaced. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - * @param epoll a {@link InputStreamEPollWrapper} object. - * @param charSpacing a long. - */ - public EpollStreamTransportCharSpaced(InputStream in, OutputStream out, InputStreamEPollWrapper epoll, - long charSpacing) { - super(in, out, epoll); - this.out = out; - this.charSpacing = charSpacing; - } + /** + *

+ * Constructor for EpollStreamTransportCharSpaced. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + * @param epoll a {@link InputStreamEPollWrapper} object. + * @param charSpacing a long. + */ + public EpollStreamTransportCharSpaced(InputStream in, OutputStream out, InputStreamEPollWrapper epoll, + long charSpacing) { + super(in, out, epoll); + this.out = out; + this.charSpacing = charSpacing; + } - /** - * {@inheritDoc} - *

- * Perform a write, ensure space between chars - */ - @Override - public void write(byte[] data) throws IOException { + /** + * {@inheritDoc} + *

+ * Perform a write, ensure space between chars + */ + @Override + public void write(byte[] data) throws IOException { - try { - long waited = 0, writeStart, writeEnd, waitRemaining; - for (byte b : data) { - writeStart = System.nanoTime(); - out.write(b); - writeEnd = System.nanoTime(); - waited = writeEnd - writeStart; - if (waited < this.charSpacing) { - waitRemaining = this.charSpacing - waited; - Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); - } + try { + long waited = 0, writeStart, writeEnd, waitRemaining; + for (byte b : data) { + writeStart = System.nanoTime(); + out.write(b); + writeEnd = System.nanoTime(); + waited = writeEnd - writeStart; + if (waited < this.charSpacing) { + waitRemaining = this.charSpacing - waited; + Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); + } - } - } - catch (Exception e) { - throw new IOException(e); - } - out.flush(); - } + } + } catch (Exception e) { + throw new IOException(e); + } + out.flush(); + } - public void write(byte[] data, int len) throws IOException { - try { - long waited = 0, writeStart, writeEnd, waitRemaining; - for (int i = 0; i < len; i++) { - writeStart = System.nanoTime(); - out.write(data[i]); - writeEnd = System.nanoTime(); - waited = writeEnd - writeStart; - if (waited < this.charSpacing) { - waitRemaining = this.charSpacing - waited; - Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); - } + public void write(byte[] data, int len) throws IOException { + try { + long waited = 0, writeStart, writeEnd, waitRemaining; + for (int i = 0; i < len; i++) { + writeStart = System.nanoTime(); + out.write(data[i]); + writeEnd = System.nanoTime(); + waited = writeEnd - writeStart; + if (waited < this.charSpacing) { + waitRemaining = this.charSpacing - waited; + Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); + } - } - } - catch (Exception e) { - throw new IOException(e); - } - out.flush(); - } + } + } catch (Exception e) { + throw new IOException(e); + } + out.flush(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingMessage.java index ad921f485..e7b48f14d 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingMessage.java @@ -27,6 +27,6 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface IncomingMessage { - // A marker interface + // A marker interface } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingRequestMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingRequestMessage.java index 34b3cf49a..13c5d0132 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingRequestMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingRequestMessage.java @@ -27,6 +27,6 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface IncomingRequestMessage extends IncomingMessage { - // A marker interface. + // A marker interface. } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingResponseMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingResponseMessage.java index a9571c904..0209839bb 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingResponseMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/IncomingResponseMessage.java @@ -27,6 +27,6 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface IncomingResponseMessage extends IncomingMessage { - // A marker interface + // A marker interface } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/InputStreamListener.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/InputStreamListener.java index 1e53baec4..92a55f1b5 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/InputStreamListener.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/InputStreamListener.java @@ -31,118 +31,119 @@ import java.io.InputStream; */ public class InputStreamListener implements Runnable { - private static final int DEFAULT_READ_DELAY = 50; + private static final int DEFAULT_READ_DELAY = 50; - private final InputStream in; + private final InputStream in; - private final DataConsumer consumer; + private final DataConsumer consumer; - private volatile boolean running = true; + private volatile boolean running = true; - /** - * Defaulted to 20ms, this value tells the listener how long to wait between polls. - * Setting this to very small values (as low as 1ms) can result in high processor - * consumption, but better responsiveness when data arrives in the stream. Very high - * values have the opposite effect. - */ - private int readDelay = DEFAULT_READ_DELAY; + /** + * Defaulted to 20ms, this value tells the listener how long to wait between polls. + * Setting this to very small values (as low as 1ms) can result in high processor + * consumption, but better responsiveness when data arrives in the stream. Very high + * values have the opposite effect. + */ + private int readDelay = DEFAULT_READ_DELAY; - /** - *

- * Constructor for InputStreamListener. - *

- * @param in a {@link InputStream} object. - * @param consumer a {@link DataConsumer} object. - */ - public InputStreamListener(InputStream in, DataConsumer consumer) { - this.in = in; - this.consumer = consumer; - } + /** + *

+ * Constructor for InputStreamListener. + *

+ * + * @param in a {@link InputStream} object. + * @param consumer a {@link DataConsumer} object. + */ + public InputStreamListener(InputStream in, DataConsumer consumer) { + this.in = in; + this.consumer = consumer; + } - /** - *

- * Getter for the field readDelay. - *

- * @return a int. - */ - public int getReadDelay() { - return readDelay; - } + /** + *

+ * Getter for the field readDelay. + *

+ * + * @return a int. + */ + public int getReadDelay() { + return readDelay; + } - /** - *

- * Setter for the field readDelay. - *

- * @param readDelay a int. - */ - public void setReadDelay(int readDelay) { - if (readDelay < 1) - throw new IllegalArgumentException("readDelay can't be less than one"); - this.readDelay = readDelay; - } + /** + *

+ * Setter for the field readDelay. + *

+ * + * @param readDelay a int. + */ + public void setReadDelay(int readDelay) { + if (readDelay < 1) + throw new IllegalArgumentException("readDelay can't be less than one"); + this.readDelay = readDelay; + } - /** - *

- * start. - *

- * @param threadName a {@link String} object. - */ - public void start(String threadName) { - Thread thread = new Thread(this, threadName); - thread.setDaemon(true); - thread.start(); - } + /** + *

+ * start. + *

+ * + * @param threadName a {@link String} object. + */ + public void start(String threadName) { + Thread thread = new Thread(this, threadName); + thread.setDaemon(true); + thread.start(); + } - /** - *

- * stop. - *

- */ - public void stop() { - running = false; - synchronized (this) { - notify(); - } - } + /** + *

+ * stop. + *

+ */ + public void stop() { + running = false; + synchronized (this) { + notify(); + } + } - /** - *

- * run. - *

- */ - public void run() { - byte[] buf = new byte[1024]; - int readcount; - try { - while (running) { - try { - if (in.available() == 0) { - synchronized (this) { - try { - wait(readDelay); - } - catch (InterruptedException e) { - // no op - } - } - continue; - } + /** + *

+ * run. + *

+ */ + public void run() { + byte[] buf = new byte[1024]; + int readcount; + try { + while (running) { + try { + if (in.available() == 0) { + synchronized (this) { + try { + wait(readDelay); + } catch (InterruptedException e) { + // no op + } + } + continue; + } - readcount = in.read(buf); - consumer.data(buf, readcount); - } - catch (IOException e) { - consumer.handleIOException(e); - if (e.getMessage().equals("Stream closed.")) - break; - if (e.getMessage().contains("nativeavailable")) - break; - } - } - } - finally { - running = false; - } - } + readcount = in.read(buf); + consumer.data(buf, readcount); + } catch (IOException e) { + consumer.handleIOException(e); + if (e.getMessage().equals("Stream closed.")) + break; + if (e.getMessage().contains("nativeavailable")) + break; + } + } + } finally { + running = false; + } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageControl.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageControl.java index e43390bea..bb38d66c5 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageControl.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageControl.java @@ -38,340 +38,351 @@ import java.io.IOException; */ public class MessageControl implements DataConsumer { - private static int DEFAULT_RETRIES = 2; + private static int DEFAULT_RETRIES = 2; - private static int DEFAULT_TIMEOUT = 500; + private static int DEFAULT_TIMEOUT = 500; - private final WaitingRoom waitingRoom = new WaitingRoom(); + private final WaitingRoom waitingRoom = new WaitingRoom(); - private final ByteQueue dataBuffer = new ByteQueue(); + private final ByteQueue dataBuffer = new ByteQueue(); - public boolean DEBUG = false; + public boolean DEBUG = false; - private Transport transport; + private Transport transport; - private MessageParser messageParser; + private MessageParser messageParser; - private RequestHandler requestHandler; + private RequestHandler requestHandler; - private WaitingRoomKeyFactory waitingRoomKeyFactory; + private WaitingRoomKeyFactory waitingRoomKeyFactory; - private MessagingExceptionHandler exceptionHandler = new DefaultMessagingExceptionHandler(); + private MessagingExceptionHandler exceptionHandler = new DefaultMessagingExceptionHandler(); - private int retries = DEFAULT_RETRIES; + private int retries = DEFAULT_RETRIES; - private int timeout = DEFAULT_TIMEOUT; + private int timeout = DEFAULT_TIMEOUT; - private int discardDataDelay = 0; + private int discardDataDelay = 0; - private long lastDataTimestamp; + private long lastDataTimestamp; - private BaseIOLog ioLog; + private BaseIOLog ioLog; - private TimeSource timeSource = new SystemTimeSource(); + private TimeSource timeSource = new SystemTimeSource(); - /** - *

- * start. - *

- * @param transport a {@link com.serotonin.modbus4j.sero.messaging.Transport} object. - * @param messageParser a {@link com.serotonin.modbus4j.sero.messaging.MessageParser} - * object. - * @param handler a {@link com.serotonin.modbus4j.sero.messaging.RequestHandler} - * object. - * @param waitingRoomKeyFactory a - * {@link com.serotonin.modbus4j.sero.messaging.WaitingRoomKeyFactory} object. - * @throws java.io.IOException if any. - */ - public void start(Transport transport, MessageParser messageParser, RequestHandler handler, - WaitingRoomKeyFactory waitingRoomKeyFactory) throws IOException { - if (transport == null) { - throw new IllegalArgumentException("transport can't be null"); - } - this.transport = transport; - this.messageParser = messageParser; - this.requestHandler = handler; - this.waitingRoomKeyFactory = waitingRoomKeyFactory; - waitingRoom.setKeyFactory(waitingRoomKeyFactory); - transport.setConsumer(this); - } + /** + *

+ * start. + *

+ * + * @param transport a {@link com.serotonin.modbus4j.sero.messaging.Transport} object. + * @param messageParser a {@link com.serotonin.modbus4j.sero.messaging.MessageParser} + * object. + * @param handler a {@link com.serotonin.modbus4j.sero.messaging.RequestHandler} + * object. + * @param waitingRoomKeyFactory a + * {@link com.serotonin.modbus4j.sero.messaging.WaitingRoomKeyFactory} object. + * @throws java.io.IOException if any. + */ + public void start(Transport transport, MessageParser messageParser, RequestHandler handler, + WaitingRoomKeyFactory waitingRoomKeyFactory) throws IOException { + if (transport == null) { + throw new IllegalArgumentException("transport can't be null"); + } + this.transport = transport; + this.messageParser = messageParser; + this.requestHandler = handler; + this.waitingRoomKeyFactory = waitingRoomKeyFactory; + waitingRoom.setKeyFactory(waitingRoomKeyFactory); + transport.setConsumer(this); + } - /** - *

- * close. - *

- */ - public void close() { - if (transport != null) { - transport.removeConsumer(); - } - } + /** + *

+ * close. + *

+ */ + public void close() { + if (transport != null) { + transport.removeConsumer(); + } + } - /** - *

- * Setter for the field exceptionHandler. - *

- * @param exceptionHandler a - * {@link com.serotonin.modbus4j.sero.messaging.MessagingExceptionHandler} object. - */ - public void setExceptionHandler(MessagingExceptionHandler exceptionHandler) { - if (exceptionHandler == null) - this.exceptionHandler = new DefaultMessagingExceptionHandler(); - else - this.exceptionHandler = exceptionHandler; - } + /** + *

+ * Setter for the field exceptionHandler. + *

+ * + * @param exceptionHandler a + * {@link com.serotonin.modbus4j.sero.messaging.MessagingExceptionHandler} object. + */ + public void setExceptionHandler(MessagingExceptionHandler exceptionHandler) { + if (exceptionHandler == null) + this.exceptionHandler = new DefaultMessagingExceptionHandler(); + else + this.exceptionHandler = exceptionHandler; + } - /** - *

- * Getter for the field retries. - *

- * @return a int. - */ - public int getRetries() { - return retries; - } + /** + *

+ * Getter for the field retries. + *

+ * + * @return a int. + */ + public int getRetries() { + return retries; + } - /** - *

- * Setter for the field retries. - *

- * @param retries a int. - */ - public void setRetries(int retries) { - this.retries = retries; - } + /** + *

+ * Setter for the field retries. + *

+ * + * @param retries a int. + */ + public void setRetries(int retries) { + this.retries = retries; + } - /** - *

- * Getter for the field timeout. - *

- * @return a int. - */ - public int getTimeout() { - return timeout; - } + /** + *

+ * Getter for the field timeout. + *

+ * + * @return a int. + */ + public int getTimeout() { + return timeout; + } - /** - *

- * Setter for the field timeout. - *

- * @param timeout a int. - */ - public void setTimeout(int timeout) { - this.timeout = timeout; - } + /** + *

+ * Setter for the field timeout. + *

+ * + * @param timeout a int. + */ + public void setTimeout(int timeout) { + this.timeout = timeout; + } - /** - *

- * Getter for the field discardDataDelay. - *

- * @return a int. - */ - public int getDiscardDataDelay() { - return discardDataDelay; - } + /** + *

+ * Getter for the field discardDataDelay. + *

+ * + * @return a int. + */ + public int getDiscardDataDelay() { + return discardDataDelay; + } - /** - *

- * Setter for the field discardDataDelay. - *

- * @param discardDataDelay a int. - */ - public void setDiscardDataDelay(int discardDataDelay) { - this.discardDataDelay = discardDataDelay; - } + /** + *

+ * Setter for the field discardDataDelay. + *

+ * + * @param discardDataDelay a int. + */ + public void setDiscardDataDelay(int discardDataDelay) { + this.discardDataDelay = discardDataDelay; + } - /** - *

- * Getter for the field ioLog. - *

- * @return a {@link com.serotonin.modbus4j.sero.log.BaseIOLog} object. - */ - public BaseIOLog getIoLog() { - return ioLog; - } + /** + *

+ * Getter for the field ioLog. + *

+ * + * @return a {@link com.serotonin.modbus4j.sero.log.BaseIOLog} object. + */ + public BaseIOLog getIoLog() { + return ioLog; + } - /** - *

- * Setter for the field ioLog. - *

- * @param ioLog a {@link com.serotonin.modbus4j.sero.log.BaseIOLog} object. - */ - public void setIoLog(BaseIOLog ioLog) { - this.ioLog = ioLog; - } + /** + *

+ * Setter for the field ioLog. + *

+ * + * @param ioLog a {@link com.serotonin.modbus4j.sero.log.BaseIOLog} object. + */ + public void setIoLog(BaseIOLog ioLog) { + this.ioLog = ioLog; + } - /** - *

- * Getter for the field timeSource. - *

- * @return a {@link com.serotonin.modbus4j.sero.timer.TimeSource} object. - */ - public TimeSource getTimeSource() { - return timeSource; - } + /** + *

+ * Getter for the field timeSource. + *

+ * + * @return a {@link com.serotonin.modbus4j.sero.timer.TimeSource} object. + */ + public TimeSource getTimeSource() { + return timeSource; + } - /** - *

- * Setter for the field timeSource. - *

- * @param timeSource a {@link com.serotonin.modbus4j.sero.timer.TimeSource} object. - */ - public void setTimeSource(TimeSource timeSource) { - this.timeSource = timeSource; - } + /** + *

+ * Setter for the field timeSource. + *

+ * + * @param timeSource a {@link com.serotonin.modbus4j.sero.timer.TimeSource} object. + */ + public void setTimeSource(TimeSource timeSource) { + this.timeSource = timeSource; + } - /** - *

- * send. - *

- * @param request a - * {@link com.serotonin.modbus4j.sero.messaging.OutgoingRequestMessage} object. - * @return a {@link com.serotonin.modbus4j.sero.messaging.IncomingResponseMessage} - * object. - * @throws java.io.IOException if any. - */ - public IncomingResponseMessage send(OutgoingRequestMessage request) throws IOException { - return send(request, timeout, retries); - } + /** + *

+ * send. + *

+ * + * @param request a + * {@link com.serotonin.modbus4j.sero.messaging.OutgoingRequestMessage} object. + * @return a {@link com.serotonin.modbus4j.sero.messaging.IncomingResponseMessage} + * object. + * @throws java.io.IOException if any. + */ + public IncomingResponseMessage send(OutgoingRequestMessage request) throws IOException { + return send(request, timeout, retries); + } - /** - *

- * send. - *

- * @param request a - * {@link com.serotonin.modbus4j.sero.messaging.OutgoingRequestMessage} object. - * @param timeout a int. - * @param retries a int. - * @return a {@link com.serotonin.modbus4j.sero.messaging.IncomingResponseMessage} - * object. - * @throws java.io.IOException if any. - */ - public IncomingResponseMessage send(OutgoingRequestMessage request, int timeout, int retries) throws IOException { - byte[] data = request.getMessageData(); - if (DEBUG) - System.out.println("MessagingControl.send: " + StreamUtils.dumpHex(data)); + /** + *

+ * send. + *

+ * + * @param request a + * {@link com.serotonin.modbus4j.sero.messaging.OutgoingRequestMessage} object. + * @param timeout a int. + * @param retries a int. + * @return a {@link com.serotonin.modbus4j.sero.messaging.IncomingResponseMessage} + * object. + * @throws java.io.IOException if any. + */ + public IncomingResponseMessage send(OutgoingRequestMessage request, int timeout, int retries) throws IOException { + byte[] data = request.getMessageData(); + if (DEBUG) + System.out.println("MessagingControl.send: " + StreamUtils.dumpHex(data)); - IncomingResponseMessage response = null; + IncomingResponseMessage response = null; - if (request.expectsResponse()) { - WaitingRoomKey key = waitingRoomKeyFactory.createWaitingRoomKey(request); + if (request.expectsResponse()) { + WaitingRoomKey key = waitingRoomKeyFactory.createWaitingRoomKey(request); - // Enter the waiting room - waitingRoom.enter(key); + // Enter the waiting room + waitingRoom.enter(key); - try { - do { - // Send the request. - write(data); + try { + do { + // Send the request. + write(data); - // Wait for the response. - response = waitingRoom.getResponse(key, timeout); + // Wait for the response. + response = waitingRoom.getResponse(key, timeout); - if (DEBUG && response == null) - System.out.println("Timeout waiting for response"); - } - while (response == null && retries-- > 0); - } - finally { - // Leave the waiting room. - waitingRoom.leave(key); - } + if (DEBUG && response == null) + System.out.println("Timeout waiting for response"); + } + while (response == null && retries-- > 0); + } finally { + // Leave the waiting room. + waitingRoom.leave(key); + } - if (response == null) - throw new TimeoutException("request=" + request); - } - else - write(data); + if (response == null) + throw new TimeoutException("request=" + request); + } else + write(data); - return response; - } + return response; + } - /** - *

- * send. - *

- * @param response a - * {@link com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage} object. - * @throws java.io.IOException if any. - */ - public void send(OutgoingResponseMessage response) throws IOException { - write(response.getMessageData()); - } + /** + *

+ * send. + *

+ * + * @param response a + * {@link com.serotonin.modbus4j.sero.messaging.OutgoingResponseMessage} object. + * @throws java.io.IOException if any. + */ + public void send(OutgoingResponseMessage response) throws IOException { + write(response.getMessageData()); + } - /** - * {@inheritDoc} - *

- * Incoming data from the transport. Single-threaded. - */ - public void data(byte[] b, int len) { - if (DEBUG) - System.out.println("MessagingConnection.read: " + StreamUtils.dumpHex(b, 0, len)); - if (ioLog != null) - ioLog.input(b, 0, len); + /** + * {@inheritDoc} + *

+ * Incoming data from the transport. Single-threaded. + */ + public void data(byte[] b, int len) { + if (DEBUG) + System.out.println("MessagingConnection.read: " + StreamUtils.dumpHex(b, 0, len)); + if (ioLog != null) + ioLog.input(b, 0, len); - if (discardDataDelay > 0) { - long now = timeSource.currentTimeMillis(); - if (now - lastDataTimestamp > discardDataDelay) - dataBuffer.clear(); - lastDataTimestamp = now; - } + if (discardDataDelay > 0) { + long now = timeSource.currentTimeMillis(); + if (now - lastDataTimestamp > discardDataDelay) + dataBuffer.clear(); + lastDataTimestamp = now; + } - dataBuffer.push(b, 0, len); + dataBuffer.push(b, 0, len); - // There may be multiple messages in the data, so enter a loop. - while (true) { - // Attempt to parse a message. - try { - // Mark where we are in the buffer. The entire message may not be in yet, - // but since the parser - // will consume the buffer we need to be able to backtrack. - dataBuffer.mark(); + // There may be multiple messages in the data, so enter a loop. + while (true) { + // Attempt to parse a message. + try { + // Mark where we are in the buffer. The entire message may not be in yet, + // but since the parser + // will consume the buffer we need to be able to backtrack. + dataBuffer.mark(); - IncomingMessage message = messageParser.parseMessage(dataBuffer); + IncomingMessage message = messageParser.parseMessage(dataBuffer); - if (message == null) { - // Nothing to do. Reset the buffer and exit the loop. - dataBuffer.reset(); - break; - } + if (message == null) { + // Nothing to do. Reset the buffer and exit the loop. + dataBuffer.reset(); + break; + } - if (message instanceof IncomingRequestMessage) { - // Received a request. Give it to the request handler - if (requestHandler != null) { - OutgoingResponseMessage response = requestHandler - .handleRequest((IncomingRequestMessage) message); + if (message instanceof IncomingRequestMessage) { + // Received a request. Give it to the request handler + if (requestHandler != null) { + OutgoingResponseMessage response = requestHandler + .handleRequest((IncomingRequestMessage) message); - if (response != null) - send(response); - } - } - else - // Must be a response. Give it to the waiting room. - waitingRoom.response((IncomingResponseMessage) message); - } - catch (Exception e) { - exceptionHandler.receivedException(e); - // Clear the buffer - // dataBuffer.clear(); - } - } - } + if (response != null) + send(response); + } + } else + // Must be a response. Give it to the waiting room. + waitingRoom.response((IncomingResponseMessage) message); + } catch (Exception e) { + exceptionHandler.receivedException(e); + // Clear the buffer + // dataBuffer.clear(); + } + } + } - private void write(byte[] data) throws IOException { - if (ioLog != null) - ioLog.output(data); + private void write(byte[] data) throws IOException { + if (ioLog != null) + ioLog.output(data); - synchronized (transport) { - transport.write(data); - } - } + synchronized (transport) { + transport.write(data); + } + } - /** - * {@inheritDoc} - */ - public void handleIOException(IOException e) { - exceptionHandler.receivedException(e); - } + /** + * {@inheritDoc} + */ + public void handleIOException(IOException e) { + exceptionHandler.receivedException(e); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageParser.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageParser.java index 48154cc19..651e0f057 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageParser.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessageParser.java @@ -27,21 +27,22 @@ import com.serotonin.modbus4j.sero.util.queue.ByteQueue; */ public interface MessageParser { - /** - * Attempt to parse a message out of the queue. Data in the queue may be discarded if - * it is unusable (i.e. a start indicator is not found), but otherwise if a message is - * not found due to the data being incomplete, the method should return null. As - * additional data arrives, it will be appended to the queue and this method will be - * called again. - *

- * Implementations should not modify the queue unless it is safe to do so. No copy of - * the data is made before calling this method. - * @param queue the queue from which to access data for the creation of the message - * @return the message if one was able to be created, or null otherwise. - * @throws Exception if the data in the queue is sufficient to construct a message, - * but the message data is invalid, this method must throw an exception, or it will - * keep getting the same data. - */ - IncomingMessage parseMessage(ByteQueue queue) throws Exception; + /** + * Attempt to parse a message out of the queue. Data in the queue may be discarded if + * it is unusable (i.e. a start indicator is not found), but otherwise if a message is + * not found due to the data being incomplete, the method should return null. As + * additional data arrives, it will be appended to the queue and this method will be + * called again. + *

+ * Implementations should not modify the queue unless it is safe to do so. No copy of + * the data is made before calling this method. + * + * @param queue the queue from which to access data for the creation of the message + * @return the message if one was able to be created, or null otherwise. + * @throws Exception if the data in the queue is sufficient to construct a message, + * but the message data is invalid, this method must throw an exception, or it will + * keep getting the same data. + */ + IncomingMessage parseMessage(ByteQueue queue) throws Exception; } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessagingExceptionHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessagingExceptionHandler.java index aa78c85c9..bdca78e23 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessagingExceptionHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/MessagingExceptionHandler.java @@ -27,12 +27,13 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface MessagingExceptionHandler { - /** - *

- * receivedException. - *

- * @param e a {@link Exception} object. - */ - public void receivedException(Exception e); + /** + *

+ * receivedException. + *

+ * + * @param e a {@link Exception} object. + */ + public void receivedException(Exception e); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingMessage.java index 702668275..71f2e9156 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingMessage.java @@ -27,10 +27,11 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface OutgoingMessage { - /** - * Return the byte array representing the serialization of the request. - * @return byte array representing the serialization of the request - */ - byte[] getMessageData(); + /** + * Return the byte array representing the serialization of the request. + * + * @return byte array representing the serialization of the request + */ + byte[] getMessageData(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingRequestMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingRequestMessage.java index 293e7f98b..6b0aff6f9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingRequestMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingRequestMessage.java @@ -27,10 +27,11 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface OutgoingRequestMessage extends OutgoingMessage { - /** - * Whether the request is expecting a response or not. - * @return true if a response is expected, false otherwise. - */ - boolean expectsResponse(); + /** + * Whether the request is expecting a response or not. + * + * @return true if a response is expected, false otherwise. + */ + boolean expectsResponse(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingResponseMessage.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingResponseMessage.java index c6fa9ab92..15aee7c5f 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingResponseMessage.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/OutgoingResponseMessage.java @@ -27,6 +27,6 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface OutgoingResponseMessage extends OutgoingMessage { - // A marker interface. + // A marker interface. } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/RequestHandler.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/RequestHandler.java index 251a1459b..6ad5652f9 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/RequestHandler.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/RequestHandler.java @@ -27,13 +27,14 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface RequestHandler { - /** - * Handle the request and return the appropriate response object. - * @param request the request to handle - * @return the response object or null if no response is to be sent. null may also be - * returned if the request is handled asynchronously. - * @throws Exception if necessary - */ - OutgoingResponseMessage handleRequest(IncomingRequestMessage request) throws Exception; + /** + * Handle the request and return the appropriate response object. + * + * @param request the request to handle + * @return the response object or null if no response is to be sent. null may also be + * returned if the request is handled asynchronously. + * @throws Exception if necessary + */ + OutgoingResponseMessage handleRequest(IncomingRequestMessage request) throws Exception; } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransport.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransport.java index 7429e80e0..95ec456b4 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransport.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransport.java @@ -34,92 +34,96 @@ import java.io.OutputStream; */ public class StreamTransport implements Transport, Runnable { - protected OutputStream out; + protected OutputStream out; - protected InputStream in; + protected InputStream in; - private InputStreamListener listener; + private InputStreamListener listener; - /** - *

- * Constructor for StreamTransport. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - */ - public StreamTransport(InputStream in, OutputStream out) { - this.out = out; - this.in = in; - } + /** + *

+ * Constructor for StreamTransport. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + */ + public StreamTransport(InputStream in, OutputStream out) { + this.out = out; + this.in = in; + } - /** - *

- * setReadDelay. - *

- * @param readDelay a int. - */ - public void setReadDelay(int readDelay) { - if (listener != null) - listener.setReadDelay(readDelay); - } + /** + *

+ * setReadDelay. + *

+ * + * @param readDelay a int. + */ + public void setReadDelay(int readDelay) { + if (listener != null) + listener.setReadDelay(readDelay); + } - /** - *

- * start. - *

- * @param threadName a {@link String} object. - */ - public void start(String threadName) { - listener.start(threadName); - } + /** + *

+ * start. + *

+ * + * @param threadName a {@link String} object. + */ + public void start(String threadName) { + listener.start(threadName); + } - /** - *

- * stop. - *

- */ - public void stop() { - listener.stop(); - } + /** + *

+ * stop. + *

+ */ + public void stop() { + listener.stop(); + } - /** - *

- * run. - *

- */ - public void run() { - listener.run(); - } + /** + *

+ * run. + *

+ */ + public void run() { + listener.run(); + } - public void setConsumer(DataConsumer consumer) { - listener = new InputStreamListener(in, consumer); - } + public void setConsumer(DataConsumer consumer) { + listener = new InputStreamListener(in, consumer); + } - /** - *

- * removeConsumer. - *

- */ - public void removeConsumer() { - listener.stop(); - listener = null; - } + /** + *

+ * removeConsumer. + *

+ */ + public void removeConsumer() { + listener.stop(); + listener = null; + } - /** - *

- * write. - *

- * @param data an array of {@link byte} objects. - * @throws IOException if any. - */ - public void write(byte[] data) throws IOException { - out.write(data); - out.flush(); - } + /** + *

+ * write. + *

+ * + * @param data an array of {@link byte} objects. + * @throws IOException if any. + */ + public void write(byte[] data) throws IOException { + out.write(data); + out.flush(); + } - public void write(byte[] data, int len) throws IOException { - out.write(data, 0, len); - out.flush(); - } + public void write(byte[] data, int len) throws IOException { + out.write(data, 0, len); + out.flush(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransportCharSpaced.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransportCharSpaced.java index b8cb16730..8aac58183 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransportCharSpaced.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/StreamTransportCharSpaced.java @@ -30,68 +30,67 @@ import java.io.OutputStream; */ public class StreamTransportCharSpaced extends StreamTransport { - private final long charSpacing; + private final long charSpacing; - /** - *

- * Constructor for StreamTransportCharSpaced. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - * @param charSpacing a long. - */ - public StreamTransportCharSpaced(InputStream in, OutputStream out, long charSpacing) { - super(in, out); - this.charSpacing = charSpacing; - } + /** + *

+ * Constructor for StreamTransportCharSpaced. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + * @param charSpacing a long. + */ + public StreamTransportCharSpaced(InputStream in, OutputStream out, long charSpacing) { + super(in, out); + this.charSpacing = charSpacing; + } - /** - * {@inheritDoc} - *

- * Perform a write, ensure space between chars - */ - @Override - public void write(byte[] data) throws IOException { + /** + * {@inheritDoc} + *

+ * Perform a write, ensure space between chars + */ + @Override + public void write(byte[] data) throws IOException { - try { - long waited = 0, writeStart, writeEnd, waitRemaining; - for (byte b : data) { - writeStart = System.nanoTime(); - out.write(b); - writeEnd = System.nanoTime(); - waited = writeEnd - writeStart; - if (waited < this.charSpacing) { - waitRemaining = this.charSpacing - waited; - Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); - } + try { + long waited = 0, writeStart, writeEnd, waitRemaining; + for (byte b : data) { + writeStart = System.nanoTime(); + out.write(b); + writeEnd = System.nanoTime(); + waited = writeEnd - writeStart; + if (waited < this.charSpacing) { + waitRemaining = this.charSpacing - waited; + Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); + } - } - } - catch (Exception e) { - throw new IOException(e); - } - out.flush(); - } + } + } catch (Exception e) { + throw new IOException(e); + } + out.flush(); + } - public void write(byte[] data, int len) throws IOException { - try { - long waited = 0, writeStart, writeEnd, waitRemaining; - for (int i = 0; i < len; i++) { - writeStart = System.nanoTime(); - out.write(data[i]); - writeEnd = System.nanoTime(); - waited = writeEnd - writeStart; - if (waited < this.charSpacing) { - waitRemaining = this.charSpacing - waited; - Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); - } + public void write(byte[] data, int len) throws IOException { + try { + long waited = 0, writeStart, writeEnd, waitRemaining; + for (int i = 0; i < len; i++) { + writeStart = System.nanoTime(); + out.write(data[i]); + writeEnd = System.nanoTime(); + waited = writeEnd - writeStart; + if (waited < this.charSpacing) { + waitRemaining = this.charSpacing - waited; + Thread.sleep(waitRemaining / 1000000, (int) (waitRemaining % 1000000)); + } - } - } - catch (Exception e) { - throw new IOException(e); - } - out.flush(); - } + } + } catch (Exception e) { + throw new IOException(e); + } + out.flush(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TestableTransport.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TestableTransport.java index 6f66da845..eb3b03ff8 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TestableTransport.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TestableTransport.java @@ -30,46 +30,48 @@ import java.io.OutputStream; */ public class TestableTransport extends StreamTransport { - /** - *

- * Constructor for TestableTransport. - *

- * @param in a {@link InputStream} object. - * @param out a {@link OutputStream} object. - */ - public TestableTransport(InputStream in, OutputStream out) { - super(new TestableBufferedInputStream(in), out); - } + /** + *

+ * Constructor for TestableTransport. + *

+ * + * @param in a {@link InputStream} object. + * @param out a {@link OutputStream} object. + */ + public TestableTransport(InputStream in, OutputStream out) { + super(new TestableBufferedInputStream(in), out); + } - /** - *

- * testInputStream. - *

- * @throws IOException if any. - */ - public void testInputStream() throws IOException { - ((TestableBufferedInputStream) in).test(); - } + /** + *

+ * testInputStream. + *

+ * + * @throws IOException if any. + */ + public void testInputStream() throws IOException { + ((TestableBufferedInputStream) in).test(); + } - static class TestableBufferedInputStream extends BufferedInputStream { + static class TestableBufferedInputStream extends BufferedInputStream { - public TestableBufferedInputStream(InputStream in) { - super(in); - } + public TestableBufferedInputStream(InputStream in) { + super(in); + } - @Override - public synchronized int read(byte[] buf) throws IOException { - return super.read(buf); - } + @Override + public synchronized int read(byte[] buf) throws IOException { + return super.read(buf); + } - public synchronized void test() throws IOException { - mark(1); - int i = read(); - if (i == -1) - throw new IOException("Stream closed"); - reset(); - } + public synchronized void test() throws IOException { + mark(1); + int i = read(); + if (i == -1) + throw new IOException("Stream closed"); + reset(); + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TimeoutException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TimeoutException.java index 04aa8a4d6..4ce3a8959 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TimeoutException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/TimeoutException.java @@ -30,17 +30,18 @@ import java.io.Serial; */ public class TimeoutException extends IOException { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - *

- * Constructor for TimeoutException. - *

- * @param message a {@link String} object. - */ - public TimeoutException(String message) { - super(message); - } + /** + *

+ * Constructor for TimeoutException. + *

+ * + * @param message a {@link String} object. + */ + public TimeoutException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/Transport.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/Transport.java index 121bc6d55..5611394a6 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/Transport.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/Transport.java @@ -28,39 +28,42 @@ import java.io.IOException; */ public interface Transport { - /** - *

- * setConsumer. - *

- * @param consumer a {@link DataConsumer} object. - * @throws IOException if any. - */ - abstract void setConsumer(DataConsumer consumer) throws IOException; + /** + *

+ * setConsumer. + *

+ * + * @param consumer a {@link DataConsumer} object. + * @throws IOException if any. + */ + abstract void setConsumer(DataConsumer consumer) throws IOException; - /** - *

- * removeConsumer. - *

- */ - abstract void removeConsumer(); + /** + *

+ * removeConsumer. + *

+ */ + abstract void removeConsumer(); - /** - *

- * write. - *

- * @param data an array of {@link byte} objects. - * @throws IOException if any. - */ - abstract void write(byte[] data) throws IOException; + /** + *

+ * write. + *

+ * + * @param data an array of {@link byte} objects. + * @throws IOException if any. + */ + abstract void write(byte[] data) throws IOException; - /** - *

- * write. - *

- * @param data an array of {@link byte} objects. - * @param len a int. - * @throws IOException if any. - */ - abstract void write(byte[] data, int len) throws IOException; + /** + *

+ * write. + *

+ * + * @param data an array of {@link byte} objects. + * @param len a int. + * @throws IOException if any. + */ + abstract void write(byte[] data, int len) throws IOException; } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoom.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoom.java index 7bff387d7..0297835e0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoom.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoom.java @@ -31,132 +31,132 @@ import java.util.Map; */ class WaitingRoom { - private static final Log LOG = LogFactory.getLog(WaitingRoom.class); + private static final Log LOG = LogFactory.getLog(WaitingRoom.class); - private final Map waitHere = new HashMap(); + private final Map waitHere = new HashMap(); - private WaitingRoomKeyFactory keyFactory; + private WaitingRoomKeyFactory keyFactory; - void setKeyFactory(WaitingRoomKeyFactory keyFactory) { - this.keyFactory = keyFactory; - } + void setKeyFactory(WaitingRoomKeyFactory keyFactory) { + this.keyFactory = keyFactory; + } - /** - * The request message should be sent AFTER entering the waiting room so that the - * (vanishingly small) chance of a response being returned before the thread is - * waiting for it is eliminated. - * @return - */ - void enter(WaitingRoomKey key) { - Member member = new Member(); - synchronized (this) { - while (waitHere.get(key) != null) { - if (LOG.isDebugEnabled()) - LOG.debug("Duplicate waiting room key found. Waiting for member to leave."); - try { - wait(); - } - catch (InterruptedException e) { - // no op - } - } - // Member dup = waitHere.get(key); - // if (dup != null) { - // - // throw new WaitingRoomException("Waiting room too crowded. Already contains - // the key " + key); - // } + /** + * The request message should be sent AFTER entering the waiting room so that the + * (vanishingly small) chance of a response being returned before the thread is + * waiting for it is eliminated. + * + * @return + */ + void enter(WaitingRoomKey key) { + Member member = new Member(); + synchronized (this) { + while (waitHere.get(key) != null) { + if (LOG.isDebugEnabled()) + LOG.debug("Duplicate waiting room key found. Waiting for member to leave."); + try { + wait(); + } catch (InterruptedException e) { + // no op + } + } + // Member dup = waitHere.get(key); + // if (dup != null) { + // + // throw new WaitingRoomException("Waiting room too crowded. Already contains + // the key " + key); + // } - waitHere.put(key, member); - } - } + waitHere.put(key, member); + } + } - IncomingResponseMessage getResponse(WaitingRoomKey key, long timeout) throws WaitingRoomException { - // Get the member. - Member member; - synchronized (this) { - member = waitHere.get(key); - } + IncomingResponseMessage getResponse(WaitingRoomKey key, long timeout) throws WaitingRoomException { + // Get the member. + Member member; + synchronized (this) { + member = waitHere.get(key); + } - if (member == null) - throw new WaitingRoomException("No member for key " + key); + if (member == null) + throw new WaitingRoomException("No member for key " + key); - // Wait for the response. - return member.getResponse(timeout); - } + // Wait for the response. + return member.getResponse(timeout); + } - void leave(WaitingRoomKey key) { - // Leave the waiting room - synchronized (this) { - waitHere.remove(key); + void leave(WaitingRoomKey key) { + // Leave the waiting room + synchronized (this) { + waitHere.remove(key); - // Notify any threads that are waiting to get in. This could probably be just - // a notify() call. - notifyAll(); - } - } + // Notify any threads that are waiting to get in. This could probably be just + // a notify() call. + notifyAll(); + } + } - /** - * This method is used by the data listening thread to post responses as they are - * received from the transport. - * @param response the response message - * @throws WaitingRoomException - */ - void response(IncomingResponseMessage response) throws WaitingRoomException { - WaitingRoomKey key = keyFactory.createWaitingRoomKey(response); - if (key == null) - // The key factory can return a null key if the response should be ignored. - return; + /** + * This method is used by the data listening thread to post responses as they are + * received from the transport. + * + * @param response the response message + * @throws WaitingRoomException + */ + void response(IncomingResponseMessage response) throws WaitingRoomException { + WaitingRoomKey key = keyFactory.createWaitingRoomKey(response); + if (key == null) + // The key factory can return a null key if the response should be ignored. + return; - Member member; + Member member; - synchronized (this) { - member = waitHere.get(key); - } + synchronized (this) { + member = waitHere.get(key); + } - if (member != null) - member.setResponse(response); - else - throw new WaitingRoomException("No recipient was found waiting for response for key " + key); - } + if (member != null) + member.setResponse(response); + else + throw new WaitingRoomException("No recipient was found waiting for response for key " + key); + } - /** - * This class is used by network message controllers to manage the blocking of threads - * sending confirmed messages. The instance itself serves as a monitor upon which the - * sending thread can wait (with a timeout). When a response is received, the message - * controller can set it in here, automatically notifying the sending thread that the - * response is available. - * - * @author Matthew Lohbihler - */ - class Member { + /** + * This class is used by network message controllers to manage the blocking of threads + * sending confirmed messages. The instance itself serves as a monitor upon which the + * sending thread can wait (with a timeout). When a response is received, the message + * controller can set it in here, automatically notifying the sending thread that the + * response is available. + * + * @author Matthew Lohbihler + */ + class Member { - private IncomingResponseMessage response; + private IncomingResponseMessage response; - synchronized void setResponse(IncomingResponseMessage response) { - this.response = response; - notify(); - } + synchronized void setResponse(IncomingResponseMessage response) { + this.response = response; + notify(); + } - synchronized IncomingResponseMessage getResponse(long timeout) { - // Check if there is a response object now. - if (response != null) - return response; + synchronized IncomingResponseMessage getResponse(long timeout) { + // Check if there is a response object now. + if (response != null) + return response; - // If not, wait the timeout and then check again. - waitNoThrow(timeout); - return response; - } + // If not, wait the timeout and then check again. + waitNoThrow(timeout); + return response; + } - private void waitNoThrow(long timeout) { - try { - wait(timeout); - } - catch (InterruptedException e) { - // Ignore - } - } + private void waitNoThrow(long timeout) { + try { + wait(timeout); + } catch (InterruptedException e) { + // Ignore + } + } - } + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomException.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomException.java index 63a6d9cee..d421066f3 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomException.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomException.java @@ -30,17 +30,18 @@ import java.io.Serial; */ public class WaitingRoomException extends IOException { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - /** - *

- * Constructor for WaitingRoomException. - *

- * @param message a {@link String} object. - */ - public WaitingRoomException(String message) { - super(message); - } + /** + *

+ * Constructor for WaitingRoomException. + *

+ * + * @param message a {@link String} object. + */ + public WaitingRoomException(String message) { + super(message); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKey.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKey.java index 8e61a1613..fcf00c81a 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKey.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKey.java @@ -26,6 +26,6 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface WaitingRoomKey { - // Implementation needs to have hashcode and equals implementations. + // Implementation needs to have hashcode and equals implementations. } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKeyFactory.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKeyFactory.java index bedc34d4a..fd51a35fd 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKeyFactory.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/messaging/WaitingRoomKeyFactory.java @@ -27,22 +27,24 @@ package com.serotonin.modbus4j.sero.messaging; */ public interface WaitingRoomKeyFactory { - /** - *

- * createWaitingRoomKey. - *

- * @param request a {@link OutgoingRequestMessage} object. - * @return a {@link WaitingRoomKey} object. - */ - WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request); + /** + *

+ * createWaitingRoomKey. + *

+ * + * @param request a {@link OutgoingRequestMessage} object. + * @return a {@link WaitingRoomKey} object. + */ + WaitingRoomKey createWaitingRoomKey(OutgoingRequestMessage request); - /** - *

- * createWaitingRoomKey. - *

- * @param response a {@link IncomingResponseMessage} object. - * @return a {@link WaitingRoomKey} object. - */ - WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response); + /** + *

+ * createWaitingRoomKey. + *

+ * + * @param response a {@link IncomingResponseMessage} object. + * @return a {@link WaitingRoomKey} object. + */ + WaitingRoomKey createWaitingRoomKey(IncomingResponseMessage response); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/SystemTimeSource.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/SystemTimeSource.java index b9e4998e6..21d7ed58c 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/SystemTimeSource.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/SystemTimeSource.java @@ -25,14 +25,15 @@ package com.serotonin.modbus4j.sero.timer; */ public class SystemTimeSource implements TimeSource { - /** - *

- * currentTimeMillis. - *

- * @return a long. - */ - public long currentTimeMillis() { - return System.currentTimeMillis(); - } + /** + *

+ * currentTimeMillis. + *

+ * + * @return a long. + */ + public long currentTimeMillis() { + return System.currentTimeMillis(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/TimeSource.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/TimeSource.java index 2a08d1118..d050044c0 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/TimeSource.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/timer/TimeSource.java @@ -26,12 +26,13 @@ package com.serotonin.modbus4j.sero.timer; */ public interface TimeSource { - /** - *

- * currentTimeMillis. - *

- * @return a long. - */ - long currentTimeMillis(); + /** + *

+ * currentTimeMillis. + *

+ * + * @return a long. + */ + long currentTimeMillis(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ArrayUtils.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ArrayUtils.java index 3abaebdb6..ac6ae9b76 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ArrayUtils.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ArrayUtils.java @@ -29,369 +29,390 @@ import java.util.List; */ public class ArrayUtils { - private static int[] bitFromMask = { 0xff, 0x7f, 0x3f, 0x1f, 0xf, 0x7, 0x3, 0x1 }; + private static int[] bitFromMask = {0xff, 0x7f, 0x3f, 0x1f, 0xf, 0x7, 0x3, 0x1}; - /** - *

- * toHexString. - *

- * @param bytes an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String toHexString(byte[] bytes) { - return toHexString(bytes, 0, bytes.length); - } + /** + *

+ * toHexString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String toHexString(byte[] bytes) { + return toHexString(bytes, 0, bytes.length); + } - /** - *

- * toHexString. - *

- * @param bytes an array of {@link byte} objects. - * @param start a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String toHexString(byte[] bytes, int start, int len) { - if (len == 0) - return "[]"; + /** + *

+ * toHexString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @param start a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String toHexString(byte[] bytes, int start, int len) { + if (len == 0) + return "[]"; - StringBuffer sb = new StringBuffer(); - sb.append('['); - sb.append(Integer.toHexString(bytes[start] & 0xff)); - for (int i = 1; i < len; i++) - sb.append(',').append(Integer.toHexString(bytes[start + i] & 0xff)); - sb.append("]"); + StringBuffer sb = new StringBuffer(); + sb.append('['); + sb.append(Integer.toHexString(bytes[start] & 0xff)); + for (int i = 1; i < len; i++) + sb.append(',').append(Integer.toHexString(bytes[start + i] & 0xff)); + sb.append("]"); - return sb.toString(); - } + return sb.toString(); + } - /** - *

- * toPlainHexString. - *

- * @param bytes an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String toPlainHexString(byte[] bytes) { - return toPlainHexString(bytes, 0, bytes.length); - } + /** + *

+ * toPlainHexString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String toPlainHexString(byte[] bytes) { + return toPlainHexString(bytes, 0, bytes.length); + } - /** - *

- * toPlainHexString. - *

- * @param bytes an array of {@link byte} objects. - * @param start a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String toPlainHexString(byte[] bytes, int start, int len) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < len; i++) { - String s = Integer.toHexString(bytes[start + i] & 0xff); - if (s.length() < 2) - sb.append('0'); - sb.append(s); - } - return sb.toString(); - } + /** + *

+ * toPlainHexString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @param start a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String toPlainHexString(byte[] bytes, int start, int len) { + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < len; i++) { + String s = Integer.toHexString(bytes[start + i] & 0xff); + if (s.length() < 2) + sb.append('0'); + sb.append(s); + } + return sb.toString(); + } - /** - *

- * toString. - *

- * @param bytes an array of {@link byte} objects. - * @return a {@link String} object. - */ - public static String toString(byte[] bytes) { - return toString(bytes, 0, bytes.length); - } + /** + *

+ * toString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @return a {@link String} object. + */ + public static String toString(byte[] bytes) { + return toString(bytes, 0, bytes.length); + } - /** - *

- * toString. - *

- * @param bytes an array of {@link byte} objects. - * @param start a int. - * @param len a int. - * @return a {@link String} object. - */ - public static String toString(byte[] bytes, int start, int len) { - if (len == 0) - return "[]"; + /** + *

+ * toString. + *

+ * + * @param bytes an array of {@link byte} objects. + * @param start a int. + * @param len a int. + * @return a {@link String} object. + */ + public static String toString(byte[] bytes, int start, int len) { + if (len == 0) + return "[]"; - StringBuffer sb = new StringBuffer(); - sb.append('['); - sb.append(Integer.toString(bytes[start] & 0xff)); - for (int i = 1; i < len; i++) - sb.append(',').append(Integer.toString(bytes[start + i] & 0xff)); - sb.append("]"); + StringBuffer sb = new StringBuffer(); + sb.append('['); + sb.append(Integer.toString(bytes[start] & 0xff)); + for (int i = 1; i < len; i++) + sb.append(',').append(Integer.toString(bytes[start + i] & 0xff)); + sb.append("]"); - return sb.toString(); - } + return sb.toString(); + } - /** - *

- * isEmpty. - *

- * @param value an array of {@link int} objects. - * @return a boolean. - */ - public static boolean isEmpty(int[] value) { - return value == null || value.length == 0; - } + /** + *

+ * isEmpty. + *

+ * + * @param value an array of {@link int} objects. + * @return a boolean. + */ + public static boolean isEmpty(int[] value) { + return value == null || value.length == 0; + } - /** - *

- * indexOf. - *

- * @param values an array of {@link String} objects. - * @param value a {@link String} object. - * @return a int. - */ - public static int indexOf(String[] values, String value) { - if (values == null) - return -1; + /** + *

+ * indexOf. + *

+ * + * @param values an array of {@link String} objects. + * @param value a {@link String} object. + * @return a int. + */ + public static int indexOf(String[] values, String value) { + if (values == null) + return -1; - for (int i = 0; i < values.length; i++) { - if (values[i].equals(value)) - return i; - } + for (int i = 0; i < values.length; i++) { + if (values[i].equals(value)) + return i; + } - return -1; - } + return -1; + } - /** - *

- * containsIgnoreCase. - *

- * @param values an array of {@link String} objects. - * @param value a {@link String} object. - * @return a boolean. - */ - public static boolean containsIgnoreCase(String[] values, String value) { - if (values == null) - return false; + /** + *

+ * containsIgnoreCase. + *

+ * + * @param values an array of {@link String} objects. + * @param value a {@link String} object. + * @return a boolean. + */ + public static boolean containsIgnoreCase(String[] values, String value) { + if (values == null) + return false; - for (int i = 0; i < values.length; i++) { - if (values[i].equalsIgnoreCase(value)) - return true; - } + for (int i = 0; i < values.length; i++) { + if (values[i].equalsIgnoreCase(value)) + return true; + } - return false; - } + return false; + } - /** - *

- * indexOf. - *

- * @param src an array of {@link byte} objects. - * @param target an array of {@link byte} objects. - * @return a int. - */ - public static int indexOf(byte[] src, byte[] target) { - return indexOf(src, 0, src.length, target); - } + /** + *

+ * indexOf. + *

+ * + * @param src an array of {@link byte} objects. + * @param target an array of {@link byte} objects. + * @return a int. + */ + public static int indexOf(byte[] src, byte[] target) { + return indexOf(src, 0, src.length, target); + } - /** - *

- * indexOf. - *

- * @param src an array of {@link byte} objects. - * @param len a int. - * @param target an array of {@link byte} objects. - * @return a int. - */ - public static int indexOf(byte[] src, int len, byte[] target) { - return indexOf(src, 0, len, target); - } + /** + *

+ * indexOf. + *

+ * + * @param src an array of {@link byte} objects. + * @param len a int. + * @param target an array of {@link byte} objects. + * @return a int. + */ + public static int indexOf(byte[] src, int len, byte[] target) { + return indexOf(src, 0, len, target); + } - /** - *

- * indexOf. - *

- * @param src an array of {@link byte} objects. - * @param start a int. - * @param len a int. - * @param target an array of {@link byte} objects. - * @return a int. - */ - public static int indexOf(byte[] src, int start, int len, byte[] target) { - int pos = start; - int i; - boolean matched; - while (pos + target.length <= len) { - // Check for a match on the first character - if (src[pos] == target[0]) { - // Now check for matches in the rest of the characters - matched = true; - i = 1; - while (i < target.length) { - if (src[pos + i] != target[i]) { - matched = false; - break; - } - i++; - } + /** + *

+ * indexOf. + *

+ * + * @param src an array of {@link byte} objects. + * @param start a int. + * @param len a int. + * @param target an array of {@link byte} objects. + * @return a int. + */ + public static int indexOf(byte[] src, int start, int len, byte[] target) { + int pos = start; + int i; + boolean matched; + while (pos + target.length <= len) { + // Check for a match on the first character + if (src[pos] == target[0]) { + // Now check for matches in the rest of the characters + matched = true; + i = 1; + while (i < target.length) { + if (src[pos + i] != target[i]) { + matched = false; + break; + } + i++; + } - if (matched) - return pos; - } - pos++; - } + if (matched) + return pos; + } + pos++; + } - return -1; - } + return -1; + } - /** - * Returns the value of the bits in the given range. Ranges can extend multiple bytes. - * No range checking is done. Invalid ranges will result in - * {@link ArrayIndexOutOfBoundsException}. - * @param b the array of bytes. - * @param offset the location at which to begin - * @param length the number of bits to include in the value. - * @return the value of the bits in the range. - */ - public static long bitRangeValueLong(byte[] b, int offset, int length) { - if (length <= 0) - return 0; + /** + * Returns the value of the bits in the given range. Ranges can extend multiple bytes. + * No range checking is done. Invalid ranges will result in + * {@link ArrayIndexOutOfBoundsException}. + * + * @param b the array of bytes. + * @param offset the location at which to begin + * @param length the number of bits to include in the value. + * @return the value of the bits in the range. + */ + public static long bitRangeValueLong(byte[] b, int offset, int length) { + if (length <= 0) + return 0; - int byteFrom = offset / 8; - int byteTo = (offset + length - 1) / 8; + int byteFrom = offset / 8; + int byteTo = (offset + length - 1) / 8; - long result = b[byteFrom] & bitFromMask[offset % 8]; + long result = b[byteFrom] & bitFromMask[offset % 8]; - for (int i = byteFrom + 1; i <= byteTo; i++) { - result <<= 8; - result |= b[i] & 0xff; - } + for (int i = byteFrom + 1; i <= byteTo; i++) { + result <<= 8; + result |= b[i] & 0xff; + } - result >>= 8 - (((offset + length - 1) % 8) + 1); + result >>= 8 - (((offset + length - 1) % 8) + 1); - return result; - } + return result; + } - /** - *

- * bitRangeValue. - *

- * @param b an array of {@link byte} objects. - * @param offset a int. - * @param length a int. - * @return a int. - */ - public static int bitRangeValue(byte[] b, int offset, int length) { - return (int) bitRangeValueLong(b, offset, length); - } + /** + *

+ * bitRangeValue. + *

+ * + * @param b an array of {@link byte} objects. + * @param offset a int. + * @param length a int. + * @return a int. + */ + public static int bitRangeValue(byte[] b, int offset, int length) { + return (int) bitRangeValueLong(b, offset, length); + } - /** - *

- * byteRangeValueLong. - *

- * @param b an array of {@link byte} objects. - * @param offset a int. - * @param length a int. - * @return a long. - */ - public static long byteRangeValueLong(byte[] b, int offset, int length) { - long result = 0; + /** + *

+ * byteRangeValueLong. + *

+ * + * @param b an array of {@link byte} objects. + * @param offset a int. + * @param length a int. + * @return a long. + */ + public static long byteRangeValueLong(byte[] b, int offset, int length) { + long result = 0; - for (int i = offset; i < offset + length; i++) { - result <<= 8; - result |= b[i] & 0xff; - } + for (int i = offset; i < offset + length; i++) { + result <<= 8; + result |= b[i] & 0xff; + } - return result; - } + return result; + } - /** - *

- * byteRangeValue. - *

- * @param b an array of {@link byte} objects. - * @param offset a int. - * @param length a int. - * @return a int. - */ - public static int byteRangeValue(byte[] b, int offset, int length) { - return (int) byteRangeValueLong(b, offset, length); - } + /** + *

+ * byteRangeValue. + *

+ * + * @param b an array of {@link byte} objects. + * @param offset a int. + * @param length a int. + * @return a int. + */ + public static int byteRangeValue(byte[] b, int offset, int length) { + return (int) byteRangeValueLong(b, offset, length); + } - /** - *

- * sum. - *

- * @param a an array of {@link int} objects. - * @return a int. - */ - public static int sum(int[] a) { - int sum = 0; - for (int i = 0; i < a.length; i++) - sum += a[i]; - return sum; - } + /** + *

+ * sum. + *

+ * + * @param a an array of {@link int} objects. + * @return a int. + */ + public static int sum(int[] a) { + int sum = 0; + for (int i = 0; i < a.length; i++) + sum += a[i]; + return sum; + } - /** - *

- * toIntArray. - *

- * @param list a {@link List} object. - * @return an array of {@link int} objects. - */ - public static int[] toIntArray(List list) { - int[] result = new int[list.size()]; - for (int i = 0; i < result.length; i++) - result[i] = list.get(i); - return result; - } + /** + *

+ * toIntArray. + *

+ * + * @param list a {@link List} object. + * @return an array of {@link int} objects. + */ + public static int[] toIntArray(List list) { + int[] result = new int[list.size()]; + for (int i = 0; i < result.length; i++) + result[i] = list.get(i); + return result; + } - /** - *

- * toDoubleArray. - *

- * @param list a {@link List} object. - * @return an array of {@link double} objects. - */ - public static double[] toDoubleArray(List list) { - double[] result = new double[list.size()]; - for (int i = 0; i < result.length; i++) - result[i] = list.get(i); - return result; - } + /** + *

+ * toDoubleArray. + *

+ * + * @param list a {@link List} object. + * @return an array of {@link double} objects. + */ + public static double[] toDoubleArray(List list) { + double[] result = new double[list.size()]; + for (int i = 0; i < result.length; i++) + result[i] = list.get(i); + return result; + } - /** - *

- * concatenate. - *

- * @param a an array of {@link Object} objects. - * @param delimiter a {@link String} object. - * @return a {@link String} object. - */ - public static String concatenate(Object[] a, String delimiter) { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for (Object o : a) { - if (first) - first = false; - else - sb.append(delimiter); - sb.append(o); - } - return sb.toString(); - } + /** + *

+ * concatenate. + *

+ * + * @param a an array of {@link Object} objects. + * @param delimiter a {@link String} object. + * @return a {@link String} object. + */ + public static String concatenate(Object[] a, String delimiter) { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for (Object o : a) { + if (first) + first = false; + else + sb.append(delimiter); + sb.append(o); + } + return sb.toString(); + } - /** - *

- * shift. - *

- * @param a an array of {@link Object} objects. - * @param count a int. - */ - public static void shift(Object[] a, int count) { - if (count > 0) - System.arraycopy(a, 0, a, count, a.length - count); - else - System.arraycopy(a, -count, a, 0, a.length + count); - } + /** + *

+ * shift. + *

+ * + * @param a an array of {@link Object} objects. + * @param count a int. + */ + public static void shift(Object[] a, int count) { + if (count > 0) + System.arraycopy(a, 0, a, count, a.length - count); + else + System.arraycopy(a, -count, a, 0, a.length + count); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTask.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTask.java index 627bb1df8..78f35cdec 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTask.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTask.java @@ -26,123 +26,127 @@ package com.serotonin.modbus4j.sero.util; * @version 2025.9.0 */ abstract /** - * Progressive Task - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Progressive Task + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ProgressiveTask implements Runnable { - protected boolean completed = false; + protected boolean completed = false; - private boolean cancelled = false; + private boolean cancelled = false; - private ProgressiveTaskListener listener; + private ProgressiveTaskListener listener; - /** - *

- * Constructor for ProgressiveTask. - *

- */ - public ProgressiveTask() { - // no op - } + /** + *

+ * Constructor for ProgressiveTask. + *

+ */ + public ProgressiveTask() { + // no op + } - /** - *

- * Constructor for ProgressiveTask. - *

- * @param l a {@link ProgressiveTaskListener} object. - */ - public ProgressiveTask(ProgressiveTaskListener l) { - listener = l; - } + /** + *

+ * Constructor for ProgressiveTask. + *

+ * + * @param l a {@link ProgressiveTaskListener} object. + */ + public ProgressiveTask(ProgressiveTaskListener l) { + listener = l; + } - /** - *

- * cancel. - *

- */ - public void cancel() { - cancelled = true; - } + /** + *

+ * cancel. + *

+ */ + public void cancel() { + cancelled = true; + } - /** - *

- * isCancelled. - *

- * @return a boolean. - */ - public boolean isCancelled() { - return cancelled; - } + /** + *

+ * isCancelled. + *

+ * + * @return a boolean. + */ + public boolean isCancelled() { + return cancelled; + } - /** - *

- * isCompleted. - *

- * @return a boolean. - */ - public boolean isCompleted() { - return completed; - } + /** + *

+ * isCompleted. + *

+ * + * @return a boolean. + */ + public boolean isCompleted() { + return completed; + } - /** - *

- * run. - *

- */ - public final void run() { - while (true) { - if (isCancelled()) { - declareFinished(true); - break; - } + /** + *

+ * run. + *

+ */ + public final void run() { + while (true) { + if (isCancelled()) { + declareFinished(true); + break; + } - runImpl(); + runImpl(); - if (isCompleted()) { - declareFinished(false); - break; - } - } - completed = true; - } + if (isCompleted()) { + declareFinished(false); + break; + } + } + completed = true; + } - /** - *

- * declareProgress. - *

- * @param progress a float. - */ - protected void declareProgress(float progress) { - ProgressiveTaskListener l = listener; - if (l != null) - l.progressUpdate(progress); - } + /** + *

+ * declareProgress. + *

+ * + * @param progress a float. + */ + protected void declareProgress(float progress) { + ProgressiveTaskListener l = listener; + if (l != null) + l.progressUpdate(progress); + } - private void declareFinished(boolean cancelled) { - ProgressiveTaskListener l = listener; - if (l != null) { - if (cancelled) - l.taskCancelled(); - else - l.taskCompleted(); - } - } + private void declareFinished(boolean cancelled) { + ProgressiveTaskListener l = listener; + if (l != null) { + if (cancelled) + l.taskCancelled(); + else + l.taskCompleted(); + } + } - /** - * Implementers of this method MUST return from it occasionally so that the cancelled - * status can be checked. Each return must leave the class and thread state with the - * expectation that runImpl will not be called again, while acknowledging the - * possibility that it will. - *

- * Implementations SHOULD call the declareProgress method with each runImpl execution - * such that the listener can be notified. - *

- * Implementations MUST set the completed field to true when the task is finished. - */ - abstract protected void runImpl(); + /** + * Implementers of this method MUST return from it occasionally so that the cancelled + * status can be checked. Each return must leave the class and thread state with the + * expectation that runImpl will not be called again, while acknowledging the + * possibility that it will. + *

+ * Implementations SHOULD call the declareProgress method with each runImpl execution + * such that the listener can be notified. + *

+ * Implementations MUST set the completed field to true when the task is finished. + */ + abstract protected void runImpl(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTaskListener.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTaskListener.java index 7cdb0e907..2e92c686b 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTaskListener.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/ProgressiveTaskListener.java @@ -27,23 +27,24 @@ package com.serotonin.modbus4j.sero.util; */ public interface ProgressiveTaskListener { - /** - * Optionally called occasionally by the task to declare the progress that has been - * made. - * @param progress float between 0 and 1 where 0 is no progress and 1 is completed. - */ - void progressUpdate(float progress); + /** + * Optionally called occasionally by the task to declare the progress that has been + * made. + * + * @param progress float between 0 and 1 where 0 is no progress and 1 is completed. + */ + void progressUpdate(float progress); - /** - * Notification that the task has been cancelled. Should only be called once for the - * task. - */ - void taskCancelled(); + /** + * Notification that the task has been cancelled. Should only be called once for the + * task. + */ + void taskCancelled(); - /** - * Notification that the task has been completed. Should only be called once for the - * task. - */ - void taskCompleted(); + /** + * Notification that the task has been completed. Should only be called once for the + * task. + */ + void taskCompleted(); } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/queue/ByteQueue.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/queue/ByteQueue.java index 0f8dcfde6..eb3601ca5 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/queue/ByteQueue.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/sero/util/queue/ByteQueue.java @@ -32,898 +32,943 @@ import java.nio.charset.Charset; */ public class ByteQueue implements Cloneable { - private byte[] queue; - - private int head = -1; - - private int tail = 0; - - private int size = 0; - - private int markHead; - - private int markTail; - - private int markSize; - - /** - *

- * Constructor for ByteQueue. - *

- */ - public ByteQueue() { - this(1024); - } - - /** - *

- * Constructor for ByteQueue. - *

- * @param initialLength a int. - */ - public ByteQueue(int initialLength) { - queue = new byte[initialLength]; - } - - /** - *

- * Constructor for ByteQueue. - *

- * @param b an array of {@link byte} objects. - */ - public ByteQueue(byte[] b) { - this(b.length); - push(b, 0, b.length); - } - - /** - *

- * Constructor for ByteQueue. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param length a int. - */ - public ByteQueue(byte[] b, int pos, int length) { - this(length); - push(b, pos, length); - } - - /** - *

- * Constructor for ByteQueue. - *

- * @param hex a {@link String} object. - */ - public ByteQueue(String hex) { - this(hex.length() / 2); - push(hex); - } - - /** - *

- * push. - *

- * @param hex a {@link String} object. - */ - public void push(String hex) { - if (hex.length() % 2 != 0) - throw new IllegalArgumentException("Hex string must have an even number of characters"); - byte[] b = new byte[hex.length() / 2]; - for (int i = 0; i < b.length; i++) - b[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); - push(b, 0, b.length); - } - - /** - *

- * push. - *

- * @param b a byte. - */ - public void push(byte b) { - if (room() == 0) - expand(); - - queue[tail] = b; - - if (head == -1) - head = 0; - tail = (tail + 1) % queue.length; - size++; - } - - /** - *

- * push. - *

- * @param i a int. - */ - public void push(int i) { - push((byte) i); - } - - /** - *

- * push. - *

- * @param l a long. - */ - public void push(long l) { - push((byte) l); - } - - /** - * Push unsigned 2 bytes. - * @param i a int. - */ - public void pushU2B(int i) { - push((byte) (i >> 8)); - push((byte) i); - } - - /** - * Push unsigned 3 bytes. - * @param i a int. - */ - public void pushU3B(int i) { - push((byte) (i >> 16)); - push((byte) (i >> 8)); - push((byte) i); - } - - /** - * Push signed 4 bytes. - * @param i a int. - */ - public void pushS4B(int i) { - pushInt(i); - } - - /** - * Push unsigned 4 bytes. - * @param l a long. - */ - public void pushU4B(long l) { - push((byte) (l >> 24)); - push((byte) (l >> 16)); - push((byte) (l >> 8)); - push((byte) l); - } - - /** - *

- * pushChar. - *

- * @param c a char. - */ - public void pushChar(char c) { - push((byte) (c >> 8)); - push((byte) c); - } - - /** - *

- * pushDouble. - *

- * @param d a double. - */ - public void pushDouble(double d) { - pushLong(Double.doubleToLongBits(d)); - } - - /** - *

- * pushFloat. - *

- * @param f a float. - */ - public void pushFloat(float f) { - pushInt(Float.floatToIntBits(f)); - } - - /** - *

- * pushInt. - *

- * @param i a int. - */ - public void pushInt(int i) { - push((byte) (i >> 24)); - push((byte) (i >> 16)); - push((byte) (i >> 8)); - push((byte) i); - } - - /** - *

- * pushLong. - *

- * @param l a long. - */ - public void pushLong(long l) { - push((byte) (l >> 56)); - push((byte) (l >> 48)); - push((byte) (l >> 40)); - push((byte) (l >> 32)); - push((byte) (l >> 24)); - push((byte) (l >> 16)); - push((byte) (l >> 8)); - push((byte) l); - } - - /** - *

- * pushShort. - *

- * @param s a short. - */ - public void pushShort(short s) { - push((byte) (s >> 8)); - push((byte) s); - } - - /** - *

- * read. - *

- * @param in a {@link InputStream} object. - * @param length a int. - * @throws IOException if any. - */ - public void read(InputStream in, int length) throws IOException { - if (length == 0) - return; - - while (room() < length) - expand(); - - int tailLength = queue.length - tail; - if (tailLength > length) - readImpl(in, tail, length); - else - readImpl(in, tail, tailLength); - - if (length > tailLength) - readImpl(in, 0, length - tailLength); - - if (head == -1) - head = 0; - tail = (tail + length) % queue.length; - size += length; - } - - private void readImpl(InputStream in, int offset, int length) throws IOException { - int readcount; - while (length > 0) { - readcount = in.read(queue, offset, length); - offset += readcount; - length -= readcount; - } - } - - /** - *

- * push. - *

- * @param b an array of {@link byte} objects. - */ - public void push(byte[] b) { - push(b, 0, b.length); - } - - /** - *

- * push. - *

- * @param b an array of {@link byte} objects. - * @param pos a int. - * @param length a int. - */ - public void push(byte[] b, int pos, int length) { - if (length == 0) - return; - - while (room() < length) - expand(); - - int tailLength = queue.length - tail; - if (tailLength > length) - System.arraycopy(b, pos, queue, tail, length); - else - System.arraycopy(b, pos, queue, tail, tailLength); - - if (length > tailLength) - System.arraycopy(b, tailLength + pos, queue, 0, length - tailLength); - - if (head == -1) - head = 0; - tail = (tail + length) % queue.length; - size += length; - } - - /** - *

- * push. - *

- * @param source a {@link ByteQueue} object. - */ - public void push(ByteQueue source) { - if (source.size == 0) - return; - - if (source == this) - source = (ByteQueue) clone(); - - int firstCopyLen = source.queue.length - source.head; - if (source.size < firstCopyLen) - firstCopyLen = source.size; - push(source.queue, source.head, firstCopyLen); - - if (firstCopyLen < source.size) - push(source.queue, 0, source.tail); - } - - /** - *

- * push. - *

- * @param source a {@link ByteQueue} object. - * @param len a int. - */ - public void push(ByteQueue source, int len) { - // TODO There is certainly a more elegant way to do this... - while (len-- > 0) - push(source.pop()); - } - - /** - *

- * push. - *

- * @param source a {@link ByteBuffer} object. - */ - public void push(ByteBuffer source) { - int length = source.remaining(); - if (length == 0) - return; - - while (room() < length) - expand(); - - int tailLength = queue.length - tail; - if (tailLength > length) - source.get(queue, tail, length); - else - source.get(queue, tail, tailLength); - - if (length > tailLength) - source.get(queue, 0, length - tailLength); - - if (head == -1) - head = 0; - tail = (tail + length) % queue.length; - size += length; - } - - /** - *

- * mark. - *

- */ - public void mark() { - markHead = head; - markTail = tail; - markSize = size; - } - - /** - *

- * reset. - *

- */ - public void reset() { - head = markHead; - tail = markTail; - size = markSize; - } - - /** - *

- * pop. - *

- * @return a byte. - */ - public byte pop() { - byte retval = queue[head]; - - if (size == 1) { - head = -1; - tail = 0; - } - else - head = (head + 1) % queue.length; - - size--; - - return retval; - } - - /** - *

- * popU1B. - *

- * @return a int. - */ - public int popU1B() { - return pop() & 0xff; - } - - /** - *

- * popU2B. - *

- * @return a int. - */ - public int popU2B() { - return ((pop() & 0xff) << 8) | (pop() & 0xff); - } - - /** - *

- * popU3B. - *

- * @return a int. - */ - public int popU3B() { - return ((pop() & 0xff) << 16) | ((pop() & 0xff) << 8) | (pop() & 0xff); - } - - /** - *

- * popS2B. - *

- * @return a short. - */ - public short popS2B() { - return (short) (((pop() & 0xff) << 8) | (pop() & 0xff)); - } - - /** - *

- * popS4B. - *

- * @return a int. - */ - public int popS4B() { - return ((pop() & 0xff) << 24) | ((pop() & 0xff) << 16) | ((pop() & 0xff) << 8) | (pop() & 0xff); - } - - /** - *

- * popU4B. - *

- * @return a long. - */ - public long popU4B() { - return ((long) (pop() & 0xff) << 24) | ((long) (pop() & 0xff) << 16) | ((long) (pop() & 0xff) << 8) - | (pop() & 0xff); - } - - /** - *

- * pop. - *

- * @param buf an array of {@link byte} objects. - * @return a int. - */ - public int pop(byte[] buf) { - return pop(buf, 0, buf.length); - } - - /** - *

- * pop. - *

- * @param buf an array of {@link byte} objects. - * @param pos a int. - * @param length a int. - * @return a int. - */ - public int pop(byte[] buf, int pos, int length) { - length = peek(buf, pos, length); - - size -= length; - - if (size == 0) { - head = -1; - tail = 0; - } - else - head = (head + length) % queue.length; - - return length; - } - - /** - *

- * pop. - *

- * @param length a int. - * @return a int. - */ - public int pop(int length) { - if (length == 0) - return 0; - if (size == 0) - throw new ArrayIndexOutOfBoundsException(-1); - - if (length > size) - length = size; - - size -= length; - - if (size == 0) { - head = -1; - tail = 0; - } - else - head = (head + length) % queue.length; - - return length; - } - - /** - *

- * popString. - *

- * @param length a int. - * @param charset a {@link Charset} object. - * @return a {@link String} object. - */ - public String popString(int length, Charset charset) { - byte[] b = new byte[length]; - pop(b); - return new String(b, charset); - } - - /** - *

- * popAll. - *

- * @return an array of {@link byte} objects. - */ - public byte[] popAll() { - byte[] data = new byte[size]; - pop(data, 0, data.length); - return data; - } - - /** - *

- * write. - *

- * @param out a {@link OutputStream} object. - * @throws IOException if any. - */ - public void write(OutputStream out) throws IOException { - write(out, size); - } - - /** - *

- * write. - *

- * @param out a {@link OutputStream} object. - * @param length a int. - * @throws IOException if any. - */ - public void write(OutputStream out, int length) throws IOException { - if (length == 0) - return; - if (size == 0) - throw new ArrayIndexOutOfBoundsException(-1); - - if (length > size) - length = size; - - int firstCopyLen = queue.length - head; - if (length < firstCopyLen) - firstCopyLen = length; - - out.write(queue, head, firstCopyLen); - if (firstCopyLen < length) - out.write(queue, 0, length - firstCopyLen); - - size -= length; - - if (size == 0) { - head = -1; - tail = 0; - } - else - head = (head + length) % queue.length; - } - - /** - *

- * tailPop. - *

- * @return a byte. - */ - public byte tailPop() { - if (size == 0) - throw new ArrayIndexOutOfBoundsException(-1); - - tail = (tail + queue.length - 1) % queue.length; - byte retval = queue[tail]; - - if (size == 1) { - head = -1; - tail = 0; - } - - size--; - - return retval; - } - - /** - *

- * peek. - *

- * @param index a int. - * @return a byte. - */ - public byte peek(int index) { - if (index >= size) - throw new IllegalArgumentException("index " + index + " is >= queue size " + size); - - index = (index + head) % queue.length; - return queue[index]; - } - - /** - *

- * peek. - *

- * @param index a int. - * @param length a int. - * @return an array of {@link byte} objects. - */ - public byte[] peek(int index, int length) { - byte[] result = new byte[length]; - // TODO: use System.arraycopy instead. - for (int i = 0; i < length; i++) - result[i] = peek(index + i); - return result; - } - - /** - *

- * peekAll. - *

- * @return an array of {@link byte} objects. - */ - public byte[] peekAll() { - byte[] data = new byte[size]; - peek(data, 0, data.length); - return data; - } - - /** - *

- * peek. - *

- * @param buf an array of {@link byte} objects. - * @return a int. - */ - public int peek(byte[] buf) { - return peek(buf, 0, buf.length); - } - - /** - *

- * peek. - *

- * @param buf an array of {@link byte} objects. - * @param pos a int. - * @param length a int. - * @return a int. - */ - public int peek(byte[] buf, int pos, int length) { - if (length == 0) - return 0; - if (size == 0) - throw new ArrayIndexOutOfBoundsException(-1); - - if (length > size) - length = size; - - int firstCopyLen = queue.length - head; - if (length < firstCopyLen) - firstCopyLen = length; - - System.arraycopy(queue, head, buf, pos, firstCopyLen); - if (firstCopyLen < length) - System.arraycopy(queue, 0, buf, pos + firstCopyLen, length - firstCopyLen); - - return length; - } - - /** - *

- * indexOf. - *

- * @param b a byte. - * @return a int. - */ - public int indexOf(byte b) { - return indexOf(b, 0); - } - - /** - *

- * indexOf. - *

- * @param b a byte. - * @param start a int. - * @return a int. - */ - public int indexOf(byte b, int start) { - if (start >= size) - return -1; - - int index = (head + start) % queue.length; - for (int i = start; i < size; i++) { - if (queue[index] == b) - return i; - index = (index + 1) % queue.length; - } - return -1; - } - - /** - *

- * indexOf. - *

- * @param b an array of {@link byte} objects. - * @return a int. - */ - public int indexOf(byte[] b) { - return indexOf(b, 0); - } - - /** - *

- * indexOf. - *

- * @param b an array of {@link byte} objects. - * @param start a int. - * @return a int. - */ - public int indexOf(byte[] b, int start) { - if (b == null || b.length == 0) - throw new IllegalArgumentException("can't search for empty values"); - - while ((start = indexOf(b[0], start)) != -1 && start < size - b.length + 1) { - boolean found = true; - for (int i = 1; i < b.length; i++) { - if (peek(start + i) != b[i]) { - found = false; - break; - } - } - - if (found) { - return start; - } - - start++; - } - - return -1; - } - - /** - *

- * size. - *

- * @return a int. - */ - public int size() { - return size; - } - - /** - *

- * clear. - *

- */ - public void clear() { - size = 0; - head = -1; - tail = 0; - } - - private int room() { - return queue.length - size; - } - - private void expand() { - byte[] newb = new byte[queue.length * 2]; - - if (head == -1) { - queue = newb; - return; - } - - if (tail > head) { - System.arraycopy(queue, head, newb, head, tail - head); - queue = newb; - return; - } - - System.arraycopy(queue, head, newb, head + queue.length, queue.length - head); - System.arraycopy(queue, 0, newb, 0, tail); - head += queue.length; - queue = newb; - } - - @Override - public Object clone() { - try { - ByteQueue clone = (ByteQueue) super.clone(); - // Array is mutable, so make a copy of it too. - clone.queue = queue.clone(); - return clone; - } - catch (CloneNotSupportedException e) { /* - * Will never happen because we're - * Cloneable - */ - } - return null; - } - - @Override - public String toString() { - if (size == 0) - return "[]"; - - StringBuffer sb = new StringBuffer(); - sb.append('['); - sb.append(Integer.toHexString(peek(0) & 0xff)); - for (int i = 1; i < size; i++) - sb.append(',').append(Integer.toHexString(peek(i) & 0xff)); - sb.append("]"); - - return sb.toString(); - } - - /** - *

- * dumpQueue. - *

- * @return a {@link String} object. - */ - public String dumpQueue() { - StringBuffer sb = new StringBuffer(); - - if (queue.length == 0) - sb.append("[]"); - else { - sb.append('['); - sb.append(queue[0]); - for (int i = 1; i < queue.length; i++) { - sb.append(", "); - sb.append(queue[i]); - } - sb.append("]"); - } - - sb.append(", h=").append(head).append(", t=").append(tail).append(", s=").append(size); - return sb.toString(); - } + private byte[] queue; + + private int head = -1; + + private int tail = 0; + + private int size = 0; + + private int markHead; + + private int markTail; + + private int markSize; + + /** + *

+ * Constructor for ByteQueue. + *

+ */ + public ByteQueue() { + this(1024); + } + + /** + *

+ * Constructor for ByteQueue. + *

+ * + * @param initialLength a int. + */ + public ByteQueue(int initialLength) { + queue = new byte[initialLength]; + } + + /** + *

+ * Constructor for ByteQueue. + *

+ * + * @param b an array of {@link byte} objects. + */ + public ByteQueue(byte[] b) { + this(b.length); + push(b, 0, b.length); + } + + /** + *

+ * Constructor for ByteQueue. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param length a int. + */ + public ByteQueue(byte[] b, int pos, int length) { + this(length); + push(b, pos, length); + } + + /** + *

+ * Constructor for ByteQueue. + *

+ * + * @param hex a {@link String} object. + */ + public ByteQueue(String hex) { + this(hex.length() / 2); + push(hex); + } + + /** + *

+ * push. + *

+ * + * @param hex a {@link String} object. + */ + public void push(String hex) { + if (hex.length() % 2 != 0) + throw new IllegalArgumentException("Hex string must have an even number of characters"); + byte[] b = new byte[hex.length() / 2]; + for (int i = 0; i < b.length; i++) + b[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); + push(b, 0, b.length); + } + + /** + *

+ * push. + *

+ * + * @param b a byte. + */ + public void push(byte b) { + if (room() == 0) + expand(); + + queue[tail] = b; + + if (head == -1) + head = 0; + tail = (tail + 1) % queue.length; + size++; + } + + /** + *

+ * push. + *

+ * + * @param i a int. + */ + public void push(int i) { + push((byte) i); + } + + /** + *

+ * push. + *

+ * + * @param l a long. + */ + public void push(long l) { + push((byte) l); + } + + /** + * Push unsigned 2 bytes. + * + * @param i a int. + */ + public void pushU2B(int i) { + push((byte) (i >> 8)); + push((byte) i); + } + + /** + * Push unsigned 3 bytes. + * + * @param i a int. + */ + public void pushU3B(int i) { + push((byte) (i >> 16)); + push((byte) (i >> 8)); + push((byte) i); + } + + /** + * Push signed 4 bytes. + * + * @param i a int. + */ + public void pushS4B(int i) { + pushInt(i); + } + + /** + * Push unsigned 4 bytes. + * + * @param l a long. + */ + public void pushU4B(long l) { + push((byte) (l >> 24)); + push((byte) (l >> 16)); + push((byte) (l >> 8)); + push((byte) l); + } + + /** + *

+ * pushChar. + *

+ * + * @param c a char. + */ + public void pushChar(char c) { + push((byte) (c >> 8)); + push((byte) c); + } + + /** + *

+ * pushDouble. + *

+ * + * @param d a double. + */ + public void pushDouble(double d) { + pushLong(Double.doubleToLongBits(d)); + } + + /** + *

+ * pushFloat. + *

+ * + * @param f a float. + */ + public void pushFloat(float f) { + pushInt(Float.floatToIntBits(f)); + } + + /** + *

+ * pushInt. + *

+ * + * @param i a int. + */ + public void pushInt(int i) { + push((byte) (i >> 24)); + push((byte) (i >> 16)); + push((byte) (i >> 8)); + push((byte) i); + } + + /** + *

+ * pushLong. + *

+ * + * @param l a long. + */ + public void pushLong(long l) { + push((byte) (l >> 56)); + push((byte) (l >> 48)); + push((byte) (l >> 40)); + push((byte) (l >> 32)); + push((byte) (l >> 24)); + push((byte) (l >> 16)); + push((byte) (l >> 8)); + push((byte) l); + } + + /** + *

+ * pushShort. + *

+ * + * @param s a short. + */ + public void pushShort(short s) { + push((byte) (s >> 8)); + push((byte) s); + } + + /** + *

+ * read. + *

+ * + * @param in a {@link InputStream} object. + * @param length a int. + * @throws IOException if any. + */ + public void read(InputStream in, int length) throws IOException { + if (length == 0) + return; + + while (room() < length) + expand(); + + int tailLength = queue.length - tail; + if (tailLength > length) + readImpl(in, tail, length); + else + readImpl(in, tail, tailLength); + + if (length > tailLength) + readImpl(in, 0, length - tailLength); + + if (head == -1) + head = 0; + tail = (tail + length) % queue.length; + size += length; + } + + private void readImpl(InputStream in, int offset, int length) throws IOException { + int readcount; + while (length > 0) { + readcount = in.read(queue, offset, length); + offset += readcount; + length -= readcount; + } + } + + /** + *

+ * push. + *

+ * + * @param b an array of {@link byte} objects. + */ + public void push(byte[] b) { + push(b, 0, b.length); + } + + /** + *

+ * push. + *

+ * + * @param b an array of {@link byte} objects. + * @param pos a int. + * @param length a int. + */ + public void push(byte[] b, int pos, int length) { + if (length == 0) + return; + + while (room() < length) + expand(); + + int tailLength = queue.length - tail; + if (tailLength > length) + System.arraycopy(b, pos, queue, tail, length); + else + System.arraycopy(b, pos, queue, tail, tailLength); + + if (length > tailLength) + System.arraycopy(b, tailLength + pos, queue, 0, length - tailLength); + + if (head == -1) + head = 0; + tail = (tail + length) % queue.length; + size += length; + } + + /** + *

+ * push. + *

+ * + * @param source a {@link ByteQueue} object. + */ + public void push(ByteQueue source) { + if (source.size == 0) + return; + + if (source == this) + source = (ByteQueue) clone(); + + int firstCopyLen = source.queue.length - source.head; + if (source.size < firstCopyLen) + firstCopyLen = source.size; + push(source.queue, source.head, firstCopyLen); + + if (firstCopyLen < source.size) + push(source.queue, 0, source.tail); + } + + /** + *

+ * push. + *

+ * + * @param source a {@link ByteQueue} object. + * @param len a int. + */ + public void push(ByteQueue source, int len) { + // TODO There is certainly a more elegant way to do this... + while (len-- > 0) + push(source.pop()); + } + + /** + *

+ * push. + *

+ * + * @param source a {@link ByteBuffer} object. + */ + public void push(ByteBuffer source) { + int length = source.remaining(); + if (length == 0) + return; + + while (room() < length) + expand(); + + int tailLength = queue.length - tail; + if (tailLength > length) + source.get(queue, tail, length); + else + source.get(queue, tail, tailLength); + + if (length > tailLength) + source.get(queue, 0, length - tailLength); + + if (head == -1) + head = 0; + tail = (tail + length) % queue.length; + size += length; + } + + /** + *

+ * mark. + *

+ */ + public void mark() { + markHead = head; + markTail = tail; + markSize = size; + } + + /** + *

+ * reset. + *

+ */ + public void reset() { + head = markHead; + tail = markTail; + size = markSize; + } + + /** + *

+ * pop. + *

+ * + * @return a byte. + */ + public byte pop() { + byte retval = queue[head]; + + if (size == 1) { + head = -1; + tail = 0; + } else + head = (head + 1) % queue.length; + + size--; + + return retval; + } + + /** + *

+ * popU1B. + *

+ * + * @return a int. + */ + public int popU1B() { + return pop() & 0xff; + } + + /** + *

+ * popU2B. + *

+ * + * @return a int. + */ + public int popU2B() { + return ((pop() & 0xff) << 8) | (pop() & 0xff); + } + + /** + *

+ * popU3B. + *

+ * + * @return a int. + */ + public int popU3B() { + return ((pop() & 0xff) << 16) | ((pop() & 0xff) << 8) | (pop() & 0xff); + } + + /** + *

+ * popS2B. + *

+ * + * @return a short. + */ + public short popS2B() { + return (short) (((pop() & 0xff) << 8) | (pop() & 0xff)); + } + + /** + *

+ * popS4B. + *

+ * + * @return a int. + */ + public int popS4B() { + return ((pop() & 0xff) << 24) | ((pop() & 0xff) << 16) | ((pop() & 0xff) << 8) | (pop() & 0xff); + } + + /** + *

+ * popU4B. + *

+ * + * @return a long. + */ + public long popU4B() { + return ((long) (pop() & 0xff) << 24) | ((long) (pop() & 0xff) << 16) | ((long) (pop() & 0xff) << 8) + | (pop() & 0xff); + } + + /** + *

+ * pop. + *

+ * + * @param buf an array of {@link byte} objects. + * @return a int. + */ + public int pop(byte[] buf) { + return pop(buf, 0, buf.length); + } + + /** + *

+ * pop. + *

+ * + * @param buf an array of {@link byte} objects. + * @param pos a int. + * @param length a int. + * @return a int. + */ + public int pop(byte[] buf, int pos, int length) { + length = peek(buf, pos, length); + + size -= length; + + if (size == 0) { + head = -1; + tail = 0; + } else + head = (head + length) % queue.length; + + return length; + } + + /** + *

+ * pop. + *

+ * + * @param length a int. + * @return a int. + */ + public int pop(int length) { + if (length == 0) + return 0; + if (size == 0) + throw new ArrayIndexOutOfBoundsException(-1); + + if (length > size) + length = size; + + size -= length; + + if (size == 0) { + head = -1; + tail = 0; + } else + head = (head + length) % queue.length; + + return length; + } + + /** + *

+ * popString. + *

+ * + * @param length a int. + * @param charset a {@link Charset} object. + * @return a {@link String} object. + */ + public String popString(int length, Charset charset) { + byte[] b = new byte[length]; + pop(b); + return new String(b, charset); + } + + /** + *

+ * popAll. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] popAll() { + byte[] data = new byte[size]; + pop(data, 0, data.length); + return data; + } + + /** + *

+ * write. + *

+ * + * @param out a {@link OutputStream} object. + * @throws IOException if any. + */ + public void write(OutputStream out) throws IOException { + write(out, size); + } + + /** + *

+ * write. + *

+ * + * @param out a {@link OutputStream} object. + * @param length a int. + * @throws IOException if any. + */ + public void write(OutputStream out, int length) throws IOException { + if (length == 0) + return; + if (size == 0) + throw new ArrayIndexOutOfBoundsException(-1); + + if (length > size) + length = size; + + int firstCopyLen = queue.length - head; + if (length < firstCopyLen) + firstCopyLen = length; + + out.write(queue, head, firstCopyLen); + if (firstCopyLen < length) + out.write(queue, 0, length - firstCopyLen); + + size -= length; + + if (size == 0) { + head = -1; + tail = 0; + } else + head = (head + length) % queue.length; + } + + /** + *

+ * tailPop. + *

+ * + * @return a byte. + */ + public byte tailPop() { + if (size == 0) + throw new ArrayIndexOutOfBoundsException(-1); + + tail = (tail + queue.length - 1) % queue.length; + byte retval = queue[tail]; + + if (size == 1) { + head = -1; + tail = 0; + } + + size--; + + return retval; + } + + /** + *

+ * peek. + *

+ * + * @param index a int. + * @return a byte. + */ + public byte peek(int index) { + if (index >= size) + throw new IllegalArgumentException("index " + index + " is >= queue size " + size); + + index = (index + head) % queue.length; + return queue[index]; + } + + /** + *

+ * peek. + *

+ * + * @param index a int. + * @param length a int. + * @return an array of {@link byte} objects. + */ + public byte[] peek(int index, int length) { + byte[] result = new byte[length]; + // TODO: use System.arraycopy instead. + for (int i = 0; i < length; i++) + result[i] = peek(index + i); + return result; + } + + /** + *

+ * peekAll. + *

+ * + * @return an array of {@link byte} objects. + */ + public byte[] peekAll() { + byte[] data = new byte[size]; + peek(data, 0, data.length); + return data; + } + + /** + *

+ * peek. + *

+ * + * @param buf an array of {@link byte} objects. + * @return a int. + */ + public int peek(byte[] buf) { + return peek(buf, 0, buf.length); + } + + /** + *

+ * peek. + *

+ * + * @param buf an array of {@link byte} objects. + * @param pos a int. + * @param length a int. + * @return a int. + */ + public int peek(byte[] buf, int pos, int length) { + if (length == 0) + return 0; + if (size == 0) + throw new ArrayIndexOutOfBoundsException(-1); + + if (length > size) + length = size; + + int firstCopyLen = queue.length - head; + if (length < firstCopyLen) + firstCopyLen = length; + + System.arraycopy(queue, head, buf, pos, firstCopyLen); + if (firstCopyLen < length) + System.arraycopy(queue, 0, buf, pos + firstCopyLen, length - firstCopyLen); + + return length; + } + + /** + *

+ * indexOf. + *

+ * + * @param b a byte. + * @return a int. + */ + public int indexOf(byte b) { + return indexOf(b, 0); + } + + /** + *

+ * indexOf. + *

+ * + * @param b a byte. + * @param start a int. + * @return a int. + */ + public int indexOf(byte b, int start) { + if (start >= size) + return -1; + + int index = (head + start) % queue.length; + for (int i = start; i < size; i++) { + if (queue[index] == b) + return i; + index = (index + 1) % queue.length; + } + return -1; + } + + /** + *

+ * indexOf. + *

+ * + * @param b an array of {@link byte} objects. + * @return a int. + */ + public int indexOf(byte[] b) { + return indexOf(b, 0); + } + + /** + *

+ * indexOf. + *

+ * + * @param b an array of {@link byte} objects. + * @param start a int. + * @return a int. + */ + public int indexOf(byte[] b, int start) { + if (b == null || b.length == 0) + throw new IllegalArgumentException("can't search for empty values"); + + while ((start = indexOf(b[0], start)) != -1 && start < size - b.length + 1) { + boolean found = true; + for (int i = 1; i < b.length; i++) { + if (peek(start + i) != b[i]) { + found = false; + break; + } + } + + if (found) { + return start; + } + + start++; + } + + return -1; + } + + /** + *

+ * size. + *

+ * + * @return a int. + */ + public int size() { + return size; + } + + /** + *

+ * clear. + *

+ */ + public void clear() { + size = 0; + head = -1; + tail = 0; + } + + private int room() { + return queue.length - size; + } + + private void expand() { + byte[] newb = new byte[queue.length * 2]; + + if (head == -1) { + queue = newb; + return; + } + + if (tail > head) { + System.arraycopy(queue, head, newb, head, tail - head); + queue = newb; + return; + } + + System.arraycopy(queue, head, newb, head + queue.length, queue.length - head); + System.arraycopy(queue, 0, newb, 0, tail); + head += queue.length; + queue = newb; + } + + @Override + public Object clone() { + try { + ByteQueue clone = (ByteQueue) super.clone(); + // Array is mutable, so make a copy of it too. + clone.queue = queue.clone(); + return clone; + } catch (CloneNotSupportedException e) { /* + * Will never happen because we're + * Cloneable + */ + } + return null; + } + + @Override + public String toString() { + if (size == 0) + return "[]"; + + StringBuffer sb = new StringBuffer(); + sb.append('['); + sb.append(Integer.toHexString(peek(0) & 0xff)); + for (int i = 1; i < size; i++) + sb.append(',').append(Integer.toHexString(peek(i) & 0xff)); + sb.append("]"); + + return sb.toString(); + } + + /** + *

+ * dumpQueue. + *

+ * + * @return a {@link String} object. + */ + public String dumpQueue() { + StringBuffer sb = new StringBuffer(); + + if (queue.length == 0) + sb.append("[]"); + else { + sb.append('['); + sb.append(queue[0]); + for (int i = 1; i < queue.length; i++) { + sb.append(", "); + sb.append(queue[i]); + } + sb.append("]"); + } + + sb.append(", h=").append(head).append(", t=").append(tail).append(", s=").append(size); + return sb.toString(); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/value/ModbusValue.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/value/ModbusValue.java index 1f32d57c6..9930a92bd 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/value/ModbusValue.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/com/serotonin/modbus4j/value/ModbusValue.java @@ -30,134 +30,143 @@ import java.math.BigInteger; * @version 2025.9.0 */ abstract /** - * Modbus Value - * - * @author pnoker - * @version 2025.9.0 - * @since 2022.1.0 - */ + * Modbus Value + * + * @author pnoker + * @version 2025.9.0 + * @since 2022.1.0 + */ public class ModbusValue { - private final DataType type; + private final DataType type; - private final Object value; + private final Object value; - /** - *

- * Constructor for ModbusValue. - *

- * @param type a {@link DataType} object. - * @param value a {@link Object} object. - */ - public ModbusValue(DataType type, Object value) { - this.type = type; - this.value = value; - } + /** + *

+ * Constructor for ModbusValue. + *

+ * + * @param type a {@link DataType} object. + * @param value a {@link Object} object. + */ + public ModbusValue(DataType type, Object value) { + this.type = type; + this.value = value; + } - /** - *

- * Getter for the field type. - *

- * @return a {@link DataType} object. - */ - public DataType getType() { - return type; - } + /** + *

+ * Getter for the field type. + *

+ * + * @return a {@link DataType} object. + */ + public DataType getType() { + return type; + } - /** - *

- * Getter for the field value. - *

- * @return a {@link Object} object. - */ - public Object getValue() { - return value; - } + /** + *

+ * Getter for the field value. + *

+ * + * @return a {@link Object} object. + */ + public Object getValue() { + return value; + } - /** - *

- * booleanValue. - *

- * @return a boolean. - */ - public boolean booleanValue() { - if (value instanceof Boolean) - return ((Boolean) value).booleanValue(); - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to boolean"); - } + /** + *

+ * booleanValue. + *

+ * + * @return a boolean. + */ + public boolean booleanValue() { + if (value instanceof Boolean) + return ((Boolean) value).booleanValue(); + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to boolean"); + } - /** - *

- * intValue. - *

- * @return a int. - */ - public int intValue() { - if (value instanceof Integer) - return ((Integer) value).intValue(); - if (value instanceof Short) - return ((Short) value).shortValue() & 0xffff; - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to int"); - } + /** + *

+ * intValue. + *

+ * + * @return a int. + */ + public int intValue() { + if (value instanceof Integer) + return ((Integer) value).intValue(); + if (value instanceof Short) + return ((Short) value).shortValue() & 0xffff; + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to int"); + } - /** - *

- * longValue. - *

- * @return a long. - */ - public long longValue() { - if (value instanceof Long) - return ((Long) value).longValue(); - if (value instanceof Integer) - return ((Integer) value).intValue() & 0xffffffff; - if (value instanceof Short) - return ((Short) value).shortValue() & 0xffff; - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to long"); - } + /** + *

+ * longValue. + *

+ * + * @return a long. + */ + public long longValue() { + if (value instanceof Long) + return ((Long) value).longValue(); + if (value instanceof Integer) + return ((Integer) value).intValue() & 0xffffffff; + if (value instanceof Short) + return ((Short) value).shortValue() & 0xffff; + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to long"); + } - /** - *

- * bigIntegerValue. - *

- * @return a {@link BigInteger} object. - */ - public BigInteger bigIntegerValue() { - if (value instanceof BigInteger) - return (BigInteger) value; - if (value instanceof Long) - return BigInteger.valueOf(((Long) value).longValue()); - if (value instanceof Integer) - return BigInteger.valueOf(((Integer) value).intValue() & 0xffffffff); - if (value instanceof Short) - return BigInteger.valueOf(((Short) value).shortValue() & 0xffff); - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to BigInteger"); - } + /** + *

+ * bigIntegerValue. + *

+ * + * @return a {@link BigInteger} object. + */ + public BigInteger bigIntegerValue() { + if (value instanceof BigInteger) + return (BigInteger) value; + if (value instanceof Long) + return BigInteger.valueOf(((Long) value).longValue()); + if (value instanceof Integer) + return BigInteger.valueOf(((Integer) value).intValue() & 0xffffffff); + if (value instanceof Short) + return BigInteger.valueOf(((Short) value).shortValue() & 0xffff); + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to BigInteger"); + } - /** - *

- * floatValue. - *

- * @return a float. - */ - public float floatValue() { - if (value instanceof Float) - return ((Float) value).floatValue(); - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to float"); - } + /** + *

+ * floatValue. + *

+ * + * @return a float. + */ + public float floatValue() { + if (value instanceof Float) + return ((Float) value).floatValue(); + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to float"); + } - /** - *

- * doubleValue. - *

- * @return a double. - */ - public double doubleValue() { - if (value instanceof Double) - return ((Double) value).doubleValue(); - if (value instanceof Float) - return ((Float) value).doubleValue(); - throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to float"); - } + /** + *

+ * doubleValue. + *

+ * + * @return a double. + */ + public double doubleValue() { + if (value instanceof Double) + return ((Double) value).doubleValue(); + if (value instanceof Float) + return ((Float) value).doubleValue(); + throw new InvalidDataConversionException("Can't convert " + value.getClass() + " to float"); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/ModbusTcpDriverApplication.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/ModbusTcpDriverApplication.java index c4731d781..700242d58 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/ModbusTcpDriverApplication.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/ModbusTcpDriverApplication.java @@ -32,12 +32,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ModbusTcpDriverApplication { - /** - * Main method to start the Modbus TCP driver application - * @param args Command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(ModbusTcpDriverApplication.class, args); - } + /** + * Main method to start the Modbus TCP driver application + * + * @param args Command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(ModbusTcpDriverApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 78e1ca348..3fe377bed 100644 --- a/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-modbus-tcp/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -69,235 +69,237 @@ import java.util.concurrent.TimeUnit; @Service public class DriverCustomServiceImpl implements DriverCustomService { - /** - * Modbus factory for creating ModbusMaster instances. - */ - static ModbusFactory modbusFactory; + /** + * Modbus factory for creating ModbusMaster instances. + */ + static ModbusFactory modbusFactory; - static { - modbusFactory = new ModbusFactory(); - } + static { + modbusFactory = new ModbusFactory(); + } - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Cache of device ID to ModbusMaster connections. - */ - private Map connectMap; + /** + * Cache of device ID to ModbusMaster connections. + */ + private Map connectMap; - @Override - public void initial() { - connectMap = new ConcurrentHashMap<>(16); - } + @Override + public void initial() { + connectMap = new ConcurrentHashMap<>(16); + } - @Override - public void schedule() { - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + @Override + public void schedule() { + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - @Override - public void event(MetadataEventDTO metadataEvent) { - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + @Override + public void event(MetadataEventDTO metadataEvent) { + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - // Remove stale connection when device is updated or deleted - if (MetadataOperateTypeEnum.DELETE.equals(operateType) - || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { - connectMap.remove(metadataEvent.getId()); - } - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + // Remove stale connection when device is updated or deleted + if (MetadataOperateTypeEnum.DELETE.equals(operateType) + || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { + connectMap.remove(metadataEvent.getId()); + } + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - return new RValue(device, point, - readValue(getConnector(device.getId(), driverConfig), pointConfig, point.getPointTypeFlag().getCode())); - } + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + return new RValue(device, point, + readValue(getConnector(device.getId(), driverConfig), pointConfig, point.getPointTypeFlag().getCode())); + } - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - ModbusMaster modbusMaster = getConnector(device.getId(), driverConfig); - return writeValue(modbusMaster, pointConfig, wValue); - } + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + ModbusMaster modbusMaster = getConnector(device.getId(), driverConfig); + return writeValue(modbusMaster, pointConfig, wValue); + } - /** - * Get or create a Modbus TCP connection for the given device. - * @param deviceId unique device identifier - * @param driverConfig driver configuration containing host and port - * @return cached or newly created ModbusMaster - * @throws ConnectorException if connection initialization fails - */ - private ModbusMaster getConnector(Long deviceId, Map driverConfig) { - log.debug("Modbus Tcp Connection Info: {}", JsonUtil.toJsonString(driverConfig)); - ModbusMaster modbusMaster = connectMap.get(deviceId); - if (Objects.isNull(modbusMaster)) { - IpParameters params = new IpParameters(); - params.setHost(driverConfig.get("host").getValue(String.class)); - params.setPort(driverConfig.get("port").getValue(Integer.class)); - modbusMaster = modbusFactory.createTcpMaster(params, true); - try { - modbusMaster.init(); - connectMap.put(deviceId, modbusMaster); - } - catch (ModbusInitException e) { - connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); - log.error("Connect modbus master error: {}", e.getMessage(), e); - throw new ConnectorException(e.getMessage()); - } - } - return modbusMaster; - } + /** + * Get or create a Modbus TCP connection for the given device. + * + * @param deviceId unique device identifier + * @param driverConfig driver configuration containing host and port + * @return cached or newly created ModbusMaster + * @throws ConnectorException if connection initialization fails + */ + private ModbusMaster getConnector(Long deviceId, Map driverConfig) { + log.debug("Modbus Tcp Connection Info: {}", JsonUtil.toJsonString(driverConfig)); + ModbusMaster modbusMaster = connectMap.get(deviceId); + if (Objects.isNull(modbusMaster)) { + IpParameters params = new IpParameters(); + params.setHost(driverConfig.get("host").getValue(String.class)); + params.setPort(driverConfig.get("port").getValue(Integer.class)); + modbusMaster = modbusFactory.createTcpMaster(params, true); + try { + modbusMaster.init(); + connectMap.put(deviceId, modbusMaster); + } catch (ModbusInitException e) { + connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); + log.error("Connect modbus master error: {}", e.getMessage(), e); + throw new ConnectorException(e.getMessage()); + } + } + return modbusMaster; + } - /** - * Read a point value from the Modbus device by function code. - *

- * Function codes: 1=coil, 2=input status, 3=holding register, 4=input register. - * @param modbusMaster active Modbus connection - * @param pointConfig point configuration (slaveId, functionCode, offset) - * @param type point value type for register data interpretation - * @return read value as string, or "0" for unsupported function codes - */ - private String readValue(ModbusMaster modbusMaster, Map pointConfig, String type) { - int slaveId = pointConfig.get("slaveId").getValue(Integer.class); - int functionCode = pointConfig.get("functionCode").getValue(Integer.class); - int offset = pointConfig.get("offset").getValue(Integer.class); - switch (functionCode) { - case 1: - BaseLocator coilLocator = BaseLocator.coilStatus(slaveId, offset); - Boolean coilValue = getMasterValue(modbusMaster, coilLocator); - return String.valueOf(coilValue); - case 2: - BaseLocator inputLocator = BaseLocator.inputStatus(slaveId, offset); - Boolean inputStatusValue = getMasterValue(modbusMaster, inputLocator); - return String.valueOf(inputStatusValue); - case 3: - BaseLocator holdingLocator = BaseLocator.holdingRegister(slaveId, offset, getValueType(type)); - Number holdingValue = getMasterValue(modbusMaster, holdingLocator); - return String.valueOf(holdingValue); - case 4: - BaseLocator inputRegister = BaseLocator.inputRegister(slaveId, offset, getValueType(type)); - Number inputRegisterValue = getMasterValue(modbusMaster, inputRegister); - return String.valueOf(inputRegisterValue); - default: - return "0"; - } - } + /** + * Read a point value from the Modbus device by function code. + *

+ * Function codes: 1=coil, 2=input status, 3=holding register, 4=input register. + * + * @param modbusMaster active Modbus connection + * @param pointConfig point configuration (slaveId, functionCode, offset) + * @param type point value type for register data interpretation + * @return read value as string, or "0" for unsupported function codes + */ + private String readValue(ModbusMaster modbusMaster, Map pointConfig, String type) { + int slaveId = pointConfig.get("slaveId").getValue(Integer.class); + int functionCode = pointConfig.get("functionCode").getValue(Integer.class); + int offset = pointConfig.get("offset").getValue(Integer.class); + switch (functionCode) { + case 1: + BaseLocator coilLocator = BaseLocator.coilStatus(slaveId, offset); + Boolean coilValue = getMasterValue(modbusMaster, coilLocator); + return String.valueOf(coilValue); + case 2: + BaseLocator inputLocator = BaseLocator.inputStatus(slaveId, offset); + Boolean inputStatusValue = getMasterValue(modbusMaster, inputLocator); + return String.valueOf(inputStatusValue); + case 3: + BaseLocator holdingLocator = BaseLocator.holdingRegister(slaveId, offset, getValueType(type)); + Number holdingValue = getMasterValue(modbusMaster, holdingLocator); + return String.valueOf(holdingValue); + case 4: + BaseLocator inputRegister = BaseLocator.inputRegister(slaveId, offset, getValueType(type)); + Number inputRegisterValue = getMasterValue(modbusMaster, inputRegister); + return String.valueOf(inputRegisterValue); + default: + return "0"; + } + } - /** - * Read a value from the Modbus device using the given locator. - * @param modbusMaster active Modbus connection - * @param locator identifies the target point (slave, function, offset) - * @param value type determined by the locator - * @return the read value - * @throws ReadPointException if a transport or error response occurs - */ - private T getMasterValue(ModbusMaster modbusMaster, BaseLocator locator) { - try { - return modbusMaster.getValue(locator); - } - catch (ModbusTransportException | ErrorResponseException e) { - log.error("Read modbus master value error: {}", e.getMessage(), e); - throw new ReadPointException(e.getMessage()); - } - } + /** + * Read a value from the Modbus device using the given locator. + * + * @param modbusMaster active Modbus connection + * @param locator identifies the target point (slave, function, offset) + * @param value type determined by the locator + * @return the read value + * @throws ReadPointException if a transport or error response occurs + */ + private T getMasterValue(ModbusMaster modbusMaster, BaseLocator locator) { + try { + return modbusMaster.getValue(locator); + } catch (ModbusTransportException | ErrorResponseException e) { + log.error("Read modbus master value error: {}", e.getMessage(), e); + throw new ReadPointException(e.getMessage()); + } + } - /** - * Write a point value to the Modbus device by function code. - *

- * Function codes: 1=write coil, 3=write holding register. Others return false. - * @param modbusMaster active Modbus connection - * @param pointConfig point configuration (slaveId, functionCode, offset) - * @param wValue value to write - * @return true if write succeeded, false if failed or unsupported function code - */ - private boolean writeValue(ModbusMaster modbusMaster, Map pointConfig, WValue wValue) { - int slaveId = pointConfig.get("slaveId").getValue(Integer.class); - int functionCode = pointConfig.get("functionCode").getValue(Integer.class); - int offset = pointConfig.get("offset").getValue(Integer.class); - switch (functionCode) { - case 1: - WriteCoilResponse coilResponse = setMasterValue(modbusMaster, slaveId, offset, wValue); - return !coilResponse.isException(); - case 3: - BaseLocator locator = BaseLocator.holdingRegister(slaveId, offset, - getValueType(wValue.getType().getCode())); - setMasterValue(modbusMaster, locator, wValue); - return true; - default: - return false; - } - } + /** + * Write a point value to the Modbus device by function code. + *

+ * Function codes: 1=write coil, 3=write holding register. Others return false. + * + * @param modbusMaster active Modbus connection + * @param pointConfig point configuration (slaveId, functionCode, offset) + * @param wValue value to write + * @return true if write succeeded, false if failed or unsupported function code + */ + private boolean writeValue(ModbusMaster modbusMaster, Map pointConfig, WValue wValue) { + int slaveId = pointConfig.get("slaveId").getValue(Integer.class); + int functionCode = pointConfig.get("functionCode").getValue(Integer.class); + int offset = pointConfig.get("offset").getValue(Integer.class); + switch (functionCode) { + case 1: + WriteCoilResponse coilResponse = setMasterValue(modbusMaster, slaveId, offset, wValue); + return !coilResponse.isException(); + case 3: + BaseLocator locator = BaseLocator.holdingRegister(slaveId, offset, + getValueType(wValue.getType().getCode())); + setMasterValue(modbusMaster, locator, wValue); + return true; + default: + return false; + } + } - /** - * Map a point type flag to a Modbus DataType constant. - *

- * LONG->4-byte int, FLOAT->4-byte float, DOUBLE->8-byte float, else 2-byte int. - * @param type point type code - * @return Modbus DataType constant - * @throws UnSupportException if the type is unknown - */ - private int getValueType(String type) { - PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(type); - if (Objects.isNull(valueType)) { - throw new UnSupportException("Unsupported type of " + type); - } + /** + * Map a point type flag to a Modbus DataType constant. + *

+ * LONG->4-byte int, FLOAT->4-byte float, DOUBLE->8-byte float, else 2-byte int. + * + * @param type point type code + * @return Modbus DataType constant + * @throws UnSupportException if the type is unknown + */ + private int getValueType(String type) { + PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(type); + if (Objects.isNull(valueType)) { + throw new UnSupportException("Unsupported type of " + type); + } - return switch (valueType) { - case LONG -> DataType.FOUR_BYTE_INT_SIGNED; - case FLOAT -> DataType.FOUR_BYTE_FLOAT; - case DOUBLE -> DataType.EIGHT_BYTE_FLOAT; - default -> DataType.TWO_BYTE_INT_SIGNED; - }; - } + return switch (valueType) { + case LONG -> DataType.FOUR_BYTE_INT_SIGNED; + case FLOAT -> DataType.FOUR_BYTE_FLOAT; + case DOUBLE -> DataType.EIGHT_BYTE_FLOAT; + default -> DataType.TWO_BYTE_INT_SIGNED; + }; + } - /** - * Write a boolean value to a Modbus coil. - * @param modbusMaster active Modbus connection - * @param slaveId target slave address - * @param offset coil offset - * @param wValue value containing the boolean to write - * @return the coil write response - * @throws WritePointException if a transport error occurs - */ - private WriteCoilResponse setMasterValue(ModbusMaster modbusMaster, int slaveId, int offset, WValue wValue) { - try { - WriteCoilRequest coilRequest = new WriteCoilRequest(slaveId, offset, wValue.getValue(Boolean.class)); - return (WriteCoilResponse) modbusMaster.send(coilRequest); - } - catch (ModbusTransportException e) { - log.error("Write modbus master value error: {}", e.getMessage(), e); - throw new WritePointException(e.getMessage()); - } - } + /** + * Write a boolean value to a Modbus coil. + * + * @param modbusMaster active Modbus connection + * @param slaveId target slave address + * @param offset coil offset + * @param wValue value containing the boolean to write + * @return the coil write response + * @throws WritePointException if a transport error occurs + */ + private WriteCoilResponse setMasterValue(ModbusMaster modbusMaster, int slaveId, int offset, WValue wValue) { + try { + WriteCoilRequest coilRequest = new WriteCoilRequest(slaveId, offset, wValue.getValue(Boolean.class)); + return (WriteCoilResponse) modbusMaster.send(coilRequest); + } catch (ModbusTransportException e) { + log.error("Write modbus master value error: {}", e.getMessage(), e); + throw new WritePointException(e.getMessage()); + } + } - /** - * Write a numeric value to a Modbus holding register via the given locator. - * @param modbusMaster active Modbus connection - * @param locator identifies the target register - * @param wValue value to write (read as Float) - * @param value type determined by the locator - * @throws WritePointException if a transport or error response occurs - */ - private void setMasterValue(ModbusMaster modbusMaster, BaseLocator locator, WValue wValue) { - try { - modbusMaster.setValue(locator, wValue.getValue(Float.class)); - } - catch (ModbusTransportException | ErrorResponseException e) { - log.error("Write modbus master value error: {}", e.getMessage(), e); - throw new WritePointException(e.getMessage()); - } - } + /** + * Write a numeric value to a Modbus holding register via the given locator. + * + * @param modbusMaster active Modbus connection + * @param locator identifies the target register + * @param wValue value to write (read as Float) + * @param value type determined by the locator + * @throws WritePointException if a transport or error response occurs + */ + private void setMasterValue(ModbusMaster modbusMaster, BaseLocator locator, WValue wValue) { + try { + modbusMaster.setValue(locator, wValue.getValue(Float.class)); + } catch (ModbusTransportException | ErrorResponseException e) { + log.error("Write modbus master value error: {}", e.getMessage(), e); + throw new WritePointException(e.getMessage()); + } + } } diff --git a/dc3-driver/dc3-driver-mqtt/README.md b/dc3-driver/dc3-driver-mqtt/README.md index ad434b16c..452b0a747 100644 --- a/dc3-driver/dc3-driver-mqtt/README.md +++ b/dc3-driver/dc3-driver-mqtt/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-mqtt` is the MQTT protocol driver of the IoT DC3 platform. It subscribes to configured MQTT topics, parses incoming payloads as device point values, and forwards +`dc3-driver-mqtt` is the MQTT protocol driver of the IoT DC3 platform. It subscribes to configured MQTT topics, parses +incoming payloads as device point values, and forwards commands to devices via MQTT publish. ## Module Information diff --git a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/MqttDriverApplication.java b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/MqttDriverApplication.java index 982683d56..115ae2ef1 100644 --- a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/MqttDriverApplication.java +++ b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/MqttDriverApplication.java @@ -35,12 +35,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MqttDriverApplication { - /** - * Main entry point for the MQTT driver application. - * @param args command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(MqttDriverApplication.class, args); - } + /** + * Main entry point for the MQTT driver application. + * + * @param args command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(MqttDriverApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/mqtt/service/impl/MqttReceiveServiceImpl.java b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/mqtt/service/impl/MqttReceiveServiceImpl.java index 01d88c2bd..5b1cbf363 100644 --- a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/mqtt/service/impl/MqttReceiveServiceImpl.java +++ b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/mqtt/service/impl/MqttReceiveServiceImpl.java @@ -45,44 +45,46 @@ import java.util.List; @Service public class MqttReceiveServiceImpl implements MqttReceiveService { - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Processes a single MQTT message received from the broker. - *

- * This method parses the MQTT message payload into a PointValue object, sets the - * creation time, and forwards it to the platform. - *

- * @param mqttMessage the MQTT message containing topic, payload, and metadata - */ - @Override - public void receiveValue(MqttMessage mqttMessage) { - // do something to process your mqtt messages - log.info(JsonUtil.toJsonString(mqttMessage)); - PointValue pointValue = JsonUtil.parseObject(mqttMessage.getPayload(), PointValue.class); - pointValue.setCreateTime(LocalDateTimeUtil.now()); - driverSenderService.pointValueSender(pointValue); - } + /** + * Processes a single MQTT message received from the broker. + *

+ * This method parses the MQTT message payload into a PointValue object, sets the + * creation time, and forwards it to the platform. + *

+ * + * @param mqttMessage the MQTT message containing topic, payload, and metadata + */ + @Override + public void receiveValue(MqttMessage mqttMessage) { + // do something to process your mqtt messages + log.info(JsonUtil.toJsonString(mqttMessage)); + PointValue pointValue = JsonUtil.parseObject(mqttMessage.getPayload(), PointValue.class); + pointValue.setCreateTime(LocalDateTimeUtil.now()); + driverSenderService.pointValueSender(pointValue); + } - /** - * Processes a batch of MQTT messages received from the broker. - *

- * This method parses multiple MQTT messages into PointValue objects, sets their - * creation times, and forwards them as a batch to the platform. - *

- * @param mqttMessageList list of MQTT messages to process - */ - @Override - public void receiveValues(List mqttMessageList) { - // do something to process your mqtt messages - log.info(JsonUtil.toJsonString(mqttMessageList)); - List pointValues = mqttMessageList.stream().map(mqttMessage -> { - PointValue pointValue = JsonUtil.parseObject(mqttMessage.getPayload(), PointValue.class); - pointValue.setCreateTime(LocalDateTimeUtil.now()); - return pointValue; - }).toList(); - driverSenderService.pointValueSender(pointValues); - } + /** + * Processes a batch of MQTT messages received from the broker. + *

+ * This method parses multiple MQTT messages into PointValue objects, sets their + * creation times, and forwards them as a batch to the platform. + *

+ * + * @param mqttMessageList list of MQTT messages to process + */ + @Override + public void receiveValues(List mqttMessageList) { + // do something to process your mqtt messages + log.info(JsonUtil.toJsonString(mqttMessageList)); + List pointValues = mqttMessageList.stream().map(mqttMessage -> { + PointValue pointValue = JsonUtil.parseObject(mqttMessage.getPayload(), PointValue.class); + pointValue.setCreateTime(LocalDateTimeUtil.now()); + return pointValue; + }).toList(); + driverSenderService.pointValueSender(pointValues); + } } diff --git a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/MqttSendService.java b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/MqttSendService.java index 8fb1bc9ee..e443fac41 100644 --- a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/MqttSendService.java +++ b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/MqttSendService.java @@ -33,32 +33,36 @@ import org.springframework.messaging.handler.annotation.Header; @MessagingGateway(defaultRequestChannel = "mqttOutboundChannel") public interface MqttSendService { - /** - * Send data using the default topic and default QoS - * @param data string - */ - void sendToMqtt(String data); + /** + * Send data using the default topic and default QoS + * + * @param data string + */ + void sendToMqtt(String data); - /** - * Send data using the default topic and a custom QoS - * @param qos Custom QoS - * @param data string - */ - void sendToMqtt(@Header(MqttHeaders.QOS) Integer qos, String data); + /** + * Send data using the default topic and a custom QoS + * + * @param qos Custom QoS + * @param data string + */ + void sendToMqtt(@Header(MqttHeaders.QOS) Integer qos, String data); - /** - * Send data using a custom topic and the default QoS - * @param topic Custom topic - * @param data string - */ - void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String data); + /** + * Send data using a custom topic and the default QoS + * + * @param topic Custom topic + * @param data string + */ + void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, String data); - /** - * Send data using a custom topic and a custom QoS - * @param topic Custom topic - * @param qos Custom QoS - * @param data string - */ - void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) Integer qos, String data); + /** + * Send data using a custom topic and a custom QoS + * + * @param topic Custom topic + * @param qos Custom QoS + * @param data string + */ + void sendToMqtt(@Header(MqttHeaders.TOPIC) String topic, @Header(MqttHeaders.QOS) Integer qos, String data); } diff --git a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 5077970d5..29fdae61d 100644 --- a/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-mqtt/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -54,169 +54,170 @@ import java.util.concurrent.TimeUnit; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - @Resource - private MqttSendService mqttSendService; + @Resource + private MqttSendService mqttSendService; - /** - * Initializes the MQTT driver. - *

- * This method is called when the driver starts. Override this method to implement - * custom initialization logic specific to your MQTT devices and subscriptions. - *

- */ - @Override - public void initial() { - /* - * Driver initialization logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. This method is automatically executed when the - * driver starts, and you can perform specific initialization operations here. - * - */ - } + /** + * Initializes the MQTT driver. + *

+ * This method is called when the driver starts. Override this method to implement + * custom initialization logic specific to your MQTT devices and subscriptions. + *

+ */ + @Override + public void initial() { + /* + * Driver initialization logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. This method is automatically executed when the + * driver starts, and you can perform specific initialization operations here. + * + */ + } - /** - * Scheduled task to report device status. - *

- * This method is called periodically to update device status. By default, all devices - * are reported as ONLINE with a 25-second validity period. Override this method to - * implement custom status reporting logic. - *

- */ - @Override - public void schedule() { - /* - * Device status upload logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. Device status upload can be flexibly implemented - * based on specific requirements. Here are some common approaches: - Determine - * device status based on read data in the `read` method; - Periodically check - * device status in a custom scheduled task; - Trigger device status judgment - * based on specific business logic or events. - * - * Finally, submit the device status to the SDK management through the {@link - * DriverSenderService#deviceStatusSender(Long, DeviceStatusEnum)} interface. The - * device status enumeration {@link DeviceStatusEnum} includes the following - * states: - ONLINE: Device online - OFFLINE: Device offline - MAINTAIN: Device - * under maintenance - FAULT: Device fault - * - * In the following example, all devices are set to {@link - * DeviceStatusEnum#ONLINE}, with a status validity period of 25 {@link - * TimeUnit#SECONDS}. - */ - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + /** + * Scheduled task to report device status. + *

+ * This method is called periodically to update device status. By default, all devices + * are reported as ONLINE with a 25-second validity period. Override this method to + * implement custom status reporting logic. + *

+ */ + @Override + public void schedule() { + /* + * Device status upload logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. Device status upload can be flexibly implemented + * based on specific requirements. Here are some common approaches: - Determine + * device status based on read data in the `read` method; - Periodically check + * device status in a custom scheduled task; - Trigger device status judgment + * based on specific business logic or events. + * + * Finally, submit the device status to the SDK management through the {@link + * DriverSenderService#deviceStatusSender(Long, DeviceStatusEnum)} interface. The + * device status enumeration {@link DeviceStatusEnum} includes the following + * states: - ONLINE: Device online - OFFLINE: Device offline - MAINTAIN: Device + * under maintenance - FAULT: Device fault + * + * In the following example, all devices are set to {@link + * DeviceStatusEnum#ONLINE}, with a status validity period of 25 {@link + * TimeUnit#SECONDS}. + */ + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - /** - * Handles metadata change events for drivers, devices, and points. - *

- * This method is called when metadata is created, updated, or deleted. Override this - * method to implement custom event handling logic such as managing MQTT topic - * subscriptions. - *

- * @param metadataEvent the metadata event containing type, operation, and ID - * information - */ - @Override - public void event(MetadataEventDTO metadataEvent) { - /* - * Receive metadata events for driver, device, and point creation, update, and - * deletion. - * - * Metadata type: {@link MetadataTypeEnum} (DRIVER, DEVICE, POINT) Metadata - * operation type: {@link MetadataOperateTypeEnum} (ADD, DELETE, UPDATE) - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. - */ - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - // to do something for device event - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - // to do something for point event - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + /** + * Handles metadata change events for drivers, devices, and points. + *

+ * This method is called when metadata is created, updated, or deleted. Override this + * method to implement custom event handling logic such as managing MQTT topic + * subscriptions. + *

+ * + * @param metadataEvent the metadata event containing type, operation, and ID + * information + */ + @Override + public void event(MetadataEventDTO metadataEvent) { + /* + * Receive metadata events for driver, device, and point creation, update, and + * deletion. + * + * Metadata type: {@link MetadataTypeEnum} (DRIVER, DEVICE, POINT) Metadata + * operation type: {@link MetadataOperateTypeEnum} (ADD, DELETE, UPDATE) + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. + */ + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + // to do something for device event + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + // to do something for point event + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - /** - * Reads data from an MQTT device point. - *

- * Since MQTT uses a publish-subscribe model, data is passively received through - * subscriptions rather than actively polled. This method returns null as the actual - * data processing is handled by - * {@link io.github.pnoker.common.mqtt.handler.MqttReceiveHandler#handlerValue}. - *

- * @param driverConfig driver configuration attributes - * @param pointConfig point configuration attributes - * @param device the device to read from - * @param point the point to read - * @return null (data is received asynchronously) - */ - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - /* - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. - * - * Since MQTT data is passively received, there is no need to implement the `read` - * method here. The processing logic for receiving data has been implemented in - * {@link io.github.pnoker.common.mqtt.handler.MqttReceiveHandler#handlerValue}. - */ - return null; - } + /** + * Reads data from an MQTT device point. + *

+ * Since MQTT uses a publish-subscribe model, data is passively received through + * subscriptions rather than actively polled. This method returns null as the actual + * data processing is handled by + * {@link io.github.pnoker.common.mqtt.handler.MqttReceiveHandler#handlerValue}. + *

+ * + * @param driverConfig driver configuration attributes + * @param pointConfig point configuration attributes + * @param device the device to read from + * @param point the point to read + * @return null (data is received asynchronously) + */ + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + /* + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. + * + * Since MQTT data is passively received, there is no need to implement the `read` + * method here. The processing logic for receiving data has been implemented in + * {@link io.github.pnoker.common.mqtt.handler.MqttReceiveHandler#handlerValue}. + */ + return null; + } - /** - * Writes data to an MQTT device point. - *

- * This method publishes messages to MQTT topics for device control. It retrieves the - * command topic from point configuration and optionally uses a configured QoS level. - * If QoS configuration fails, it falls back to the default QoS. - *

- * @param driverConfig driver configuration attributes - * @param pointConfig point configuration attributes (must contain "commandTopic", - * optionally "commandQos") - * @param device the device to write to - * @param point the point to write - * @param values the value containing the data to write - * @return true if the write operation succeeded, false otherwise - */ - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue values) { - /* - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. - * - * This method is used to write data to an MQTT topic. First, retrieve the command - * topic `commandTopic` and the value to be sent `value` from `pointConfig`. If - * the configuration specifies a QoS level `commandQos`, attempt to send the - * message with the specified QoS; if not specified or an exception occurs, send - * the message with the default QoS. Finally, return `true` to indicate a - * successful write operation. - */ - String commandTopic = pointConfig.get("commandTopic").getValue(String.class); - String value = values.getValue(); - try { - int commandQos = pointConfig.get("commandQos").getValue(Integer.class); - mqttSendService.sendToMqtt(commandTopic, commandQos, value); - } - catch (Exception e) { - mqttSendService.sendToMqtt(commandTopic, value); - } - return true; - } + /** + * Writes data to an MQTT device point. + *

+ * This method publishes messages to MQTT topics for device control. It retrieves the + * command topic from point configuration and optionally uses a configured QoS level. + * If QoS configuration fails, it falls back to the default QoS. + *

+ * + * @param driverConfig driver configuration attributes + * @param pointConfig point configuration attributes (must contain "commandTopic", + * optionally "commandQos") + * @param device the device to write to + * @param point the point to write + * @param values the value containing the data to write + * @return true if the write operation succeeded, false otherwise + */ + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue values) { + /* + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. + * + * This method is used to write data to an MQTT topic. First, retrieve the command + * topic `commandTopic` and the value to be sent `value` from `pointConfig`. If + * the configuration specifies a QoS level `commandQos`, attempt to send the + * message with the specified QoS; if not specified or an exception occurs, send + * the message with the default QoS. Finally, return `true` to indicate a + * successful write operation. + */ + String commandTopic = pointConfig.get("commandTopic").getValue(String.class); + String value = values.getValue(); + try { + int commandQos = pointConfig.get("commandQos").getValue(Integer.class); + mqttSendService.sendToMqtt(commandTopic, commandQos, value); + } catch (Exception e) { + mqttSendService.sendToMqtt(commandTopic, value); + } + return true; + } } diff --git a/dc3-driver/dc3-driver-opc-da/README.md b/dc3-driver/dc3-driver-opc-da/README.md index b4c6f8e43..2a5c470c0 100644 --- a/dc3-driver/dc3-driver-opc-da/README.md +++ b/dc3-driver/dc3-driver-opc-da/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-opc-da` is the OPC DA (Data Access) protocol driver of the IoT DC3 platform. It connects to OPC DA servers using DCOM/J-Interop to read real-time process data from +`dc3-driver-opc-da` is the OPC DA (Data Access) protocol driver of the IoT DC3 platform. It connects to OPC DA servers +using DCOM/J-Interop to read real-time process data from OPC-compliant industrial devices and SCADA systems. ## Module Information diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/OpcDaApplication.java b/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/OpcDaApplication.java index 6f4a42e6c..f1ca2504b 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/OpcDaApplication.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/OpcDaApplication.java @@ -32,12 +32,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OpcDaApplication { - /** - * Main method to start the OPC-DA driver application - * @param args Command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(OpcDaApplication.class, args); - } + /** + * Main method to start the OPC-DA driver application + * + * @param args Command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(OpcDaApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 0014c1cf2..baa42eefc 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -67,235 +67,236 @@ import java.util.concurrent.TimeUnit; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Cache of device ID to OPC DA server connections. - */ - private Map connectMap; + /** + * Cache of device ID to OPC DA server connections. + */ + private Map connectMap; - @Override - public void initial() { - connectMap = new ConcurrentHashMap<>(16); - } + @Override + public void initial() { + connectMap = new ConcurrentHashMap<>(16); + } - @Override - public void schedule() { - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + @Override + public void schedule() { + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - @Override - public void event(MetadataEventDTO metadataEvent) { - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + @Override + public void event(MetadataEventDTO metadataEvent) { + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - // Remove stale connection when device is updated or deleted - if (MetadataOperateTypeEnum.DELETE.equals(operateType) - || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { - connectMap.remove(metadataEvent.getId()); - } - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + // Remove stale connection when device is updated or deleted + if (MetadataOperateTypeEnum.DELETE.equals(operateType) + || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { + connectMap.remove(metadataEvent.getId()); + } + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - return new RValue(device, point, readValue(getConnector(device.getId(), driverConfig), pointConfig)); - } + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + return new RValue(device, point, readValue(getConnector(device.getId(), driverConfig), pointConfig)); + } - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - Server server = getConnector(device.getId(), driverConfig); - return writeValue(server, pointConfig, wValue); - } + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + Server server = getConnector(device.getId(), driverConfig); + return writeValue(server, pointConfig, wValue); + } - /** - * Get or create an OPC DA server connection for the given device. - * @param deviceId unique device identifier - * @param driverConfig driver configuration (host, clsId, username, password) - * @return cached or newly connected OPC DA Server - * @throws ConnectorException if the connection fails - */ - private Server getConnector(Long deviceId, Map driverConfig) { - log.debug("Opc Da Server Connection Info {}", JsonUtil.toJsonString(driverConfig)); - Server server = connectMap.get(deviceId); - if (Objects.isNull(server)) { - String host = driverConfig.get("host").getValue(String.class); - String clsId = driverConfig.get("clsId").getValue(String.class); - String user = driverConfig.get("username").getValue(String.class); - String password = driverConfig.get("password").getValue(String.class); - ConnectionInformation connectionInformation = new ConnectionInformation(host, clsId, user, password); - server = new Server(connectionInformation, Executors.newSingleThreadScheduledExecutor()); - try { - server.connect(); - connectMap.put(deviceId, server); - } - catch (AlreadyConnectedException | UnknownHostException | JIException e) { - connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); - log.error("Connect opc da server error: {}", e.getMessage(), e); - throw new ConnectorException(e.getMessage()); - } - } - return server; - } + /** + * Get or create an OPC DA server connection for the given device. + * + * @param deviceId unique device identifier + * @param driverConfig driver configuration (host, clsId, username, password) + * @return cached or newly connected OPC DA Server + * @throws ConnectorException if the connection fails + */ + private Server getConnector(Long deviceId, Map driverConfig) { + log.debug("Opc Da Server Connection Info {}", JsonUtil.toJsonString(driverConfig)); + Server server = connectMap.get(deviceId); + if (Objects.isNull(server)) { + String host = driverConfig.get("host").getValue(String.class); + String clsId = driverConfig.get("clsId").getValue(String.class); + String user = driverConfig.get("username").getValue(String.class); + String password = driverConfig.get("password").getValue(String.class); + ConnectionInformation connectionInformation = new ConnectionInformation(host, clsId, user, password); + server = new Server(connectionInformation, Executors.newSingleThreadScheduledExecutor()); + try { + server.connect(); + connectMap.put(deviceId, server); + } catch (AlreadyConnectedException | UnknownHostException | JIException e) { + connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); + log.error("Connect opc da server error: {}", e.getMessage(), e); + throw new ConnectorException(e.getMessage()); + } + } + return server; + } - /** - * Resolve an OPC DA Item from the server, creating the group if needed. - * @param server connected OPC DA server - * @param pointConfig point configuration (group, tag) - * @return the resolved Item - */ - public Item getItem(Server server, Map pointConfig) throws NotConnectedException, JIException, - UnknownHostException, DuplicateGroupException, AddFailedException { - Group group; - String groupName = pointConfig.get("group").getValue(String.class); - try { - group = server.findGroup(groupName); - } - catch (UnknownGroupException e) { - group = server.addGroup(groupName); - } - return group.addItem(pointConfig.get("tag").getValue(String.class)); - } + /** + * Resolve an OPC DA Item from the server, creating the group if needed. + * + * @param server connected OPC DA server + * @param pointConfig point configuration (group, tag) + * @return the resolved Item + */ + public Item getItem(Server server, Map pointConfig) throws NotConnectedException, JIException, + UnknownHostException, DuplicateGroupException, AddFailedException { + Group group; + String groupName = pointConfig.get("group").getValue(String.class); + try { + group = server.findGroup(groupName); + } catch (UnknownGroupException e) { + group = server.addGroup(groupName); + } + return group.addItem(pointConfig.get("tag").getValue(String.class)); + } - /** - * Read a tag value from the OPC DA server. - * @param server active OPC DA server connection - * @param pointConfig tag configuration (group, tag) - * @return the tag value as a string - * @throws ReadPointException if reading fails (server is disposed on error) - */ - private String readValue(Server server, Map pointConfig) { - try { - Item item = getItem(server, pointConfig); - return readItem(item); - } - catch (NotConnectedException | JIException | AddFailedException | DuplicateGroupException - | UnknownHostException e) { - server.dispose(); - log.error("Read opc da value error: {}", e.getMessage(), e); - throw new ReadPointException(e.getMessage()); - } - } + /** + * Read a tag value from the OPC DA server. + * + * @param server active OPC DA server connection + * @param pointConfig tag configuration (group, tag) + * @return the tag value as a string + * @throws ReadPointException if reading fails (server is disposed on error) + */ + private String readValue(Server server, Map pointConfig) { + try { + Item item = getItem(server, pointConfig); + return readItem(item); + } catch (NotConnectedException | JIException | AddFailedException | DuplicateGroupException + | UnknownHostException e) { + server.dispose(); + log.error("Read opc da value error: {}", e.getMessage(), e); + throw new ReadPointException(e.getMessage()); + } + } - /** - * Read and convert an OPC DA Item value to string. - *

- * Supports VT_I2, VT_I4, VT_I8, VT_R4, VT_R8, VT_BOOL, VT_BSTR; falls back to - * toString(). - * @param item the OPC DA Item to read - * @return the value as a string - * @throws JIException if DCOM communication fails - */ - public String readItem(Item item) throws JIException { - JIVariant jiVariant = item.read(false).getValue(); - switch (jiVariant.getType()) { - case JIVariant.VT_I2: - short shortValue = jiVariant.getObjectAsShort(); - return String.valueOf(shortValue); - case JIVariant.VT_I4: - int intValue = jiVariant.getObjectAsInt(); - return String.valueOf(intValue); - case JIVariant.VT_I8: - long longValue = jiVariant.getObjectAsLong(); - return String.valueOf(longValue); - case JIVariant.VT_R4: - float floatValue = jiVariant.getObjectAsFloat(); - return String.valueOf(floatValue); - case JIVariant.VT_R8: - double doubleValue = jiVariant.getObjectAsDouble(); - return String.valueOf(doubleValue); - case JIVariant.VT_BOOL: - boolean boolValue = jiVariant.getObjectAsBoolean(); - return String.valueOf(boolValue); - case JIVariant.VT_BSTR: - return jiVariant.getObjectAsString2(); - default: - return jiVariant.getObject().toString(); - } - } + /** + * Read and convert an OPC DA Item value to string. + *

+ * Supports VT_I2, VT_I4, VT_I8, VT_R4, VT_R8, VT_BOOL, VT_BSTR; falls back to + * toString(). + * + * @param item the OPC DA Item to read + * @return the value as a string + * @throws JIException if DCOM communication fails + */ + public String readItem(Item item) throws JIException { + JIVariant jiVariant = item.read(false).getValue(); + switch (jiVariant.getType()) { + case JIVariant.VT_I2: + short shortValue = jiVariant.getObjectAsShort(); + return String.valueOf(shortValue); + case JIVariant.VT_I4: + int intValue = jiVariant.getObjectAsInt(); + return String.valueOf(intValue); + case JIVariant.VT_I8: + long longValue = jiVariant.getObjectAsLong(); + return String.valueOf(longValue); + case JIVariant.VT_R4: + float floatValue = jiVariant.getObjectAsFloat(); + return String.valueOf(floatValue); + case JIVariant.VT_R8: + double doubleValue = jiVariant.getObjectAsDouble(); + return String.valueOf(doubleValue); + case JIVariant.VT_BOOL: + boolean boolValue = jiVariant.getObjectAsBoolean(); + return String.valueOf(boolValue); + case JIVariant.VT_BSTR: + return jiVariant.getObjectAsString2(); + default: + return jiVariant.getObject().toString(); + } + } - /** - * Write a value to an OPC DA tag. - * @param server active OPC DA server connection - * @param pointConfig tag configuration (group, tag) - * @param wValue value to write - * @return true if the write succeeded - * @throws WritePointException if writing fails (server is disposed on error) - */ - private boolean writeValue(Server server, Map pointConfig, WValue wValue) { - try { - Item item = getItem(server, pointConfig); - return writeItem(item, wValue); - } - catch (NotConnectedException | AddFailedException | DuplicateGroupException | UnknownHostException - | JIException e) { - server.dispose(); - log.error("Write opc da value error: {}", e.getMessage(), e); - throw new WritePointException(e.getMessage()); - } - } + /** + * Write a value to an OPC DA tag. + * + * @param server active OPC DA server connection + * @param pointConfig tag configuration (group, tag) + * @param wValue value to write + * @return true if the write succeeded + * @throws WritePointException if writing fails (server is disposed on error) + */ + private boolean writeValue(Server server, Map pointConfig, WValue wValue) { + try { + Item item = getItem(server, pointConfig); + return writeItem(item, wValue); + } catch (NotConnectedException | AddFailedException | DuplicateGroupException | UnknownHostException + | JIException e) { + server.dispose(); + log.error("Write opc da value error: {}", e.getMessage(), e); + throw new WritePointException(e.getMessage()); + } + } - /** - * Write a typed value to an OPC DA Item via JIVariant. - *

- * Supports SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. - * @param item target OPC DA Item - * @param wValue value and type to write - * @return true if the server reported success - * @throws JIException if DCOM communication fails - * @throws UnSupportException if the value type is unsupported - */ - private boolean writeItem(Item item, WValue wValue) throws JIException { - PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(wValue.getType().getCode()); - if (Objects.isNull(valueType)) { - throw new UnSupportException("Unsupported type of " + wValue.getType()); - } + /** + * Write a typed value to an OPC DA Item via JIVariant. + *

+ * Supports SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. + * + * @param item target OPC DA Item + * @param wValue value and type to write + * @return true if the server reported success + * @throws JIException if DCOM communication fails + * @throws UnSupportException if the value type is unsupported + */ + private boolean writeItem(Item item, WValue wValue) throws JIException { + PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(wValue.getType().getCode()); + if (Objects.isNull(valueType)) { + throw new UnSupportException("Unsupported type of " + wValue.getType()); + } - int writeResult = 0; - switch (valueType) { - case SHORT: - short shortValue = wValue.getValue(Short.class); - writeResult = item.write(new JIVariant(shortValue, false)); - break; - case INT: - int intValue = wValue.getValue(Integer.class); - writeResult = item.write(new JIVariant(intValue, false)); - break; - case LONG: - long longValue = wValue.getValue(Long.class); - writeResult = item.write(new JIVariant(longValue, false)); - break; - case FLOAT: - float floatValue = wValue.getValue(Float.class); - writeResult = item.write(new JIVariant(floatValue, false)); - break; - case DOUBLE: - double doubleValue = wValue.getValue(Double.class); - writeResult = item.write(new JIVariant(doubleValue, false)); - break; - case BOOLEAN: - boolean booleanValue = wValue.getValue(Boolean.class); - writeResult = item.write(new JIVariant(booleanValue, false)); - break; - case STRING: - writeResult = item.write(new JIVariant(wValue.getValue(), false)); - break; - default: - break; - } - return writeResult > 0; - } + int writeResult = 0; + switch (valueType) { + case SHORT: + short shortValue = wValue.getValue(Short.class); + writeResult = item.write(new JIVariant(shortValue, false)); + break; + case INT: + int intValue = wValue.getValue(Integer.class); + writeResult = item.write(new JIVariant(intValue, false)); + break; + case LONG: + long longValue = wValue.getValue(Long.class); + writeResult = item.write(new JIVariant(longValue, false)); + break; + case FLOAT: + float floatValue = wValue.getValue(Float.class); + writeResult = item.write(new JIVariant(floatValue, false)); + break; + case DOUBLE: + double doubleValue = wValue.getValue(Double.class); + writeResult = item.write(new JIVariant(doubleValue, false)); + break; + case BOOLEAN: + boolean booleanValue = wValue.getValue(Boolean.class); + writeResult = item.write(new JIVariant(booleanValue, false)); + break; + case STRING: + writeResult = item.write(new JIVariant(wValue.getValue(), false)); + break; + default: + break; + } + return writeResult > 0; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Categories.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Categories.java index 3fb8e2ae1..f14ddf9dd 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Categories.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Categories.java @@ -19,12 +19,12 @@ package org.openscada.opc.dcom.common; public interface Categories { - public static final String OPCDAServer10 = "63D5F430-CFE4-11d1-B2C8-0060083BA1FB"; + public static final String OPCDAServer10 = "63D5F430-CFE4-11d1-B2C8-0060083BA1FB"; - public static final String OPCDAServer20 = "63D5F432-CFE4-11d1-B2C8-0060083BA1FB"; + public static final String OPCDAServer20 = "63D5F432-CFE4-11d1-B2C8-0060083BA1FB"; - public static final String OPCDAServer30 = "CC603642-66D7-48f1-B69A-B625E73652D7"; + public static final String OPCDAServer30 = "CC603642-66D7-48f1-B69A-B625E73652D7"; - public static final String XMLDAServer10 = "3098EDA4-A006-48b2-A27F-247453959408"; + public static final String XMLDAServer10 = "3098EDA4-A006-48b2-A27F-247453959408"; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Constants.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Constants.java index db87d4ad3..3d1059f43 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Constants.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Constants.java @@ -19,18 +19,18 @@ package org.openscada.opc.dcom.common; public interface Constants { - public static final String IConnectionPointContainer_IID = "B196B284-BAB4-101A-B69C-00AA00341D07"; + public static final String IConnectionPointContainer_IID = "B196B284-BAB4-101A-B69C-00AA00341D07"; - public static final String IConnectionPoint_IID = "B196B286-BAB4-101A-B69C-00AA00341D07"; + public static final String IConnectionPoint_IID = "B196B286-BAB4-101A-B69C-00AA00341D07"; - public static final String IOPCCommon_IID = "F31DFDE2-07B6-11D2-B2D8-0060083BA1FB"; + public static final String IOPCCommon_IID = "F31DFDE2-07B6-11D2-B2D8-0060083BA1FB"; - public static final String IEnumString_IID = "00000101-0000-0000-C000-000000000046"; + public static final String IEnumString_IID = "00000101-0000-0000-C000-000000000046"; - public static final String IEnumGUID_IID = "0002E000-0000-0000-C000-000000000046"; + public static final String IEnumGUID_IID = "0002E000-0000-0000-C000-000000000046"; - public static final int S_OK = 0; + public static final int S_OK = 0; - public static final int S_FALSE = 1; + public static final int S_FALSE = 1; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/EventHandler.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/EventHandler.java index eb94e8575..2b2572b29 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/EventHandler.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/EventHandler.java @@ -22,10 +22,10 @@ import org.jinterop.dcom.core.IJIComObject; public interface EventHandler { - public String getIdentifier(); + public String getIdentifier(); - public IJIComObject getObject(); + public IJIComObject getObject(); - public void detach() throws JIException; + public void detach() throws JIException; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/FILETIME.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/FILETIME.java index b440c6fa1..a74b85985 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/FILETIME.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/FILETIME.java @@ -25,130 +25,130 @@ import java.util.Calendar; public class FILETIME { - private int high = 0; + private int high = 0; - private int low = 0; + private int low = 0; - public FILETIME() { - } + public FILETIME() { + } - public FILETIME(final FILETIME arg0) { - this.high = arg0.high; - this.low = arg0.low; - } + public FILETIME(final FILETIME arg0) { + this.high = arg0.high; + this.low = arg0.low; + } - public FILETIME(final int high, final int low) { - this.high = high; - this.low = low; - } + public FILETIME(final int high, final int low) { + this.high = high; + this.low = low; + } - public static JIStruct getStruct() throws JIException { - final JIStruct struct = new JIStruct(); + public static JIStruct getStruct() throws JIException { + final JIStruct struct = new JIStruct(); - struct.addMember(Integer.class); - struct.addMember(Integer.class); + struct.addMember(Integer.class); + struct.addMember(Integer.class); - return struct; - } + return struct; + } - public static FILETIME fromStruct(final JIStruct struct) { - final FILETIME ft = new FILETIME(); + public static FILETIME fromStruct(final JIStruct struct) { + final FILETIME ft = new FILETIME(); - ft.setLow((Integer) struct.getMember(0)); - ft.setHigh((Integer) struct.getMember(1)); + ft.setLow((Integer) struct.getMember(0)); + ft.setHigh((Integer) struct.getMember(1)); - return ft; - } + return ft; + } - public int getHigh() { - return this.high; - } + public int getHigh() { + return this.high; + } - public void setHigh(final int high) { - this.high = high; - } + public void setHigh(final int high) { + this.high = high; + } - public int getLow() { - return this.low; - } + public int getLow() { + return this.low; + } - public void setLow(final int low) { - this.low = low; - } + public void setLow(final int low) { + this.low = low; + } - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + this.high; - result = PRIME * result + this.low; - return result; - } + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + this.high; + result = PRIME * result + this.low; + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final FILETIME other = (FILETIME) obj; - if (this.high != other.high) { - return false; - } - if (this.low != other.low) { - return false; - } - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final FILETIME other = (FILETIME) obj; + if (this.high != other.high) { + return false; + } + if (this.low != other.low) { + return false; + } + return true; + } - public Calendar asCalendar() { - final Calendar c = Calendar.getInstance(); + public Calendar asCalendar() { + final Calendar c = Calendar.getInstance(); - /* - * The following "strange" stuff is needed since we miss a ulong type - */ - long i = 0xFFFFFFFFL & this.high; - i = i << 32; - long j = 0xFFFFFFFFFFFFFFFFL & i; + /* + * The following "strange" stuff is needed since we miss a ulong type + */ + long i = 0xFFFFFFFFL & this.high; + i = i << 32; + long j = 0xFFFFFFFFFFFFFFFFL & i; - i = 0xFFFFFFFFL & this.low; - j += i; - j /= 10000L; - j -= 11644473600000L; + i = 0xFFFFFFFFL & this.low; + j += i; + j /= 10000L; + j -= 11644473600000L; - c.setTimeInMillis(j); + c.setTimeInMillis(j); - return c; - } + return c; + } - public Calendar asBigDecimalCalendar() { - final Calendar c = Calendar.getInstance(); + public Calendar asBigDecimalCalendar() { + final Calendar c = Calendar.getInstance(); - /* - * The following "strange" stuff is needed since we miss a ulong type - */ - long i = 0xFFFFFFFFL & this.high; - i = i << 32; - BigDecimal d1 = new BigDecimal(0xFFFFFFFFFFFFFFFFL & i); + /* + * The following "strange" stuff is needed since we miss a ulong type + */ + long i = 0xFFFFFFFFL & this.high; + i = i << 32; + BigDecimal d1 = new BigDecimal(0xFFFFFFFFFFFFFFFFL & i); - i = 0xFFFFFFFFL & this.low; - d1 = d1.add(new BigDecimal(i)); - d1 = d1.divide(new BigDecimal(10000L)); - d1 = d1.subtract(new BigDecimal(11644473600000L)); + i = 0xFFFFFFFFL & this.low; + d1 = d1.add(new BigDecimal(i)); + d1 = d1.divide(new BigDecimal(10000L)); + d1 = d1.subtract(new BigDecimal(11644473600000L)); - c.setTimeInMillis(d1.longValue()); + c.setTimeInMillis(d1.longValue()); - return c; - } + return c; + } - @Override - public String toString() { - return String.format("%s/%s", this.high, this.low); - } + @Override + public String toString() { + return String.format("%s/%s", this.high, this.low); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResult.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResult.java index ccab9b100..0b00c3b26 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResult.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResult.java @@ -19,23 +19,23 @@ package org.openscada.opc.dcom.common; public class KeyedResult extends Result { - private K key; + private K key; - public KeyedResult() { - super(); - } + public KeyedResult() { + super(); + } - public KeyedResult(final K key, final V value, final int errorCode) { - super(value, errorCode); - this.key = key; - } + public KeyedResult(final K key, final V value, final int errorCode) { + super(value, errorCode); + this.key = key; + } - public K getKey() { - return this.key; - } + public K getKey() { + return this.key; + } - public void setKey(final K key) { - this.key = key; - } + public void setKey(final K key) { + this.key = key; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResultSet.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResultSet.java index c1aab97dc..4012fcb99 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResultSet.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/KeyedResultSet.java @@ -22,15 +22,15 @@ import java.util.ArrayList; public class KeyedResultSet extends ArrayList> { - @Serial - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; - public KeyedResultSet() { - super(); - } + public KeyedResultSet() { + super(); + } - public KeyedResultSet(final int size) { - super(size); // me - } + public KeyedResultSet(final int size) { + super(size); // me + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Result.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Result.java index 0dec0e5c4..3885e1cc9 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Result.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/Result.java @@ -19,36 +19,36 @@ package org.openscada.opc.dcom.common; public class Result { - private T value; + private T value; - private int errorCode; + private int errorCode; - public Result() { - } + public Result() { + } - public Result(final T value, final int errorCode) { - this.value = value; - this.errorCode = errorCode; - } + public Result(final T value, final int errorCode) { + this.value = value; + this.errorCode = errorCode; + } - public int getErrorCode() { - return this.errorCode; - } + public int getErrorCode() { + return this.errorCode; + } - public void setErrorCode(final int errorCode) { - this.errorCode = errorCode; - } + public void setErrorCode(final int errorCode) { + this.errorCode = errorCode; + } - public T getValue() { - return this.value; - } + public T getValue() { + return this.value; + } - public void setValue(final T value) { - this.value = value; - } + public void setValue(final T value) { + this.value = value; + } - public boolean isFailed() { - return this.errorCode != 0; - } + public boolean isFailed() { + return this.errorCode != 0; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/ResultSet.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/ResultSet.java index 027a26595..311e63f41 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/ResultSet.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/ResultSet.java @@ -21,14 +21,14 @@ import java.util.ArrayList; public class ResultSet extends ArrayList> { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public ResultSet() { - super(); - } + public ResultSet() { + super(); + } - public ResultSet(final int size) { - super(size); // me - } + public ResultSet(final int size) { + super(size); // me + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/BaseCOMObject.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/BaseCOMObject.java index 22a2ab8fd..6a9d730eb 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/BaseCOMObject.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/BaseCOMObject.java @@ -21,18 +21,19 @@ import org.jinterop.dcom.core.IJIComObject; public class BaseCOMObject { - private IJIComObject comObject = null; + private IJIComObject comObject = null; - /** - * Create a new base COM object - * @param comObject The COM object to wrap but be addRef'ed - */ - public BaseCOMObject(final IJIComObject comObject) { - this.comObject = comObject; - } + /** + * Create a new base COM object + * + * @param comObject The COM object to wrap but be addRef'ed + */ + public BaseCOMObject(final IJIComObject comObject) { + this.comObject = comObject; + } - protected synchronized IJIComObject getCOMObject() { - return this.comObject; - } + protected synchronized IJIComObject getCOMObject() { + return this.comObject; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumGUID.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumGUID.java index b430e1151..38dc4ca8b 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumGUID.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumGUID.java @@ -31,91 +31,91 @@ import java.util.List; public class EnumGUID extends BaseCOMObject { - public static final int DEFAULT_BATCH_SIZE = Integer.getInteger("openscada.dcom.enum-batch-size", 10); + public static final int DEFAULT_BATCH_SIZE = Integer.getInteger("openscada.dcom.enum-batch-size", 10); - public EnumGUID(final IJIComObject enumStringObject) - throws IllegalArgumentException, UnknownHostException, JIException { - super(enumStringObject.queryInterface(org.openscada.opc.dcom.common.Constants.IEnumGUID_IID)); - } + public EnumGUID(final IJIComObject enumStringObject) + throws IllegalArgumentException, UnknownHostException, JIException { + super(enumStringObject.queryInterface(org.openscada.opc.dcom.common.Constants.IEnumGUID_IID)); + } - public int next(final List list, final int num) throws JIException { - if (num <= 0) { - return 0; - } + public int next(final List list, final int num) throws JIException { + if (num <= 0) { + return 0; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIArray(UUID.class, null, 1, true, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIArray(UUID.class, null, 1, true, true), JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - UUID[] resultData = (UUID[]) ((JIArray) result[0]).getArrayInstance(); - Integer cnt = (Integer) result[1]; + UUID[] resultData = (UUID[]) ((JIArray) result[0]).getArrayInstance(); + Integer cnt = (Integer) result[1]; - for (int i = 0; i < cnt; i++) { - list.add(resultData[i]); - } - return cnt; - } + for (int i = 0; i < cnt; i++) { + list.add(resultData[i]); + } + return cnt; + } - public Collection next(final int num) throws JIException { - List list = new ArrayList(num); - next(list, num); - return list; - } + public Collection next(final int num) throws JIException { + List list = new ArrayList(num); + next(list, num); + return list; + } - public void skip(final int num) throws JIException { - if (num <= 0) { - return; - } + public void skip(final int num) throws JIException { + if (num <= 0) { + return; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public void reset() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public void reset() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public EnumGUID cloneObject() throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + public EnumGUID cloneObject() throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - IJIComObject object = (IJIComObject) result[0]; + IJIComObject object = (IJIComObject) result[0]; - return new EnumGUID(object); - } + return new EnumGUID(object); + } - public Collection asCollection(final int batchSize) throws JIException { - reset(); + public Collection asCollection(final int batchSize) throws JIException { + reset(); - List data = new ArrayList(); - int i = 0; - do { - i = next(data, batchSize); - } - while (i == batchSize); + List data = new ArrayList(); + int i = 0; + do { + i = next(data, batchSize); + } + while (i == batchSize); - return data; - } + return data; + } - public Collection asCollection() throws JIException { - return asCollection(DEFAULT_BATCH_SIZE); - } + public Collection asCollection() throws JIException { + return asCollection(DEFAULT_BATCH_SIZE); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumString.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumString.java index ac039be7b..7dc4bbbad 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumString.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EnumString.java @@ -27,98 +27,98 @@ import java.util.List; public class EnumString extends BaseCOMObject { - public static final int DEFAULT_BATCH_SIZE = Integer.getInteger("openscada.dcom.enum-batch-size", 10); + public static final int DEFAULT_BATCH_SIZE = Integer.getInteger("openscada.dcom.enum-batch-size", 10); - public EnumString(final IJIComObject enumStringObject) - throws IllegalArgumentException, UnknownHostException, JIException { - super(enumStringObject.queryInterface(org.openscada.opc.dcom.common.Constants.IEnumString_IID)); - } + public EnumString(final IJIComObject enumStringObject) + throws IllegalArgumentException, UnknownHostException, JIException { + super(enumStringObject.queryInterface(org.openscada.opc.dcom.common.Constants.IEnumString_IID)); + } - public int next(final List list, final int num) throws JIException { - if (num <= 0) { - return 0; - } + public int next(final List list, final int num) throws JIException { + if (num <= 0) { + return 0; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); - // callObject.addInParamAsInt ( num, JIFlags.FLAG_NULL ); - // callObject.addOutParamAsObject ( new JIArray ( new JIPointer ( new JIString ( - // JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR ) ), null, 1, true, true ), - // JIFlags.FLAG_NULL ); - callObject.addOutParamAsObject( - new JIArray(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR), null, 1, true, true), - JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); + // callObject.addInParamAsInt ( num, JIFlags.FLAG_NULL ); + // callObject.addOutParamAsObject ( new JIArray ( new JIPointer ( new JIString ( + // JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR ) ), null, 1, true, true ), + // JIFlags.FLAG_NULL ); + callObject.addOutParamAsObject( + new JIArray(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR), null, 1, true, true), + JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - // JIPointer[] resultData = (JIPointer[]) ( (JIArray) ( result[0] ) - // ).getArrayInstance (); - JIString[] resultData = (JIString[]) ((JIArray) result[0]).getArrayInstance(); - Integer cnt = (Integer) result[1]; + // JIPointer[] resultData = (JIPointer[]) ( (JIArray) ( result[0] ) + // ).getArrayInstance (); + JIString[] resultData = (JIString[]) ((JIArray) result[0]).getArrayInstance(); + Integer cnt = (Integer) result[1]; - for (int i = 0; i < cnt; i++) { - // list.add ( ( (JIString)resultData[i].getReferent () ).getString () ); - list.add(resultData[i].getString()); - } - return cnt; - } + for (int i = 0; i < cnt; i++) { + // list.add ( ( (JIString)resultData[i].getReferent () ).getString () ); + list.add(resultData[i].getString()); + } + return cnt; + } - public Collection next(final int num) throws JIException { - List list = new ArrayList(num); - next(list, num); - return list; - } + public Collection next(final int num) throws JIException { + List list = new ArrayList(num); + next(list, num); + return list; + } - public void skip(final int num) throws JIException { - if (num <= 0) { - return; - } + public void skip(final int num) throws JIException { + if (num <= 0) { + return; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(num, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public void reset() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public void reset() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public EnumString cloneObject() throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + public EnumString cloneObject() throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - IJIComObject object = (IJIComObject) result[0]; - return new EnumString(object); - } + IJIComObject object = (IJIComObject) result[0]; + return new EnumString(object); + } - public Collection asCollection(final int batchSize) throws JIException { - reset(); + public Collection asCollection(final int batchSize) throws JIException { + reset(); - List data = new ArrayList(); - int i = 0; - do { - i = next(data, batchSize); - } - while (i == batchSize); + List data = new ArrayList(); + int i = 0; + do { + i = next(data, batchSize); + } + while (i == batchSize); - return data; - } + return data; + } - public Collection asCollection() throws JIException { - return asCollection(DEFAULT_BATCH_SIZE); - } + public Collection asCollection() throws JIException { + return asCollection(DEFAULT_BATCH_SIZE); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EventHandlerImpl.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EventHandlerImpl.java index a44e89eb6..72054cf85 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EventHandlerImpl.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/EventHandlerImpl.java @@ -24,33 +24,32 @@ import org.openscada.opc.dcom.common.EventHandler; public class EventHandlerImpl implements EventHandler { - private String identifier = null; + private String identifier = null; - private IJIComObject object = null; + private IJIComObject object = null; - public String getIdentifier() { - return this.identifier; - } + public String getIdentifier() { + return this.identifier; + } - public synchronized IJIComObject getObject() { - return this.object; - } + public synchronized IJIComObject getObject() { + return this.object; + } - public synchronized void setInfo(final IJIComObject object, final String identifier) { - this.object = object; - this.identifier = identifier; - } + public synchronized void setInfo(final IJIComObject object, final String identifier) { + this.object = object; + this.identifier = identifier; + } - public synchronized void detach() throws JIException { - if (this.object != null && this.identifier != null) { - try { - JIFrameworkHelper.detachEventHandler(this.object, this.identifier); - } - finally { - this.object = null; - this.identifier = null; - } - } - } + public synchronized void detach() throws JIException { + if (this.object != null && this.identifier != null) { + try { + JIFrameworkHelper.detachEventHandler(this.object, this.identifier); + } finally { + this.object = null; + this.identifier = null; + } + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/Helper.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/Helper.java index 3d3d4d324..e785873c2 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/Helper.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/Helper.java @@ -25,40 +25,41 @@ import org.jinterop.dcom.core.JIVariant; public class Helper { - /** - * Make the COM call but do not treat S_FALSE as error condition for the whole call - * @param object the object to make to call on - * @param callObject the call object - * @return the result of the call - * @throws JIException JIException - */ - public static Object[] callRespectSFALSE(final IJIComObject object, final JICallBuilder callObject) - throws JIException { - try { - return object.call(callObject); - } - catch (JIException e) { - if (e.getErrorCode() != org.openscada.opc.dcom.common.Constants.S_FALSE) { - throw e; - } - return callObject.getResultsInCaseOfException(); - } - } + /** + * Make the COM call but do not treat S_FALSE as error condition for the whole call + * + * @param object the object to make to call on + * @param callObject the call object + * @return the result of the call + * @throws JIException JIException + */ + public static Object[] callRespectSFALSE(final IJIComObject object, final JICallBuilder callObject) + throws JIException { + try { + return object.call(callObject); + } catch (JIException e) { + if (e.getErrorCode() != org.openscada.opc.dcom.common.Constants.S_FALSE) { + throw e; + } + return callObject.getResultsInCaseOfException(); + } + } - /** - * Perform some fixes on the variant when writing it to OPC items. This method only - * changes control information on the variant and not the value itself! - * @param value the value to fix - * @return the fixed value - * @throws JIException JIException - */ - public static JIVariant fixVariant(final JIVariant value) throws JIException { - if (value.isArray()) { - if (value.getObjectAsArray().getArrayInstance() instanceof Boolean[]) { - value.setFlag(JIFlags.FLAG_REPRESENTATION_VARIANT_BOOL); - } - } - return value; - } + /** + * Perform some fixes on the variant when writing it to OPC items. This method only + * changes control information on the variant and not the value itself! + * + * @param value the value to fix + * @return the fixed value + * @throws JIException JIException + */ + public static JIVariant fixVariant(final JIVariant value) throws JIException { + if (value.isArray()) { + if (value.getObjectAsArray().getArrayInstance() instanceof Boolean[]) { + value.setFlag(JIFlags.FLAG_REPRESENTATION_VARIANT_BOOL); + } + } + return value; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/OPCCommon.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/OPCCommon.java index 7de2b01e6..dba679ce4 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/OPCCommon.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/common/impl/OPCCommon.java @@ -26,64 +26,64 @@ import java.util.Collection; public class OPCCommon extends BaseCOMObject { - public OPCCommon(final IJIComObject opcObject) throws IllegalArgumentException, UnknownHostException, JIException { - super(opcObject.queryInterface(org.openscada.opc.dcom.common.Constants.IOPCCommon_IID)); - } + public OPCCommon(final IJIComObject opcObject) throws IllegalArgumentException, UnknownHostException, JIException { + super(opcObject.queryInterface(org.openscada.opc.dcom.common.Constants.IOPCCommon_IID)); + } - public int getLocaleID() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + public int getLocaleID() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addOutParamAsObject(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(Integer.class, JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); - return (Integer) result[0]; - } + Object[] result = getCOMObject().call(callObject); + return (Integer) result[0]; + } - public void setLocaleID(final int localeID) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + public void setLocaleID(final int localeID) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public String getErrorString(final int errorCode, final int localeID) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + public String getErrorString(final int errorCode, final int localeID) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addInParamAsInt(errorCode, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), - JIFlags.FLAG_NULL); + callObject.addInParamAsInt(errorCode, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), + JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); - return ((JIString) ((JIPointer) result[0]).getReferent()).getString(); - } + Object[] result = getCOMObject().call(callObject); + return ((JIString) ((JIPointer) result[0]).getReferent()).getString(); + } - public void setClientName(final String clientName) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(4); + public void setClientName(final String clientName) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(4); - callObject.addInParamAsString(clientName, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsString(clientName, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public Collection queryAvailableLocaleIDs() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public Collection queryAvailableLocaleIDs() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - JIArray resultArray = (JIArray) ((JIPointer) result[1]).getReferent(); - Integer[] intArray = (Integer[]) resultArray.getArrayInstance(); + JIArray resultArray = (JIArray) ((JIPointer) result[1]).getReferent(); + Integer[] intArray = (Integer[]) resultArray.getArrayInstance(); - return Arrays.asList(intArray); - } + return Arrays.asList(intArray); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/Constants.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/Constants.java index c8ef2ea26..bd16e1cbf 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/Constants.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/Constants.java @@ -19,24 +19,24 @@ package org.openscada.opc.dcom.da; public interface Constants extends org.openscada.opc.dcom.common.Constants { - public static final String IOPCServer_IID = "39C13A4D-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCServer_IID = "39C13A4D-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCGroupStateMgt_IID = "39C13A50-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCGroupStateMgt_IID = "39C13A50-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCBrowse_IID = "39227004-A18F-4B57-8B0A-5235670F4468"; + public static final String IOPCBrowse_IID = "39227004-A18F-4B57-8B0A-5235670F4468"; - public static final String IOPCBrowseServerAddressSpace_IID = "39C13A4F-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCBrowseServerAddressSpace_IID = "39C13A4F-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCItemMgt_IID = "39C13A54-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCItemMgt_IID = "39C13A54-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCItemProperties_IID = "39C13A72-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCItemProperties_IID = "39C13A72-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCItemIO_IID = "85C0B427-2893-4CBC-BD78-E5FC5146F08F"; + public static final String IOPCItemIO_IID = "85C0B427-2893-4CBC-BD78-E5FC5146F08F"; - public static final String IOPCDataCallback_IID = "39C13A70-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCDataCallback_IID = "39C13A70-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCAsyncIO2_IID = "39C13A71-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCAsyncIO2_IID = "39C13A71-011E-11D0-9675-0020AFD8ADB3"; - public static final String IOPCSyncIO_IID = "39C13A52-011E-11D0-9675-0020AFD8ADB3"; + public static final String IOPCSyncIO_IID = "39C13A52-011E-11D0-9675-0020AFD8ADB3"; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IOPCDataCallback.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IOPCDataCallback.java index 5baa6e6f6..47dea0dda 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IOPCDataCallback.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IOPCDataCallback.java @@ -22,14 +22,14 @@ import org.openscada.opc.dcom.common.ResultSet; public interface IOPCDataCallback { - public void dataChange(int transactionId, int serverGroupHandle, int masterQuality, int masterErrorCode, - KeyedResultSet result); + public void dataChange(int transactionId, int serverGroupHandle, int masterQuality, int masterErrorCode, + KeyedResultSet result); - public void readComplete(int transactionId, int serverGroupHandle, int masterQuality, int masterErrorCode, - KeyedResultSet result); + public void readComplete(int transactionId, int serverGroupHandle, int masterQuality, int masterErrorCode, + KeyedResultSet result); - public void writeComplete(int transactionId, int serverGroupHandle, int masterErrorCode, ResultSet result); + public void writeComplete(int transactionId, int serverGroupHandle, int masterErrorCode, ResultSet result); - public void cancelComplete(int transactionId, int serverGroupHandle); + public void cancelComplete(int transactionId, int serverGroupHandle); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IORequest.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IORequest.java index 2b339a9ac..28de94337 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IORequest.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/IORequest.java @@ -19,29 +19,29 @@ package org.openscada.opc.dcom.da; public class IORequest { - private String itemID; + private String itemID; - private int maxAge; + private int maxAge; - public IORequest(final String itemID, final int maxAge) { - this.itemID = itemID; - this.maxAge = maxAge; - } + public IORequest(final String itemID, final int maxAge) { + this.itemID = itemID; + this.maxAge = maxAge; + } - public String getItemID() { - return this.itemID; - } + public String getItemID() { + return this.itemID; + } - public void setItemID(final String itemID) { - this.itemID = itemID; - } + public void setItemID(final String itemID) { + this.itemID = itemID; + } - public int getMaxAge() { - return this.maxAge; - } + public int getMaxAge() { + return this.maxAge; + } - public void setMaxAge(final int maxAge) { - this.maxAge = maxAge; - } + public void setMaxAge(final int maxAge) { + this.maxAge = maxAge; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSEDIRECTION.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSEDIRECTION.java index a5d18bd4a..757b1b38d 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSEDIRECTION.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSEDIRECTION.java @@ -19,29 +19,29 @@ package org.openscada.opc.dcom.da; public enum OPCBROWSEDIRECTION { - OPC_BROWSE_UP(1), OPC_BROWSE_DOWN(2), OPC_BROWSE_TO(3), OPC_BROWSE_UNKNOWN(0); + OPC_BROWSE_UP(1), OPC_BROWSE_DOWN(2), OPC_BROWSE_TO(3), OPC_BROWSE_UNKNOWN(0); - private int _id; + private int _id; - private OPCBROWSEDIRECTION(final int id) { - this._id = id; - } + private OPCBROWSEDIRECTION(final int id) { + this._id = id; + } - public static OPCBROWSEDIRECTION fromID(final int id) { - switch (id) { - case 1: - return OPC_BROWSE_UP; - case 2: - return OPC_BROWSE_DOWN; - case 3: - return OPC_BROWSE_TO; - default: - return OPC_BROWSE_UNKNOWN; - } - } + public static OPCBROWSEDIRECTION fromID(final int id) { + switch (id) { + case 1: + return OPC_BROWSE_UP; + case 2: + return OPC_BROWSE_DOWN; + case 3: + return OPC_BROWSE_TO; + default: + return OPC_BROWSE_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSETYPE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSETYPE.java index 0710518db..901301f31 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSETYPE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCBROWSETYPE.java @@ -19,29 +19,29 @@ package org.openscada.opc.dcom.da; public enum OPCBROWSETYPE { - OPC_BRANCH(1), OPC_LEAF(2), OPC_FLAT(3), OPC_UNKNOWN(0); + OPC_BRANCH(1), OPC_LEAF(2), OPC_FLAT(3), OPC_UNKNOWN(0); - private int _id; + private int _id; - private OPCBROWSETYPE(final int id) { - this._id = id; - } + private OPCBROWSETYPE(final int id) { + this._id = id; + } - public static OPCBROWSETYPE fromID(final int id) { - switch (id) { - case 1: - return OPC_BRANCH; - case 2: - return OPC_LEAF; - case 3: - return OPC_FLAT; - default: - return OPC_UNKNOWN; - } - } + public static OPCBROWSETYPE fromID(final int id) { + switch (id) { + case 1: + return OPC_BRANCH; + case 2: + return OPC_LEAF; + case 3: + return OPC_FLAT; + default: + return OPC_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCDATASOURCE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCDATASOURCE.java index 54a7f7ede..c2c0668fc 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCDATASOURCE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCDATASOURCE.java @@ -19,27 +19,27 @@ package org.openscada.opc.dcom.da; public enum OPCDATASOURCE { - OPC_DS_CACHE(1), OPC_DS_DEVICE(2), OPC_DS_UNKNOWN(0); + OPC_DS_CACHE(1), OPC_DS_DEVICE(2), OPC_DS_UNKNOWN(0); - private int _id; + private int _id; - private OPCDATASOURCE(final int id) { - this._id = id; - } + private OPCDATASOURCE(final int id) { + this._id = id; + } - public static OPCDATASOURCE fromID(final int id) { - switch (id) { - case 1: - return OPC_DS_CACHE; - case 2: - return OPC_DS_DEVICE; - default: - return OPC_DS_UNKNOWN; - } - } + public static OPCDATASOURCE fromID(final int id) { + switch (id) { + case 1: + return OPC_DS_CACHE; + case 2: + return OPC_DS_DEVICE; + default: + return OPC_DS_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCENUMSCOPE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCENUMSCOPE.java index c17d16393..c99f7a6d9 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCENUMSCOPE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCENUMSCOPE.java @@ -19,36 +19,36 @@ package org.openscada.opc.dcom.da; public enum OPCENUMSCOPE { - OPC_ENUM_PRIVATE_CONNECTIONS(1), OPC_ENUM_PUBLIC_CONNECTIONS(2), OPC_ENUM_ALL_CONNECTIONS(3), OPC_ENUM_PRIVATE(4), - OPC_ENUM_PUBLIC(5), OPC_ENUM_ALL(6), OPC_ENUM_UNKNOWN(0); + OPC_ENUM_PRIVATE_CONNECTIONS(1), OPC_ENUM_PUBLIC_CONNECTIONS(2), OPC_ENUM_ALL_CONNECTIONS(3), OPC_ENUM_PRIVATE(4), + OPC_ENUM_PUBLIC(5), OPC_ENUM_ALL(6), OPC_ENUM_UNKNOWN(0); - private int _id; + private int _id; - private OPCENUMSCOPE(final int id) { - this._id = id; - } + private OPCENUMSCOPE(final int id) { + this._id = id; + } - public static OPCENUMSCOPE fromID(final int id) { - switch (id) { - case 1: - return OPC_ENUM_PRIVATE_CONNECTIONS; - case 2: - return OPC_ENUM_PUBLIC_CONNECTIONS; - case 3: - return OPC_ENUM_ALL_CONNECTIONS; - case 4: - return OPC_ENUM_PRIVATE; - case 5: - return OPC_ENUM_PUBLIC; - case 6: - return OPC_ENUM_ALL; - default: - return OPC_ENUM_UNKNOWN; - } - } + public static OPCENUMSCOPE fromID(final int id) { + switch (id) { + case 1: + return OPC_ENUM_PRIVATE_CONNECTIONS; + case 2: + return OPC_ENUM_PUBLIC_CONNECTIONS; + case 3: + return OPC_ENUM_ALL_CONNECTIONS; + case 4: + return OPC_ENUM_PRIVATE; + case 5: + return OPC_ENUM_PUBLIC; + case 6: + return OPC_ENUM_ALL; + default: + return OPC_ENUM_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCGroupState.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCGroupState.java index 0a0634a58..469301bf5 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCGroupState.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCGroupState.java @@ -19,84 +19,84 @@ package org.openscada.opc.dcom.da; public class OPCGroupState { - private int _updateRate = 1000; + private int _updateRate = 1000; - private boolean _active = true; + private boolean _active = true; - private String _name = ""; + private String _name = ""; - private int _timeBias = 0; + private int _timeBias = 0; - private float _percentDeadband = 0.0f; + private float _percentDeadband = 0.0f; - private int _localeID = 0; + private int _localeID = 0; - private int _clientHandle = 0; + private int _clientHandle = 0; - private int _serverHandle = 0; + private int _serverHandle = 0; - public boolean isActive() { - return this._active; - } + public boolean isActive() { + return this._active; + } - public void setActive(final boolean active) { - this._active = active; - } + public void setActive(final boolean active) { + this._active = active; + } - public int getClientHandle() { - return this._clientHandle; - } + public int getClientHandle() { + return this._clientHandle; + } - public void setClientHandle(final int clientHandle) { - this._clientHandle = clientHandle; - } + public void setClientHandle(final int clientHandle) { + this._clientHandle = clientHandle; + } - public int getLocaleID() { - return this._localeID; - } + public int getLocaleID() { + return this._localeID; + } - public void setLocaleID(final int localeID) { - this._localeID = localeID; - } + public void setLocaleID(final int localeID) { + this._localeID = localeID; + } - public String getName() { - return this._name; - } + public String getName() { + return this._name; + } - public void setName(final String name) { - this._name = name; - } + public void setName(final String name) { + this._name = name; + } - public float getPercentDeadband() { - return this._percentDeadband; - } + public float getPercentDeadband() { + return this._percentDeadband; + } - public void setPercentDeadband(final float percentDeadband) { - this._percentDeadband = percentDeadband; - } + public void setPercentDeadband(final float percentDeadband) { + this._percentDeadband = percentDeadband; + } - public int getServerHandle() { - return this._serverHandle; - } + public int getServerHandle() { + return this._serverHandle; + } - public void setServerHandle(final int serverHandle) { - this._serverHandle = serverHandle; - } + public void setServerHandle(final int serverHandle) { + this._serverHandle = serverHandle; + } - public int getTimeBias() { - return this._timeBias; - } + public int getTimeBias() { + return this._timeBias; + } - public void setTimeBias(final int timeBias) { - this._timeBias = timeBias; - } + public void setTimeBias(final int timeBias) { + this._timeBias = timeBias; + } - public int getUpdateRate() { - return this._updateRate; - } + public int getUpdateRate() { + return this._updateRate; + } - public void setUpdateRate(final int updateRate) { - this._updateRate = updateRate; - } + public void setUpdateRate(final int updateRate) { + this._updateRate = updateRate; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMDEF.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMDEF.java index df135426b..a73856fff 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMDEF.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMDEF.java @@ -22,84 +22,85 @@ import org.jinterop.dcom.core.*; public class OPCITEMDEF { - private String accessPath = ""; + private String accessPath = ""; - private String itemID = ""; + private String itemID = ""; - private boolean active = true; + private boolean active = true; - private int clientHandle; + private int clientHandle; - private short requestedDataType = JIVariant.VT_EMPTY; + private short requestedDataType = JIVariant.VT_EMPTY; - private short reserved; + private short reserved; - public String getAccessPath() { - return this.accessPath; - } + public String getAccessPath() { + return this.accessPath; + } - public void setAccessPath(final String accessPath) { - this.accessPath = accessPath; - } + public void setAccessPath(final String accessPath) { + this.accessPath = accessPath; + } - public int getClientHandle() { - return this.clientHandle; - } + public int getClientHandle() { + return this.clientHandle; + } - public void setClientHandle(final int clientHandle) { - this.clientHandle = clientHandle; - } + public void setClientHandle(final int clientHandle) { + this.clientHandle = clientHandle; + } - public boolean isActive() { - return this.active; - } + public boolean isActive() { + return this.active; + } - public void setActive(final boolean active) { - this.active = active; - } + public void setActive(final boolean active) { + this.active = active; + } - public String getItemID() { - return this.itemID; - } + public String getItemID() { + return this.itemID; + } - public void setItemID(final String itemID) { - this.itemID = itemID; - } + public void setItemID(final String itemID) { + this.itemID = itemID; + } - public short getRequestedDataType() { - return this.requestedDataType; - } + public short getRequestedDataType() { + return this.requestedDataType; + } - public void setRequestedDataType(final short requestedDataType) { - this.requestedDataType = requestedDataType; - } + public void setRequestedDataType(final short requestedDataType) { + this.requestedDataType = requestedDataType; + } - public short getReserved() { - return this.reserved; - } + public short getReserved() { + return this.reserved; + } - public void setReserved(final short reserved) { - this.reserved = reserved; - } + public void setReserved(final short reserved) { + this.reserved = reserved; + } - /** - * Convert to structure to a J-Interop structure - * @return the j-interop structe - * @throws JIException JIException - */ - public JIStruct toStruct() throws JIException { - final JIStruct struct = new JIStruct(); - struct.addMember(new JIString(getAccessPath(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); - struct.addMember(new JIString(getItemID(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); - struct.addMember(isActive() ? 1 : 0); - struct.addMember(getClientHandle()); + /** + * Convert to structure to a J-Interop structure + * + * @return the j-interop structe + * @throws JIException JIException + */ + public JIStruct toStruct() throws JIException { + final JIStruct struct = new JIStruct(); + struct.addMember(new JIString(getAccessPath(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); + struct.addMember(new JIString(getItemID(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)); + struct.addMember(isActive() ? 1 : 0); + struct.addMember(getClientHandle()); - struct.addMember(0); // blob size - struct.addMember(new JIPointer(null)); // blob + struct.addMember(0); // blob size + struct.addMember(new JIPointer(null)); // blob - struct.addMember(getRequestedDataType()); - struct.addMember(getReserved()); - return struct; - } + struct.addMember(getRequestedDataType()); + struct.addMember(getReserved()); + return struct; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMRESULT.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMRESULT.java index c4717959e..f04b64cd5 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMRESULT.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMRESULT.java @@ -25,69 +25,69 @@ import org.jinterop.dcom.core.JIVariant; public class OPCITEMRESULT { - private int _serverHandle = 0; + private int _serverHandle = 0; - private short _canonicalDataType = JIVariant.VT_EMPTY; + private short _canonicalDataType = JIVariant.VT_EMPTY; - private short _reserved = 0; + private short _reserved = 0; - private int _accessRights = 0; + private int _accessRights = 0; - public static JIStruct getStruct() throws JIException { - JIStruct struct = new JIStruct(); + public static JIStruct getStruct() throws JIException { + JIStruct struct = new JIStruct(); - struct.addMember(Integer.class); // Server handle - struct.addMember(Short.class); // data type - struct.addMember(Short.class); // reserved - struct.addMember(Integer.class); // access rights - struct.addMember(Integer.class); // blob size - // grab the normally unused byte array - struct.addMember(new JIPointer(new JIArray(Byte.class, null, 1, true, false))); + struct.addMember(Integer.class); // Server handle + struct.addMember(Short.class); // data type + struct.addMember(Short.class); // reserved + struct.addMember(Integer.class); // access rights + struct.addMember(Integer.class); // blob size + // grab the normally unused byte array + struct.addMember(new JIPointer(new JIArray(Byte.class, null, 1, true, false))); - return struct; - } + return struct; + } - public static OPCITEMRESULT fromStruct(final JIStruct struct) { - OPCITEMRESULT result = new OPCITEMRESULT(); + public static OPCITEMRESULT fromStruct(final JIStruct struct) { + OPCITEMRESULT result = new OPCITEMRESULT(); - result.setServerHandle((Integer) struct.getMember(0)); - result.setCanonicalDataType((Short) struct.getMember(1)); - result.setReserved((Short) struct.getMember(2)); - result.setAccessRights((Integer) struct.getMember(3)); + result.setServerHandle((Integer) struct.getMember(0)); + result.setCanonicalDataType((Short) struct.getMember(1)); + result.setReserved((Short) struct.getMember(2)); + result.setAccessRights((Integer) struct.getMember(3)); - return result; - } + return result; + } - public int getAccessRights() { - return this._accessRights; - } + public int getAccessRights() { + return this._accessRights; + } - public void setAccessRights(final int accessRights) { - this._accessRights = accessRights; - } + public void setAccessRights(final int accessRights) { + this._accessRights = accessRights; + } - public short getCanonicalDataType() { - return this._canonicalDataType; - } + public short getCanonicalDataType() { + return this._canonicalDataType; + } - public void setCanonicalDataType(final short canonicalDataType) { - this._canonicalDataType = canonicalDataType; - } + public void setCanonicalDataType(final short canonicalDataType) { + this._canonicalDataType = canonicalDataType; + } - public short getReserved() { - return this._reserved; - } + public short getReserved() { + return this._reserved; + } - public void setReserved(final short reserved) { - this._reserved = reserved; - } + public void setReserved(final short reserved) { + this._reserved = reserved; + } - public int getServerHandle() { - return this._serverHandle; - } + public int getServerHandle() { + return this._serverHandle; + } - public void setServerHandle(final int serverHandle) { - this._serverHandle = serverHandle; - } + public void setServerHandle(final int serverHandle) { + this._serverHandle = serverHandle; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMSTATE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMSTATE.java index 91659661e..6e90ef594 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMSTATE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCITEMSTATE.java @@ -24,78 +24,78 @@ import org.openscada.opc.dcom.common.FILETIME; public class OPCITEMSTATE { - private int _clientHandle = 0; + private int _clientHandle = 0; - private FILETIME _timestamp = null; + private FILETIME _timestamp = null; - private short _quality = 0; + private short _quality = 0; - private short _reserved = 0; + private short _reserved = 0; - private JIVariant _value = null; + private JIVariant _value = null; - public static JIStruct getStruct() throws JIException { - JIStruct struct = new JIStruct(); + public static JIStruct getStruct() throws JIException { + JIStruct struct = new JIStruct(); - struct.addMember(Integer.class); - struct.addMember(FILETIME.getStruct()); - struct.addMember(Short.class); - struct.addMember(Short.class); - struct.addMember(JIVariant.class); + struct.addMember(Integer.class); + struct.addMember(FILETIME.getStruct()); + struct.addMember(Short.class); + struct.addMember(Short.class); + struct.addMember(JIVariant.class); - return struct; - } + return struct; + } - public static OPCITEMSTATE fromStruct(final JIStruct struct) { - OPCITEMSTATE itemState = new OPCITEMSTATE(); + public static OPCITEMSTATE fromStruct(final JIStruct struct) { + OPCITEMSTATE itemState = new OPCITEMSTATE(); - itemState.setClientHandle((Integer) struct.getMember(0)); - itemState.setTimestamp(FILETIME.fromStruct((JIStruct) struct.getMember(1))); - itemState.setQuality((Short) struct.getMember(2)); - itemState.setReserved((Short) struct.getMember(3)); - itemState.setValue((JIVariant) struct.getMember(4)); + itemState.setClientHandle((Integer) struct.getMember(0)); + itemState.setTimestamp(FILETIME.fromStruct((JIStruct) struct.getMember(1))); + itemState.setQuality((Short) struct.getMember(2)); + itemState.setReserved((Short) struct.getMember(3)); + itemState.setValue((JIVariant) struct.getMember(4)); - return itemState; - } + return itemState; + } - public int getClientHandle() { - return this._clientHandle; - } + public int getClientHandle() { + return this._clientHandle; + } - public void setClientHandle(final int clientHandle) { - this._clientHandle = clientHandle; - } + public void setClientHandle(final int clientHandle) { + this._clientHandle = clientHandle; + } - public short getQuality() { - return this._quality; - } + public short getQuality() { + return this._quality; + } - public void setQuality(final short quality) { - this._quality = quality; - } + public void setQuality(final short quality) { + this._quality = quality; + } - public short getReserved() { - return this._reserved; - } + public short getReserved() { + return this._reserved; + } - public void setReserved(final short reserved) { - this._reserved = reserved; - } + public void setReserved(final short reserved) { + this._reserved = reserved; + } - public FILETIME getTimestamp() { - return this._timestamp; - } + public FILETIME getTimestamp() { + return this._timestamp; + } - public void setTimestamp(final FILETIME timestamp) { - this._timestamp = timestamp; - } + public void setTimestamp(final FILETIME timestamp) { + this._timestamp = timestamp; + } - public JIVariant getValue() { - return this._value; - } + public JIVariant getValue() { + return this._value; + } - public void setValue(final JIVariant value) { - this._value = value; - } + public void setValue(final JIVariant value) { + this._value = value; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCNAMESPACETYPE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCNAMESPACETYPE.java index 04866d560..552917e89 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCNAMESPACETYPE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCNAMESPACETYPE.java @@ -19,27 +19,27 @@ package org.openscada.opc.dcom.da; public enum OPCNAMESPACETYPE { - OPC_NS_HIERARCHIAL(1), OPC_NS_FLAT(2), OPC_NS_UNKNOWN(0); + OPC_NS_HIERARCHIAL(1), OPC_NS_FLAT(2), OPC_NS_UNKNOWN(0); - private int _id; + private int _id; - private OPCNAMESPACETYPE(final int id) { - this._id = id; - } + private OPCNAMESPACETYPE(final int id) { + this._id = id; + } - public static OPCNAMESPACETYPE fromID(final int id) { - switch (id) { - case 1: - return OPC_NS_HIERARCHIAL; - case 2: - return OPC_NS_FLAT; - default: - return OPC_NS_UNKNOWN; - } - } + public static OPCNAMESPACETYPE fromID(final int id) { + switch (id) { + case 1: + return OPC_NS_HIERARCHIAL; + case 2: + return OPC_NS_FLAT; + default: + return OPC_NS_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATE.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATE.java index 73f72b815..a9ae113cd 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATE.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATE.java @@ -19,36 +19,36 @@ package org.openscada.opc.dcom.da; public enum OPCSERVERSTATE { - OPC_STATUS_RUNNING(1), OPC_STATUS_FAILED(2), OPC_STATUS_NOCONFIG(3), OPC_STATUS_SUSPENDED(4), OPC_STATUS_TEST(5), - OPC_STATUS_COMM_FAULT(6), OPC_STATUS_UNKNOWN(0); + OPC_STATUS_RUNNING(1), OPC_STATUS_FAILED(2), OPC_STATUS_NOCONFIG(3), OPC_STATUS_SUSPENDED(4), OPC_STATUS_TEST(5), + OPC_STATUS_COMM_FAULT(6), OPC_STATUS_UNKNOWN(0); - private int _id; + private int _id; - private OPCSERVERSTATE(final int id) { - this._id = id; - } + private OPCSERVERSTATE(final int id) { + this._id = id; + } - public static OPCSERVERSTATE fromID(final int id) { - switch (id) { - case 1: - return OPC_STATUS_RUNNING; - case 2: - return OPC_STATUS_FAILED; - case 3: - return OPC_STATUS_NOCONFIG; - case 4: - return OPC_STATUS_SUSPENDED; - case 5: - return OPC_STATUS_TEST; - case 6: - return OPC_STATUS_COMM_FAULT; - default: - return OPC_STATUS_UNKNOWN; - } - } + public static OPCSERVERSTATE fromID(final int id) { + switch (id) { + case 1: + return OPC_STATUS_RUNNING; + case 2: + return OPC_STATUS_FAILED; + case 3: + return OPC_STATUS_NOCONFIG; + case 4: + return OPC_STATUS_SUSPENDED; + case 5: + return OPC_STATUS_TEST; + case 6: + return OPC_STATUS_COMM_FAULT; + default: + return OPC_STATUS_UNKNOWN; + } + } - public int id() { - return this._id; - } + public int id() { + return this._id; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATUS.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATUS.java index 73a1b7a89..13ccbc8f8 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATUS.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/OPCSERVERSTATUS.java @@ -26,151 +26,151 @@ import org.openscada.opc.dcom.common.FILETIME; public class OPCSERVERSTATUS { - private FILETIME _startTime = null; + private FILETIME _startTime = null; - private FILETIME _currentTime = null; + private FILETIME _currentTime = null; - private FILETIME _lastUpdateTime = null; + private FILETIME _lastUpdateTime = null; - private OPCSERVERSTATE _serverState = null; + private OPCSERVERSTATE _serverState = null; - private int _groupCount = -1; + private int _groupCount = -1; - private int _bandWidth = -1; + private int _bandWidth = -1; - private short _majorVersion = -1; + private short _majorVersion = -1; - private short _minorVersion = -1; + private short _minorVersion = -1; - private short _buildNumber = -1; + private short _buildNumber = -1; - private short _reserved = 0; + private short _reserved = 0; - private String _vendorInfo = null; + private String _vendorInfo = null; - public static JIStruct getStruct() throws JIException { - JIStruct struct = new JIStruct(); + public static JIStruct getStruct() throws JIException { + JIStruct struct = new JIStruct(); - struct.addMember(FILETIME.getStruct()); - struct.addMember(FILETIME.getStruct()); - struct.addMember(FILETIME.getStruct()); - struct.addMember(Short.class); // enum: OPCSERVERSTATE - struct.addMember(Integer.class); - struct.addMember(Integer.class); - struct.addMember(Short.class); - struct.addMember(Short.class); - struct.addMember(Short.class); - struct.addMember(Short.class); - struct.addMember(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR))); + struct.addMember(FILETIME.getStruct()); + struct.addMember(FILETIME.getStruct()); + struct.addMember(FILETIME.getStruct()); + struct.addMember(Short.class); // enum: OPCSERVERSTATE + struct.addMember(Integer.class); + struct.addMember(Integer.class); + struct.addMember(Short.class); + struct.addMember(Short.class); + struct.addMember(Short.class); + struct.addMember(Short.class); + struct.addMember(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR))); - return struct; - } + return struct; + } - public static OPCSERVERSTATUS fromStruct(final JIStruct struct) { - OPCSERVERSTATUS status = new OPCSERVERSTATUS(); + public static OPCSERVERSTATUS fromStruct(final JIStruct struct) { + OPCSERVERSTATUS status = new OPCSERVERSTATUS(); - status._startTime = FILETIME.fromStruct((JIStruct) struct.getMember(0)); - status._currentTime = FILETIME.fromStruct((JIStruct) struct.getMember(1)); - status._lastUpdateTime = FILETIME.fromStruct((JIStruct) struct.getMember(2)); + status._startTime = FILETIME.fromStruct((JIStruct) struct.getMember(0)); + status._currentTime = FILETIME.fromStruct((JIStruct) struct.getMember(1)); + status._lastUpdateTime = FILETIME.fromStruct((JIStruct) struct.getMember(2)); - status._serverState = OPCSERVERSTATE.fromID((Short) struct.getMember(3)); - status._groupCount = (Integer) struct.getMember(4); - status._bandWidth = (Integer) struct.getMember(5); - status._majorVersion = (Short) struct.getMember(6); - status._minorVersion = (Short) struct.getMember(7); - status._buildNumber = (Short) struct.getMember(8); - status._reserved = (Short) struct.getMember(9); - status._vendorInfo = ((JIString) ((JIPointer) struct.getMember(10)).getReferent()).getString(); + status._serverState = OPCSERVERSTATE.fromID((Short) struct.getMember(3)); + status._groupCount = (Integer) struct.getMember(4); + status._bandWidth = (Integer) struct.getMember(5); + status._majorVersion = (Short) struct.getMember(6); + status._minorVersion = (Short) struct.getMember(7); + status._buildNumber = (Short) struct.getMember(8); + status._reserved = (Short) struct.getMember(9); + status._vendorInfo = ((JIString) ((JIPointer) struct.getMember(10)).getReferent()).getString(); - return status; - } + return status; + } - public int getBandWidth() { - return this._bandWidth; - } + public int getBandWidth() { + return this._bandWidth; + } - public void setBandWidth(final int bandWidth) { - this._bandWidth = bandWidth; - } + public void setBandWidth(final int bandWidth) { + this._bandWidth = bandWidth; + } - public short getBuildNumber() { - return this._buildNumber; - } + public short getBuildNumber() { + return this._buildNumber; + } - public void setBuildNumber(final short buildNumber) { - this._buildNumber = buildNumber; - } + public void setBuildNumber(final short buildNumber) { + this._buildNumber = buildNumber; + } - public FILETIME getCurrentTime() { - return this._currentTime; - } + public FILETIME getCurrentTime() { + return this._currentTime; + } - public void setCurrentTime(final FILETIME currentTime) { - this._currentTime = currentTime; - } + public void setCurrentTime(final FILETIME currentTime) { + this._currentTime = currentTime; + } - public int getGroupCount() { - return this._groupCount; - } + public int getGroupCount() { + return this._groupCount; + } - public void setGroupCount(final int groupCount) { - this._groupCount = groupCount; - } + public void setGroupCount(final int groupCount) { + this._groupCount = groupCount; + } - public FILETIME getLastUpdateTime() { - return this._lastUpdateTime; - } + public FILETIME getLastUpdateTime() { + return this._lastUpdateTime; + } - public void setLastUpdateTime(final FILETIME lastUpdateTime) { - this._lastUpdateTime = lastUpdateTime; - } + public void setLastUpdateTime(final FILETIME lastUpdateTime) { + this._lastUpdateTime = lastUpdateTime; + } - public short getMajorVersion() { - return this._majorVersion; - } + public short getMajorVersion() { + return this._majorVersion; + } - public void setMajorVersion(final short majorVersion) { - this._majorVersion = majorVersion; - } + public void setMajorVersion(final short majorVersion) { + this._majorVersion = majorVersion; + } - public short getMinorVersion() { - return this._minorVersion; - } + public short getMinorVersion() { + return this._minorVersion; + } - public void setMinorVersion(final short minorVersion) { - this._minorVersion = minorVersion; - } + public void setMinorVersion(final short minorVersion) { + this._minorVersion = minorVersion; + } - public short getReserved() { - return this._reserved; - } + public short getReserved() { + return this._reserved; + } - public void setReserved(final short reserved) { - this._reserved = reserved; - } + public void setReserved(final short reserved) { + this._reserved = reserved; + } - public FILETIME getStartTime() { - return this._startTime; - } + public FILETIME getStartTime() { + return this._startTime; + } - public void setStartTime(final FILETIME startTime) { - this._startTime = startTime; - } + public void setStartTime(final FILETIME startTime) { + this._startTime = startTime; + } - public String getVendorInfo() { - return this._vendorInfo; - } + public String getVendorInfo() { + return this._vendorInfo; + } - public void setVendorInfo(final String vendorInfo) { - this._vendorInfo = vendorInfo; - } + public void setVendorInfo(final String vendorInfo) { + this._vendorInfo = vendorInfo; + } - public OPCSERVERSTATE getServerState() { - return this._serverState; - } + public OPCSERVERSTATE getServerState() { + return this._serverState; + } - public void setServerState(final OPCSERVERSTATE dwServerState) { - this._serverState = dwServerState; - } + public void setServerState(final OPCSERVERSTATE dwServerState) { + this._serverState = dwServerState; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/PropertyDescription.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/PropertyDescription.java index daaf0dccb..911d3f432 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/PropertyDescription.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/PropertyDescription.java @@ -19,34 +19,34 @@ package org.openscada.opc.dcom.da; public class PropertyDescription { - private int _id = -1; + private int _id = -1; - private String _description = ""; + private String _description = ""; - private short _varType = 0; + private short _varType = 0; - public String getDescription() { - return this._description; - } + public String getDescription() { + return this._description; + } - public void setDescription(final String description) { - this._description = description; - } + public void setDescription(final String description) { + this._description = description; + } - public int getId() { - return this._id; - } + public int getId() { + return this._id; + } - public void setId(final int id) { - this._id = id; - } + public void setId(final int id) { + this._id = id; + } - public short getVarType() { - return this._varType; - } + public short getVarType() { + return this._varType; + } - public void setVarType(final short varType) { - this._varType = varType; - } + public void setVarType(final short varType) { + this._varType = varType; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/ValueData.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/ValueData.java index b118eb280..9ae388870 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/ValueData.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/ValueData.java @@ -23,34 +23,34 @@ import java.util.Calendar; public class ValueData { - private JIVariant value; + private JIVariant value; - private short quality; + private short quality; - private Calendar timestamp; + private Calendar timestamp; - public short getQuality() { - return this.quality; - } + public short getQuality() { + return this.quality; + } - public void setQuality(final short quality) { - this.quality = quality; - } + public void setQuality(final short quality) { + this.quality = quality; + } - public Calendar getTimestamp() { - return this.timestamp; - } + public Calendar getTimestamp() { + return this.timestamp; + } - public void setTimestamp(final Calendar timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(final Calendar timestamp) { + this.timestamp = timestamp; + } - public JIVariant getValue() { - return this.value; - } + public JIVariant getValue() { + return this.value; + } - public void setValue(final JIVariant value) { - this.value = value; - } + public void setValue(final JIVariant value) { + this.value = value; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/WriteRequest.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/WriteRequest.java index 201546c66..d0f350fc5 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/WriteRequest.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/WriteRequest.java @@ -26,42 +26,43 @@ import org.jinterop.dcom.core.JIVariant; */ public class WriteRequest { - private int serverHandle = 0; + private int serverHandle = 0; - private JIVariant value = JIVariant.EMPTY(); + private JIVariant value = JIVariant.EMPTY(); - public WriteRequest() { - } + public WriteRequest() { + } - public WriteRequest(final WriteRequest request) { - this.serverHandle = request.serverHandle; - this.value = request.value; - } + public WriteRequest(final WriteRequest request) { + this.serverHandle = request.serverHandle; + this.value = request.value; + } - /** - * Create a new write request with pre-fille data - * @param serverHandle the server handle of the item to write to - * @param value the value to write. - */ - public WriteRequest(final int serverHandle, final JIVariant value) { - this.serverHandle = serverHandle; - this.value = value; - } + /** + * Create a new write request with pre-fille data + * + * @param serverHandle the server handle of the item to write to + * @param value the value to write. + */ + public WriteRequest(final int serverHandle, final JIVariant value) { + this.serverHandle = serverHandle; + this.value = value; + } - public int getServerHandle() { - return this.serverHandle; - } + public int getServerHandle() { + return this.serverHandle; + } - public void setServerHandle(final int serverHandle) { - this.serverHandle = serverHandle; - } + public void setServerHandle(final int serverHandle) { + this.serverHandle = serverHandle; + } - public JIVariant getValue() { - return this.value; - } + public JIVariant getValue() { + return this.value; + } - public void setValue(final JIVariant value) { - this.value = value; - } + public void setValue(final JIVariant value) { + this.value = value; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCAsyncIO2.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCAsyncIO2.java index 043a0d8ca..c1649596a 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCAsyncIO2.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCAsyncIO2.java @@ -29,97 +29,97 @@ import java.net.UnknownHostException; public class OPCAsyncIO2 extends BaseCOMObject { - public OPCAsyncIO2(final IJIComObject opcAsyncIO2) - throws IllegalArgumentException, UnknownHostException, JIException { - super(opcAsyncIO2.queryInterface(Constants.IOPCAsyncIO2_IID)); - } + public OPCAsyncIO2(final IJIComObject opcAsyncIO2) + throws IllegalArgumentException, UnknownHostException, JIException { + super(opcAsyncIO2.queryInterface(Constants.IOPCAsyncIO2_IID)); + } - public void setEnable(final boolean state) throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(4); + public void setEnable(final boolean state) throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(4); - callObject.addInParamAsInt(state ? 1 : 0, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(state ? 1 : 0, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public int refresh(final OPCDATASOURCE dataSource, final int transactionID) throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public int refresh(final OPCDATASOURCE dataSource, final int transactionID) throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsShort((short) dataSource.id(), JIFlags.FLAG_NULL); - callObject.addInParamAsInt(transactionID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addInParamAsShort((short) dataSource.id(), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(transactionID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - final Object result[] = getCOMObject().call(callObject); + final Object result[] = getCOMObject().call(callObject); - return (Integer) result[0]; - } + return (Integer) result[0]; + } - public void cancel(final int cancelId) throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + public void cancel(final int cancelId) throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addInParamAsInt(cancelId, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(cancelId, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public AsyncResult read(final int transactionId, final Integer... serverHandles) throws JIException { - if (serverHandles == null || serverHandles.length == 0) { - return new AsyncResult(); - } + public AsyncResult read(final int transactionId, final Integer... serverHandles) throws JIException { + if (serverHandles == null || serverHandles.length == 0) { + return new AsyncResult(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); - callObject.addInParamAsInt(transactionId, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(transactionId, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object[] result = getCOMObject().call(callObject); + final Object[] result = getCOMObject().call(callObject); - final Integer cancelId = (Integer) result[0]; - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + final Integer cancelId = (Integer) result[0]; + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - final ResultSet resultSet = new ResultSet(); + final ResultSet resultSet = new ResultSet(); - for (int i = 0; i < serverHandles.length; i++) { - resultSet.add(new Result(serverHandles[i], errorCodes[i])); - } + for (int i = 0; i < serverHandles.length; i++) { + resultSet.add(new Result(serverHandles[i], errorCodes[i])); + } - return new AsyncResult(resultSet, cancelId); - } + return new AsyncResult(resultSet, cancelId); + } - public class AsyncResult { + public class AsyncResult { - private final ResultSet result; + private final ResultSet result; - private final Integer cancelId; + private final Integer cancelId; - public AsyncResult() { - super(); - this.result = new ResultSet(); - this.cancelId = null; - } + public AsyncResult() { + super(); + this.result = new ResultSet(); + this.cancelId = null; + } - public AsyncResult(final ResultSet result, final Integer cancelId) { - super(); - this.result = result; - this.cancelId = cancelId; - } + public AsyncResult(final ResultSet result, final Integer cancelId) { + super(); + this.result = result; + this.cancelId = cancelId; + } - public Integer getCancelId() { - return this.cancelId; - } + public Integer getCancelId() { + return this.cancelId; + } - public ResultSet getResult() { - return this.result; - } + public ResultSet getResult() { + return this.result; + } - } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowse.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowse.java index 60210004b..9581902e6 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowse.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowse.java @@ -26,8 +26,8 @@ import java.net.UnknownHostException; public class OPCBrowse extends BaseCOMObject { - public OPCBrowse(final IJIComObject opcServer) throws IllegalArgumentException, UnknownHostException, JIException { - super(opcServer.queryInterface(Constants.IOPCBrowse_IID)); - } + public OPCBrowse(final IJIComObject opcServer) throws IllegalArgumentException, UnknownHostException, JIException { + super(opcServer.queryInterface(Constants.IOPCBrowse_IID)); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowseServerAddressSpace.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowseServerAddressSpace.java index a9093f80f..f218fd735 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowseServerAddressSpace.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCBrowseServerAddressSpace.java @@ -36,114 +36,118 @@ import java.net.UnknownHostException; */ public class OPCBrowseServerAddressSpace extends BaseCOMObject { - public OPCBrowseServerAddressSpace(final IJIComObject opcServer) - throws IllegalArgumentException, UnknownHostException, JIException { - super(opcServer.queryInterface(Constants.IOPCBrowseServerAddressSpace_IID)); - } + public OPCBrowseServerAddressSpace(final IJIComObject opcServer) + throws IllegalArgumentException, UnknownHostException, JIException { + super(opcServer.queryInterface(Constants.IOPCBrowseServerAddressSpace_IID)); + } - /** - * Get the information how the namespace is organized - * @return the organization of the namespace - * @throws JIException JIException - */ - public OPCNAMESPACETYPE queryOrganization() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + /** + * Get the information how the namespace is organized + * + * @return the organization of the namespace + * @throws JIException JIException + */ + public OPCNAMESPACETYPE queryOrganization() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addOutParamAsType(Short.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Short.class, JIFlags.FLAG_NULL); - Object result[] = getCOMObject().call(callObject); + Object result[] = getCOMObject().call(callObject); - return OPCNAMESPACETYPE.fromID((Short) result[0]); - } + return OPCNAMESPACETYPE.fromID((Short) result[0]); + } - /** - * Direct the browser to another position - *

- * Depending on the direction the new position will be set based on the - * provided position information. If the direction is - * {@link OPCBROWSEDIRECTION#OPC_BROWSE_TO} then the position is the item to - * go to. If the direction is {@link OPCBROWSEDIRECTION#OPC_BROWSE_DOWN} the browser - * will descent into the tree down (not to) the branch item in position. - * Passing {@link OPCBROWSEDIRECTION#OPC_BROWSE_UP} won't need a position - * (pass null) and will ascent in the tree one level. - *

- * Passing {@link OPCBROWSEDIRECTION#OPC_BROWSE_TO} and null as position - * will go to the first root entry of the namespace. - * @param position The item position reference for the direction - * @param direction The direction to go based on the position - * @throws JIException JIException - */ - public void changePosition(final String position, final OPCBROWSEDIRECTION direction) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + /** + * Direct the browser to another position + *

+ * Depending on the direction the new position will be set based on the + * provided position information. If the direction is + * {@link OPCBROWSEDIRECTION#OPC_BROWSE_TO} then the position is the item to + * go to. If the direction is {@link OPCBROWSEDIRECTION#OPC_BROWSE_DOWN} the browser + * will descent into the tree down (not to) the branch item in position. + * Passing {@link OPCBROWSEDIRECTION#OPC_BROWSE_UP} won't need a position + * (pass null) and will ascent in the tree one level. + *

+ * Passing {@link OPCBROWSEDIRECTION#OPC_BROWSE_TO} and null as position + * will go to the first root entry of the namespace. + * + * @param position The item position reference for the direction + * @param direction The direction to go based on the position + * @throws JIException JIException + */ + public void changePosition(final String position, final OPCBROWSEDIRECTION direction) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsShort((short) direction.id(), JIFlags.FLAG_NULL); - callObject.addInParamAsString(position, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsShort((short) direction.id(), JIFlags.FLAG_NULL); + callObject.addInParamAsString(position, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - getCOMObject().call(callObject); + getCOMObject().call(callObject); - } + } - public EnumString browse(final OPCBROWSETYPE browseType, final String filterCriteria, final int accessRights, - final int dataType) throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public EnumString browse(final OPCBROWSETYPE browseType, final String filterCriteria, final int accessRights, + final int dataType) throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsShort((short) browseType.id(), JIFlags.FLAG_NULL); - callObject.addInParamAsString(filterCriteria, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsShort((short) dataType, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(accessRights, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsShort((short) browseType.id(), JIFlags.FLAG_NULL); + callObject.addInParamAsString(filterCriteria, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsShort((short) dataType, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(accessRights, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - return new EnumString((IJIComObject) result[0]); - } + return new EnumString((IJIComObject) result[0]); + } - /** - * Return the possible access paths for an item - * @param itemID the item to query - * @return A string enumerator for the possible access paths - * @throws JIException JIException - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - */ - public EnumString browseAccessPaths(final String itemID) - throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(4); + /** + * Return the possible access paths for an item + * + * @param itemID the item to query + * @return A string enumerator for the possible access paths + * @throws JIException JIException + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + */ + public EnumString browseAccessPaths(final String itemID) + throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(4); - callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - return new EnumString((IJIComObject) result[0]); - } + return new EnumString((IJIComObject) result[0]); + } - /** - * Get the complete item id from an item at the local position. - *

- * Browsing a hierarchical namespace the browse method will return items based on the - * local level in the namespace. So actually only the last part of the item ID - * hierarchy is returned. In order to convert this to the full item ID one can use - * this method. It will only work if the browser is still at the position in question. - * @param item the local item - * @return the complete item ID - * @throws JIException JIException - */ - public String getItemID(final String item) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + /** + * Get the complete item id from an item at the local position. + *

+ * Browsing a hierarchical namespace the browse method will return items based on the + * local level in the namespace. So actually only the last part of the item ID + * hierarchy is returned. In order to convert this to the full item ID one can use + * this method. It will only work if the browser is still at the position in question. + * + * @param item the local item + * @return the complete item ID + * @throws JIException JIException + */ + public String getItemID(final String item) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addInParamAsString(item, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), - JIFlags.FLAG_NULL); + callObject.addInParamAsString(item, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), + JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - return ((JIString) ((JIPointer) result[0]).getReferent()).getString(); - } + return ((JIString) ((JIPointer) result[0]).getReferent()).getString(); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCDataCallback.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCDataCallback.java index e4d8c3c45..2efc952c1 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCDataCallback.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCDataCallback.java @@ -30,201 +30,198 @@ import java.util.List; public class OPCDataCallback extends EventHandlerImpl { - private IOPCDataCallback callback = null; + private IOPCDataCallback callback = null; - private JILocalCoClass coClass = null; + private JILocalCoClass coClass = null; - public OPCDataCallback() { - super(); - } + public OPCDataCallback() { + super(); + } - public Object[] OnDataChange(final int transactionId, final int serverGroupHandle, final int masterQuality, - final int masterErrorCode, final int count, final JIArray clientHandles, final JIArray values, - final JIArray qualities, final JIArray timestamps, final JIArray errors) { - final IOPCDataCallback callback = this.callback; - if (callback == null) { - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + public Object[] OnDataChange(final int transactionId, final int serverGroupHandle, final int masterQuality, + final int masterErrorCode, final int count, final JIArray clientHandles, final JIArray values, + final JIArray qualities, final JIArray timestamps, final JIArray errors) { + final IOPCDataCallback callback = this.callback; + if (callback == null) { + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - // get arrays for more readable code later ;-) - final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); - final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); - final Short[] qualitiesArray = (Short[]) qualities.getArrayInstance(); - final JIVariant[] valuesArray = (JIVariant[]) values.getArrayInstance(); - final JIStruct[] timestampArray = (JIStruct[]) timestamps.getArrayInstance(); + // get arrays for more readable code later ;-) + final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); + final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); + final Short[] qualitiesArray = (Short[]) qualities.getArrayInstance(); + final JIVariant[] valuesArray = (JIVariant[]) values.getArrayInstance(); + final JIStruct[] timestampArray = (JIStruct[]) timestamps.getArrayInstance(); - // create result data - final KeyedResultSet result = new KeyedResultSet(); - for (int i = 0; i < count; i++) { - final ValueData vd = new ValueData(); - vd.setQuality(qualitiesArray[i]); - vd.setTimestamp(FILETIME.fromStruct(timestampArray[i]).asCalendar()); - vd.setValue(valuesArray[i]); - result.add(new KeyedResult(itemHandles[i], vd, errorCodes[i])); - } + // create result data + final KeyedResultSet result = new KeyedResultSet(); + for (int i = 0; i < count; i++) { + final ValueData vd = new ValueData(); + vd.setQuality(qualitiesArray[i]); + vd.setTimestamp(FILETIME.fromStruct(timestampArray[i]).asCalendar()); + vd.setValue(valuesArray[i]); + result.add(new KeyedResult(itemHandles[i], vd, errorCodes[i])); + } - // fire event - try { - callback.dataChange(transactionId, serverGroupHandle, masterQuality, masterErrorCode, result); - } - catch (final Throwable e) { - e.printStackTrace(); - } + // fire event + try { + callback.dataChange(transactionId, serverGroupHandle, masterQuality, masterErrorCode, result); + } catch (final Throwable e) { + e.printStackTrace(); + } - // The client must always return S_OK - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + // The client must always return S_OK + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - public synchronized Object[] OnReadComplete(final int transactionId, final int serverGroupHandle, - final int masterQuality, final int masterErrorCode, final int count, final JIArray clientHandles, - final JIArray values, final JIArray qualities, final JIArray timestamps, final JIArray errors) { - if (this.callback == null) { - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + public synchronized Object[] OnReadComplete(final int transactionId, final int serverGroupHandle, + final int masterQuality, final int masterErrorCode, final int count, final JIArray clientHandles, + final JIArray values, final JIArray qualities, final JIArray timestamps, final JIArray errors) { + if (this.callback == null) { + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - // get arrays for more readable code later ;-) - final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); - final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); - final Short[] qualitiesArray = (Short[]) qualities.getArrayInstance(); - final JIVariant[] valuesArray = (JIVariant[]) values.getArrayInstance(); - final JIStruct[] timestampArray = (JIStruct[]) timestamps.getArrayInstance(); + // get arrays for more readable code later ;-) + final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); + final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); + final Short[] qualitiesArray = (Short[]) qualities.getArrayInstance(); + final JIVariant[] valuesArray = (JIVariant[]) values.getArrayInstance(); + final JIStruct[] timestampArray = (JIStruct[]) timestamps.getArrayInstance(); - // create result data - final KeyedResultSet result = new KeyedResultSet(); - for (int i = 0; i < count; i++) { - final ValueData vd = new ValueData(); - vd.setQuality(qualitiesArray[i]); - vd.setTimestamp(FILETIME.fromStruct(timestampArray[i]).asCalendar()); - vd.setValue(valuesArray[i]); - result.add(new KeyedResult(itemHandles[i], vd, errorCodes[i])); - } + // create result data + final KeyedResultSet result = new KeyedResultSet(); + for (int i = 0; i < count; i++) { + final ValueData vd = new ValueData(); + vd.setQuality(qualitiesArray[i]); + vd.setTimestamp(FILETIME.fromStruct(timestampArray[i]).asCalendar()); + vd.setValue(valuesArray[i]); + result.add(new KeyedResult(itemHandles[i], vd, errorCodes[i])); + } - // fire event - try { - this.callback.readComplete(transactionId, serverGroupHandle, masterQuality, masterErrorCode, result); - } - catch (final Throwable e) { - e.printStackTrace(); - } + // fire event + try { + this.callback.readComplete(transactionId, serverGroupHandle, masterQuality, masterErrorCode, result); + } catch (final Throwable e) { + e.printStackTrace(); + } - // The client must always return S_OK - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + // The client must always return S_OK + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - public synchronized Object[] OnWriteComplete(final int transactionId, final int serverGroupHandle, - final int masterErrorCode, final int count, final JIArray clientHandles, final JIArray errors) { - if (this.callback == null) { - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + public synchronized Object[] OnWriteComplete(final int transactionId, final int serverGroupHandle, + final int masterErrorCode, final int count, final JIArray clientHandles, final JIArray errors) { + if (this.callback == null) { + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - // get arrays for more readable code later ;-) - final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); - final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); + // get arrays for more readable code later ;-) + final Integer[] errorCodes = (Integer[]) errors.getArrayInstance(); + final Integer[] itemHandles = (Integer[]) clientHandles.getArrayInstance(); - // create result data - final ResultSet result = new ResultSet(); - for (int i = 0; i < count; i++) { - result.add(new Result(itemHandles[i], errorCodes[i])); - } + // create result data + final ResultSet result = new ResultSet(); + for (int i = 0; i < count; i++) { + result.add(new Result(itemHandles[i], errorCodes[i])); + } - // fire event - try { - this.callback.writeComplete(transactionId, serverGroupHandle, masterErrorCode, result); - } - catch (final Throwable e) { - e.printStackTrace(); - } + // fire event + try { + this.callback.writeComplete(transactionId, serverGroupHandle, masterErrorCode, result); + } catch (final Throwable e) { + e.printStackTrace(); + } - // The client must always return S_OK - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + // The client must always return S_OK + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - public synchronized Object[] OnCancelComplete(final int transactionId, final int serverGroupHandle) { - if (this.callback == null) { - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + public synchronized Object[] OnCancelComplete(final int transactionId, final int serverGroupHandle) { + if (this.callback == null) { + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - this.callback.cancelComplete(transactionId, serverGroupHandle); + this.callback.cancelComplete(transactionId, serverGroupHandle); - // The client must always return S_OK - return new Object[] { org.openscada.opc.dcom.common.Constants.S_OK }; - } + // The client must always return S_OK + return new Object[]{org.openscada.opc.dcom.common.Constants.S_OK}; + } - public synchronized JILocalCoClass getCoClass() throws JIException { - if (this.coClass != null) { - return this.coClass; - } + public synchronized JILocalCoClass getCoClass() throws JIException { + if (this.coClass != null) { + return this.coClass; + } - this.coClass = new JILocalCoClass(new JILocalInterfaceDefinition(Constants.IOPCDataCallback_IID, false), this, - false); + this.coClass = new JILocalCoClass(new JILocalInterfaceDefinition(Constants.IOPCDataCallback_IID, false), this, + false); - JILocalParamsDescriptor params; - JILocalMethodDescriptor method; + JILocalParamsDescriptor params; + JILocalMethodDescriptor method; - // OnDataChange - params = new JILocalParamsDescriptor(); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // trans id - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // group handle - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // master quality - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // master error - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // count - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); // item - // handles - params.addInParamAsObject(new JIArray(JIVariant.class, null, 1, true), JIFlags.FLAG_NULL); // values - params.addInParamAsObject(new JIArray(Short.class, null, 1, true), JIFlags.FLAG_NULL); // qualities - params.addInParamAsObject(new JIArray(FILETIME.getStruct(), null, 1, true), JIFlags.FLAG_NULL); // timestamps - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); // errors + // OnDataChange + params = new JILocalParamsDescriptor(); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // trans id + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // group handle + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // master quality + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // master error + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); // count + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); // item + // handles + params.addInParamAsObject(new JIArray(JIVariant.class, null, 1, true), JIFlags.FLAG_NULL); // values + params.addInParamAsObject(new JIArray(Short.class, null, 1, true), JIFlags.FLAG_NULL); // qualities + params.addInParamAsObject(new JIArray(FILETIME.getStruct(), null, 1, true), JIFlags.FLAG_NULL); // timestamps + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); // errors - method = new JILocalMethodDescriptor("OnDataChange", params); - this.coClass.getInterfaceDefinition().addMethodDescriptor(method); + method = new JILocalMethodDescriptor("OnDataChange", params); + this.coClass.getInterfaceDefinition().addMethodDescriptor(method); - // OnReadComplete - params = new JILocalParamsDescriptor(); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(JIVariant.class, null, 1, true), JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(Short.class, null, 1, true), JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(FILETIME.getStruct(), null, 1, true), JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); - method = new JILocalMethodDescriptor("OnReadComplete", params); - this.coClass.getInterfaceDefinition().addMethodDescriptor(method); + // OnReadComplete + params = new JILocalParamsDescriptor(); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(JIVariant.class, null, 1, true), JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(Short.class, null, 1, true), JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(FILETIME.getStruct(), null, 1, true), JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); + method = new JILocalMethodDescriptor("OnReadComplete", params); + this.coClass.getInterfaceDefinition().addMethodDescriptor(method); - // OnWriteComplete - params = new JILocalParamsDescriptor(); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); - params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); - method = new JILocalMethodDescriptor("OnWriteComplete", params); - this.coClass.getInterfaceDefinition().addMethodDescriptor(method); + // OnWriteComplete + params = new JILocalParamsDescriptor(); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); + params.addInParamAsObject(new JIArray(Integer.class, null, 1, true), JIFlags.FLAG_NULL); + method = new JILocalMethodDescriptor("OnWriteComplete", params); + this.coClass.getInterfaceDefinition().addMethodDescriptor(method); - // OnCancelComplete - params = new JILocalParamsDescriptor(); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); - method = new JILocalMethodDescriptor("OnCancelComplete", params); - this.coClass.getInterfaceDefinition().addMethodDescriptor(method); + // OnCancelComplete + params = new JILocalParamsDescriptor(); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + params.addInParamAsType(Integer.class, JIFlags.FLAG_NULL); + method = new JILocalMethodDescriptor("OnCancelComplete", params); + this.coClass.getInterfaceDefinition().addMethodDescriptor(method); - // Add supported event interfaces - final List eventInterfaces = new LinkedList(); - eventInterfaces.add(Constants.IOPCDataCallback_IID); - this.coClass.setSupportedEventInterfaces(eventInterfaces); + // Add supported event interfaces + final List eventInterfaces = new LinkedList(); + eventInterfaces.add(Constants.IOPCDataCallback_IID); + this.coClass.setSupportedEventInterfaces(eventInterfaces); - return this.coClass; - } + return this.coClass; + } - public IOPCDataCallback getCallback() { - return this.callback; - } + public IOPCDataCallback getCallback() { + return this.callback; + } - public void setCallback(final IOPCDataCallback callback) { - this.callback = callback; - } + public void setCallback(final IOPCDataCallback callback) { + this.callback = callback; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCGroupStateMgt.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCGroupStateMgt.java index 3b644228f..5db0ee630 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCGroupStateMgt.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCGroupStateMgt.java @@ -35,156 +35,157 @@ import java.net.UnknownHostException; */ public class OPCGroupStateMgt extends BaseCOMObject { - public OPCGroupStateMgt(final IJIComObject opcGroup) - throws IllegalArgumentException, UnknownHostException, JIException { - super(opcGroup.queryInterface(Constants.IOPCGroupStateMgt_IID)); - } + public OPCGroupStateMgt(final IJIComObject opcGroup) + throws IllegalArgumentException, UnknownHostException, JIException { + super(opcGroup.queryInterface(Constants.IOPCGroupStateMgt_IID)); + } - public OPCGroupState getState() throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + public OPCGroupState getState() throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Boolean.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Float.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Boolean.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Float.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - final Object result[] = getCOMObject().call(callObject); + final Object result[] = getCOMObject().call(callObject); - final OPCGroupState state = new OPCGroupState(); - state.setUpdateRate((Integer) result[0]); - state.setActive((Boolean) result[1]); - state.setName(((JIString) ((JIPointer) result[2]).getReferent()).getString()); - state.setTimeBias((Integer) result[3]); - state.setPercentDeadband((Float) result[4]); - state.setLocaleID((Integer) result[5]); - state.setClientHandle((Integer) result[6]); - state.setServerHandle((Integer) result[7]); + final OPCGroupState state = new OPCGroupState(); + state.setUpdateRate((Integer) result[0]); + state.setActive((Boolean) result[1]); + state.setName(((JIString) ((JIPointer) result[2]).getReferent()).getString()); + state.setTimeBias((Integer) result[3]); + state.setPercentDeadband((Float) result[4]); + state.setLocaleID((Integer) result[5]); + state.setClientHandle((Integer) result[6]); + state.setServerHandle((Integer) result[7]); - return state; - } + return state; + } - /** - * Set the group state Leaving any of the parameters null will keep the - * current value untouched. - * @param requestedUpdateRate the requested update rate - * @param active Flag if the group is active or not - * @param timeBias The time bias - * @param percentDeadband the deadband percent - * @param localeID the locale ID - * @param clientHandle the client handle - * @return the granted update rate - * @throws JIException JIException - */ - public int setState(final Integer requestedUpdateRate, final Boolean active, final Integer timeBias, - final Float percentDeadband, final Integer localeID, final Integer clientHandle) throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + /** + * Set the group state Leaving any of the parameters null will keep the + * current value untouched. + * + * @param requestedUpdateRate the requested update rate + * @param active Flag if the group is active or not + * @param timeBias The time bias + * @param percentDeadband the deadband percent + * @param localeID the locale ID + * @param clientHandle the client handle + * @return the granted update rate + * @throws JIException JIException + */ + public int setState(final Integer requestedUpdateRate, final Boolean active, final Integer timeBias, + final Float percentDeadband, final Integer localeID, final Integer clientHandle) throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsPointer(new JIPointer(requestedUpdateRate), JIFlags.FLAG_NULL); - if (active != null) { - callObject.addInParamAsPointer(new JIPointer(Integer.valueOf(active.booleanValue() ? 1 : 0)), - JIFlags.FLAG_NULL); - } - else { - callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); - } - callObject.addInParamAsPointer(new JIPointer(timeBias), JIFlags.FLAG_NULL); - callObject.addInParamAsPointer(new JIPointer(percentDeadband), JIFlags.FLAG_NULL); - callObject.addInParamAsPointer(new JIPointer(localeID), JIFlags.FLAG_NULL); - callObject.addInParamAsPointer(new JIPointer(clientHandle), JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(requestedUpdateRate), JIFlags.FLAG_NULL); + if (active != null) { + callObject.addInParamAsPointer(new JIPointer(Integer.valueOf(active.booleanValue() ? 1 : 0)), + JIFlags.FLAG_NULL); + } else { + callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); + } + callObject.addInParamAsPointer(new JIPointer(timeBias), JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(percentDeadband), JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(localeID), JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(clientHandle), JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - final Object[] result = getCOMObject().call(callObject); + final Object[] result = getCOMObject().call(callObject); - return (Integer) result[0]; - } + return (Integer) result[0]; + } - public OPCItemMgt getItemManagement() throws JIException { - return new OPCItemMgt(getCOMObject()); - } + public OPCItemMgt getItemManagement() throws JIException { + return new OPCItemMgt(getCOMObject()); + } - /** - * Rename to group - * @param name the new name - * @throws JIException JIException - */ - public void setName(final String name) throws JIException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + /** + * Rename to group + * + * @param name the new name + * @throws JIException JIException + */ + public void setName(final String name) throws JIException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - /** - * Clone the group - * @param name the name of the cloned group - * @return The cloned group - * @throws JIException JIException - * @throws UnknownHostException UnknownHostException - * @throws IllegalArgumentException IllegalArgumentException - */ - public OPCGroupStateMgt clone(final String name) - throws JIException, IllegalArgumentException, UnknownHostException { - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + /** + * Clone the group + * + * @param name the name of the cloned group + * @return The cloned group + * @throws JIException JIException + * @throws UnknownHostException UnknownHostException + * @throws IllegalArgumentException IllegalArgumentException + */ + public OPCGroupStateMgt clone(final String name) + throws JIException, IllegalArgumentException, UnknownHostException { + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - final Object[] result = getCOMObject().call(callObject); - return new OPCGroupStateMgt((IJIComObject) result[0]); - } + final Object[] result = getCOMObject().call(callObject); + return new OPCGroupStateMgt((IJIComObject) result[0]); + } - /** - * Attach a new callback to the group - * @param callback The callback to attach - * @return The event handler information - * @throws JIException JIException - */ - public EventHandler attach(final IOPCDataCallback callback) throws JIException { - final OPCDataCallback callbackObject = new OPCDataCallback(); + /** + * Attach a new callback to the group + * + * @param callback The callback to attach + * @return The event handler information + * @throws JIException JIException + */ + public EventHandler attach(final IOPCDataCallback callback) throws JIException { + final OPCDataCallback callbackObject = new OPCDataCallback(); - callbackObject.setCallback(callback); + callbackObject.setCallback(callback); - // sync the callback object so that no calls get through the callback - // until the callback information is set - // If happens in some cases that the callback is triggered before - // the method attachEventHandler returns. - synchronized (callbackObject) { - final String id = JIFrameworkHelper.attachEventHandler(getCOMObject(), Constants.IOPCDataCallback_IID, - JIObjectFactory.buildObject(getCOMObject().getAssociatedSession(), callbackObject.getCoClass())); + // sync the callback object so that no calls get through the callback + // until the callback information is set + // If happens in some cases that the callback is triggered before + // the method attachEventHandler returns. + synchronized (callbackObject) { + final String id = JIFrameworkHelper.attachEventHandler(getCOMObject(), Constants.IOPCDataCallback_IID, + JIObjectFactory.buildObject(getCOMObject().getAssociatedSession(), callbackObject.getCoClass())); - callbackObject.setInfo(getCOMObject(), id); - } - return callbackObject; - } + callbackObject.setInfo(getCOMObject(), id); + } + return callbackObject; + } - public OPCAsyncIO2 getAsyncIO2() { - try { - return new OPCAsyncIO2(getCOMObject()); - } - catch (final Exception e) { - return null; - } - } + public OPCAsyncIO2 getAsyncIO2() { + try { + return new OPCAsyncIO2(getCOMObject()); + } catch (final Exception e) { + return null; + } + } - public OPCSyncIO getSyncIO() { - try { - return new OPCSyncIO(getCOMObject()); - } - catch (final Exception e) { - return null; - } - } + public OPCSyncIO getSyncIO() { + try { + return new OPCSyncIO(getCOMObject()); + } catch (final Exception e) { + return null; + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemIO.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemIO.java index 0d78b050b..343685adb 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemIO.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemIO.java @@ -28,36 +28,36 @@ import java.net.UnknownHostException; public class OPCItemIO extends BaseCOMObject { - public OPCItemIO(final IJIComObject opcItemIO) throws IllegalArgumentException, UnknownHostException, JIException { - super(opcItemIO.queryInterface(Constants.IOPCItemIO_IID)); - } + public OPCItemIO(final IJIComObject opcItemIO) throws IllegalArgumentException, UnknownHostException, JIException { + super(opcItemIO.queryInterface(Constants.IOPCItemIO_IID)); + } - public void read(final IORequest[] requests) throws JIException { - if (requests.length == 0) { - return; - } + public void read(final IORequest[] requests) throws JIException { + if (requests.length == 0) { + return; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - JIString itemIDs[] = new JIString[requests.length]; - Integer maxAges[] = new Integer[requests.length]; - for (int i = 0; i < requests.length; i++) { - itemIDs[i] = new JIString(requests[i].getItemID(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - maxAges[i] = requests[i].getMaxAge(); - } + JIString itemIDs[] = new JIString[requests.length]; + Integer maxAges[] = new Integer[requests.length]; + for (int i = 0; i < requests.length; i++) { + itemIDs[i] = new JIString(requests[i].getItemID(), JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + maxAges[i] = requests[i].getMaxAge(); + } - callObject.addInParamAsInt(requests.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(itemIDs, true), JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(maxAges, true), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(requests.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(itemIDs, true), JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(maxAges, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(JIVariant.class, null, 1, true)), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(FILETIME.getStruct(), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(JIVariant.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(FILETIME.getStruct(), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemMgt.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemMgt.java index 38041badc..281f8115e 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemMgt.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemMgt.java @@ -31,162 +31,162 @@ import org.openscada.opc.dcom.da.OPCITEMRESULT; public class OPCItemMgt extends BaseCOMObject { - public OPCItemMgt(final IJIComObject opcGroup) throws JIException { - super(opcGroup.queryInterface(Constants.IOPCItemMgt_IID)); - } + public OPCItemMgt(final IJIComObject opcGroup) throws JIException { + super(opcGroup.queryInterface(Constants.IOPCItemMgt_IID)); + } - public KeyedResultSet validate(final OPCITEMDEF... items) throws JIException { - if (items.length == 0) { - return new KeyedResultSet(); - } + public KeyedResultSet validate(final OPCITEMDEF... items) throws JIException { + if (items.length == 0) { + return new KeyedResultSet(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - final JIStruct struct[] = new JIStruct[items.length]; - for (int i = 0; i < items.length; i++) { - struct[i] = items[i].toStruct(); - } - final JIArray itemArray = new JIArray(struct, true); + final JIStruct struct[] = new JIStruct[items.length]; + for (int i = 0; i < items.length; i++) { + struct[i] = items[i].toStruct(); + } + final JIArray itemArray = new JIArray(struct, true); - callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(itemArray, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(0, JIFlags.FLAG_NULL); // don't update blobs - callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMRESULT.getStruct(), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(itemArray, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(0, JIFlags.FLAG_NULL); // don't update blobs + callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMRESULT.getStruct(), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - final JIStruct[] results = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + final JIStruct[] results = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - final KeyedResultSet resultList = new KeyedResultSet( - items.length); - for (int i = 0; i < items.length; i++) { - final OPCITEMRESULT itemResult = OPCITEMRESULT.fromStruct(results[i]); - final KeyedResult resultEntry = new KeyedResult( - items[i], itemResult, errorCodes[i]); - resultList.add(resultEntry); - } + final KeyedResultSet resultList = new KeyedResultSet( + items.length); + for (int i = 0; i < items.length; i++) { + final OPCITEMRESULT itemResult = OPCITEMRESULT.fromStruct(results[i]); + final KeyedResult resultEntry = new KeyedResult( + items[i], itemResult, errorCodes[i]); + resultList.add(resultEntry); + } - return resultList; - } + return resultList; + } - public KeyedResultSet add(final OPCITEMDEF... items) throws JIException { - if (items.length == 0) { - return new KeyedResultSet(); - } + public KeyedResultSet add(final OPCITEMDEF... items) throws JIException { + if (items.length == 0) { + return new KeyedResultSet(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - final JIStruct struct[] = new JIStruct[items.length]; - for (int i = 0; i < items.length; i++) { - struct[i] = items[i].toStruct(); - } - final JIArray itemArray = new JIArray(struct, true); + final JIStruct struct[] = new JIStruct[items.length]; + for (int i = 0; i < items.length; i++) { + struct[i] = items[i].toStruct(); + } + final JIArray itemArray = new JIArray(struct, true); - callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(itemArray, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(itemArray, JIFlags.FLAG_NULL); - /* - * callObject.addOutParamAsObject ( new JIPointer ( new JIArray ( - * OPCITEMRESULT.getStruct (), null, 1, true ) ), JIFlags.FLAG_NULL ); - * callObject.addOutParamAsObject ( new JIPointer ( new JIArray ( Integer.class, - * null, 1, true ) ), JIFlags.FLAG_NULL ); - */ - callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMRESULT.getStruct(), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + /* + * callObject.addOutParamAsObject ( new JIPointer ( new JIArray ( + * OPCITEMRESULT.getStruct (), null, 1, true ) ), JIFlags.FLAG_NULL ); + * callObject.addOutParamAsObject ( new JIPointer ( new JIArray ( Integer.class, + * null, 1, true ) ), JIFlags.FLAG_NULL ); + */ + callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMRESULT.getStruct(), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - final JIStruct[] results = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + final JIStruct[] results = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - final KeyedResultSet resultList = new KeyedResultSet( - items.length); - for (int i = 0; i < items.length; i++) { - final OPCITEMRESULT itemResult = OPCITEMRESULT.fromStruct(results[i]); - final KeyedResult resultEntry = new KeyedResult( - items[i], itemResult, errorCodes[i]); - resultList.add(resultEntry); - } + final KeyedResultSet resultList = new KeyedResultSet( + items.length); + for (int i = 0; i < items.length; i++) { + final OPCITEMRESULT itemResult = OPCITEMRESULT.fromStruct(results[i]); + final KeyedResult resultEntry = new KeyedResult( + items[i], itemResult, errorCodes[i]); + resultList.add(resultEntry); + } - return resultList; - } + return resultList; + } - public ResultSet remove(final Integer... serverHandles) throws JIException { - if (serverHandles.length == 0) { - return new ResultSet(); - } + public ResultSet remove(final Integer... serverHandles) throws JIException { + if (serverHandles.length == 0) { + return new ResultSet(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + final Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - final ResultSet results = new ResultSet(serverHandles.length); - for (int i = 0; i < serverHandles.length; i++) { - results.add(new Result(serverHandles[i], errorCodes[i])); - } - return results; - } + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + final ResultSet results = new ResultSet(serverHandles.length); + for (int i = 0; i < serverHandles.length; i++) { + results.add(new Result(serverHandles[i], errorCodes[i])); + } + return results; + } - public ResultSet setActiveState(final boolean state, final Integer... items) throws JIException { - if (items.length == 0) { - return new ResultSet(); - } + public ResultSet setActiveState(final boolean state, final Integer... items) throws JIException { + if (items.length == 0) { + return new ResultSet(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(items, true), JIFlags.FLAG_NULL); - callObject.addInParamAsInt(state ? 1 : 0, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(items.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(items, true), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(state ? 1 : 0, JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + final Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - final ResultSet results = new ResultSet(items.length); - for (int i = 0; i < items.length; i++) { - results.add(new Result(items[i], errorCodes[i])); - } - return results; - } + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + final ResultSet results = new ResultSet(items.length); + for (int i = 0; i < items.length; i++) { + results.add(new Result(items[i], errorCodes[i])); + } + return results; + } - public ResultSet setClientHandles(final Integer[] serverHandles, final Integer[] clientHandles) - throws JIException { - if (serverHandles.length != clientHandles.length) { - throw new JIException(0, "Array sizes don't match"); - } - if (serverHandles.length == 0) { - return new ResultSet(); - } + public ResultSet setClientHandles(final Integer[] serverHandles, final Integer[] clientHandles) + throws JIException { + if (serverHandles.length != clientHandles.length) { + throw new JIException(0, "Array sizes don't match"); + } + if (serverHandles.length == 0) { + return new ResultSet(); + } - final JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(4); + final JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(4); - callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(clientHandles, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(clientHandles, true), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - final Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + final Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - final ResultSet results = new ResultSet(serverHandles.length); - for (int i = 0; i < serverHandles.length; i++) { - results.add(new Result(serverHandles[i], errorCodes[i])); - } - return results; - } + final Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + final ResultSet results = new ResultSet(serverHandles.length); + for (int i = 0; i < serverHandles.length; i++) { + results.add(new Result(serverHandles[i], errorCodes[i])); + } + return results; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemProperties.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemProperties.java index 9793b238c..c290c0888 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemProperties.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCItemProperties.java @@ -33,112 +33,112 @@ import java.util.List; public class OPCItemProperties extends BaseCOMObject { - public OPCItemProperties(final IJIComObject opcItemProperties) - throws IllegalArgumentException, UnknownHostException, JIException { - super(opcItemProperties.queryInterface(Constants.IOPCItemProperties_IID)); - } + public OPCItemProperties(final IJIComObject opcItemProperties) + throws IllegalArgumentException, UnknownHostException, JIException { + super(opcItemProperties.queryInterface(Constants.IOPCItemProperties_IID)); + } - public Collection queryAvailableProperties(final String itemID) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + public Collection queryAvailableProperties(final String itemID) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject( - new JIPointer(new JIArray(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_BSTR), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Short.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject( + new JIPointer(new JIArray(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_BSTR), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Short.class, null, 1, true)), JIFlags.FLAG_NULL); - Object result[] = getCOMObject().call(callObject); + Object result[] = getCOMObject().call(callObject); - List properties = new LinkedList(); + List properties = new LinkedList(); - int len = (Integer) result[0]; - Integer[] ids = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - JIString[] descriptions = (JIString[]) ((JIArray) ((JIPointer) result[2]).getReferent()).getArrayInstance(); - Short[] variableTypes = (Short[]) ((JIArray) ((JIPointer) result[3]).getReferent()).getArrayInstance(); + int len = (Integer) result[0]; + Integer[] ids = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + JIString[] descriptions = (JIString[]) ((JIArray) ((JIPointer) result[2]).getReferent()).getArrayInstance(); + Short[] variableTypes = (Short[]) ((JIArray) ((JIPointer) result[3]).getReferent()).getArrayInstance(); - for (int i = 0; i < len; i++) { - PropertyDescription pd = new PropertyDescription(); - pd.setId(ids[i]); - pd.setDescription(descriptions[i].getString()); - pd.setVarType(variableTypes[i]); - properties.add(pd); - } - return properties; - } + for (int i = 0; i < len; i++) { + PropertyDescription pd = new PropertyDescription(); + pd.setId(ids[i]); + pd.setDescription(descriptions[i].getString()); + pd.setVarType(variableTypes[i]); + properties.add(pd); + } + return properties; + } - public KeyedResultSet getItemProperties(final String itemID, final int... properties) - throws JIException { - if (properties.length == 0) { - return new KeyedResultSet(); - } + public KeyedResultSet getItemProperties(final String itemID, final int... properties) + throws JIException { + if (properties.length == 0) { + return new KeyedResultSet(); + } - Integer[] ids = new Integer[properties.length]; - for (int i = 0; i < properties.length; i++) { - ids[i] = properties[i]; - } + Integer[] ids = new Integer[properties.length]; + for (int i = 0; i < properties.length; i++) { + ids[i] = properties[i]; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsInt(properties.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(ids, true), JIFlags.FLAG_NULL); + callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsInt(properties.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(ids, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(JIVariant.class, null, 1, true)), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(JIVariant.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - JIVariant[] values = (JIVariant[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + JIVariant[] values = (JIVariant[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - KeyedResultSet results = new KeyedResultSet(); - for (int i = 0; i < properties.length; i++) { - results.add(new KeyedResult(properties[i], values[i], errorCodes[i])); - } - return results; - } + KeyedResultSet results = new KeyedResultSet(); + for (int i = 0; i < properties.length; i++) { + results.add(new KeyedResult(properties[i], values[i], errorCodes[i])); + } + return results; + } - public KeyedResultSet lookupItemIDs(final String itemID, final int... properties) - throws JIException { - if (properties.length == 0) { - return new KeyedResultSet(); - } + public KeyedResultSet lookupItemIDs(final String itemID, final int... properties) + throws JIException { + if (properties.length == 0) { + return new KeyedResultSet(); + } - Integer[] ids = new Integer[properties.length]; - for (int i = 0; i < properties.length; i++) { - ids[i] = properties[i]; - } + Integer[] ids = new Integer[properties.length]; + for (int i = 0; i < properties.length; i++) { + ids[i] = properties[i]; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsInt(properties.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(ids, true), JIFlags.FLAG_NULL); + callObject.addInParamAsString(itemID, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsInt(properties.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(ids, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer( - new JIArray(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer( + new JIArray(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - JIPointer[] itemIDs = (JIPointer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + JIPointer[] itemIDs = (JIPointer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - KeyedResultSet results = new KeyedResultSet(); + KeyedResultSet results = new KeyedResultSet(); - for (int i = 0; i < properties.length; i++) { - results.add(new KeyedResult(properties[i], - ((JIString) itemIDs[i].getReferent()).getString(), errorCodes[i])); - } - return results; - } + for (int i = 0; i < properties.length; i++) { + results.add(new KeyedResult(properties[i], + ((JIString) itemIDs[i].getReferent()).getString(), errorCodes[i])); + } + return results; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCServer.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCServer.java index c6af42431..a455179fd 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCServer.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCServer.java @@ -31,142 +31,142 @@ import java.net.UnknownHostException; public class OPCServer extends BaseCOMObject { - public OPCServer(final IJIComObject opcServer) throws IllegalArgumentException, UnknownHostException, JIException { - super(opcServer.queryInterface(Constants.IOPCServer_IID)); - } + public OPCServer(final IJIComObject opcServer) throws IllegalArgumentException, UnknownHostException, JIException { + super(opcServer.queryInterface(Constants.IOPCServer_IID)); + } - /** - * Retrieve the current server status - * @return the current server status - * @throws JIException JIException - */ - public OPCSERVERSTATUS getStatus() throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(3); + /** + * Retrieve the current server status + * + * @return the current server status + * @throws JIException JIException + */ + public OPCSERVERSTATUS getStatus() throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(3); - callObject.addOutParamAsObject(new JIPointer(OPCSERVERSTATUS.getStruct()), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(OPCSERVERSTATUS.getStruct()), JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - return OPCSERVERSTATUS.fromStruct((JIStruct) ((JIPointer) result[0]).getReferent()); - } + return OPCSERVERSTATUS.fromStruct((JIStruct) ((JIPointer) result[0]).getReferent()); + } - public OPCGroupStateMgt addGroup(final String name, final boolean active, final int updateRate, - final int clientHandle, final Integer timeBias, final Float percentDeadband, final int localeID) - throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + public OPCGroupStateMgt addGroup(final String name, final boolean active, final int updateRate, + final int clientHandle, final Integer timeBias, final Float percentDeadband, final int localeID) + throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsInt(active ? 1 : 0, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(updateRate, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(clientHandle, JIFlags.FLAG_NULL); - callObject.addInParamAsPointer(new JIPointer(timeBias), JIFlags.FLAG_NULL); - callObject.addInParamAsPointer(new JIPointer(percentDeadband), JIFlags.FLAG_NULL); - callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); - callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsInt(active ? 1 : 0, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(updateRate, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(clientHandle, JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(timeBias), JIFlags.FLAG_NULL); + callObject.addInParamAsPointer(new JIPointer(percentDeadband), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(localeID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(Integer.class, JIFlags.FLAG_NULL); + callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - return new OPCGroupStateMgt((IJIComObject) result[2]); - } + return new OPCGroupStateMgt((IJIComObject) result[2]); + } - public void removeGroup(final int serverHandle, final boolean force) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(4); + public void removeGroup(final int serverHandle, final boolean force) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(4); - callObject.addInParamAsInt(serverHandle, JIFlags.FLAG_NULL); - callObject.addInParamAsInt(force ? 1 : 0, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(serverHandle, JIFlags.FLAG_NULL); + callObject.addInParamAsInt(force ? 1 : 0, JIFlags.FLAG_NULL); - getCOMObject().call(callObject); - } + getCOMObject().call(callObject); + } - public void removeGroup(final OPCGroupStateMgt group, final boolean force) throws JIException { - removeGroup(group.getState().getServerHandle(), force); - } + public void removeGroup(final OPCGroupStateMgt group, final boolean force) throws JIException { + removeGroup(group.getState().getServerHandle(), force); + } - public OPCGroupStateMgt getGroupByName(final String name) - throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public OPCGroupStateMgt getGroupByName(final String name) + throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsString(name, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addInParamAsUUID(Constants.IOPCGroupStateMgt_IID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = getCOMObject().call(callObject); + Object[] result = getCOMObject().call(callObject); - return new OPCGroupStateMgt((IJIComObject) result[0]); - } + return new OPCGroupStateMgt((IJIComObject) result[0]); + } - /** - * Get the groups - * @param scope The scope to get - * @return A string enumerator with the groups - * @throws JIException JIException - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - */ - public EnumString getGroups(final OPCENUMSCOPE scope) - throws JIException, IllegalArgumentException, UnknownHostException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(5); + /** + * Get the groups + * + * @param scope The scope to get + * @return A string enumerator with the groups + * @throws JIException JIException + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + */ + public EnumString getGroups(final OPCENUMSCOPE scope) + throws JIException, IllegalArgumentException, UnknownHostException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(5); - callObject.addInParamAsShort((short) scope.id(), JIFlags.FLAG_NULL); - callObject.addInParamAsUUID(org.openscada.opc.dcom.common.Constants.IEnumString_IID, JIFlags.FLAG_NULL); - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + callObject.addInParamAsShort((short) scope.id(), JIFlags.FLAG_NULL); + callObject.addInParamAsUUID(org.openscada.opc.dcom.common.Constants.IEnumString_IID, JIFlags.FLAG_NULL); + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - return new EnumString((IJIComObject) result[0]); - } + return new EnumString((IJIComObject) result[0]); + } - public OPCItemProperties getItemPropertiesService() { - try { - return new OPCItemProperties(getCOMObject()); - } - catch (Exception e) { - return null; - } - } + public OPCItemProperties getItemPropertiesService() { + try { + return new OPCItemProperties(getCOMObject()); + } catch (Exception e) { + return null; + } + } - public OPCItemIO getItemIOService() { - try { - return new OPCItemIO(getCOMObject()); - } - catch (Exception e) { - return null; - } - } + public OPCItemIO getItemIOService() { + try { + return new OPCItemIO(getCOMObject()); + } catch (Exception e) { + return null; + } + } - /** - * Get the browser object (IOPCBrowseServerAddressSpace) from the server - * instance - * @return the browser object - */ - public OPCBrowseServerAddressSpace getBrowser() { - try { - return new OPCBrowseServerAddressSpace(getCOMObject()); - } - catch (Exception e) { - return null; - } - } + /** + * Get the browser object (IOPCBrowseServerAddressSpace) from the server + * instance + * + * @return the browser object + */ + public OPCBrowseServerAddressSpace getBrowser() { + try { + return new OPCBrowseServerAddressSpace(getCOMObject()); + } catch (Exception e) { + return null; + } + } - /** - * Get the common interface if supported - * @return the common interface or null if it is not supported - */ - public OPCCommon getCommon() { - try { - return new OPCCommon(getCOMObject()); - } - catch (Exception e) { - return null; - } - } + /** + * Get the common interface if supported + * + * @return the common interface or null if it is not supported + */ + public OPCCommon getCommon() { + try { + return new OPCCommon(getCOMObject()); + } catch (Exception e) { + return null; + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCSyncIO.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCSyncIO.java index c8513f614..a16ad456a 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCSyncIO.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/da/impl/OPCSyncIO.java @@ -32,70 +32,70 @@ import org.openscada.opc.dcom.da.WriteRequest; public class OPCSyncIO extends BaseCOMObject { - public OPCSyncIO(final IJIComObject opcSyncIO) throws JIException { - super(opcSyncIO.queryInterface(Constants.IOPCSyncIO_IID)); - } + public OPCSyncIO(final IJIComObject opcSyncIO) throws JIException { + super(opcSyncIO.queryInterface(Constants.IOPCSyncIO_IID)); + } - public KeyedResultSet read(final OPCDATASOURCE source, final Integer... serverHandles) - throws JIException { - if (serverHandles == null || serverHandles.length == 0) { - return new KeyedResultSet(); - } + public KeyedResultSet read(final OPCDATASOURCE source, final Integer... serverHandles) + throws JIException { + if (serverHandles == null || serverHandles.length == 0) { + return new KeyedResultSet(); + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - callObject.addInParamAsShort((short) source.id(), JIFlags.FLAG_NULL); - callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); + callObject.addInParamAsShort((short) source.id(), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(serverHandles.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(serverHandles, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMSTATE.getStruct(), null, 1, true)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(OPCITEMSTATE.getStruct(), null, 1, true)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - KeyedResultSet results = new KeyedResultSet(); - JIStruct[] states = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); + KeyedResultSet results = new KeyedResultSet(); + JIStruct[] states = (JIStruct[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[1]).getReferent()).getArrayInstance(); - for (int i = 0; i < serverHandles.length; i++) { - results.add(new KeyedResult(serverHandles[i], OPCITEMSTATE.fromStruct(states[i]), - errorCodes[i])); - } + for (int i = 0; i < serverHandles.length; i++) { + results.add(new KeyedResult(serverHandles[i], OPCITEMSTATE.fromStruct(states[i]), + errorCodes[i])); + } - return results; - } + return results; + } - public ResultSet write(final WriteRequest... requests) throws JIException { - if (requests.length == 0) { - return new ResultSet(); - } + public ResultSet write(final WriteRequest... requests) throws JIException { + if (requests.length == 0) { + return new ResultSet(); + } - Integer[] items = new Integer[requests.length]; - JIVariant[] values = new JIVariant[requests.length]; - for (int i = 0; i < requests.length; i++) { - items[i] = requests[i].getServerHandle(); - values[i] = Helper.fixVariant(requests[i].getValue()); - } + Integer[] items = new Integer[requests.length]; + JIVariant[] values = new JIVariant[requests.length]; + for (int i = 0; i < requests.length; i++) { + items[i] = requests[i].getServerHandle(); + values[i] = Helper.fixVariant(requests[i].getValue()); + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsInt(requests.length, JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(items, true), JIFlags.FLAG_NULL); - callObject.addInParamAsArray(new JIArray(values, true), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); + callObject.addInParamAsInt(requests.length, JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(items, true), JIFlags.FLAG_NULL); + callObject.addInParamAsArray(new JIArray(values, true), JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIArray(Integer.class, null, 1, true)), JIFlags.FLAG_NULL); - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); + Integer[] errorCodes = (Integer[]) ((JIArray) ((JIPointer) result[0]).getReferent()).getArrayInstance(); - ResultSet results = new ResultSet(); - for (int i = 0; i < requests.length; i++) { - results.add(new Result(requests[i], errorCodes[i])); - } - return results; - } + ResultSet results = new ResultSet(); + for (int i = 0; i < requests.length; i++) { + results.add(new Result(requests[i], errorCodes[i])); + } + return results; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/ClassDetails.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/ClassDetails.java index d066a82ae..9befe7d27 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/ClassDetails.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/ClassDetails.java @@ -25,34 +25,34 @@ package org.openscada.opc.dcom.list; */ public class ClassDetails { - private String _clsId; + private String _clsId; - private String _progId; + private String _progId; - private String _description; + private String _description; - public String getClsId() { - return this._clsId; - } + public String getClsId() { + return this._clsId; + } - public void setClsId(final String clsId) { - this._clsId = clsId; - } + public void setClsId(final String clsId) { + this._clsId = clsId; + } - public String getDescription() { - return this._description; - } + public String getDescription() { + return this._description; + } - public void setDescription(final String description) { - this._description = description; - } + public void setDescription(final String description) { + this._description = description; + } - public String getProgId() { - return this._progId; - } + public String getProgId() { + return this._progId; + } - public void setProgId(final String progId) { - this._progId = progId; - } + public void setProgId(final String progId) { + this._progId = progId; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/Constants.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/Constants.java index ee07cb0ac..f84668424 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/Constants.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/Constants.java @@ -19,8 +19,8 @@ package org.openscada.opc.dcom.list; public interface Constants extends org.openscada.opc.dcom.common.Constants { - public static final String IOPCServerList_IID = "13486D50-4821-11D2-A494-3CB306C10000"; + public static final String IOPCServerList_IID = "13486D50-4821-11D2-A494-3CB306C10000"; - public static final String OPCServerList_CLSID = "13486D51-4821-11D2-A494-3CB306C10000"; + public static final String OPCServerList_CLSID = "13486D51-4821-11D2-A494-3CB306C10000"; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/impl/OPCServerList.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/impl/OPCServerList.java index c01b74b85..2e1c6b905 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/impl/OPCServerList.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/dcom/list/impl/OPCServerList.java @@ -35,112 +35,110 @@ import java.net.UnknownHostException; */ public class OPCServerList extends BaseCOMObject { - public OPCServerList(final IJIComObject listObject) throws JIException { - super(listObject.queryInterface(Constants.IOPCServerList_IID)); - } + public OPCServerList(final IJIComObject listObject) throws JIException { + super(listObject.queryInterface(Constants.IOPCServerList_IID)); + } - public JIClsid getCLSIDFromProgID(final String progId) throws JIException { - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(2); + public JIClsid getCLSIDFromProgID(final String progId) throws JIException { + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(2); - callObject.addInParamAsString(progId, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); - callObject.addOutParamAsType(UUID.class, JIFlags.FLAG_NULL); + callObject.addInParamAsString(progId, JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR); + callObject.addOutParamAsType(UUID.class, JIFlags.FLAG_NULL); - try { - Object[] result = getCOMObject().call(callObject); - return JIClsid.valueOf(((UUID) result[0]).toString()); - } - catch (JIException e) { - if (e.getErrorCode() == 0x800401F3) { - return null; - } - throw e; - } - } + try { + Object[] result = getCOMObject().call(callObject); + return JIClsid.valueOf(((UUID) result[0]).toString()); + } catch (JIException e) { + if (e.getErrorCode() == 0x800401F3) { + return null; + } + throw e; + } + } - /** - * Return details about a serve class - * @param clsId A server class - * @return ClassDetails - * @throws JIException JIException - */ - public ClassDetails getClassDetails(final JIClsid clsId) throws JIException { - if (clsId == null) { - return null; - } + /** + * Return details about a serve class + * + * @param clsId A server class + * @return ClassDetails + * @throws JIException JIException + */ + public ClassDetails getClassDetails(final JIClsid clsId) throws JIException { + if (clsId == null) { + return null; + } - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(1); + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(1); - callObject.addInParamAsUUID(clsId.getCLSID(), JIFlags.FLAG_NULL); + callObject.addInParamAsUUID(clsId.getCLSID(), JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), - JIFlags.FLAG_NULL); - callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), - JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), + JIFlags.FLAG_NULL); + callObject.addOutParamAsObject(new JIPointer(new JIString(JIFlags.FLAG_REPRESENTATION_STRING_LPWSTR)), + JIFlags.FLAG_NULL); - Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); + Object[] result = Helper.callRespectSFALSE(getCOMObject(), callObject); - ClassDetails cd = new ClassDetails(); - cd.setClsId(clsId.getCLSID()); - cd.setProgId(((JIString) ((JIPointer) result[0]).getReferent()).getString()); - cd.setDescription(((JIString) ((JIPointer) result[1]).getReferent()).getString()); + ClassDetails cd = new ClassDetails(); + cd.setClsId(clsId.getCLSID()); + cd.setProgId(((JIString) ((JIPointer) result[0]).getReferent()).getString()); + cd.setDescription(((JIString) ((JIPointer) result[1]).getReferent()).getString()); - return cd; - } + return cd; + } - /* - * HRESULT EnumClassesOfCategories( [in] ULONG cImplemented, - * [in,size_is(cImplemented)] CATID rgcatidImpl[], [in] ULONG cRequired, - * [in,size_is(cRequired)] CATID rgcatidReq[], [out] IEnumGUID ** ppenumClsid ); - */ + /* + * HRESULT EnumClassesOfCategories( [in] ULONG cImplemented, + * [in,size_is(cImplemented)] CATID rgcatidImpl[], [in] ULONG cRequired, + * [in,size_is(cRequired)] CATID rgcatidReq[], [out] IEnumGUID ** ppenumClsid ); + */ - public EnumGUID enumClassesOfCategories(final String[] implemented, final String[] required) - throws IllegalArgumentException, UnknownHostException, JIException { - UUID[] u1 = new UUID[implemented.length]; - UUID[] u2 = new UUID[required.length]; + public EnumGUID enumClassesOfCategories(final String[] implemented, final String[] required) + throws IllegalArgumentException, UnknownHostException, JIException { + UUID[] u1 = new UUID[implemented.length]; + UUID[] u2 = new UUID[required.length]; - for (int i = 0; i < implemented.length; i++) { - u1[i] = new UUID(implemented[i]); - } + for (int i = 0; i < implemented.length; i++) { + u1[i] = new UUID(implemented[i]); + } - for (int i = 0; i < required.length; i++) { - u2[i] = new UUID(required[i]); - } + for (int i = 0; i < required.length; i++) { + u2[i] = new UUID(required[i]); + } - return enumClassesOfCategories(u1, u2); - } + return enumClassesOfCategories(u1, u2); + } - public EnumGUID enumClassesOfCategories(final UUID[] implemented, final UUID[] required) - throws IllegalArgumentException, UnknownHostException, JIException { - // ** CALL - JICallBuilder callObject = new JICallBuilder(true); - callObject.setOpnum(0); + public EnumGUID enumClassesOfCategories(final UUID[] implemented, final UUID[] required) + throws IllegalArgumentException, UnknownHostException, JIException { + // ** CALL + JICallBuilder callObject = new JICallBuilder(true); + callObject.setOpnum(0); - // ** IN - callObject.addInParamAsInt(implemented.length, JIFlags.FLAG_NULL); - if (implemented.length == 0) { - callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); - } - else { - callObject.addInParamAsArray(new JIArray(implemented, true), JIFlags.FLAG_NULL); - } + // ** IN + callObject.addInParamAsInt(implemented.length, JIFlags.FLAG_NULL); + if (implemented.length == 0) { + callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); + } else { + callObject.addInParamAsArray(new JIArray(implemented, true), JIFlags.FLAG_NULL); + } - callObject.addInParamAsInt(required.length, JIFlags.FLAG_NULL); - if (required.length == 0) { - callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); - } - else { - callObject.addInParamAsArray(new JIArray(required, true), JIFlags.FLAG_NULL); - } + callObject.addInParamAsInt(required.length, JIFlags.FLAG_NULL); + if (required.length == 0) { + callObject.addInParamAsPointer(new JIPointer(null), JIFlags.FLAG_NULL); + } else { + callObject.addInParamAsArray(new JIArray(required, true), JIFlags.FLAG_NULL); + } - // ** OUT - callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); + // ** OUT + callObject.addOutParamAsType(IJIComObject.class, JIFlags.FLAG_NULL); - // ** RESULT - Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); + // ** RESULT + Object result[] = Helper.callRespectSFALSE(getCOMObject(), callObject); - return new EnumGUID((IJIComObject) result[0]); - } + return new EnumGUID((IJIComObject) result[0]); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/AlreadyConnectedException.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/AlreadyConnectedException.java index db3de44a7..8db7134d7 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/AlreadyConnectedException.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/AlreadyConnectedException.java @@ -19,6 +19,6 @@ package org.openscada.opc.lib.common; public class AlreadyConnectedException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/ConnectionInformation.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/ConnectionInformation.java index f20741fbe..2beb60abe 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/ConnectionInformation.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/ConnectionInformation.java @@ -27,111 +27,111 @@ package org.openscada.opc.lib.common; */ public class ConnectionInformation { - private String _host = "localhost"; + private String _host = "localhost"; - private String _domain = "localhost"; + private String _domain = "localhost"; - private String _user = ""; + private String _user = ""; - private String _password = ""; + private String _password = ""; - private String _clsid = null; + private String _clsid = null; - private String _progId = null; + private String _progId = null; - public ConnectionInformation() { - super(); - } + public ConnectionInformation() { + super(); + } - public ConnectionInformation(String host, String clsid, String user, String password) { - this._host = host; - this._clsid = clsid; - this._user = user; - this._password = password; - } + public ConnectionInformation(String host, String clsid, String user, String password) { + this._host = host; + this._clsid = clsid; + this._user = user; + this._password = password; + } - public ConnectionInformation(final String user, final String password) { - super(); - this._user = user; - this._password = password; - } + public ConnectionInformation(final String user, final String password) { + super(); + this._user = user; + this._password = password; + } - public ConnectionInformation(final ConnectionInformation arg0) { - super(); - this._user = arg0._user; - this._password = arg0._password; - this._domain = arg0._domain; - this._host = arg0._host; - this._progId = arg0._progId; - this._clsid = arg0._clsid; - } + public ConnectionInformation(final ConnectionInformation arg0) { + super(); + this._user = arg0._user; + this._password = arg0._password; + this._domain = arg0._domain; + this._host = arg0._host; + this._progId = arg0._progId; + this._clsid = arg0._clsid; + } - public String getDomain() { - return this._domain; - } + public String getDomain() { + return this._domain; + } - /** - * Set the domain of the user used for logging on - * @param domain Domain - */ - public void setDomain(final String domain) { - this._domain = domain; - } + /** + * Set the domain of the user used for logging on + * + * @param domain Domain + */ + public void setDomain(final String domain) { + this._domain = domain; + } - public String getHost() { - return this._host; - } + public String getHost() { + return this._host; + } - /** - * Set the host on which the server is located - * @param host The host to use, either an IP address oder hostname - */ - public void setHost(final String host) { - this._host = host; - } + /** + * Set the host on which the server is located + * + * @param host The host to use, either an IP address oder hostname + */ + public void setHost(final String host) { + this._host = host; + } - public String getPassword() { - return this._password; - } + public String getPassword() { + return this._password; + } - public void setPassword(final String password) { - this._password = password; - } + public void setPassword(final String password) { + this._password = password; + } - public String getUser() { - return this._user; - } + public String getUser() { + return this._user; + } - public void setUser(final String user) { - this._user = user; - } + public void setUser(final String user) { + this._user = user; + } - public String getClsid() { - return this._clsid; - } + public String getClsid() { + return this._clsid; + } - public void setClsid(final String clsid) { - this._clsid = clsid; - } + public void setClsid(final String clsid) { + this._clsid = clsid; + } - public String getProgId() { - return this._progId; - } + public String getProgId() { + return this._progId; + } - public void setProgId(final String progId) { - this._progId = progId; - } + public void setProgId(final String progId) { + this._progId = progId; + } - public String getClsOrProgId() { - if (this._clsid != null) { - return this._clsid; - } - else if (this._progId != null) { - return this._progId; - } - else { - return null; - } - } + public String getClsOrProgId() { + if (this._clsid != null) { + return this._clsid; + } else if (this._progId != null) { + return this._progId; + } else { + return null; + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/NotConnectedException.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/NotConnectedException.java index 03bdf9b3d..df75150f7 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/NotConnectedException.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/common/NotConnectedException.java @@ -19,6 +19,6 @@ package org.openscada.opc.lib.common; public class NotConnectedException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessBase.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessBase.java index 6b22a566a..f912af176 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessBase.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessBase.java @@ -33,273 +33,265 @@ import java.util.concurrent.CopyOnWriteArrayList; @Slf4j public abstract class AccessBase implements ServerConnectionStateListener { - private final List stateListeners = new CopyOnWriteArrayList(); + private final List stateListeners = new CopyOnWriteArrayList(); - protected Server server = null; + protected Server server = null; - protected Group group = null; + protected Group group = null; - protected boolean active = false; + protected boolean active = false; - /** - * Holds the item to callback assignment - */ - protected Map items = new HashMap(); + /** + * Holds the item to callback assignment + */ + protected Map items = new HashMap(); - protected Map itemMap = new HashMap(); + protected Map itemMap = new HashMap(); - protected Map itemCache = new HashMap(); + protected Map itemCache = new HashMap(); - protected Map itemSet = new HashMap(); + protected Map itemSet = new HashMap(); - protected String logTag = null; + protected String logTag = null; - protected Logger dataLogger = null; + protected Logger dataLogger = null; - private boolean bound = false; + private boolean bound = false; - private int period = 0; + private int period = 0; - public AccessBase(final Server server, final int period) throws IllegalArgumentException, UnknownHostException, - NotConnectedException, JIException, DuplicateGroupException { - super(); - this.server = server; - this.period = period; - } + public AccessBase(final Server server, final int period) throws IllegalArgumentException, UnknownHostException, + NotConnectedException, JIException, DuplicateGroupException { + super(); + this.server = server; + this.period = period; + } - public AccessBase(final Server server, final int period, final String logTag) { - super(); - this.server = server; - this.period = period; - this.logTag = logTag; - if (this.logTag != null) { - this.dataLogger = LoggerFactory.getLogger("opc.data." + logTag); - } - } + public AccessBase(final Server server, final int period, final String logTag) { + super(); + this.server = server; + this.period = period; + this.logTag = logTag; + if (this.logTag != null) { + this.dataLogger = LoggerFactory.getLogger("opc.data." + logTag); + } + } - public boolean isBound() { - return this.bound; - } + public boolean isBound() { + return this.bound; + } - public synchronized void bind() { - if (isBound()) { - return; - } + public synchronized void bind() { + if (isBound()) { + return; + } - this.server.addStateListener(this); - this.bound = true; - } + this.server.addStateListener(this); + this.bound = true; + } - public synchronized void unbind() throws JIException { - if (!isBound()) { - return; - } + public synchronized void unbind() throws JIException { + if (!isBound()) { + return; + } - this.server.removeStateListener(this); - this.bound = false; + this.server.removeStateListener(this); + this.bound = false; - stop(); - } + stop(); + } - public boolean isActive() { - return this.active; - } + public boolean isActive() { + return this.active; + } - public void addStateListener(final AccessStateListener listener) { - this.stateListeners.add(listener); - listener.stateChanged(isActive()); - } + public void addStateListener(final AccessStateListener listener) { + this.stateListeners.add(listener); + listener.stateChanged(isActive()); + } - public void removeStateListener(final AccessStateListener listener) { - this.stateListeners.remove(listener); - } + public void removeStateListener(final AccessStateListener listener) { + this.stateListeners.remove(listener); + } - protected void notifyStateListenersState(final boolean state) { - final List list = new ArrayList(this.stateListeners); + protected void notifyStateListenersState(final boolean state) { + final List list = new ArrayList(this.stateListeners); - for (final AccessStateListener listener : list) { - listener.stateChanged(state); - } - } + for (final AccessStateListener listener : list) { + listener.stateChanged(state); + } + } - protected void notifyStateListenersError(final Throwable t) { - final List list = new ArrayList(this.stateListeners); + protected void notifyStateListenersError(final Throwable t) { + final List list = new ArrayList(this.stateListeners); - for (final AccessStateListener listener : list) { - listener.errorOccured(t); - } - } + for (final AccessStateListener listener : list) { + listener.errorOccured(t); + } + } - public int getPeriod() { - return this.period; - } + public int getPeriod() { + return this.period; + } - public synchronized void addItem(final String itemId, final DataCallback dataCallback) - throws JIException, AddFailedException { - if (this.itemSet.containsKey(itemId)) { - return; - } + public synchronized void addItem(final String itemId, final DataCallback dataCallback) + throws JIException, AddFailedException { + if (this.itemSet.containsKey(itemId)) { + return; + } - this.itemSet.put(itemId, dataCallback); + this.itemSet.put(itemId, dataCallback); - if (isActive()) { - realizeItem(itemId); - } - } + if (isActive()) { + realizeItem(itemId); + } + } - public synchronized void removeItem(final String itemId) { - if (!this.itemSet.containsKey(itemId)) { - return; - } + public synchronized void removeItem(final String itemId) { + if (!this.itemSet.containsKey(itemId)) { + return; + } - this.itemSet.remove(itemId); + this.itemSet.remove(itemId); - if (isActive()) { - unrealizeItem(itemId); - } - } + if (isActive()) { + unrealizeItem(itemId); + } + } - public void connectionStateChanged(final boolean connected) { - try { - if (connected) { - start(); - } - else { - stop(); - } - } - catch (final Exception e) { - log.error(String.format("Failed to change state (%s)", connected), e); - } - } + public void connectionStateChanged(final boolean connected) { + try { + if (connected) { + start(); + } else { + stop(); + } + } catch (final Exception e) { + log.error(String.format("Failed to change state (%s)", connected), e); + } + } - protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, - NotConnectedException, DuplicateGroupException { - if (isActive()) { - return; - } + protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, + NotConnectedException, DuplicateGroupException { + if (isActive()) { + return; + } - log.debug("Create a new group"); - this.group = this.server.addGroup(); - this.group.setActive(true); - this.active = true; + log.debug("Create a new group"); + this.group = this.server.addGroup(); + this.group.setActive(true); + this.active = true; - notifyStateListenersState(true); + notifyStateListenersState(true); - realizeAll(); - } + realizeAll(); + } - protected void realizeItem(final String itemId) throws JIException, AddFailedException { - log.debug("Realizing item: {}", itemId); + protected void realizeItem(final String itemId) throws JIException, AddFailedException { + log.debug("Realizing item: {}", itemId); - final DataCallback dataCallback = this.itemSet.get(itemId); - if (dataCallback == null) { - return; - } + final DataCallback dataCallback = this.itemSet.get(itemId); + if (dataCallback == null) { + return; + } - final Item item = this.group.addItem(itemId); - this.items.put(item, dataCallback); - this.itemMap.put(itemId, item); - } + final Item item = this.group.addItem(itemId); + this.items.put(item, dataCallback); + this.itemMap.put(itemId, item); + } - protected void unrealizeItem(final String itemId) { - final Item item = this.itemMap.remove(itemId); - this.items.remove(item); - this.itemCache.remove(item); + protected void unrealizeItem(final String itemId) { + final Item item = this.itemMap.remove(itemId); + this.items.remove(item); + this.itemCache.remove(item); - try { - this.group.removeItem(itemId); - } - catch (final Throwable e) { - log.error(String.format("Failed to unrealize item '%s'", itemId), e); - } - } + try { + this.group.removeItem(itemId); + } catch (final Throwable e) { + log.error(String.format("Failed to unrealize item '%s'", itemId), e); + } + } - /* - * FIXME: need some perfomance boost: subscribe all in one call - */ - protected void realizeAll() { - for (final String itemId : this.itemSet.keySet()) { - try { - realizeItem(itemId); - } - catch (final AddFailedException e) { - Integer rc = e.getErrors().get(itemId); - if (rc == null) { - rc = -1; - } - log.warn(String.format("Failed to add item: %s (%08X)", itemId, rc)); + /* + * FIXME: need some perfomance boost: subscribe all in one call + */ + protected void realizeAll() { + for (final String itemId : this.itemSet.keySet()) { + try { + realizeItem(itemId); + } catch (final AddFailedException e) { + Integer rc = e.getErrors().get(itemId); + if (rc == null) { + rc = -1; + } + log.warn(String.format("Failed to add item: %s (%08X)", itemId, rc)); - } - catch (final Exception e) { - log.warn("Failed to realize item: " + itemId, e); - } - } - } + } catch (final Exception e) { + log.warn("Failed to realize item: " + itemId, e); + } + } + } - protected void unrealizeAll() { - this.items.clear(); - this.itemCache.clear(); - try { - this.group.clear(); - } - catch (final JIException e) { - log.info("Failed to clear group. No problem if we already lost the connection", e); - } - } + protected void unrealizeAll() { + this.items.clear(); + this.itemCache.clear(); + try { + this.group.clear(); + } catch (final JIException e) { + log.info("Failed to clear group. No problem if we already lost the connection", e); + } + } - protected synchronized void stop() throws JIException { - if (!isActive()) { - return; - } + protected synchronized void stop() throws JIException { + if (!isActive()) { + return; + } - unrealizeAll(); + unrealizeAll(); - this.active = false; - notifyStateListenersState(false); + this.active = false; + notifyStateListenersState(false); - try { - this.group.remove(); - } - catch (final Throwable t) { - log.warn("Failed to disable group. No problem if we already lost connection"); - } - this.group = null; - } + try { + this.group.remove(); + } catch (final Throwable t) { + log.warn("Failed to disable group. No problem if we already lost connection"); + } + this.group = null; + } - public synchronized void clear() { - this.itemSet.clear(); - this.items.clear(); - this.itemMap.clear(); - this.itemCache.clear(); - } + public synchronized void clear() { + this.itemSet.clear(); + this.items.clear(); + this.itemMap.clear(); + this.itemCache.clear(); + } - protected void updateItem(final Item item, final ItemState itemState) { - if (this.dataLogger != null) { - this.dataLogger.debug("Update item: {}, {}", item.getId(), itemState); - } + protected void updateItem(final Item item, final ItemState itemState) { + if (this.dataLogger != null) { + this.dataLogger.debug("Update item: {}, {}", item.getId(), itemState); + } - final DataCallback dataCallback = this.items.get(item); - if (dataCallback == null) { - return; - } + final DataCallback dataCallback = this.items.get(item); + if (dataCallback == null) { + return; + } - final ItemState cachedState = this.itemCache.get(item); - if (cachedState == null) { - this.itemCache.put(item, itemState); - dataCallback.changed(item, itemState); - } - else { - if (!cachedState.equals(itemState)) { - this.itemCache.put(item, itemState); - dataCallback.changed(item, itemState); - } - } - } + final ItemState cachedState = this.itemCache.get(item); + if (cachedState == null) { + this.itemCache.put(item, itemState); + dataCallback.changed(item, itemState); + } else { + if (!cachedState.equals(itemState)) { + this.itemCache.put(item, itemState); + dataCallback.changed(item, itemState); + } + } + } - protected void handleError(final Throwable e) { - notifyStateListenersError(e); - this.server.dispose(); - } + protected void handleError(final Throwable e) { + notifyStateListenersError(e); + this.server.dispose(); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessStateListener.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessStateListener.java index 54a77c685..e7d35022c 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessStateListener.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AccessStateListener.java @@ -19,8 +19,8 @@ package org.openscada.opc.lib.da; public interface AccessStateListener { - public abstract void stateChanged(boolean state); + public abstract void stateChanged(boolean state); - public abstract void errorOccured(Throwable t); + public abstract void errorOccured(Throwable t); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AddFailedException.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AddFailedException.java index 2ddafda96..ca349c83d 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AddFailedException.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AddFailedException.java @@ -22,35 +22,37 @@ import java.util.Map; public class AddFailedException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - private Map _errors = new HashMap(); + private Map _errors = new HashMap(); - private Map _items = new HashMap(); + private Map _items = new HashMap(); - public AddFailedException(final Map errors, final Map items) { - super(); - this._errors = errors; - this._items = items; - } + public AddFailedException(final Map errors, final Map items) { + super(); + this._errors = errors; + this._items = items; + } - /** - * Get the map of item id to error code - * @return the result map containing the failed items - */ - public Map getErrors() { - return this._errors; - } + /** + * Get the map of item id to error code + * + * @return the result map containing the failed items + */ + public Map getErrors() { + return this._errors; + } - /** - * Get the map of item it to item object - * @return the result map containing the succeeded items - */ - public Map getItems() { - return this._items; - } + /** + * Get the map of item it to item object + * + * @return the result map containing the succeeded items + */ + public Map getItems() { + return this._items; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Async20Access.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Async20Access.java index 9311f480e..3b9b620e6 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Async20Access.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Async20Access.java @@ -34,92 +34,91 @@ import java.net.UnknownHostException; @Slf4j public class Async20Access extends AccessBase implements IOPCDataCallback { - private EventHandler eventHandler = null; + private EventHandler eventHandler = null; - private boolean initialRefresh = false; + private boolean initialRefresh = false; - public Async20Access(final Server server, final int period, final boolean initialRefresh) - throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, - DuplicateGroupException { - super(server, period); - this.initialRefresh = initialRefresh; - } + public Async20Access(final Server server, final int period, final boolean initialRefresh) + throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, + DuplicateGroupException { + super(server, period); + this.initialRefresh = initialRefresh; + } - public Async20Access(final Server server, final int period, final boolean initialRefresh, final String logTag) - throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, - DuplicateGroupException { - super(server, period, logTag); - this.initialRefresh = initialRefresh; - } + public Async20Access(final Server server, final int period, final boolean initialRefresh, final String logTag) + throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, + DuplicateGroupException { + super(server, period, logTag); + this.initialRefresh = initialRefresh; + } - @Override - protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, - NotConnectedException, DuplicateGroupException { - if (isActive()) { - return; - } + @Override + protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, + NotConnectedException, DuplicateGroupException { + if (isActive()) { + return; + } - super.start(); + super.start(); - this.eventHandler = this.group.attach(this); - if (!this.items.isEmpty() && this.initialRefresh) { - final OPCAsyncIO2 async20 = this.group.getAsyncIO20(); - if (async20 == null) { - throw new NotConnectedException(); - } + this.eventHandler = this.group.attach(this); + if (!this.items.isEmpty() && this.initialRefresh) { + final OPCAsyncIO2 async20 = this.group.getAsyncIO20(); + if (async20 == null) { + throw new NotConnectedException(); + } - this.group.getAsyncIO20().refresh(OPCDATASOURCE.OPC_DS_CACHE, 0); - } - } + this.group.getAsyncIO20().refresh(OPCDATASOURCE.OPC_DS_CACHE, 0); + } + } - @Override - protected synchronized void stop() throws JIException { - if (!isActive()) { - return; - } + @Override + protected synchronized void stop() throws JIException { + if (!isActive()) { + return; + } - if (this.eventHandler != null) { - try { - this.eventHandler.detach(); - } - catch (final Throwable e) { - log.warn("Failed to detach group", e); - } + if (this.eventHandler != null) { + try { + this.eventHandler.detach(); + } catch (final Throwable e) { + log.warn("Failed to detach group", e); + } - this.eventHandler = null; - } + this.eventHandler = null; + } - super.stop(); - } + super.stop(); + } - public void cancelComplete(final int transactionId, final int serverGroupHandle) { - } + public void cancelComplete(final int transactionId, final int serverGroupHandle) { + } - public void dataChange(final int transactionId, final int serverGroupHandle, final int masterQuality, - final int masterErrorCode, final KeyedResultSet result) { - log.debug("dataChange - transId {}, items: {}", transactionId, result.size()); + public void dataChange(final int transactionId, final int serverGroupHandle, final int masterQuality, + final int masterErrorCode, final KeyedResultSet result) { + log.debug("dataChange - transId {}, items: {}", transactionId, result.size()); - final Group group = this.group; - if (group == null) { - return; - } + final Group group = this.group; + if (group == null) { + return; + } - for (final KeyedResult entry : result) { - final Item item = group.findItemByClientHandle(entry.getKey()); - log.debug("Update for '{}'", item.getId()); - updateItem(item, new ItemState(entry.getErrorCode(), entry.getValue().getValue(), - entry.getValue().getTimestamp(), entry.getValue().getQuality())); - } - } + for (final KeyedResult entry : result) { + final Item item = group.findItemByClientHandle(entry.getKey()); + log.debug("Update for '{}'", item.getId()); + updateItem(item, new ItemState(entry.getErrorCode(), entry.getValue().getValue(), + entry.getValue().getTimestamp(), entry.getValue().getQuality())); + } + } - public void readComplete(final int transactionId, final int serverGroupHandle, final int masterQuality, - final int masterErrorCode, final KeyedResultSet result) { - log.debug("readComplete - transId {}", transactionId); - } + public void readComplete(final int transactionId, final int serverGroupHandle, final int masterQuality, + final int masterErrorCode, final KeyedResultSet result) { + log.debug("readComplete - transId {}", transactionId); + } - public void writeComplete(final int transactionId, final int serverGroupHandle, final int masterErrorCode, - final ResultSet result) { - log.debug("writeComplete - transId {}", transactionId); - } + public void writeComplete(final int transactionId, final int serverGroupHandle, final int masterErrorCode, + final ResultSet result) { + log.debug("writeComplete - transId {}", transactionId); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectController.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectController.java index 2c86a234f..866a87bb4 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectController.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectController.java @@ -25,167 +25,163 @@ import java.util.concurrent.CopyOnWriteArraySet; @Slf4j public class AutoReconnectController implements ServerConnectionStateListener { - private static final int DEFAULT_DELAY = 5 * 1000; + private static final int DEFAULT_DELAY = 5 * 1000; - private final Server _server; + private final Server _server; - private final Set _listeners = new CopyOnWriteArraySet(); + private final Set _listeners = new CopyOnWriteArraySet(); - private int _delay; + private int _delay; - private AutoReconnectState _state = AutoReconnectState.DISABLED; + private AutoReconnectState _state = AutoReconnectState.DISABLED; - private Thread _connectTask = null; + private Thread _connectTask = null; - public AutoReconnectController(final Server server) { - this(server, DEFAULT_DELAY); - } + public AutoReconnectController(final Server server) { + this(server, DEFAULT_DELAY); + } - public AutoReconnectController(final Server server, final int delay) { - super(); - setDelay(delay); + public AutoReconnectController(final Server server, final int delay) { + super(); + setDelay(delay); - this._server = server; - this._server.addStateListener(this); - } + this._server = server; + this._server.addStateListener(this); + } - public void addListener(final AutoReconnectListener listener) { - if (listener != null) { - this._listeners.add(listener); - listener.stateChanged(this._state); - } - } + public void addListener(final AutoReconnectListener listener) { + if (listener != null) { + this._listeners.add(listener); + listener.stateChanged(this._state); + } + } - public void removeListener(final AutoReconnectListener listener) { - this._listeners.remove(listener); - } + public void removeListener(final AutoReconnectListener listener) { + this._listeners.remove(listener); + } - protected void notifyStateChange(final AutoReconnectState state) { - this._state = state; - for (AutoReconnectListener listener : this._listeners) { - listener.stateChanged(state); - } - } + protected void notifyStateChange(final AutoReconnectState state) { + this._state = state; + for (AutoReconnectListener listener : this._listeners) { + listener.stateChanged(state); + } + } - public int getDelay() { - return this._delay; - } + public int getDelay() { + return this._delay; + } - /** - * Set the reconnect delay. If the delay less than or equal to zero it will be the - * default delay time. - * @param delay The delay to use - */ - public void setDelay(int delay) { - if (delay <= 0) { - delay = DEFAULT_DELAY; - } - this._delay = delay; - } + /** + * Set the reconnect delay. If the delay less than or equal to zero it will be the + * default delay time. + * + * @param delay The delay to use + */ + public void setDelay(int delay) { + if (delay <= 0) { + delay = DEFAULT_DELAY; + } + this._delay = delay; + } - public synchronized void connect() { - if (isRequested()) { - return; - } + public synchronized void connect() { + if (isRequested()) { + return; + } - log.debug("Requesting connection"); - notifyStateChange(AutoReconnectState.DISCONNECTED); + log.debug("Requesting connection"); + notifyStateChange(AutoReconnectState.DISCONNECTED); - triggerReconnect(false); - } + triggerReconnect(false); + } - public synchronized void disconnect() { - if (!isRequested()) { - return; - } + public synchronized void disconnect() { + if (!isRequested()) { + return; + } - log.debug("Un-Requesting connection"); + log.debug("Un-Requesting connection"); - notifyStateChange(AutoReconnectState.DISABLED); - this._server.disconnect(); - } + notifyStateChange(AutoReconnectState.DISABLED); + this._server.disconnect(); + } - public boolean isRequested() { - return this._state != AutoReconnectState.DISABLED; - } + public boolean isRequested() { + return this._state != AutoReconnectState.DISABLED; + } - public synchronized void connectionStateChanged(final boolean connected) { - log.debug("Connection state changed: " + connected); + public synchronized void connectionStateChanged(final boolean connected) { + log.debug("Connection state changed: " + connected); - if (!connected) { - if (isRequested()) { - notifyStateChange(AutoReconnectState.DISCONNECTED); - triggerReconnect(true); - } - } - else { - if (!isRequested()) { - this._server.disconnect(); - } - else { - notifyStateChange(AutoReconnectState.CONNECTED); - } - } - } + if (!connected) { + if (isRequested()) { + notifyStateChange(AutoReconnectState.DISCONNECTED); + triggerReconnect(true); + } + } else { + if (!isRequested()) { + this._server.disconnect(); + } else { + notifyStateChange(AutoReconnectState.CONNECTED); + } + } + } - private synchronized void triggerReconnect(final boolean wait) { - if (this._connectTask != null) { - log.info("Connect thread already running"); - return; - } + private synchronized void triggerReconnect(final boolean wait) { + if (this._connectTask != null) { + log.info("Connect thread already running"); + return; + } - log.debug("Trigger reconnect"); + log.debug("Trigger reconnect"); - this._connectTask = new Thread(new Runnable() { + this._connectTask = new Thread(new Runnable() { - public void run() { - boolean result = false; - try { - result = performReconnect(wait); - } - finally { - AutoReconnectController.this._connectTask = null; - log.debug(String.format("performReconnect completed : %s", result)); - if (!result) { - triggerReconnect(true); - } - } - } - }, "OPCReconnectThread"); - this._connectTask.setDaemon(true); - this._connectTask.start(); - } + public void run() { + boolean result = false; + try { + result = performReconnect(wait); + } finally { + AutoReconnectController.this._connectTask = null; + log.debug(String.format("performReconnect completed : %s", result)); + if (!result) { + triggerReconnect(true); + } + } + } + }, "OPCReconnectThread"); + this._connectTask.setDaemon(true); + this._connectTask.start(); + } - private boolean performReconnect(final boolean wait) { - try { - if (wait) { - notifyStateChange(AutoReconnectState.WAITING); - log.debug(String.format("Delaying (%s)...", this._delay)); - Thread.sleep(this._delay); - } - } - catch (InterruptedException e) { - } + private boolean performReconnect(final boolean wait) { + try { + if (wait) { + notifyStateChange(AutoReconnectState.WAITING); + log.debug(String.format("Delaying (%s)...", this._delay)); + Thread.sleep(this._delay); + } + } catch (InterruptedException e) { + } - if (!isRequested()) { - log.debug("Request canceled during delay"); - return true; - } + if (!isRequested()) { + log.debug("Request canceled during delay"); + return true; + } - try { - log.debug("Connecting to server"); - notifyStateChange(AutoReconnectState.CONNECTING); - synchronized (this) { - this._server.connect(); - return true; - } - // CONNECTED state will be set by server callback - } - catch (Throwable e) { - log.info("Re-connect failed", e); - notifyStateChange(AutoReconnectState.DISCONNECTED); - return false; - } - } + try { + log.debug("Connecting to server"); + notifyStateChange(AutoReconnectState.CONNECTING); + synchronized (this) { + this._server.connect(); + return true; + } + // CONNECTED state will be set by server callback + } catch (Throwable e) { + log.info("Re-connect failed", e); + notifyStateChange(AutoReconnectState.DISCONNECTED); + return false; + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectListener.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectListener.java index b66b8d067..3b94519fd 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectListener.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectListener.java @@ -19,6 +19,6 @@ package org.openscada.opc.lib.da; public interface AutoReconnectListener { - public abstract void stateChanged(AutoReconnectState state); + public abstract void stateChanged(AutoReconnectState state); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectState.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectState.java index fc9b464d8..0a55b1589 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectState.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/AutoReconnectState.java @@ -24,27 +24,27 @@ package org.openscada.opc.lib.da; */ public enum AutoReconnectState { - /** - * Auto reconnect is disabled. - */ - DISABLED, - /** - * Auto reconnect is enabled, but the connection is currently not established. - */ - DISCONNECTED, - /** - * Auto reconnect is enabled, the connection is not established and the controller is - * currently waiting the delay until it will reconnect. - */ - WAITING, - /** - * Auto reconnect is enabled, the connection is not established but the controller - * currently tries to establish the connection. - */ - CONNECTING, - /** - * Auto reconnect is enabled and the connection is established. - */ - CONNECTED + /** + * Auto reconnect is disabled. + */ + DISABLED, + /** + * Auto reconnect is enabled, but the connection is currently not established. + */ + DISCONNECTED, + /** + * Auto reconnect is enabled, the connection is not established and the controller is + * currently waiting the delay until it will reconnect. + */ + WAITING, + /** + * Auto reconnect is enabled, the connection is not established but the controller + * currently tries to establish the connection. + */ + CONNECTING, + /** + * Auto reconnect is enabled and the connection is established. + */ + CONNECTED } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DataCallback.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DataCallback.java index a3e2f7e71..8bd93021f 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DataCallback.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DataCallback.java @@ -19,6 +19,6 @@ package org.openscada.opc.lib.da; public interface DataCallback { - void changed(Item item, ItemState itemState); + void changed(Item item, ItemState itemState); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DuplicateGroupException.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DuplicateGroupException.java index 48e01d8d3..23cdecf3f 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DuplicateGroupException.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/DuplicateGroupException.java @@ -19,9 +19,9 @@ package org.openscada.opc.lib.da; public class DuplicateGroupException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ErrorMessageResolver.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ErrorMessageResolver.java index 5492e7464..8e94dd1d0 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ErrorMessageResolver.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ErrorMessageResolver.java @@ -33,39 +33,39 @@ import java.util.Map; @Slf4j public class ErrorMessageResolver { - private final Map _messageCache = new HashMap(); + private final Map _messageCache = new HashMap(); - private OPCCommon _opcCommon = null; + private OPCCommon _opcCommon = null; - private int _localeId = 0; + private int _localeId = 0; - public ErrorMessageResolver(final OPCCommon opcCommon, final int localeId) { - super(); - this._opcCommon = opcCommon; - this._localeId = localeId; - } + public ErrorMessageResolver(final OPCCommon opcCommon, final int localeId) { + super(); + this._opcCommon = opcCommon; + this._localeId = localeId; + } - /** - * Get an error message from an error code - * @param errorCode The error code to look up - * @return the error message or null if no message could be looked up - */ - public synchronized String getMessage(final int errorCode) { - String message = this._messageCache.get(Integer.valueOf(errorCode)); + /** + * Get an error message from an error code + * + * @param errorCode The error code to look up + * @return the error message or null if no message could be looked up + */ + public synchronized String getMessage(final int errorCode) { + String message = this._messageCache.get(Integer.valueOf(errorCode)); - if (message == null) { - try { - message = this._opcCommon.getErrorString(errorCode, this._localeId); - log.info(String.format("Resolved %08X to '%s'", errorCode, message)); - } - catch (JIException e) { - log.warn(String.format("Failed to resolve error code for %08X", errorCode), e); - } - if (message != null) { - this._messageCache.put(errorCode, message); - } - } - return message; - } + if (message == null) { + try { + message = this._opcCommon.getErrorString(errorCode, this._localeId); + log.info(String.format("Resolved %08X to '%s'", errorCode, message)); + } catch (JIException e) { + log.warn(String.format("Failed to resolve error code for %08X", errorCode), e); + } + if (message != null) { + this._messageCache.put(errorCode, message); + } + } + return message; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Group.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Group.java index 817292754..ab49c7813 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Group.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Group.java @@ -32,340 +32,342 @@ import java.util.*; @Slf4j public class Group { - private static Random _random = new Random(); + private static Random _random = new Random(); - private final int _serverHandle; + private final int _serverHandle; - private final Map _itemHandleMap = new HashMap(); + private final Map _itemHandleMap = new HashMap(); - private final Map _itemMap = new HashMap(); + private final Map _itemMap = new HashMap(); - private final Map _itemClientMap = new HashMap(); + private final Map _itemClientMap = new HashMap(); - private Server _server = null; + private Server _server = null; - private OPCGroupStateMgt _group = null; + private OPCGroupStateMgt _group = null; - private OPCItemMgt _items = null; + private OPCItemMgt _items = null; - private OPCSyncIO _syncIO = null; + private OPCSyncIO _syncIO = null; - Group(final Server server, final int serverHandle, final OPCGroupStateMgt group) - throws IllegalArgumentException, UnknownHostException, JIException { - log.debug("Creating new group instance with COM group " + group); - this._server = server; - this._serverHandle = serverHandle; - this._group = group; - this._items = group.getItemManagement(); - this._syncIO = group.getSyncIO(); - } + Group(final Server server, final int serverHandle, final OPCGroupStateMgt group) + throws IllegalArgumentException, UnknownHostException, JIException { + log.debug("Creating new group instance with COM group " + group); + this._server = server; + this._serverHandle = serverHandle; + this._group = group; + this._items = group.getItemManagement(); + this._syncIO = group.getSyncIO(); + } - /** - * remove the group from the server - * @throws JIException JIException - */ - public void remove() throws JIException { - this._server.removeGroup(this, true); - } + /** + * remove the group from the server + * + * @throws JIException JIException + */ + public void remove() throws JIException { + this._server.removeGroup(this, true); + } - public boolean isActive() throws JIException { - return this._group.getState().isActive(); - } + public boolean isActive() throws JIException { + return this._group.getState().isActive(); + } - public void setActive(final boolean state) throws JIException { - this._group.setState(null, state, null, null, null, null); - } + public void setActive(final boolean state) throws JIException { + this._group.setState(null, state, null, null, null, null); + } - /** - * Get the group name from the server - * @return The group name fetched from the server - * @throws JIException JIException - */ - public String getName() throws JIException { - return this._group.getState().getName(); - } + /** + * Get the group name from the server + * + * @return The group name fetched from the server + * @throws JIException JIException + */ + public String getName() throws JIException { + return this._group.getState().getName(); + } - /** - * Change the group name - * @param name the new name of the group - * @throws JIException JIException - */ - public void setName(final String name) throws JIException { - this._group.setName(name); - } + /** + * Change the group name + * + * @param name the new name of the group + * @throws JIException JIException + */ + public void setName(final String name) throws JIException { + this._group.setName(name); + } - /** - * Add a single item. Actually calls {@link #addItems(String[])} with only one - * paraemter - * @param item The item to add - * @return The added item - * @throws JIException The add operation failed - * @throws AddFailedException The item was not added due to an error - */ - public Item addItem(final String item) throws JIException, AddFailedException { - Map items = addItems(item); - return items.get(item); - } + /** + * Add a single item. Actually calls {@link #addItems(String[])} with only one + * paraemter + * + * @param item The item to add + * @return The added item + * @throws JIException The add operation failed + * @throws AddFailedException The item was not added due to an error + */ + public Item addItem(final String item) throws JIException, AddFailedException { + Map items = addItems(item); + return items.get(item); + } - /** - * Validate item ids and get additional information to them.
- * According to the OPC specification you should first validate the items and - * the add them. The spec also says that when a server lets the item pass - * validation it must also let them pass the add operation. - * @param items The items to validate - * @return A result map of item id to result information (including error code). - * @throws JIException JIException - */ - public synchronized Map> validateItems(final String... items) throws JIException { - OPCITEMDEF[] defs = new OPCITEMDEF[items.length]; - for (int i = 0; i < items.length; i++) { - defs[i] = new OPCITEMDEF(); - defs[i].setItemID(items[i]); - } + /** + * Validate item ids and get additional information to them.
+ * According to the OPC specification you should first validate the items and + * the add them. The spec also says that when a server lets the item pass + * validation it must also let them pass the add operation. + * + * @param items The items to validate + * @return A result map of item id to result information (including error code). + * @throws JIException JIException + */ + public synchronized Map> validateItems(final String... items) throws JIException { + OPCITEMDEF[] defs = new OPCITEMDEF[items.length]; + for (int i = 0; i < items.length; i++) { + defs[i] = new OPCITEMDEF(); + defs[i].setItemID(items[i]); + } - KeyedResultSet result = this._items.validate(defs); + KeyedResultSet result = this._items.validate(defs); - Map> resultMap = new HashMap>(); - for (KeyedResult resultEntry : result) { - resultMap.put(resultEntry.getKey().getItemID(), - new Result(resultEntry.getValue(), resultEntry.getErrorCode())); - } + Map> resultMap = new HashMap>(); + for (KeyedResult resultEntry : result) { + resultMap.put(resultEntry.getKey().getItemID(), + new Result(resultEntry.getValue(), resultEntry.getErrorCode())); + } - return resultMap; - } + return resultMap; + } - /** - * Add new items to the group - * @param items The items (by string id) to add - * @return A result map of id to item object - * @throws JIException The add operation completely failed. No item was added. - * @throws AddFailedException If one or more item could not be added. Item without - * error where added. - */ - public synchronized Map addItems(final String... items) throws JIException, AddFailedException { - // Find which items we already have - Map handles = findItems(items); + /** + * Add new items to the group + * + * @param items The items (by string id) to add + * @return A result map of id to item object + * @throws JIException The add operation completely failed. No item was added. + * @throws AddFailedException If one or more item could not be added. Item without + * error where added. + */ + public synchronized Map addItems(final String... items) throws JIException, AddFailedException { + // Find which items we already have + Map handles = findItems(items); - List foundItems = new ArrayList(items.length); - List missingItems = new ArrayList(); + List foundItems = new ArrayList(items.length); + List missingItems = new ArrayList(); - // separate missing items from the found ones - for (Map.Entry entry : handles.entrySet()) { - if (entry.getValue() == null) { - missingItems.add(entry.getKey()); - } - else { - foundItems.add(entry.getValue()); - } - } + // separate missing items from the found ones + for (Map.Entry entry : handles.entrySet()) { + if (entry.getValue() == null) { + missingItems.add(entry.getKey()); + } else { + foundItems.add(entry.getValue()); + } + } - // now fetch missing items from OPC server - Set newClientHandles = new HashSet(); - OPCITEMDEF[] itemDef = new OPCITEMDEF[missingItems.size()]; - for (int i = 0; i < missingItems.size(); i++) { - OPCITEMDEF def = new OPCITEMDEF(); - def.setItemID(missingItems.get(i)); - def.setActive(true); + // now fetch missing items from OPC server + Set newClientHandles = new HashSet(); + OPCITEMDEF[] itemDef = new OPCITEMDEF[missingItems.size()]; + for (int i = 0; i < missingItems.size(); i++) { + OPCITEMDEF def = new OPCITEMDEF(); + def.setItemID(missingItems.get(i)); + def.setActive(true); - Integer clientHandle; - do { - clientHandle = _random.nextInt(); - } - while (this._itemClientMap.containsKey(clientHandle) || newClientHandles.contains(clientHandle)); - newClientHandles.add(clientHandle); - def.setClientHandle(clientHandle); + Integer clientHandle; + do { + clientHandle = _random.nextInt(); + } + while (this._itemClientMap.containsKey(clientHandle) || newClientHandles.contains(clientHandle)); + newClientHandles.add(clientHandle); + def.setClientHandle(clientHandle); - itemDef[i] = def; - } + itemDef[i] = def; + } - // check the result and add new items - Map failedItems = new HashMap(); - KeyedResultSet result = this._items.add(itemDef); - int i = 0; - for (KeyedResult entry : result) { - if (entry.getErrorCode() == 0) { - Item item = new Item(this, entry.getValue().getServerHandle(), itemDef[i].getClientHandle(), - entry.getKey().getItemID()); - addItem(item); - foundItems.add(item.getServerHandle()); - } - else { - failedItems.put(entry.getKey().getItemID(), entry.getErrorCode()); - } - i++; - } + // check the result and add new items + Map failedItems = new HashMap(); + KeyedResultSet result = this._items.add(itemDef); + int i = 0; + for (KeyedResult entry : result) { + if (entry.getErrorCode() == 0) { + Item item = new Item(this, entry.getValue().getServerHandle(), itemDef[i].getClientHandle(), + entry.getKey().getItemID()); + addItem(item); + foundItems.add(item.getServerHandle()); + } else { + failedItems.put(entry.getKey().getItemID(), entry.getErrorCode()); + } + i++; + } - // if we have failed items then throw an exception with the result - if (failedItems.size() != 0) { - throw new AddFailedException(failedItems, findItems(foundItems)); - } + // if we have failed items then throw an exception with the result + if (failedItems.size() != 0) { + throw new AddFailedException(failedItems, findItems(foundItems)); + } - // simply return the result in case of success - return findItems(foundItems); - } + // simply return the result in case of success + return findItems(foundItems); + } - private synchronized void addItem(final Item item) { - log.debug(String.format("Adding item: '%s', %d", item.getId(), item.getServerHandle())); + private synchronized void addItem(final Item item) { + log.debug(String.format("Adding item: '%s', %d", item.getId(), item.getServerHandle())); - this._itemHandleMap.put(item.getId(), item.getServerHandle()); - this._itemMap.put(item.getServerHandle(), item); - this._itemClientMap.put(item.getClientHandle(), item); - } + this._itemHandleMap.put(item.getId(), item.getServerHandle()); + this._itemMap.put(item.getServerHandle(), item); + this._itemClientMap.put(item.getClientHandle(), item); + } - private synchronized void removeItem(final Item item) { - this._itemHandleMap.remove(item.getId()); - this._itemMap.remove(item.getServerHandle()); - this._itemClientMap.remove(item.getClientHandle()); - } + private synchronized void removeItem(final Item item) { + this._itemHandleMap.remove(item.getId()); + this._itemMap.remove(item.getServerHandle()); + this._itemClientMap.remove(item.getClientHandle()); + } - protected Item getItemByOPCItemId(final String opcItemId) { - Integer serverHandle = this._itemHandleMap.get(opcItemId); - if (serverHandle == null) { - log.debug(String.format("Failed to locate item with id '%s'", opcItemId)); - return null; - } - log.debug(String.format("Item '%s' has server id '%d'", opcItemId, serverHandle)); - return this._itemMap.get(serverHandle); - } + protected Item getItemByOPCItemId(final String opcItemId) { + Integer serverHandle = this._itemHandleMap.get(opcItemId); + if (serverHandle == null) { + log.debug(String.format("Failed to locate item with id '%s'", opcItemId)); + return null; + } + log.debug(String.format("Item '%s' has server id '%d'", opcItemId, serverHandle)); + return this._itemMap.get(serverHandle); + } - private synchronized Map findItems(final String[] items) { - Map data = new HashMap(); + private synchronized Map findItems(final String[] items) { + Map data = new HashMap(); - for (int i = 0; i < items.length; i++) { - data.put(items[i], this._itemHandleMap.get(items[i])); - } + for (int i = 0; i < items.length; i++) { + data.put(items[i], this._itemHandleMap.get(items[i])); + } - return data; - } + return data; + } - private synchronized Map findItems(final Collection handles) { - Map itemMap = new HashMap(); - for (Integer i : handles) { - Item item = this._itemMap.get(i); - if (item != null) { - itemMap.put(item.getId(), item); - } - } - return itemMap; - } + private synchronized Map findItems(final Collection handles) { + Map itemMap = new HashMap(); + for (Integer i : handles) { + Item item = this._itemMap.get(i); + if (item != null) { + itemMap.put(item.getId(), item); + } + } + return itemMap; + } - protected void checkItems(final Item[] items) { - for (Item item : items) { - if (item.getGroup() != this) { - throw new IllegalArgumentException("Item doesn't belong to this group"); - } - } - } + protected void checkItems(final Item[] items) { + for (Item item : items) { + if (item.getGroup() != this) { + throw new IllegalArgumentException("Item doesn't belong to this group"); + } + } + } - public void setActive(final boolean state, final Item... items) throws JIException { - checkItems(items); + public void setActive(final boolean state, final Item... items) throws JIException { + checkItems(items); - Integer[] handles = new Integer[items.length]; - for (int i = 0; i < items.length; i++) { - handles[i] = items[i].getServerHandle(); - } + Integer[] handles = new Integer[items.length]; + for (int i = 0; i < items.length; i++) { + handles[i] = items[i].getServerHandle(); + } - this._items.setActiveState(state, handles); - } + this._items.setActiveState(state, handles); + } - protected Integer[] getServerHandles(final Item[] items) { - checkItems(items); + protected Integer[] getServerHandles(final Item[] items) { + checkItems(items); - Integer[] handles = new Integer[items.length]; + Integer[] handles = new Integer[items.length]; - for (int i = 0; i < items.length; i++) { - handles[i] = items[i].getServerHandle(); - } + for (int i = 0; i < items.length; i++) { + handles[i] = items[i].getServerHandle(); + } - return handles; - } + return handles; + } - public synchronized Map write(final WriteRequest... requests) throws JIException { - Item[] items = new Item[requests.length]; + public synchronized Map write(final WriteRequest... requests) throws JIException { + Item[] items = new Item[requests.length]; - for (int i = 0; i < requests.length; i++) { - items[i] = requests[i].getItem(); - } + for (int i = 0; i < requests.length; i++) { + items[i] = requests[i].getItem(); + } - Integer[] handles = getServerHandles(items); + Integer[] handles = getServerHandles(items); - org.openscada.opc.dcom.da.WriteRequest[] wr = new org.openscada.opc.dcom.da.WriteRequest[items.length]; - for (int i = 0; i < items.length; i++) { - wr[i] = new org.openscada.opc.dcom.da.WriteRequest(handles[i], requests[i].getValue()); - } + org.openscada.opc.dcom.da.WriteRequest[] wr = new org.openscada.opc.dcom.da.WriteRequest[items.length]; + for (int i = 0; i < items.length; i++) { + wr[i] = new org.openscada.opc.dcom.da.WriteRequest(handles[i], requests[i].getValue()); + } - ResultSet resultSet = this._syncIO.write(wr); + ResultSet resultSet = this._syncIO.write(wr); - Map result = new HashMap(); - for (int i = 0; i < requests.length; i++) { - Result entry = resultSet.get(i); - result.put(requests[i].getItem(), entry.getErrorCode()); - } + Map result = new HashMap(); + for (int i = 0; i < requests.length; i++) { + Result entry = resultSet.get(i); + result.put(requests[i].getItem(), entry.getErrorCode()); + } - return result; - } + return result; + } - public synchronized Map read(final boolean device, final Item... items) throws JIException { - Integer[] handles = getServerHandles(items); + public synchronized Map read(final boolean device, final Item... items) throws JIException { + Integer[] handles = getServerHandles(items); - KeyedResultSet states = this._syncIO - .read(device ? OPCDATASOURCE.OPC_DS_DEVICE : OPCDATASOURCE.OPC_DS_CACHE, handles); + KeyedResultSet states = this._syncIO + .read(device ? OPCDATASOURCE.OPC_DS_DEVICE : OPCDATASOURCE.OPC_DS_CACHE, handles); - Map data = new HashMap(); - for (KeyedResult entry : states) { - Item item = this._itemMap.get(entry.getKey()); - ItemState state = new ItemState(entry.getErrorCode(), entry.getValue().getValue(), - entry.getValue().getTimestamp().asCalendar(), entry.getValue().getQuality()); - data.put(item, state); - } - return data; - } + Map data = new HashMap(); + for (KeyedResult entry : states) { + Item item = this._itemMap.get(entry.getKey()); + ItemState state = new ItemState(entry.getErrorCode(), entry.getValue().getValue(), + entry.getValue().getTimestamp().asCalendar(), entry.getValue().getQuality()); + data.put(item, state); + } + return data; + } - public Server getServer() { - return this._server; - } + public Server getServer() { + return this._server; + } - public synchronized void clear() throws JIException { - Integer[] handles = this._itemMap.keySet().toArray(new Integer[0]); - try { - this._items.remove(handles); - } - finally { - // in any case clear our maps - this._itemHandleMap.clear(); - this._itemMap.clear(); - this._itemClientMap.clear(); - } - } + public synchronized void clear() throws JIException { + Integer[] handles = this._itemMap.keySet().toArray(new Integer[0]); + try { + this._items.remove(handles); + } finally { + // in any case clear our maps + this._itemHandleMap.clear(); + this._itemMap.clear(); + this._itemClientMap.clear(); + } + } - public synchronized OPCAsyncIO2 getAsyncIO20() { - return this._group.getAsyncIO2(); - } + public synchronized OPCAsyncIO2 getAsyncIO20() { + return this._group.getAsyncIO2(); + } - public synchronized EventHandler attach(final IOPCDataCallback dataCallback) throws JIException { - return this._group.attach(dataCallback); - } + public synchronized EventHandler attach(final IOPCDataCallback dataCallback) throws JIException { + return this._group.attach(dataCallback); + } - public Item findItemByClientHandle(final int clientHandle) { - return this._itemClientMap.get(clientHandle); - } + public Item findItemByClientHandle(final int clientHandle) { + return this._itemClientMap.get(clientHandle); + } - public int getServerHandle() { - return this._serverHandle; - } + public int getServerHandle() { + return this._serverHandle; + } - public synchronized void removeItem(final String opcItemId) - throws IllegalArgumentException, UnknownHostException, JIException { - log.debug(String.format("Removing item '%s'", opcItemId)); - Item item = getItemByOPCItemId(opcItemId); - if (item != null) { - this._group.getItemManagement().remove(item.getServerHandle()); - removeItem(item); - log.debug(String.format("Removed item '%s'", opcItemId)); - } - else { - log.warn(String.format("Unable to find item '%s'", opcItemId)); - } - } + public synchronized void removeItem(final String opcItemId) + throws IllegalArgumentException, UnknownHostException, JIException { + log.debug(String.format("Removing item '%s'", opcItemId)); + Item item = getItemByOPCItemId(opcItemId); + if (item != null) { + this._group.getItemManagement().remove(item.getServerHandle()); + removeItem(item); + log.debug(String.format("Removed item '%s'", opcItemId)); + } else { + log.warn(String.format("Unable to find item '%s'", opcItemId)); + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Item.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Item.java index c2cbd91a0..8c2dab8b0 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Item.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Item.java @@ -24,49 +24,49 @@ import org.jinterop.dcom.core.JIVariant; @Slf4j public class Item { - private Group _group = null; + private Group _group = null; - private int _serverHandle = 0; + private int _serverHandle = 0; - private int _clientHandle = 0; + private int _clientHandle = 0; - private String _id = null; + private String _id = null; - Item(final Group group, final int serverHandle, final int clientHandle, final String id) { - super(); - log.debug(String.format("Adding new item '%s' (0x%08X) for group %s", id, serverHandle, group.toString())); - this._group = group; - this._serverHandle = serverHandle; - this._clientHandle = clientHandle; - this._id = id; - } + Item(final Group group, final int serverHandle, final int clientHandle, final String id) { + super(); + log.debug(String.format("Adding new item '%s' (0x%08X) for group %s", id, serverHandle, group.toString())); + this._group = group; + this._serverHandle = serverHandle; + this._clientHandle = clientHandle; + this._id = id; + } - public Group getGroup() { - return this._group; - } + public Group getGroup() { + return this._group; + } - public int getServerHandle() { - return this._serverHandle; - } + public int getServerHandle() { + return this._serverHandle; + } - public int getClientHandle() { - return this._clientHandle; - } + public int getClientHandle() { + return this._clientHandle; + } - public String getId() { - return this._id; - } + public String getId() { + return this._id; + } - public void setActive(final boolean state) throws JIException { - this._group.setActive(state, this); - } + public void setActive(final boolean state) throws JIException { + this._group.setActive(state, this); + } - public ItemState read(final boolean device) throws JIException { - return this._group.read(device, this).get(this); - } + public ItemState read(final boolean device) throws JIException { + return this._group.read(device, this).get(this); + } - public Integer write(final JIVariant value) throws JIException { - return this._group.write(new WriteRequest[] { new WriteRequest(this, value) }).get(this); - } + public Integer write(final JIVariant value) throws JIException { + return this._group.write(new WriteRequest[]{new WriteRequest(this, value)}).get(this); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ItemState.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ItemState.java index a442f51d7..4136377aa 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ItemState.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ItemState.java @@ -23,115 +23,112 @@ import java.util.Calendar; public class ItemState { - private int _errorCode = 0; + private int _errorCode = 0; - private JIVariant _value = null; + private JIVariant _value = null; - private Calendar _timestamp = null; + private Calendar _timestamp = null; - private Short _quality = null; + private Short _quality = null; - public ItemState(final int errorCode, final JIVariant value, final Calendar timestamp, final Short quality) { - super(); - this._errorCode = errorCode; - this._value = value; - this._timestamp = timestamp; - this._quality = quality; - } + public ItemState(final int errorCode, final JIVariant value, final Calendar timestamp, final Short quality) { + super(); + this._errorCode = errorCode; + this._value = value; + this._timestamp = timestamp; + this._quality = quality; + } - public ItemState() { - super(); - } + public ItemState() { + super(); + } - @Override - public String toString() { - return String.format("Value: %s, Timestamp: %tc, Quality: %s, ErrorCode: %08x", this._value, this._timestamp, - this._quality, this._errorCode); - } + @Override + public String toString() { + return String.format("Value: %s, Timestamp: %tc, Quality: %s, ErrorCode: %08x", this._value, this._timestamp, + this._quality, this._errorCode); + } - public Short getQuality() { - return this._quality; - } + public Short getQuality() { + return this._quality; + } - public void setQuality(final Short quality) { - this._quality = quality; - } + public void setQuality(final Short quality) { + this._quality = quality; + } - public Calendar getTimestamp() { - return this._timestamp; - } + public Calendar getTimestamp() { + return this._timestamp; + } - public void setTimestamp(final Calendar timestamp) { - this._timestamp = timestamp; - } + public void setTimestamp(final Calendar timestamp) { + this._timestamp = timestamp; + } - public JIVariant getValue() { - return this._value; - } + public JIVariant getValue() { + return this._value; + } - public void setValue(final JIVariant value) { - this._value = value; - } + public void setValue(final JIVariant value) { + this._value = value; + } - public int getErrorCode() { - return this._errorCode; - } + public int getErrorCode() { + return this._errorCode; + } - public void setErrorCode(final int errorCode) { - this._errorCode = errorCode; - } + public void setErrorCode(final int errorCode) { + this._errorCode = errorCode; + } - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + this._errorCode; - result = PRIME * result + (this._quality == null ? 0 : this._quality.hashCode()); - result = PRIME * result + (this._timestamp == null ? 0 : this._timestamp.hashCode()); - result = PRIME * result + (this._value == null ? 0 : this._value.hashCode()); - return result; - } + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + this._errorCode; + result = PRIME * result + (this._quality == null ? 0 : this._quality.hashCode()); + result = PRIME * result + (this._timestamp == null ? 0 : this._timestamp.hashCode()); + result = PRIME * result + (this._value == null ? 0 : this._value.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ItemState other = (ItemState) obj; - if (this._errorCode != other._errorCode) { - return false; - } - if (this._quality == null) { - if (other._quality != null) { - return false; - } - } - else if (!this._quality.equals(other._quality)) { - return false; - } - if (this._timestamp == null) { - if (other._timestamp != null) { - return false; - } - } - else if (!this._timestamp.equals(other._timestamp)) { - return false; - } - if (this._value == null) { - if (other._value != null) { - return false; - } - } - else if (!this._value.equals(other._value)) { - return false; - } - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ItemState other = (ItemState) obj; + if (this._errorCode != other._errorCode) { + return false; + } + if (this._quality == null) { + if (other._quality != null) { + return false; + } + } else if (!this._quality.equals(other._quality)) { + return false; + } + if (this._timestamp == null) { + if (other._timestamp != null) { + return false; + } + } else if (!this._timestamp.equals(other._timestamp)) { + return false; + } + if (this._value == null) { + if (other._value != null) { + return false; + } + } else if (!this._value.equals(other._value)) { + return false; + } + return true; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Server.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Server.java index 6dfc42668..9777d23b3 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Server.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/Server.java @@ -45,376 +45,371 @@ import java.util.concurrent.ScheduledExecutorService; @Slf4j public class Server { - private final ConnectionInformation connectionInformation; + private final ConnectionInformation connectionInformation; - private final Map groups = new HashMap<>(16); + private final Map groups = new HashMap<>(16); - private final List stateListeners = new CopyOnWriteArrayList<>(); + private final List stateListeners = new CopyOnWriteArrayList<>(); - private final ScheduledExecutorService scheduler; + private final ScheduledExecutorService scheduler; - private JISession session; + private JISession session; - private JIComServer comServer; + private JIComServer comServer; - private OPCServer server; + private OPCServer server; - private boolean defaultActive = true; + private boolean defaultActive = true; - private int defaultUpdateRate = 1000; + private int defaultUpdateRate = 1000; - private Integer defaultTimeBias; + private Integer defaultTimeBias; - private Float defaultPercentDeadband; + private Float defaultPercentDeadband; - private int defaultLocaleID = 0; + private int defaultLocaleID = 0; - private ErrorMessageResolver errorMessageResolver; + private ErrorMessageResolver errorMessageResolver; - public Server(final ConnectionInformation connectionInformation, final ScheduledExecutorService scheduler) { - super(); - this.connectionInformation = connectionInformation; - this.scheduler = scheduler; - } + public Server(final ConnectionInformation connectionInformation, final ScheduledExecutorService scheduler) { + super(); + this.connectionInformation = connectionInformation; + this.scheduler = scheduler; + } - /** - * Gets the scheduler for the server. Note that this scheduler might get blocked for a - * short time if the connection breaks. It should not be used for time critical - * operations. - * @return the scheduler for the server - */ - public ScheduledExecutorService getScheduler() { - return this.scheduler; - } + /** + * Gets the scheduler for the server. Note that this scheduler might get blocked for a + * short time if the connection breaks. It should not be used for time critical + * operations. + * + * @return the scheduler for the server + */ + public ScheduledExecutorService getScheduler() { + return this.scheduler; + } - protected synchronized boolean isConnected() { - return this.session != null; - } + protected synchronized boolean isConnected() { + return this.session != null; + } - public synchronized void connect() - throws IllegalArgumentException, UnknownHostException, JIException, AlreadyConnectedException { - if (isConnected()) { - throw new AlreadyConnectedException(); - } + public synchronized void connect() + throws IllegalArgumentException, UnknownHostException, JIException, AlreadyConnectedException { + if (isConnected()) { + throw new AlreadyConnectedException(); + } - final int socketTimeout = Integer.getInteger("rpc.socketTimeout", 0); - log.debug(String.format("Socket timeout: %s ", socketTimeout)); + final int socketTimeout = Integer.getInteger("rpc.socketTimeout", 0); + log.debug(String.format("Socket timeout: %s ", socketTimeout)); - try { - if (this.connectionInformation.getClsid() != null) { - this.session = JISession.createSession(this.connectionInformation.getDomain(), - this.connectionInformation.getUser(), this.connectionInformation.getPassword()); - this.session.setGlobalSocketTimeout(socketTimeout); - this.session.useSessionSecurity(true); - this.comServer = new JIComServer(JIClsid.valueOf(this.connectionInformation.getClsid()), - this.connectionInformation.getHost(), this.session); - } - else if (this.connectionInformation.getProgId() != null) { - this.session = JISession.createSession(this.connectionInformation.getDomain(), - this.connectionInformation.getUser(), this.connectionInformation.getPassword()); - this.session.setGlobalSocketTimeout(socketTimeout); - this.comServer = new JIComServer(JIProgId.valueOf(this.connectionInformation.getProgId()), - this.connectionInformation.getHost(), this.session); - } - else { - throw new IllegalArgumentException("Neither clsid nor progid is valid!"); - } + try { + if (this.connectionInformation.getClsid() != null) { + this.session = JISession.createSession(this.connectionInformation.getDomain(), + this.connectionInformation.getUser(), this.connectionInformation.getPassword()); + this.session.setGlobalSocketTimeout(socketTimeout); + this.session.useSessionSecurity(true); + this.comServer = new JIComServer(JIClsid.valueOf(this.connectionInformation.getClsid()), + this.connectionInformation.getHost(), this.session); + } else if (this.connectionInformation.getProgId() != null) { + this.session = JISession.createSession(this.connectionInformation.getDomain(), + this.connectionInformation.getUser(), this.connectionInformation.getPassword()); + this.session.setGlobalSocketTimeout(socketTimeout); + this.comServer = new JIComServer(JIProgId.valueOf(this.connectionInformation.getProgId()), + this.connectionInformation.getHost(), this.session); + } else { + throw new IllegalArgumentException("Neither clsid nor progid is valid!"); + } - this.server = new OPCServer(this.comServer.createInstance()); - this.errorMessageResolver = new ErrorMessageResolver(this.server.getCommon(), this.defaultLocaleID); - } - catch (final UnknownHostException e) { - log.error("Unknown host when connecting to server", e); - cleanup(); - throw e; - } - catch (final JIException e) { - log.error("Failed to connect to server", e); - cleanup(); - throw e; - } - catch (final Throwable e) { - log.error("Unknown error", e); - cleanup(); - throw new RuntimeException(e); - } + this.server = new OPCServer(this.comServer.createInstance()); + this.errorMessageResolver = new ErrorMessageResolver(this.server.getCommon(), this.defaultLocaleID); + } catch (final UnknownHostException e) { + log.error("Unknown host when connecting to server", e); + cleanup(); + throw e; + } catch (final JIException e) { + log.error("Failed to connect to server", e); + cleanup(); + throw e; + } catch (final Throwable e) { + log.error("Unknown error", e); + cleanup(); + throw new RuntimeException(e); + } - notifyConnectionStateChange(true); - } + notifyConnectionStateChange(true); + } - /** - * cleanup after the connection is closed - */ - protected void cleanup() { - log.debug("Destroying DCOM session..."); - final JISession destructSession = this.session; - final Thread destructor = new Thread(new Runnable() { + /** + * cleanup after the connection is closed + */ + protected void cleanup() { + log.debug("Destroying DCOM session..."); + final JISession destructSession = this.session; + final Thread destructor = new Thread(new Runnable() { - public void run() { - final long ts = System.currentTimeMillis(); - try { - log.debug("Starting destruction of DCOM session"); - JISession.destroySession(destructSession); - log.debug("Destructed DCOM session"); - } - catch (final Throwable e) { - log.error("Failed to destruct DCOM session", e); - } - } - }, "UtgardSessionDestructor"); - destructor.setName("OPCSessionDestructor"); - destructor.setDaemon(true); - destructor.start(); - log.debug("Destroying DCOM session... forked"); + public void run() { + final long ts = System.currentTimeMillis(); + try { + log.debug("Starting destruction of DCOM session"); + JISession.destroySession(destructSession); + log.debug("Destructed DCOM session"); + } catch (final Throwable e) { + log.error("Failed to destruct DCOM session", e); + } + } + }, "UtgardSessionDestructor"); + destructor.setName("OPCSessionDestructor"); + destructor.setDaemon(true); + destructor.start(); + log.debug("Destroying DCOM session... forked"); - this.errorMessageResolver = null; - this.session = null; - this.comServer = null; - this.server = null; + this.errorMessageResolver = null; + this.session = null; + this.comServer = null; + this.server = null; - this.groups.clear(); - } + this.groups.clear(); + } - /** - * Disconnect the connection if it is connected - */ - public synchronized void disconnect() { - if (!isConnected()) { - return; - } + /** + * Disconnect the connection if it is connected + */ + public synchronized void disconnect() { + if (!isConnected()) { + return; + } - try { - notifyConnectionStateChange(false); - } - catch (final Throwable t) { - } + try { + notifyConnectionStateChange(false); + } catch (final Throwable t) { + } - cleanup(); - } + cleanup(); + } - /** - * Dispose the connection in the case of an error - */ - public void dispose() { - disconnect(); - } + /** + * Dispose the connection in the case of an error + */ + public void dispose() { + disconnect(); + } - protected synchronized Group getGroup(final OPCGroupStateMgt groupMgt) - throws JIException, IllegalArgumentException, UnknownHostException { - final Integer serverHandle = groupMgt.getState().getServerHandle(); - if (this.groups.containsKey(serverHandle)) { - return this.groups.get(serverHandle); - } - else { - final Group group = new Group(this, serverHandle, groupMgt); - this.groups.put(serverHandle, group); - return group; - } - } + protected synchronized Group getGroup(final OPCGroupStateMgt groupMgt) + throws JIException, IllegalArgumentException, UnknownHostException { + final Integer serverHandle = groupMgt.getState().getServerHandle(); + if (this.groups.containsKey(serverHandle)) { + return this.groups.get(serverHandle); + } else { + final Group group = new Group(this, serverHandle, groupMgt); + this.groups.put(serverHandle, group); + return group; + } + } - /** - * Add a new named group to the server - * @param name The name of the group to use. Must be unique or null so - * that the server creates a unique name. - * @return The new group - * @throws NotConnectedException If the server is not connected using - * {@link Server#connect()} - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - * @throws DuplicateGroupException If a group with this name already exists - */ - public synchronized Group addGroup(final String name) throws NotConnectedException, IllegalArgumentException, - UnknownHostException, JIException, DuplicateGroupException { - if (!isConnected()) { - throw new NotConnectedException(); - } + /** + * Add a new named group to the server + * + * @param name The name of the group to use. Must be unique or null so + * that the server creates a unique name. + * @return The new group + * @throws NotConnectedException If the server is not connected using + * {@link Server#connect()} + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + * @throws DuplicateGroupException If a group with this name already exists + */ + public synchronized Group addGroup(final String name) throws NotConnectedException, IllegalArgumentException, + UnknownHostException, JIException, DuplicateGroupException { + if (!isConnected()) { + throw new NotConnectedException(); + } - try { - final OPCGroupStateMgt groupMgt = this.server.addGroup(name, this.defaultActive, this.defaultUpdateRate, 0, - this.defaultTimeBias, this.defaultPercentDeadband, this.defaultLocaleID); - return getGroup(groupMgt); - } - catch (final JIException e) { - if (e.getErrorCode() == 0xC004000C) { - throw new DuplicateGroupException(); - } - throw e; - } - } + try { + final OPCGroupStateMgt groupMgt = this.server.addGroup(name, this.defaultActive, this.defaultUpdateRate, 0, + this.defaultTimeBias, this.defaultPercentDeadband, this.defaultLocaleID); + return getGroup(groupMgt); + } catch (final JIException e) { + if (e.getErrorCode() == 0xC004000C) { + throw new DuplicateGroupException(); + } + throw e; + } + } - /** - * Add a new group and let the server generate a group name - *

- * Actually this method only calls {@link Server#addGroup(String)} with - * null as parameter. - * @return the new group - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws NotConnectedException NotConnectedException - * @throws JIException JIException - * @throws DuplicateGroupException DuplicateGroupException - */ - public Group addGroup() throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, - DuplicateGroupException { - return addGroup(null); - } + /** + * Add a new group and let the server generate a group name + *

+ * Actually this method only calls {@link Server#addGroup(String)} with + * null as parameter. + * + * @return the new group + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws NotConnectedException NotConnectedException + * @throws JIException JIException + * @throws DuplicateGroupException DuplicateGroupException + */ + public Group addGroup() throws IllegalArgumentException, UnknownHostException, NotConnectedException, JIException, + DuplicateGroupException { + return addGroup(null); + } - /** - * Find a group by its name - * @param name The name to look for - * @return The group - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - * @throws UnknownGroupException If the group was not found - * @throws NotConnectedException If the server is not connected - */ - public Group findGroup(final String name) throws IllegalArgumentException, UnknownHostException, JIException, - UnknownGroupException, NotConnectedException { - if (!isConnected()) { - throw new NotConnectedException(); - } + /** + * Find a group by its name + * + * @param name The name to look for + * @return The group + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + * @throws UnknownGroupException If the group was not found + * @throws NotConnectedException If the server is not connected + */ + public Group findGroup(final String name) throws IllegalArgumentException, UnknownHostException, JIException, + UnknownGroupException, NotConnectedException { + if (!isConnected()) { + throw new NotConnectedException(); + } - try { - final OPCGroupStateMgt groupMgt = this.server.getGroupByName(name); - return getGroup(groupMgt); - } - catch (final JIException e) { - switch (e.getErrorCode()) { - case 0x80070057: - throw new UnknownGroupException(name); - default: - throw e; - } - } - } + try { + final OPCGroupStateMgt groupMgt = this.server.getGroupByName(name); + return getGroup(groupMgt); + } catch (final JIException e) { + switch (e.getErrorCode()) { + case 0x80070057: + throw new UnknownGroupException(name); + default: + throw e; + } + } + } - public int getDefaultLocaleID() { - return this.defaultLocaleID; - } + public int getDefaultLocaleID() { + return this.defaultLocaleID; + } - public void setDefaultLocaleID(final int defaultLocaleID) { - this.defaultLocaleID = defaultLocaleID; - } + public void setDefaultLocaleID(final int defaultLocaleID) { + this.defaultLocaleID = defaultLocaleID; + } - public Float getDefaultPercentDeadband() { - return this.defaultPercentDeadband; - } + public Float getDefaultPercentDeadband() { + return this.defaultPercentDeadband; + } - public void setDefaultPercentDeadband(final Float defaultPercentDeadband) { - this.defaultPercentDeadband = defaultPercentDeadband; - } + public void setDefaultPercentDeadband(final Float defaultPercentDeadband) { + this.defaultPercentDeadband = defaultPercentDeadband; + } - public Integer getDefaultTimeBias() { - return this.defaultTimeBias; - } + public Integer getDefaultTimeBias() { + return this.defaultTimeBias; + } - public void setDefaultTimeBias(final Integer defaultTimeBias) { - this.defaultTimeBias = defaultTimeBias; - } + public void setDefaultTimeBias(final Integer defaultTimeBias) { + this.defaultTimeBias = defaultTimeBias; + } - public int getDefaultUpdateRate() { - return this.defaultUpdateRate; - } + public int getDefaultUpdateRate() { + return this.defaultUpdateRate; + } - public void setDefaultUpdateRate(final int defaultUpdateRate) { - this.defaultUpdateRate = defaultUpdateRate; - } + public void setDefaultUpdateRate(final int defaultUpdateRate) { + this.defaultUpdateRate = defaultUpdateRate; + } - public boolean isDefaultActive() { - return this.defaultActive; - } + public boolean isDefaultActive() { + return this.defaultActive; + } - public void setDefaultActive(final boolean defaultActive) { - this.defaultActive = defaultActive; - } + public void setDefaultActive(final boolean defaultActive) { + this.defaultActive = defaultActive; + } - /** - * Get the flat browser - * @return The flat browser or null if the functionality is not supported - */ - public FlatBrowser getFlatBrowser() { - final OPCBrowseServerAddressSpace browser = this.server.getBrowser(); - if (browser == null) { - return null; - } + /** + * Get the flat browser + * + * @return The flat browser or null if the functionality is not supported + */ + public FlatBrowser getFlatBrowser() { + final OPCBrowseServerAddressSpace browser = this.server.getBrowser(); + if (browser == null) { + return null; + } - return new FlatBrowser(browser); - } + return new FlatBrowser(browser); + } - /** - * Get the tree browser - * @return The tree browser or null if the functionality is not supported - * @throws JIException JIException - */ - public TreeBrowser getTreeBrowser() throws JIException { - final OPCBrowseServerAddressSpace browser = this.server.getBrowser(); - if (browser == null) { - return null; - } + /** + * Get the tree browser + * + * @return The tree browser or null if the functionality is not supported + * @throws JIException JIException + */ + public TreeBrowser getTreeBrowser() throws JIException { + final OPCBrowseServerAddressSpace browser = this.server.getBrowser(); + if (browser == null) { + return null; + } - if (browser.queryOrganization() != OPCNAMESPACETYPE.OPC_NS_HIERARCHIAL) { - return null; - } + if (browser.queryOrganization() != OPCNAMESPACETYPE.OPC_NS_HIERARCHIAL) { + return null; + } - return new TreeBrowser(browser); - } + return new TreeBrowser(browser); + } - public synchronized String getErrorMessage(final int errorCode) { - if (this.errorMessageResolver == null) { - return String.format("Unknown error (%08X)", errorCode); - } + public synchronized String getErrorMessage(final int errorCode) { + if (this.errorMessageResolver == null) { + return String.format("Unknown error (%08X)", errorCode); + } - // resolve message - final String message = this.errorMessageResolver.getMessage(errorCode); + // resolve message + final String message = this.errorMessageResolver.getMessage(errorCode); - // and return if successfull - if (message != null) { - return message; - } + // and return if successfull + if (message != null) { + return message; + } - // return default message - return String.format("Unknown error (%08X)", errorCode); - } + // return default message + return String.format("Unknown error (%08X)", errorCode); + } - public synchronized void addStateListener(final ServerConnectionStateListener listener) { - this.stateListeners.add(listener); - listener.connectionStateChanged(isConnected()); - } + public synchronized void addStateListener(final ServerConnectionStateListener listener) { + this.stateListeners.add(listener); + listener.connectionStateChanged(isConnected()); + } - public synchronized void removeStateListener(final ServerConnectionStateListener listener) { - this.stateListeners.remove(listener); - } + public synchronized void removeStateListener(final ServerConnectionStateListener listener) { + this.stateListeners.remove(listener); + } - protected void notifyConnectionStateChange(final boolean connected) { - final List list = new ArrayList( - this.stateListeners); - for (final ServerConnectionStateListener listener : list) { - listener.connectionStateChanged(connected); - } - } + protected void notifyConnectionStateChange(final boolean connected) { + final List list = new ArrayList( + this.stateListeners); + for (final ServerConnectionStateListener listener : list) { + listener.connectionStateChanged(connected); + } + } - public OPCSERVERSTATUS getServerState(final int timeout) throws Throwable { - return new ServerStateOperation(this.server).getServerState(timeout); - } + public OPCSERVERSTATUS getServerState(final int timeout) throws Throwable { + return new ServerStateOperation(this.server).getServerState(timeout); + } - public OPCSERVERSTATUS getServerState() { - try { - return getServerState(2500); - } - catch (final Throwable e) { - log.error("Server connection failed", e); - dispose(); - return null; - } - } + public OPCSERVERSTATUS getServerState() { + try { + return getServerState(2500); + } catch (final Throwable e) { + log.error("Server connection failed", e); + dispose(); + return null; + } + } - public void removeGroup(final Group group, final boolean force) throws JIException { - if (this.groups.containsKey(group.getServerHandle())) { - this.server.removeGroup(group.getServerHandle(), force); - this.groups.remove(group.getServerHandle()); - } - } + public void removeGroup(final Group group, final boolean force) throws JIException { + if (this.groups.containsKey(group.getServerHandle())) { + this.server.removeGroup(group.getServerHandle(), force); + this.groups.remove(group.getServerHandle()); + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerConnectionStateListener.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerConnectionStateListener.java index a169816ee..15303c2ab 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerConnectionStateListener.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerConnectionStateListener.java @@ -19,6 +19,6 @@ package org.openscada.opc.lib.da; public interface ServerConnectionStateListener { - public abstract void connectionStateChanged(boolean connected); + public abstract void connectionStateChanged(boolean connected); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateListener.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateListener.java index fb16e7b4a..e631d3970 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateListener.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateListener.java @@ -21,6 +21,6 @@ import org.openscada.opc.dcom.da.OPCSERVERSTATUS; public interface ServerStateListener { - public void stateUpdate(OPCSERVERSTATUS state); + public void stateUpdate(OPCSERVERSTATUS state); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateOperation.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateOperation.java index bce22d038..c852df2c2 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateOperation.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateOperation.java @@ -29,79 +29,79 @@ import org.openscada.opc.dcom.da.impl.OPCServer; @Slf4j public class ServerStateOperation implements Runnable { - public OPCSERVERSTATUS _serverStatus = null; + public OPCSERVERSTATUS _serverStatus = null; - public OPCServer _server; + public OPCServer _server; - public Throwable _error; + public Throwable _error; - public Object _lock = new Object(); + public Object _lock = new Object(); - public boolean _running = false; + public boolean _running = false; - public ServerStateOperation(final OPCServer server) { - super(); - this._server = server; - } + public ServerStateOperation(final OPCServer server) { + super(); + this._server = server; + } - /** - * Perform the operation. - *

- * This method will block until either the serve state has been aquired or the timeout - * triggers cancels the call. - *

- */ - public void run() { - synchronized (this._lock) { - this._running = true; - } - try { - this._serverStatus = this._server.getStatus(); - synchronized (this._lock) { - this._running = false; - this._lock.notify(); - } - } - catch (Throwable e) { - log.info("Failed to get server state", e); - this._error = e; - this._running = false; - synchronized (this._lock) { - this._lock.notify(); - } - } + /** + * Perform the operation. + *

+ * This method will block until either the serve state has been aquired or the timeout + * triggers cancels the call. + *

+ */ + public void run() { + synchronized (this._lock) { + this._running = true; + } + try { + this._serverStatus = this._server.getStatus(); + synchronized (this._lock) { + this._running = false; + this._lock.notify(); + } + } catch (Throwable e) { + log.info("Failed to get server state", e); + this._error = e; + this._running = false; + synchronized (this._lock) { + this._lock.notify(); + } + } - } + } - /** - * Get the server state with a timeout. - * @param timeout the timeout in ms - * @return the server state or null if the server is not set. - * @throws Throwable any error that occurred - */ - public OPCSERVERSTATUS getServerState(final int timeout) throws Throwable { - if (this._server == null) { - log.debug("No connection to server. Skipping..."); - return null; - } + /** + * Get the server state with a timeout. + * + * @param timeout the timeout in ms + * @return the server state or null if the server is not set. + * @throws Throwable any error that occurred + */ + public OPCSERVERSTATUS getServerState(final int timeout) throws Throwable { + if (this._server == null) { + log.debug("No connection to server. Skipping..."); + return null; + } - Thread t = new Thread(this, "OPCServerStateReader"); + Thread t = new Thread(this, "OPCServerStateReader"); - synchronized (this._lock) { - t.start(); - this._lock.wait(timeout); - if (this._running) { - log.warn("State operation still running. Interrupting..."); - t.interrupt(); - throw new InterruptedException("Interrupted getting server state"); - } - } - if (this._error != null) { - log.warn("An error occurred while getting server state", this._error); - throw this._error; - } + synchronized (this._lock) { + t.start(); + this._lock.wait(timeout); + if (this._running) { + log.warn("State operation still running. Interrupting..."); + t.interrupt(); + throw new InterruptedException("Interrupted getting server state"); + } + } + if (this._error != null) { + log.warn("An error occurred while getting server state", this._error); + throw this._error; + } - return this._serverStatus; - } + return this._serverStatus; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateReader.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateReader.java index 4f4c86f1a..346cb462c 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateReader.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/ServerStateReader.java @@ -30,66 +30,67 @@ import java.util.concurrent.TimeUnit; @Slf4j public class ServerStateReader { - private final List _listeners = new CopyOnWriteArrayList(); + private final List _listeners = new CopyOnWriteArrayList(); - private Server _server = null; + private Server _server = null; - private ScheduledExecutorService _scheduler = null; + private ScheduledExecutorService _scheduler = null; - private ScheduledFuture _job = null; + private ScheduledFuture _job = null; - public ServerStateReader(final Server server) { - super(); - this._server = server; - this._scheduler = this._server.getScheduler(); - } + public ServerStateReader(final Server server) { + super(); + this._server = server; + this._scheduler = this._server.getScheduler(); + } - /** - * Create a new server state reader. Please note that the scheduler might get blocked - * for a short period of time in case of a connection failure! - * @param server the server to check - * @param scheduler the scheduler to use - */ - public ServerStateReader(final Server server, final ScheduledExecutorService scheduler) { - super(); - this._server = server; - this._scheduler = scheduler; - } + /** + * Create a new server state reader. Please note that the scheduler might get blocked + * for a short period of time in case of a connection failure! + * + * @param server the server to check + * @param scheduler the scheduler to use + */ + public ServerStateReader(final Server server, final ScheduledExecutorService scheduler) { + super(); + this._server = server; + this._scheduler = scheduler; + } - public synchronized void start() { - if (this._job != null) { - return; - } + public synchronized void start() { + if (this._job != null) { + return; + } - this._job = this._scheduler.scheduleAtFixedRate(new Runnable() { + this._job = this._scheduler.scheduleAtFixedRate(new Runnable() { - public void run() { - once(); - } - }, 1000, 1000, TimeUnit.MILLISECONDS); - } + public void run() { + once(); + } + }, 1000, 1000, TimeUnit.MILLISECONDS); + } - public synchronized void stop() { - this._job.cancel(false); - this._job = null; - } + public synchronized void stop() { + this._job.cancel(false); + this._job = null; + } - protected void once() { - log.debug("Reading server state"); + protected void once() { + log.debug("Reading server state"); - final OPCSERVERSTATUS state = this._server.getServerState(); + final OPCSERVERSTATUS state = this._server.getServerState(); - for (final ServerStateListener listener : new ArrayList(this._listeners)) { - listener.stateUpdate(state); - } - } + for (final ServerStateListener listener : new ArrayList(this._listeners)) { + listener.stateUpdate(state); + } + } - public void addListener(final ServerStateListener listener) { - this._listeners.add(listener); - } + public void addListener(final ServerStateListener listener) { + this._listeners.add(listener); + } - public void removeListener(final ServerStateListener listener) { - this._listeners.remove(listener); - } + public void removeListener(final ServerStateListener listener) { + this._listeners.remove(listener); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/SyncAccess.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/SyncAccess.java index f39cd0101..fc058d391 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/SyncAccess.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/SyncAccess.java @@ -27,79 +27,77 @@ import java.util.Map; @Slf4j public class SyncAccess extends AccessBase implements Runnable { - private Thread runner = null; + private Thread runner = null; - private Throwable lastError = null; + private Throwable lastError = null; - public SyncAccess(final Server server, final int period) throws IllegalArgumentException, UnknownHostException, - NotConnectedException, JIException, DuplicateGroupException { - super(server, period); - } + public SyncAccess(final Server server, final int period) throws IllegalArgumentException, UnknownHostException, + NotConnectedException, JIException, DuplicateGroupException { + super(server, period); + } - public SyncAccess(final Server server, final int period, final String logTag) throws IllegalArgumentException, - UnknownHostException, NotConnectedException, JIException, DuplicateGroupException { - super(server, period, logTag); - } + public SyncAccess(final Server server, final int period, final String logTag) throws IllegalArgumentException, + UnknownHostException, NotConnectedException, JIException, DuplicateGroupException { + super(server, period, logTag); + } - public void run() { - while (this.active) { - try { - runOnce(); - if (this.lastError != null) { - this.lastError = null; - handleError(null); - } - } - catch (Throwable e) { - log.error("Sync read failed", e); - handleError(e); - this.server.disconnect(); - } + public void run() { + while (this.active) { + try { + runOnce(); + if (this.lastError != null) { + this.lastError = null; + handleError(null); + } + } catch (Throwable e) { + log.error("Sync read failed", e); + handleError(e); + this.server.disconnect(); + } - try { - Thread.sleep(getPeriod()); - } - catch (InterruptedException e) { - } - } - } + try { + Thread.sleep(getPeriod()); + } catch (InterruptedException e) { + } + } + } - protected void runOnce() throws JIException { - if (!this.active || this.group == null) { - return; - } + protected void runOnce() throws JIException { + if (!this.active || this.group == null) { + return; + } - Map result; + Map result; - // lock only this section since we could get into a deadlock otherwise - // calling updateItem - synchronized (this) { - Item[] items = this.items.keySet().toArray(new Item[this.items.size()]); - result = this.group.read(false, items); - } + // lock only this section since we could get into a deadlock otherwise + // calling updateItem + synchronized (this) { + Item[] items = this.items.keySet().toArray(new Item[this.items.size()]); + result = this.group.read(false, items); + } - for (Map.Entry entry : result.entrySet()) { - updateItem(entry.getKey(), entry.getValue()); - } + for (Map.Entry entry : result.entrySet()) { + updateItem(entry.getKey(), entry.getValue()); + } - } + } - @Override - protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, - NotConnectedException, DuplicateGroupException { - super.start(); + @Override + protected synchronized void start() throws JIException, IllegalArgumentException, UnknownHostException, + NotConnectedException, DuplicateGroupException { + super.start(); - this.runner = new Thread(this, "UtgardSyncReader"); - this.runner.setDaemon(true); - this.runner.start(); - } + this.runner = new Thread(this, "UtgardSyncReader"); + this.runner.setDaemon(true); + this.runner.start(); + } - @Override - protected synchronized void stop() throws JIException { - super.stop(); + @Override + protected synchronized void stop() throws JIException { + super.stop(); - this.runner = null; - this.items.clear(); - } + this.runner = null; + this.items.clear(); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/UnknownGroupException.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/UnknownGroupException.java index edab65998..d1bdf53e1 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/UnknownGroupException.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/UnknownGroupException.java @@ -19,24 +19,24 @@ package org.openscada.opc.lib.da; public class UnknownGroupException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - private String _name = null; + private String _name = null; - public UnknownGroupException(final String name) { - super(); - this._name = name; - } + public UnknownGroupException(final String name) { + super(); + this._name = name; + } - public String getName() { - return this._name; - } + public String getName() { + return this._name; + } - public void setName(final String name) { - this._name = name; - } + public void setName(final String name) { + this._name = name; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/WriteRequest.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/WriteRequest.java index 1dc3ddb68..dc62c724a 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/WriteRequest.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/WriteRequest.java @@ -21,22 +21,22 @@ import org.jinterop.dcom.core.JIVariant; public class WriteRequest { - private Item _item = null; + private Item _item = null; - private JIVariant _value = null; + private JIVariant _value = null; - public WriteRequest(final Item item, final JIVariant value) { - super(); - this._item = item; - this._value = value; - } + public WriteRequest(final Item item, final JIVariant value) { + super(); + this._item = item; + this._value = value; + } - public Item getItem() { - return this._item; - } + public Item getItem() { + return this._item; + } - public JIVariant getValue() { - return this._value; - } + public JIVariant getValue() { + return this._value; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Access.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Access.java index 8e8705fab..c02bf461f 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Access.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Access.java @@ -19,16 +19,16 @@ package org.openscada.opc.lib.da.browser; public enum Access { - READ(1), WRITE(2); + READ(1), WRITE(2); - private int _code = 0; + private int _code = 0; - private Access(final int code) { - this._code = code; - } + private Access(final int code) { + this._code = code; + } - public int getCode() { - return this._code; - } + public int getCode() { + return this._code; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/BaseBrowser.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/BaseBrowser.java index 45e7eab7a..5b9530e49 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/BaseBrowser.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/BaseBrowser.java @@ -35,82 +35,86 @@ import java.util.EnumSet; @Slf4j public class BaseBrowser { - protected OPCBrowseServerAddressSpace _browser; + protected OPCBrowseServerAddressSpace _browser; - /** - * The batch size is the number of entries that will be requested with one call from - * the server. Sometimes too big batch sizes will cause an exception. And smaller - * batch sizes degrade perfomance. The default is set by - * {@link EnumString#DEFAULT_BATCH_SIZE} and can be overridden by the java property - * openscada.dcom.enum-batch-size. - */ - protected int _batchSize; + /** + * The batch size is the number of entries that will be requested with one call from + * the server. Sometimes too big batch sizes will cause an exception. And smaller + * batch sizes degrade perfomance. The default is set by + * {@link EnumString#DEFAULT_BATCH_SIZE} and can be overridden by the java property + * openscada.dcom.enum-batch-size. + */ + protected int _batchSize; - public BaseBrowser(final OPCBrowseServerAddressSpace browser) { - this(browser, EnumString.DEFAULT_BATCH_SIZE); - } + public BaseBrowser(final OPCBrowseServerAddressSpace browser) { + this(browser, EnumString.DEFAULT_BATCH_SIZE); + } - public BaseBrowser(final OPCBrowseServerAddressSpace browser, final int batchSize) { - super(); - this._browser = browser; - this._batchSize = batchSize; - } + public BaseBrowser(final OPCBrowseServerAddressSpace browser, final int batchSize) { + super(); + this._browser = browser; + this._batchSize = batchSize; + } - /** - * Get the batch size - * @return the current batch size - */ - public int getBatchSize() { - return this._batchSize; - } + /** + * Get the batch size + * + * @return the current batch size + */ + public int getBatchSize() { + return this._batchSize; + } - /** - * Set the batch size - * @param batchSize The new batch size - */ - public void setBatchSize(final int batchSize) { - this._batchSize = batchSize; - } + /** + * Set the batch size + * + * @param batchSize The new batch size + */ + public void setBatchSize(final int batchSize) { + this._batchSize = batchSize; + } - /** - * Perform the browse operation. - * @param type OPCBROWSETYPE - * @param filterCriteria Filter Criteria - * @param accessMask Access Mask - * @param variantType Variant Type - * @return The browse result - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - protected Collection browse(final OPCBROWSETYPE type, final String filterCriteria, - final EnumSet accessMask, final int variantType) - throws IllegalArgumentException, UnknownHostException, JIException { - int accessMaskValue = 0; + /** + * Perform the browse operation. + * + * @param type OPCBROWSETYPE + * @param filterCriteria Filter Criteria + * @param accessMask Access Mask + * @param variantType Variant Type + * @return The browse result + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + protected Collection browse(final OPCBROWSETYPE type, final String filterCriteria, + final EnumSet accessMask, final int variantType) + throws IllegalArgumentException, UnknownHostException, JIException { + int accessMaskValue = 0; - if (accessMask.contains(Access.READ)) { - accessMaskValue |= Access.READ.getCode(); - } - if (accessMask.contains(Access.WRITE)) { - accessMaskValue |= Access.WRITE.getCode(); - } + if (accessMask.contains(Access.READ)) { + accessMaskValue |= Access.READ.getCode(); + } + if (accessMask.contains(Access.WRITE)) { + accessMaskValue |= Access.WRITE.getCode(); + } - log.debug("Browsing with a batch size of " + this._batchSize); + log.debug("Browsing with a batch size of " + this._batchSize); - return this._browser.browse(type, filterCriteria, accessMaskValue, variantType).asCollection(this._batchSize); - } + return this._browser.browse(type, filterCriteria, accessMaskValue, variantType).asCollection(this._batchSize); + } - /** - * Browse the access paths for one item. - * @param itemId The item ID to look up the access paths - * @return The collection of the access paths - * @throws JIException JIException - * @throws UnknownHostException UnknownHostException - * @throws IllegalArgumentException IllegalArgumentException - */ - public Collection getAccessPaths(final String itemId) - throws IllegalArgumentException, UnknownHostException, JIException { - return this._browser.browseAccessPaths(itemId).asCollection(this._batchSize); - } + /** + * Browse the access paths for one item. + * + * @param itemId The item ID to look up the access paths + * @return The collection of the access paths + * @throws JIException JIException + * @throws UnknownHostException UnknownHostException + * @throws IllegalArgumentException IllegalArgumentException + */ + public Collection getAccessPaths(final String itemId) + throws IllegalArgumentException, UnknownHostException, JIException { + return this._browser.browseAccessPaths(itemId).asCollection(this._batchSize); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Branch.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Branch.java index 6ce1cd9cc..9ddb94067 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Branch.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Branch.java @@ -23,87 +23,91 @@ import java.util.LinkedList; public class Branch { - private Branch _parent = null; + private Branch _parent = null; - private String _name = null; + private String _name = null; - private Collection _branches = new LinkedList(); + private Collection _branches = new LinkedList(); - private Collection _leaves = new LinkedList(); + private Collection _leaves = new LinkedList(); - /** - * Create a branch to the virtual root folder - */ - public Branch() { - super(); - } + /** + * Create a branch to the virtual root folder + */ + public Branch() { + super(); + } - /** - * Create a branch with a parent branch and a name of this branch. - * @param parent The parent of this branch - * @param name The name of this branch - */ - public Branch(final Branch parent, final String name) { - super(); - this._name = name; - this._parent = parent; - } + /** + * Create a branch with a parent branch and a name of this branch. + * + * @param parent The parent of this branch + * @param name The name of this branch + */ + public Branch(final Branch parent, final String name) { + super(); + this._name = name; + this._parent = parent; + } - /** - * Get all branches. - *

- * They must be filled first with a fill method from the {@link TreeBrowser} - * @return The list of branches - */ - public Collection getBranches() { - return this._branches; - } + /** + * Get all branches. + *

+ * They must be filled first with a fill method from the {@link TreeBrowser} + * + * @return The list of branches + */ + public Collection getBranches() { + return this._branches; + } - public void setBranches(final Collection branches) { - this._branches = branches; - } + public void setBranches(final Collection branches) { + this._branches = branches; + } - /** - * Get all leaves. - *

- * They must be filled first with a fill method from the {@link TreeBrowser} - * @return The list of leaves - */ - public Collection getLeaves() { - return this._leaves; - } + /** + * Get all leaves. + *

+ * They must be filled first with a fill method from the {@link TreeBrowser} + * + * @return The list of leaves + */ + public Collection getLeaves() { + return this._leaves; + } - public void setLeaves(final Collection leaves) { - this._leaves = leaves; - } + public void setLeaves(final Collection leaves) { + this._leaves = leaves; + } - public String getName() { - return this._name; - } + public String getName() { + return this._name; + } - public void setName(final String name) { - this._name = name; - } + public void setName(final String name) { + this._name = name; + } - public Branch getParent() { - return this._parent; - } + public Branch getParent() { + return this._parent; + } - /** - * Get the list of names from the parent up to this branch - * @return The stack of branch names from the parent up this one - */ - public Collection getBranchStack() { - LinkedList branches = new LinkedList(); + /** + * Get the list of names from the parent up to this branch + * + * @return The stack of branch names from the parent up this one + */ + public Collection getBranchStack() { + LinkedList branches = new LinkedList(); - Branch currentBranch = this; - while (currentBranch.getParent() != null) { - branches.add(currentBranch.getName()); - currentBranch = currentBranch.getParent(); - } + Branch currentBranch = this; + while (currentBranch.getParent() != null) { + branches.add(currentBranch.getName()); + currentBranch = currentBranch.getParent(); + } - Collections.reverse(branches); - return branches; - } + Collections.reverse(branches); + return branches; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/FlatBrowser.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/FlatBrowser.java index 6cc95fee8..fe0cb1b8e 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/FlatBrowser.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/FlatBrowser.java @@ -33,43 +33,44 @@ import java.util.EnumSet; */ public class FlatBrowser extends BaseBrowser { - public FlatBrowser(final OPCBrowseServerAddressSpace browser) { - super(browser); - } + public FlatBrowser(final OPCBrowseServerAddressSpace browser) { + super(browser); + } - public FlatBrowser(final OPCBrowseServerAddressSpace browser, final int batchSize) { - super(browser, batchSize); - } + public FlatBrowser(final OPCBrowseServerAddressSpace browser, final int batchSize) { + super(browser, batchSize); + } - /** - * Perform a flat browse operation - * @param filterCriteria The filter criteria. Use an empty string if you don't need - * one. - * @param accessMask The access mask. An empty set will search for all. - * @param variantType The variant type. Must be one of the VT_ constants - * of {@link JIVariant}. Use {@link JIVariant#VT_EMPTY} if you want to browse for all. - * @return The list of entries - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public Collection browse(final String filterCriteria, final EnumSet accessMask, - final int variantType) throws IllegalArgumentException, UnknownHostException, JIException { - return browse(OPCBROWSETYPE.OPC_FLAT, filterCriteria, accessMask, variantType); - } + /** + * Perform a flat browse operation + * + * @param filterCriteria The filter criteria. Use an empty string if you don't need + * one. + * @param accessMask The access mask. An empty set will search for all. + * @param variantType The variant type. Must be one of the VT_ constants + * of {@link JIVariant}. Use {@link JIVariant#VT_EMPTY} if you want to browse for all. + * @return The list of entries + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public Collection browse(final String filterCriteria, final EnumSet accessMask, + final int variantType) throws IllegalArgumentException, UnknownHostException, JIException { + return browse(OPCBROWSETYPE.OPC_FLAT, filterCriteria, accessMask, variantType); + } - public Collection browse(final String filterCriteria) - throws IllegalArgumentException, UnknownHostException, JIException { - return browse(filterCriteria, EnumSet.noneOf(Access.class), JIVariant.VT_EMPTY); - } + public Collection browse(final String filterCriteria) + throws IllegalArgumentException, UnknownHostException, JIException { + return browse(filterCriteria, EnumSet.noneOf(Access.class), JIVariant.VT_EMPTY); + } - public Collection browse() throws IllegalArgumentException, UnknownHostException, JIException { - return browse("", EnumSet.noneOf(Access.class), JIVariant.VT_EMPTY); - } + public Collection browse() throws IllegalArgumentException, UnknownHostException, JIException { + return browse("", EnumSet.noneOf(Access.class), JIVariant.VT_EMPTY); + } - public Collection browse(final EnumSet accessMask) - throws IllegalArgumentException, UnknownHostException, JIException { - return browse("", accessMask, JIVariant.VT_EMPTY); - } + public Collection browse(final EnumSet accessMask) + throws IllegalArgumentException, UnknownHostException, JIException { + return browse("", accessMask, JIVariant.VT_EMPTY); + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Leaf.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Leaf.java index 346b0e4ac..a874b0e84 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Leaf.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/Leaf.java @@ -19,41 +19,41 @@ package org.openscada.opc.lib.da.browser; public class Leaf { - private Branch _parent = null; + private Branch _parent = null; - private String _name = ""; + private String _name = ""; - private String _itemId = null; + private String _itemId = null; - public Leaf(final Branch parent, final String name) { - this._parent = parent; - this._name = name; - } + public Leaf(final Branch parent, final String name) { + this._parent = parent; + this._name = name; + } - public Leaf(final Branch parent, final String name, final String itemId) { - this._parent = parent; - this._name = name; - this._itemId = itemId; - } + public Leaf(final Branch parent, final String name, final String itemId) { + this._parent = parent; + this._name = name; + this._itemId = itemId; + } - public String getItemId() { - return this._itemId; - } + public String getItemId() { + return this._itemId; + } - public void setItemId(final String itemId) { - this._itemId = itemId; - } + public void setItemId(final String itemId) { + this._itemId = itemId; + } - public String getName() { - return this._name; - } + public String getName() { + return this._name; + } - public void setName(final String name) { - this._name = name; - } + public void setName(final String name) { + this._name = name; + } - public Branch getParent() { - return this._parent; - } + public Branch getParent() { + return this._parent; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/TreeBrowser.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/TreeBrowser.java index cbcff8b10..07e24e5bd 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/TreeBrowser.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/da/browser/TreeBrowser.java @@ -39,185 +39,196 @@ import java.util.LinkedList; */ public class TreeBrowser extends BaseBrowser { - private String _filterCriteria = ""; + private String _filterCriteria = ""; - private EnumSet _accessMask = EnumSet.noneOf(Access.class); + private EnumSet _accessMask = EnumSet.noneOf(Access.class); - private int _variantType = JIVariant.VT_EMPTY; + private int _variantType = JIVariant.VT_EMPTY; - /** - * Browse for all items without search parameters. - *

- * This will actually call: - * TreeBrowser ( browser, "", EnumSet.noneOf ( Access.class ), JIVariant.VT_EMPTY ); - * - * @param browser The browser to use for browsing - */ - public TreeBrowser(final OPCBrowseServerAddressSpace browser) { - super(browser); - } + /** + * Browse for all items without search parameters. + *

+ * This will actually call: + * TreeBrowser ( browser, "", EnumSet.noneOf ( Access.class ), JIVariant.VT_EMPTY ); + * + * + * @param browser The browser to use for browsing + */ + public TreeBrowser(final OPCBrowseServerAddressSpace browser) { + super(browser); + } - /** - * Browse for items with search parameters. - * @param browser The browser to use - * @param filterCriteria The filter criteria. It is specific to the server you use. - * @param accessMask The access mask (use EnumSet.noneOf ( Access.class ) - * for all) - * @param variantType The variant type (use JIVariant.VT_EMPTY for all) - */ - public TreeBrowser(final OPCBrowseServerAddressSpace browser, final String filterCriteria, - final EnumSet accessMask, final int variantType) { - super(browser); - this._filterCriteria = filterCriteria; - this._accessMask = accessMask; - this._variantType = variantType; - } + /** + * Browse for items with search parameters. + * + * @param browser The browser to use + * @param filterCriteria The filter criteria. It is specific to the server you use. + * @param accessMask The access mask (use EnumSet.noneOf ( Access.class ) + * for all) + * @param variantType The variant type (use JIVariant.VT_EMPTY for all) + */ + public TreeBrowser(final OPCBrowseServerAddressSpace browser, final String filterCriteria, + final EnumSet accessMask, final int variantType) { + super(browser); + this._filterCriteria = filterCriteria; + this._accessMask = accessMask; + this._variantType = variantType; + } - /** - * Move the tree browser to the root folder - * @throws JIException JIException - */ - protected void moveToRoot() throws JIException { - this._browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_TO); - } + /** + * Move the tree browser to the root folder + * + * @throws JIException JIException + */ + protected void moveToRoot() throws JIException { + this._browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_TO); + } - /** - * Move the tree browser to a branch - * @param branch The branch to move to - * @throws JIException JIException - */ - protected void moveToBranch(final Branch branch) throws JIException { - Collection branchStack = branch.getBranchStack(); + /** + * Move the tree browser to a branch + * + * @param branch The branch to move to + * @throws JIException JIException + */ + protected void moveToBranch(final Branch branch) throws JIException { + Collection branchStack = branch.getBranchStack(); - moveToRoot(); - for (String branchName : branchStack) { - this._browser.changePosition(branchName, OPCBROWSEDIRECTION.OPC_BROWSE_DOWN); - } - } + moveToRoot(); + for (String branchName : branchStack) { + this._browser.changePosition(branchName, OPCBROWSEDIRECTION.OPC_BROWSE_DOWN); + } + } - /** - * Browse the root branch for its sub-branches. - * @return The list of sub-branches - * @throws JIException JIException - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - */ - public Branch browseBranches() throws JIException, IllegalArgumentException, UnknownHostException { - Branch branch = new Branch(); - fillBranches(branch); - return branch; - } + /** + * Browse the root branch for its sub-branches. + * + * @return The list of sub-branches + * @throws JIException JIException + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + */ + public Branch browseBranches() throws JIException, IllegalArgumentException, UnknownHostException { + Branch branch = new Branch(); + fillBranches(branch); + return branch; + } - /** - * Browse the root branch for this leaves. - * @return The list of leaves - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public Branch browseLeaves() throws IllegalArgumentException, UnknownHostException, JIException { - Branch branch = new Branch(); - fillLeaves(branch); - return branch; - } + /** + * Browse the root branch for this leaves. + * + * @return The list of leaves + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public Branch browseLeaves() throws IllegalArgumentException, UnknownHostException, JIException { + Branch branch = new Branch(); + fillLeaves(branch); + return branch; + } - /** - * Fill the branch list of the provided branch. - * @param branch The branch to fill. - * @throws JIException JIException - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - */ - public void fillBranches(final Branch branch) throws JIException, IllegalArgumentException, UnknownHostException { - moveToBranch(branch); - browse(branch, false, true, false); - } + /** + * Fill the branch list of the provided branch. + * + * @param branch The branch to fill. + * @throws JIException JIException + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + */ + public void fillBranches(final Branch branch) throws JIException, IllegalArgumentException, UnknownHostException { + moveToBranch(branch); + browse(branch, false, true, false); + } - /** - * Fill the leaf list of the provided branch. - * @param branch The branch to fill. - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public void fillLeaves(final Branch branch) throws IllegalArgumentException, UnknownHostException, JIException { - moveToBranch(branch); - browse(branch, true, false, false); - } + /** + * Fill the leaf list of the provided branch. + * + * @param branch The branch to fill. + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public void fillLeaves(final Branch branch) throws IllegalArgumentException, UnknownHostException, JIException { + moveToBranch(branch); + browse(branch, true, false, false); + } - /** - * Browse through all levels of the tree browser. - * @return The whole expanded server address space - * @throws JIException JIException - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - */ - public Branch browse() throws JIException, IllegalArgumentException, UnknownHostException { - Branch branch = new Branch(); - fill(branch); - return branch; - } + /** + * Browse through all levels of the tree browser. + * + * @return The whole expanded server address space + * @throws JIException JIException + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + */ + public Branch browse() throws JIException, IllegalArgumentException, UnknownHostException { + Branch branch = new Branch(); + fill(branch); + return branch; + } - /** - * Fill the leaves and branches of the branch provided branches including alls - * sub-branches. - * @param branch The branch to fill. - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public void fill(final Branch branch) throws IllegalArgumentException, UnknownHostException, JIException { - moveToBranch(branch); - browse(branch, true, true, true); - } + /** + * Fill the leaves and branches of the branch provided branches including alls + * sub-branches. + * + * @param branch The branch to fill. + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public void fill(final Branch branch) throws IllegalArgumentException, UnknownHostException, JIException { + moveToBranch(branch); + browse(branch, true, true, true); + } - /** - * Fill the branch object with the leaves of this currently selected branch. - *

- * The server object is not located to the branch before browsing! - * @param branch The branch to fill - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - protected void browseLeaves(final Branch branch) - throws IllegalArgumentException, UnknownHostException, JIException { - branch.setLeaves(new LinkedList()); + /** + * Fill the branch object with the leaves of this currently selected branch. + *

+ * The server object is not located to the branch before browsing! + * + * @param branch The branch to fill + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + protected void browseLeaves(final Branch branch) + throws IllegalArgumentException, UnknownHostException, JIException { + branch.setLeaves(new LinkedList()); - for (String item : browse(OPCBROWSETYPE.OPC_LEAF, this._filterCriteria, this._accessMask, this._variantType)) { - Leaf leaf = new Leaf(branch, item, this._browser.getItemID(item)); - branch.getLeaves().add(leaf); - } - } + for (String item : browse(OPCBROWSETYPE.OPC_LEAF, this._filterCriteria, this._accessMask, this._variantType)) { + Leaf leaf = new Leaf(branch, item, this._browser.getItemID(item)); + branch.getLeaves().add(leaf); + } + } - protected void browseBranches(final Branch branch, final boolean leaves, final boolean descend) - throws IllegalArgumentException, UnknownHostException, JIException { - branch.setBranches(new LinkedList()); + protected void browseBranches(final Branch branch, final boolean leaves, final boolean descend) + throws IllegalArgumentException, UnknownHostException, JIException { + branch.setBranches(new LinkedList()); - for (String item : browse(OPCBROWSETYPE.OPC_BRANCH, this._filterCriteria, this._accessMask, - this._variantType)) { - Branch subBranch = new Branch(branch, item); - // descend only if we should - if (descend) { - this._browser.changePosition(item, OPCBROWSEDIRECTION.OPC_BROWSE_DOWN); - browse(subBranch, leaves, true, true); - this._browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_UP); - } - branch.getBranches().add(subBranch); - } - } + for (String item : browse(OPCBROWSETYPE.OPC_BRANCH, this._filterCriteria, this._accessMask, + this._variantType)) { + Branch subBranch = new Branch(branch, item); + // descend only if we should + if (descend) { + this._browser.changePosition(item, OPCBROWSEDIRECTION.OPC_BROWSE_DOWN); + browse(subBranch, leaves, true, true); + this._browser.changePosition(null, OPCBROWSEDIRECTION.OPC_BROWSE_UP); + } + branch.getBranches().add(subBranch); + } + } - protected void browse(final Branch branch, final boolean leaves, final boolean branches, final boolean descend) - throws IllegalArgumentException, UnknownHostException, JIException { - // process leaves - if (leaves) { - browseLeaves(branch); - } + protected void browse(final Branch branch, final boolean leaves, final boolean branches, final boolean descend) + throws IllegalArgumentException, UnknownHostException, JIException { + // process leaves + if (leaves) { + browseLeaves(branch); + } - // process branches - if (branches) { - browseBranches(branch, leaves, descend); - } - } + // process branches + if (branches) { + browseBranches(branch, leaves, descend); + } + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Categories.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Categories.java index e3f7dea36..565669bc2 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Categories.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Categories.java @@ -19,24 +19,24 @@ package org.openscada.opc.lib.list; public interface Categories { - /** - * Category of the OPC DA 1.0 Servers - */ - public final static Category OPCDAServer10 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer10); + /** + * Category of the OPC DA 1.0 Servers + */ + public final static Category OPCDAServer10 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer10); - /** - * Category of the OPC DA 2.0 Servers - */ - public final static Category OPCDAServer20 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer20); + /** + * Category of the OPC DA 2.0 Servers + */ + public final static Category OPCDAServer20 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer20); - /** - * Category of the OPC DA 3.0 Servers - */ - public final static Category OPCDAServer30 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer30); + /** + * Category of the OPC DA 3.0 Servers + */ + public final static Category OPCDAServer30 = new Category(org.openscada.opc.dcom.common.Categories.OPCDAServer30); - /** - * Category of the XML DA 1.0 Servers - */ - public final static Category XMLDAServer10 = new Category(org.openscada.opc.dcom.common.Categories.XMLDAServer10); + /** + * Category of the XML DA 1.0 Servers + */ + public final static Category XMLDAServer10 = new Category(org.openscada.opc.dcom.common.Categories.XMLDAServer10); } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Category.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Category.java index e870aee98..92477acec 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Category.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/Category.java @@ -19,46 +19,45 @@ package org.openscada.opc.lib.list; public class Category { - private String _catId = null; + private String _catId = null; - public Category(final String catId) { - this._catId = catId; - } + public Category(final String catId) { + this._catId = catId; + } - @Override - public String toString() { - return this._catId; - } + @Override + public String toString() { + return this._catId; + } - @Override - public int hashCode() { - final int PRIME = 31; - int result = 1; - result = PRIME * result + (this._catId == null ? 0 : this._catId.hashCode()); - return result; - } + @Override + public int hashCode() { + final int PRIME = 31; + int result = 1; + result = PRIME * result + (this._catId == null ? 0 : this._catId.hashCode()); + return result; + } - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final Category other = (Category) obj; - if (this._catId == null) { - if (other._catId != null) { - return false; - } - } - else if (!this._catId.equals(other._catId)) { - return false; - } - return true; - } + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Category other = (Category) obj; + if (this._catId == null) { + if (other._catId != null) { + return false; + } + } else if (!this._catId.equals(other._catId)) { + return false; + } + return true; + } } diff --git a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/ServerList.java b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/ServerList.java index 39678dcff..824187a5b 100644 --- a/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/ServerList.java +++ b/dc3-driver/dc3-driver-opc-da/src/main/java/org/openscada/opc/lib/list/ServerList.java @@ -40,132 +40,139 @@ import java.util.List; */ public class ServerList { - private final JISession _session; + private final JISession _session; - private final OPCServerList _serverList; + private final OPCServerList _serverList; - /** - * Create a new instance with an already existing session - * @param session the DCOM session - * @param host the host to query - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public ServerList(final JISession session, final String host) - throws IllegalArgumentException, UnknownHostException, JIException { - this._session = session; - JIComServer comServer = new JIComServer(JIClsid.valueOf(Constants.OPCServerList_CLSID), host, this._session); - this._serverList = new OPCServerList(comServer.createInstance()); - } + /** + * Create a new instance with an already existing session + * + * @param session the DCOM session + * @param host the host to query + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public ServerList(final JISession session, final String host) + throws IllegalArgumentException, UnknownHostException, JIException { + this._session = session; + JIComServer comServer = new JIComServer(JIClsid.valueOf(Constants.OPCServerList_CLSID), host, this._session); + this._serverList = new OPCServerList(comServer.createInstance()); + } - /** - * Create a new instance and a new DCOM session - * @param host the host to contact - * @param user the user to use for authentication - * @param password the password to use for authentication - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public ServerList(final String host, final String user, final String password) - throws IllegalArgumentException, UnknownHostException, JIException { - this(host, user, password, null); - } + /** + * Create a new instance and a new DCOM session + * + * @param host the host to contact + * @param user the user to use for authentication + * @param password the password to use for authentication + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public ServerList(final String host, final String user, final String password) + throws IllegalArgumentException, UnknownHostException, JIException { + this(host, user, password, null); + } - /** - * Create a new instance and a new DCOM session - * @param host the host to contact - * @param user the user to use for authentication - * @param password the password to use for authentication - * @param domain The domain to use for authentication - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public ServerList(final String host, final String user, final String password, final String domain) - throws IllegalArgumentException, UnknownHostException, JIException { - this(JISession.createSession(domain, user, password), host); - } + /** + * Create a new instance and a new DCOM session + * + * @param host the host to contact + * @param user the user to use for authentication + * @param password the password to use for authentication + * @param domain The domain to use for authentication + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public ServerList(final String host, final String user, final String password, final String domain) + throws IllegalArgumentException, UnknownHostException, JIException { + this(JISession.createSession(domain, user, password), host); + } - /** - * Get the details of a opc class - * @param clsId the class to request details for - * @return The class details - * @throws JIException JIException - */ - public ClassDetails getDetails(final String clsId) throws JIException { - return this._serverList.getClassDetails(JIClsid.valueOf(clsId)); - } + /** + * Get the details of a opc class + * + * @param clsId the class to request details for + * @return The class details + * @throws JIException JIException + */ + public ClassDetails getDetails(final String clsId) throws JIException { + return this._serverList.getClassDetails(JIClsid.valueOf(clsId)); + } - /** - * Fetch the class id of a prog id - * @param progId The prog id to look up - * @return the class id or null if none could be found. - * @throws JIException JIException - */ - public String getClsIdFromProgId(final String progId) throws JIException { - JIClsid cls = this._serverList.getCLSIDFromProgID(progId); - if (cls == null) { - return null; - } - return cls.getCLSID(); - } + /** + * Fetch the class id of a prog id + * + * @param progId The prog id to look up + * @return the class id or null if none could be found. + * @throws JIException JIException + */ + public String getClsIdFromProgId(final String progId) throws JIException { + JIClsid cls = this._serverList.getCLSIDFromProgID(progId); + if (cls == null) { + return null; + } + return cls.getCLSID(); + } - /** - * List all servers that match the requirements - * @param implemented All implemented categories - * @param required All required categories - * @return A collection of class ids - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public Collection listServers(final Category[] implemented, final Category[] required) - throws IllegalArgumentException, UnknownHostException, JIException { - // convert the type safe categories to plain UUIDs - UUID[] u1 = new UUID[implemented.length]; - UUID[] u2 = new UUID[required.length]; + /** + * List all servers that match the requirements + * + * @param implemented All implemented categories + * @param required All required categories + * @return A collection of class ids + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public Collection listServers(final Category[] implemented, final Category[] required) + throws IllegalArgumentException, UnknownHostException, JIException { + // convert the type safe categories to plain UUIDs + UUID[] u1 = new UUID[implemented.length]; + UUID[] u2 = new UUID[required.length]; - for (int i = 0; i < implemented.length; i++) { - u1[i] = new UUID(implemented[i].toString()); - } + for (int i = 0; i < implemented.length; i++) { + u1[i] = new UUID(implemented[i].toString()); + } - for (int i = 0; i < required.length; i++) { - u2[i] = new UUID(required[i].toString()); - } + for (int i = 0; i < required.length; i++) { + u2[i] = new UUID(required[i].toString()); + } - // get them as UUIDs - Collection resultU = this._serverList.enumClassesOfCategories(u1, u2).asCollection(); + // get them as UUIDs + Collection resultU = this._serverList.enumClassesOfCategories(u1, u2).asCollection(); - // and convert to easier usable strings - Collection result = new ArrayList(resultU.size()); - for (UUID uuid : resultU) { - result.add(uuid.toString()); - } - return result; - } + // and convert to easier usable strings + Collection result = new ArrayList(resultU.size()); + for (UUID uuid : resultU) { + result.add(uuid.toString()); + } + return result; + } - /** - * List all servers that match the requirements and return the class details - * @param implemented All implemented categories - * @param required All required categories - * @return a collection of matching server and their class information - * @throws IllegalArgumentException IllegalArgumentException - * @throws UnknownHostException UnknownHostException - * @throws JIException JIException - */ - public Collection listServersWithDetails(final Category[] implemented, final Category[] required) - throws IllegalArgumentException, UnknownHostException, JIException { - Collection resultString = listServers(implemented, required); + /** + * List all servers that match the requirements and return the class details + * + * @param implemented All implemented categories + * @param required All required categories + * @return a collection of matching server and their class information + * @throws IllegalArgumentException IllegalArgumentException + * @throws UnknownHostException UnknownHostException + * @throws JIException JIException + */ + public Collection listServersWithDetails(final Category[] implemented, final Category[] required) + throws IllegalArgumentException, UnknownHostException, JIException { + Collection resultString = listServers(implemented, required); - List result = new ArrayList(resultString.size()); + List result = new ArrayList(resultString.size()); - for (String clsId : resultString) { - result.add(getDetails(clsId)); - } + for (String clsId : resultString) { + result.add(getDetails(clsId)); + } - return result; - } + return result; + } } diff --git a/dc3-driver/dc3-driver-opc-ua/README.md b/dc3-driver/dc3-driver-opc-ua/README.md index fb62b1091..cde975a4f 100644 --- a/dc3-driver/dc3-driver-opc-ua/README.md +++ b/dc3-driver/dc3-driver-opc-ua/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-opc-ua` is the OPC UA (Unified Architecture) protocol driver of the IoT DC3 platform. It connects to OPC UA servers to read and write node values from industrial +`dc3-driver-opc-ua` is the OPC UA (Unified Architecture) protocol driver of the IoT DC3 platform. It connects to OPC UA +servers to read and write node values from industrial automation systems using the OPC UA binary protocol. ## Module Information diff --git a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/OpcUaApplication.java b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/OpcUaApplication.java index bb0b01f13..9905a186b 100644 --- a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/OpcUaApplication.java +++ b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/OpcUaApplication.java @@ -35,12 +35,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OpcUaApplication { - /** - * Main entry point for the OPC UA driver application. - * @param args command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(OpcUaApplication.class, args); - } + /** + * Main entry point for the OPC UA driver application. + * + * @param args command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(OpcUaApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/key/KeyLoader.java b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/key/KeyLoader.java index ad8376763..b5434fd3c 100644 --- a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/key/KeyLoader.java +++ b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/key/KeyLoader.java @@ -44,88 +44,87 @@ import java.util.regex.Pattern; @Slf4j public class KeyLoader { - /** - * IPv4 address regex pattern, used to validate if a string is a legal IPv4 address. - */ - private static final Pattern IP_ADDR_PATTERN = Pattern - .compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); + /** + * IPv4 address regex pattern, used to validate if a string is a legal IPv4 address. + */ + private static final Pattern IP_ADDR_PATTERN = Pattern + .compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); - /** - * PKCS12 keystore password, used to load/generate client certificate keystore. - */ - private static final char[] PASSWORD = "password".toCharArray(); + /** + * PKCS12 keystore password, used to load/generate client certificate keystore. + */ + private static final char[] PASSWORD = "password".toCharArray(); - /** - * Client certificate alias, used to read client private key and certificate from - * keystore. - */ - private static final String CLIENT_ALIAS = "client-ai"; + /** + * Client certificate alias, used to read client private key and certificate from + * keystore. + */ + private static final String CLIENT_ALIAS = "client-ai"; - @Getter - private X509Certificate clientCertificate; + @Getter + private X509Certificate clientCertificate; - @Getter - private KeyPair clientKeyPair; + @Getter + private KeyPair clientKeyPair; - /** - * Loads or creates the client certificate and key pair. - *

- * If the keystore doesn't exist, a new self-signed certificate is generated with the - * configured subject alternative names (hostnames and IP addresses). The certificate - * and private key are stored in a PKCS12 keystore. - *

- * @param baseDir the base directory where the keystore file is located - * @return this KeyLoader instance with loaded certificate and key pair - * @throws Exception if certificate generation or loading fails - */ - public KeyLoader load(Path baseDir) throws Exception { - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - Path serverKeyStore = baseDir.resolve("dc3-opc-ua-client.pfx"); + /** + * Loads or creates the client certificate and key pair. + *

+ * If the keystore doesn't exist, a new self-signed certificate is generated with the + * configured subject alternative names (hostnames and IP addresses). The certificate + * and private key are stored in a PKCS12 keystore. + *

+ * + * @param baseDir the base directory where the keystore file is located + * @return this KeyLoader instance with loaded certificate and key pair + * @throws Exception if certificate generation or loading fails + */ + public KeyLoader load(Path baseDir) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + Path serverKeyStore = baseDir.resolve("dc3-opc-ua-client.pfx"); - if (!Files.exists(serverKeyStore)) { - keyStore.load(null, PASSWORD); - KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048); - SelfSignedCertificateBuilder builder = new SelfSignedCertificateBuilder(keyPair) - .setCommonName("DC3 Opc Ua Client") - .setOrganization("dc3") - .setOrganizationalUnit("iot") - .setLocalityName("BeiJing") - .setStateName("BJ") - .setCountryCode("ZN") - .setApplicationUri("urn:dc3:opc:ua:client") - .addDnsName("localhost") - .addIpAddress("127.0.0.1"); + if (!Files.exists(serverKeyStore)) { + keyStore.load(null, PASSWORD); + KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048); + SelfSignedCertificateBuilder builder = new SelfSignedCertificateBuilder(keyPair) + .setCommonName("DC3 Opc Ua Client") + .setOrganization("dc3") + .setOrganizationalUnit("iot") + .setLocalityName("BeiJing") + .setStateName("BJ") + .setCountryCode("ZN") + .setApplicationUri("urn:dc3:opc:ua:client") + .addDnsName("localhost") + .addIpAddress("127.0.0.1"); - // Get as many hostnames and IP addresses as we can listed in the certificate. - for (String hostname : HostUtil.getHostNames("0.0.0.0")) { - if (IP_ADDR_PATTERN.matcher(hostname).matches()) { - builder.addIpAddress(hostname); - } - else { - builder.addDnsName(hostname); - } - } + // Get as many hostnames and IP addresses as we can listed in the certificate. + for (String hostname : HostUtil.getHostNames("0.0.0.0")) { + if (IP_ADDR_PATTERN.matcher(hostname).matches()) { + builder.addIpAddress(hostname); + } else { + builder.addDnsName(hostname); + } + } - X509Certificate certificate = builder.build(); - keyStore.setKeyEntry(CLIENT_ALIAS, keyPair.getPrivate(), PASSWORD, new X509Certificate[] { certificate }); - try (OutputStream out = Files.newOutputStream(serverKeyStore)) { - keyStore.store(out, PASSWORD); - } - } - else { - try (InputStream in = Files.newInputStream(serverKeyStore)) { - keyStore.load(in, PASSWORD); - } - } + X509Certificate certificate = builder.build(); + keyStore.setKeyEntry(CLIENT_ALIAS, keyPair.getPrivate(), PASSWORD, new X509Certificate[]{certificate}); + try (OutputStream out = Files.newOutputStream(serverKeyStore)) { + keyStore.store(out, PASSWORD); + } + } else { + try (InputStream in = Files.newInputStream(serverKeyStore)) { + keyStore.load(in, PASSWORD); + } + } - Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD); - if (serverPrivateKey instanceof PrivateKey) { - clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS); - PublicKey serverPublicKey = clientCertificate.getPublicKey(); - clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey); - } + Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD); + if (serverPrivateKey instanceof PrivateKey) { + clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS); + PublicKey serverPublicKey = clientCertificate.getPublicKey(); + clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey); + } - return this; - } + return this; + } } diff --git a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 0df23e4a9..327fc09d1 100644 --- a/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-opc-ua/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -68,203 +68,201 @@ import java.util.concurrent.*; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Cache of device ID to OPC UA client connections. - */ - private Map connectMap; + /** + * Cache of device ID to OPC UA client connections. + */ + private Map connectMap; - @Override - public void initial() { - connectMap = new ConcurrentHashMap<>(16); - } + @Override + public void initial() { + connectMap = new ConcurrentHashMap<>(16); + } - @Override - public void schedule() { - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + @Override + public void schedule() { + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - @Override - public void event(MetadataEventDTO metadataEvent) { - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + @Override + public void event(MetadataEventDTO metadataEvent) { + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - // Remove stale connection when device is updated or deleted - if (MetadataOperateTypeEnum.DELETE.equals(operateType) - || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { - connectMap.remove(metadataEvent.getId()); - } - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + // Remove stale connection when device is updated or deleted + if (MetadataOperateTypeEnum.DELETE.equals(operateType) + || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { + connectMap.remove(metadataEvent.getId()); + } + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - return new RValue(device, point, readValue(getConnector(device.getId(), driverConfig), pointConfig)); - } + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + return new RValue(device, point, readValue(getConnector(device.getId(), driverConfig), pointConfig)); + } - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - OpcUaClient client = getConnector(device.getId(), driverConfig); - return writeValue(client, pointConfig, wValue); - } + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + OpcUaClient client = getConnector(device.getId(), driverConfig); + return writeValue(client, pointConfig, wValue); + } - /** - * Get or create an OPC UA client for the given device. - * @param deviceId unique device identifier - * @param driverConfig driver configuration (host, port, path) - * @return cached or newly created OpcUaClient - * @throws ConnectorException if client creation fails - */ - private OpcUaClient getConnector(Long deviceId, Map driverConfig) { - log.debug("OPC UA server connection info: {}", JsonUtil.toJsonString(driverConfig)); - OpcUaClient opcUaClient = connectMap.get(deviceId); - if (Objects.isNull(opcUaClient)) { - String host = driverConfig.get("host").getValue(String.class); - int port = driverConfig.get("port").getValue(Integer.class); - String path = driverConfig.get("path").getValue(String.class); - String url = String.format("opc.tcp://%s:%s%s", host, port, path); - try { - opcUaClient = OpcUaClient.create(url, endpoints -> endpoints.stream().findFirst(), - configBuilder -> configBuilder - // Use anonymous authentication - .setIdentityProvider(new AnonymousProvider()) - // Set request timeout to 5000 ms - .setRequestTimeout(Unsigned.uint(5000)) - .build()); - connectMap.put(deviceId, opcUaClient); - } - catch (UaException e) { - connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); - log.error("Failed to connect OPC UA client: {}", e.getMessage(), e); - throw new ConnectorException(e.getMessage()); - } - } - return opcUaClient; - } + /** + * Get or create an OPC UA client for the given device. + * + * @param deviceId unique device identifier + * @param driverConfig driver configuration (host, port, path) + * @return cached or newly created OpcUaClient + * @throws ConnectorException if client creation fails + */ + private OpcUaClient getConnector(Long deviceId, Map driverConfig) { + log.debug("OPC UA server connection info: {}", JsonUtil.toJsonString(driverConfig)); + OpcUaClient opcUaClient = connectMap.get(deviceId); + if (Objects.isNull(opcUaClient)) { + String host = driverConfig.get("host").getValue(String.class); + int port = driverConfig.get("port").getValue(Integer.class); + String path = driverConfig.get("path").getValue(String.class); + String url = String.format("opc.tcp://%s:%s%s", host, port, path); + try { + opcUaClient = OpcUaClient.create(url, endpoints -> endpoints.stream().findFirst(), + configBuilder -> configBuilder + // Use anonymous authentication + .setIdentityProvider(new AnonymousProvider()) + // Set request timeout to 5000 ms + .setRequestTimeout(Unsigned.uint(5000)) + .build()); + connectMap.put(deviceId, opcUaClient); + } catch (UaException e) { + connectMap.entrySet().removeIf(next -> next.getKey().equals(deviceId)); + log.error("Failed to connect OPC UA client: {}", e.getMessage(), e); + throw new ConnectorException(e.getMessage()); + } + } + return opcUaClient; + } - /** - * Build a NodeId from point configuration (namespace + tag). - */ - private NodeId getNode(Map pointConfig) { - int namespace = pointConfig.get("namespace").getValue(Integer.class); - String tag = pointConfig.get("tag").getValue(String.class); - return new NodeId(namespace, tag); - } + /** + * Build a NodeId from point configuration (namespace + tag). + */ + private NodeId getNode(Map pointConfig) { + int namespace = pointConfig.get("namespace").getValue(Integer.class); + String tag = pointConfig.get("tag").getValue(String.class); + return new NodeId(namespace, tag); + } - /** - * Read a node value from the OPC UA server with a 1-second timeout. - * @param client connected OPC UA client - * @param pointConfig point configuration (namespace, tag) - * @return the node value as a string - * @throws ReadPointException if reading fails or times out - */ - private String readValue(OpcUaClient client, Map pointConfig) { - try { - NodeId nodeId = getNode(pointConfig); - client.connect().get(); - CompletableFuture value = new CompletableFuture<>(); - client.readValue(0.0, TimestampsToReturn.Both, nodeId) - .thenAccept(dataValue -> value.complete(dataValue.getValue().getValue().toString())); - return value.get(1, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - log.error("Read opc ua value error: {}", e.getMessage(), e); - Thread.currentThread().interrupt(); - throw new ReadPointException(e.getMessage()); - } - catch (ExecutionException | TimeoutException e) { - log.error("Read opc ua value error: {}", e.getMessage(), e); - throw new ReadPointException(e.getMessage()); - } - } + /** + * Read a node value from the OPC UA server with a 1-second timeout. + * + * @param client connected OPC UA client + * @param pointConfig point configuration (namespace, tag) + * @return the node value as a string + * @throws ReadPointException if reading fails or times out + */ + private String readValue(OpcUaClient client, Map pointConfig) { + try { + NodeId nodeId = getNode(pointConfig); + client.connect().get(); + CompletableFuture value = new CompletableFuture<>(); + client.readValue(0.0, TimestampsToReturn.Both, nodeId) + .thenAccept(dataValue -> value.complete(dataValue.getValue().getValue().toString())); + return value.get(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + log.error("Read opc ua value error: {}", e.getMessage(), e); + Thread.currentThread().interrupt(); + throw new ReadPointException(e.getMessage()); + } catch (ExecutionException | TimeoutException e) { + log.error("Read opc ua value error: {}", e.getMessage(), e); + throw new ReadPointException(e.getMessage()); + } + } - /** - * Write a value to an OPC UA node. - * @param client connected OPC UA client - * @param pointConfig point configuration (namespace, tag) - * @param wValue value to write - * @return true if the write succeeded - * @throws WritePointException if writing fails - */ - private boolean writeValue(OpcUaClient client, Map pointConfig, WValue wValue) { - try { - NodeId nodeId = getNode(pointConfig); - client.connect().get(); - return writeNode(client, nodeId, wValue); - } - catch (InterruptedException e) { - log.error("Write opc ua value error: {}", e.getMessage(), e); - Thread.currentThread().interrupt(); - throw new WritePointException(e.getMessage()); - } - catch (ExecutionException e) { - log.error("Write opc ua value error: {}", e.getMessage(), e); - throw new WritePointException(e.getMessage()); - } - } + /** + * Write a value to an OPC UA node. + * + * @param client connected OPC UA client + * @param pointConfig point configuration (namespace, tag) + * @param wValue value to write + * @return true if the write succeeded + * @throws WritePointException if writing fails + */ + private boolean writeValue(OpcUaClient client, Map pointConfig, WValue wValue) { + try { + NodeId nodeId = getNode(pointConfig); + client.connect().get(); + return writeNode(client, nodeId, wValue); + } catch (InterruptedException e) { + log.error("Write opc ua value error: {}", e.getMessage(), e); + Thread.currentThread().interrupt(); + throw new WritePointException(e.getMessage()); + } catch (ExecutionException e) { + log.error("Write opc ua value error: {}", e.getMessage(), e); + throw new WritePointException(e.getMessage()); + } + } - /** - * Write a typed value to an OPC UA node via DataValue/Variant. - *

- * Supports INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. - * @param client connected OPC UA client - * @param nodeId target node identifier - * @param wValue value and type to write - * @return true if the server reported a good status - */ - private boolean writeNode(OpcUaClient client, NodeId nodeId, WValue wValue) - throws ExecutionException, InterruptedException { - PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(wValue.getType().getCode()); - if (Objects.isNull(valueType)) { - throw new UnSupportException("Unsupported type of " + wValue.getType()); - } + /** + * Write a typed value to an OPC UA node via DataValue/Variant. + *

+ * Supports INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. + * + * @param client connected OPC UA client + * @param nodeId target node identifier + * @param wValue value and type to write + * @return true if the server reported a good status + */ + private boolean writeNode(OpcUaClient client, NodeId nodeId, WValue wValue) + throws ExecutionException, InterruptedException { + PointTypeFlagEnum valueType = PointTypeFlagEnum.ofCode(wValue.getType().getCode()); + if (Objects.isNull(valueType)) { + throw new UnSupportException("Unsupported type of " + wValue.getType()); + } - CompletableFuture status = new CompletableFuture<>(); - switch (valueType) { - case INT: - int intValue = wValue.getValue(Integer.class); - status = client.writeValue(nodeId, new DataValue(new Variant(intValue))); - break; - case LONG: - long longValue = wValue.getValue(Long.class); - status = client.writeValue(nodeId, new DataValue(new Variant(longValue))); - break; - case FLOAT: - float floatValue = wValue.getValue(Float.class); - status = client.writeValue(nodeId, new DataValue(new Variant(floatValue))); - break; - case DOUBLE: - double doubleValue = wValue.getValue(Double.class); - status = client.writeValue(nodeId, new DataValue(new Variant(doubleValue))); - break; - case BOOLEAN: - boolean booleanValue = wValue.getValue(Boolean.class); - status = client.writeValue(nodeId, new DataValue(new Variant(booleanValue))); - break; - case STRING: - status = client.writeValue(nodeId, new DataValue(new Variant(wValue.getValue()))); - break; - default: - break; - } + CompletableFuture status = new CompletableFuture<>(); + switch (valueType) { + case INT: + int intValue = wValue.getValue(Integer.class); + status = client.writeValue(nodeId, new DataValue(new Variant(intValue))); + break; + case LONG: + long longValue = wValue.getValue(Long.class); + status = client.writeValue(nodeId, new DataValue(new Variant(longValue))); + break; + case FLOAT: + float floatValue = wValue.getValue(Float.class); + status = client.writeValue(nodeId, new DataValue(new Variant(floatValue))); + break; + case DOUBLE: + double doubleValue = wValue.getValue(Double.class); + status = client.writeValue(nodeId, new DataValue(new Variant(doubleValue))); + break; + case BOOLEAN: + boolean booleanValue = wValue.getValue(Boolean.class); + status = client.writeValue(nodeId, new DataValue(new Variant(booleanValue))); + break; + case STRING: + status = client.writeValue(nodeId, new DataValue(new Variant(wValue.getValue()))); + break; + default: + break; + } - if (Objects.nonNull(status) && Objects.nonNull(status.get())) { - return status.get().getValue() > 0; - } - return false; - } + if (Objects.nonNull(status) && Objects.nonNull(status.get())) { + return status.get().getValue() > 0; + } + return false; + } } diff --git a/dc3-driver/dc3-driver-plcs7/README.md b/dc3-driver/dc3-driver-plcs7/README.md index 74bb8a9fd..f7fb50720 100644 --- a/dc3-driver/dc3-driver-plcs7/README.md +++ b/dc3-driver/dc3-driver-plcs7/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-plcs7` is the Siemens S7 PLC driver of the IoT DC3 platform. It communicates with Siemens S7 series PLCs (S7-200/300/400/1200/1500) using the S7 TCP protocol to read +`dc3-driver-plcs7` is the Siemens S7 PLC driver of the IoT DC3 platform. It communicates with Siemens S7 series PLCs ( +S7-200/300/400/1200/1500) using the S7 TCP protocol to read and write data block registers. ## Module Information diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/PlcS7DriverApplication.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/PlcS7DriverApplication.java index a8c4a610f..21d0a5dce 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/PlcS7DriverApplication.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/PlcS7DriverApplication.java @@ -35,12 +35,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PlcS7DriverApplication { - /** - * Main entry point for the Siemens S7 PLC driver application. - * @param args command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(PlcS7DriverApplication.class, args); - } + /** + * Main entry point for the Siemens S7 PLC driver application. + * + * @param args command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(PlcS7DriverApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/DaveArea.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/DaveArea.java index 285a20eb1..5f810d493 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/DaveArea.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/DaveArea.java @@ -28,37 +28,37 @@ package io.github.pnoker.driver.api; */ public enum DaveArea { - ANALOGINPUTS200(6), // Analog inputs (S7-200 family) - ANALOGOUTPUTS200(7), // Analog outputs (S7-200 family) - COUNTER(28), // S7 counters - COUNTER200(30), // IEC counters (S7-200 family) - DB(0x84), // Data blocks - DI(0x85), // Instance data blocks - FLAGS(0x83), // Merker/flag memory (M area) - INPUTS(0x81), // Process image inputs (I area) - LOCAL(0x86), // Local data (L stack) - OUTPUTS(0x82), // Process image outputs (Q area) - P(0x80), // Peripheral I/O (direct access) - SYSTEM_INFO(3), // System information - SYSTEM_FLAGS(5), // System flags - TIMER(29), // S7 timers - TIMER200(31), // IEC timers (S7-200 family) - V(0x87); // Variable memory (S7-200 V area) + ANALOGINPUTS200(6), // Analog inputs (S7-200 family) + ANALOGOUTPUTS200(7), // Analog outputs (S7-200 family) + COUNTER(28), // S7 counters + COUNTER200(30), // IEC counters (S7-200 family) + DB(0x84), // Data blocks + DI(0x85), // Instance data blocks + FLAGS(0x83), // Merker/flag memory (M area) + INPUTS(0x81), // Process image inputs (I area) + LOCAL(0x86), // Local data (L stack) + OUTPUTS(0x82), // Process image outputs (Q area) + P(0x80), // Peripheral I/O (direct access) + SYSTEM_INFO(3), // System information + SYSTEM_FLAGS(5), // System flags + TIMER(29), // S7 timers + TIMER200(31), // IEC timers (S7-200 family) + V(0x87); // Variable memory (S7-200 V area) - /** - * S7 area function code. - */ - final int code; + /** + * S7 area function code. + */ + final int code; - DaveArea(final int code) { - this.code = code; - } + DaveArea(final int code) { + this.code = code; + } - /** - * @return the S7 area code - */ - public int getCode() { - return this.code; - } + /** + * @return the S7 area code + */ + public int getCode() { + return this.code; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Connector.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Connector.java index 0e082c647..e5ecbb396 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Connector.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Connector.java @@ -28,23 +28,25 @@ import java.io.Closeable; */ public interface S7Connector extends Closeable { - /** - * Read bytes from a PLC memory area. - * @param area the memory area type - * @param areaNumber area number (e.g. DB number) - * @param bytes number of bytes to read - * @param offset byte offset within the area - * @return the bytes read from the PLC - */ - byte[] read(DaveArea area, int areaNumber, int bytes, int offset); + /** + * Read bytes from a PLC memory area. + * + * @param area the memory area type + * @param areaNumber area number (e.g. DB number) + * @param bytes number of bytes to read + * @param offset byte offset within the area + * @return the bytes read from the PLC + */ + byte[] read(DaveArea area, int areaNumber, int bytes, int offset); - /** - * Write bytes to a PLC memory area. - * @param area the memory area type - * @param areaNumber area number (e.g. DB number) - * @param offset byte offset within the area - * @param buffer the byte array to write - */ - void write(DaveArea area, int areaNumber, int offset, byte[] buffer); + /** + * Write bytes to a PLC memory area. + * + * @param area the memory area type + * @param areaNumber area number (e.g. DB number) + * @param offset byte offset within the area + * @param buffer the byte array to write + */ + void write(DaveArea area, int areaNumber, int offset, byte[] buffer); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializable.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializable.java index 67f61c5c7..8d015e748 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializable.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializable.java @@ -23,40 +23,42 @@ package io.github.pnoker.driver.api; */ public interface S7Serializable { - /** - * Extract a Java value from an S7 byte buffer. - * @param target type - * @param targetClass the class to deserialize into - * @param buffer raw byte buffer from the PLC - * @param byteOffset byte offset within the buffer - * @param bitOffset bit offset within the byte - * @return the deserialized value - */ - T extract(Class targetClass, byte[] buffer, int byteOffset, int bitOffset); + /** + * Extract a Java value from an S7 byte buffer. + * + * @param target type + * @param targetClass the class to deserialize into + * @param buffer raw byte buffer from the PLC + * @param byteOffset byte offset within the buffer + * @param bitOffset bit offset within the byte + * @return the deserialized value + */ + T extract(Class targetClass, byte[] buffer, int byteOffset, int bitOffset); - /** - * @return the S7 type this serializer handles - */ - S7Type getS7Type(); + /** + * @return the S7 type this serializer handles + */ + S7Type getS7Type(); - /** - * @return the size of this type in bits - */ - int getSizeInBits(); + /** + * @return the size of this type in bits + */ + int getSizeInBits(); - /** - * @return the size of this type in bytes - */ - int getSizeInBytes(); + /** + * @return the size of this type in bytes + */ + int getSizeInBytes(); - /** - * Insert a Java value into an S7 byte buffer. - * @param javaType the value to serialize - * @param buffer target byte buffer - * @param byteOffset byte offset within the buffer - * @param bitOffset bit offset within the byte - * @param size number of elements (for arrays) - */ - void insert(Object javaType, byte[] buffer, int byteOffset, int bitOffset, int size); + /** + * Insert a Java value into an S7 byte buffer. + * + * @param javaType the value to serialize + * @param buffer target byte buffer + * @param byteOffset byte offset within the buffer + * @param bitOffset bit offset within the byte + * @param size number of elements (for arrays) + */ + void insert(Object javaType, byte[] buffer, int byteOffset, int bitOffset, int size); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializer.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializer.java index c7be28fa5..db6554c52 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializer.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Serializer.java @@ -27,43 +27,47 @@ import io.github.pnoker.driver.exception.S7Exception; */ public interface S7Serializer { - /** - * Deserialize an object from a data block. - * @param target type - * @param beanClass class to deserialize into - * @param dbNum data block number - * @param byteOffset byte offset within the DB - * @return the deserialized object - * @throws S7Exception if reading fails - */ - T dispense(Class beanClass, int dbNum, int byteOffset) throws S7Exception; + /** + * Deserialize an object from a data block. + * + * @param target type + * @param beanClass class to deserialize into + * @param dbNum data block number + * @param byteOffset byte offset within the DB + * @return the deserialized object + * @throws S7Exception if reading fails + */ + T dispense(Class beanClass, int dbNum, int byteOffset) throws S7Exception; - /** - * Deserialize an object from a data block with an explicit block size. - * @param target type - * @param beanClass class to deserialize into - * @param dbNum data block number - * @param byteOffset byte offset within the DB - * @param blockSize number of bytes to read - * @return the deserialized object - * @throws S7Exception if reading fails - */ - T dispense(Class beanClass, int dbNum, int byteOffset, int blockSize) throws S7Exception; + /** + * Deserialize an object from a data block with an explicit block size. + * + * @param target type + * @param beanClass class to deserialize into + * @param dbNum data block number + * @param byteOffset byte offset within the DB + * @param blockSize number of bytes to read + * @return the deserialized object + * @throws S7Exception if reading fails + */ + T dispense(Class beanClass, int dbNum, int byteOffset, int blockSize) throws S7Exception; - /** - * Read a point value from a data block using the point variable definition. - * @param plcs7PointVariable point variable with DB number, offsets, and type - * @return the read value - * @throws S7Exception if reading fails - */ - Object dispense(PlcS7PointVariable plcs7PointVariable) throws S7Exception; + /** + * Read a point value from a data block using the point variable definition. + * + * @param plcs7PointVariable point variable with DB number, offsets, and type + * @return the read value + * @throws S7Exception if reading fails + */ + Object dispense(PlcS7PointVariable plcs7PointVariable) throws S7Exception; - /** - * Serialize and write an object to a data block. - * @param bean the value to write - * @param dbNum data block number - * @param byteOffset byte offset within the DB - */ - void store(Object bean, int dbNum, int byteOffset); + /** + * Serialize and write an object to a data block. + * + * @param bean the value to write + * @param dbNum data block number + * @param byteOffset byte offset within the DB + */ + void store(Object bean, int dbNum, int byteOffset); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Type.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Type.java index ce7e18224..bf5b4f536 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Type.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/S7Type.java @@ -26,53 +26,53 @@ import io.github.pnoker.driver.api.impl.serializer.converter.*; */ public enum S7Type { - BOOL(BitConverter.class, 0, 1), BYTE(ByteConverter.class, 1, 0), INT(ShortConverter.class, 2, 0), - DINT(LongConverter.class, 4, 0), WORD(IntegerConverter.class, 2, 0), DWORD(LongConverter.class, 4, 0), - REAL(RealConverter.class, 4, 0), - /** - * String type; size must be specified manually. - */ - STRING(StringConverter.class, 2, 0), DATE(DateConverter.class, 2, 0), - /** - * Duration in milliseconds, 4 bytes. - */ - TIME(TimeConverter.class, 4, 0), - /** - * Date and time with millisecond precision, 8 bytes. - */ - DATE_AND_TIME(DateAndTimeConverter.class, 8, 0), STRUCT(StructConverter.class, 0, 0); + BOOL(BitConverter.class, 0, 1), BYTE(ByteConverter.class, 1, 0), INT(ShortConverter.class, 2, 0), + DINT(LongConverter.class, 4, 0), WORD(IntegerConverter.class, 2, 0), DWORD(LongConverter.class, 4, 0), + REAL(RealConverter.class, 4, 0), + /** + * String type; size must be specified manually. + */ + STRING(StringConverter.class, 2, 0), DATE(DateConverter.class, 2, 0), + /** + * Duration in milliseconds, 4 bytes. + */ + TIME(TimeConverter.class, 4, 0), + /** + * Date and time with millisecond precision, 8 bytes. + */ + DATE_AND_TIME(DateAndTimeConverter.class, 8, 0), STRUCT(StructConverter.class, 0, 0); - private final int byteSize; + private final int byteSize; - private final int bitSize; + private final int bitSize; - private final Class serializer; + private final Class serializer; - S7Type(final Class serializer, final int byteSize, final int bitSize) { - this.serializer = serializer; - this.bitSize = bitSize; - this.byteSize = byteSize; - } + S7Type(final Class serializer, final int byteSize, final int bitSize) { + this.serializer = serializer; + this.bitSize = bitSize; + this.byteSize = byteSize; + } - /** - * @return size of this type in bits - */ - public int getBitSize() { - return this.bitSize; - } + /** + * @return size of this type in bits + */ + public int getBitSize() { + return this.bitSize; + } - /** - * @return size of this type in bytes - */ - public int getByteSize() { - return this.byteSize; - } + /** + * @return size of this type in bytes + */ + public int getByteSize() { + return this.byteSize; + } - /** - * @return the serializer class for this type - */ - public Class getSerializer() { - return this.serializer; - } + /** + * @return the serializer class for this type + */ + public Class getSerializer() { + return this.serializer; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/SiemensPLCS.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/SiemensPLCS.java index f2d37b0d7..c57a50ba3 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/SiemensPLCS.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/SiemensPLCS.java @@ -29,10 +29,10 @@ package io.github.pnoker.driver.api; */ public enum SiemensPLCS { - S_200, S_200_SMART, - /** - * Non-200 series (S7-300/400/1200/1500). - */ - S_NON_200, S_300, S_400, S_1200, S_1500, + S_200, S_200_SMART, + /** + * Non-200 series (S7-300/400/1200/1500). + */ + S_NON_200, S_300, S_400, S_1200, S_1500, } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Array.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Array.java index 52e05a31b..37559a3a8 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Array.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Array.java @@ -27,11 +27,11 @@ import java.lang.annotation.*; * @version 2025.9.0 * @since 2022.1.0 */ -@Target(value = { ElementType.FIELD }) +@Target(value = {ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Array { - int size(); + int size(); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Datablock.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Datablock.java index 340bfb908..fdf2110d1 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Datablock.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/Datablock.java @@ -27,7 +27,7 @@ import java.lang.annotation.*; * @version 2025.9.0 * @since 2022.1.0 */ -@Target(value = { ElementType.TYPE }) +@Target(value = {ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Datablock { diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/S7Variable.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/S7Variable.java index eddedfa1d..6606231f2 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/S7Variable.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/annotation/S7Variable.java @@ -26,34 +26,34 @@ import java.lang.annotation.*; * * @author Thomas Rudin */ -@Target(value = { ElementType.FIELD }) +@Target(value = {ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface S7Variable { - /** - * @return number of elements (for array fields) - */ - int arraySize() default 1; + /** + * @return number of elements (for array fields) + */ + int arraySize() default 1; - /** - * @return bit offset within the byte - */ - int bitOffset() default 0; + /** + * @return bit offset within the byte + */ + int bitOffset() default 0; - /** - * @return byte offset within the data block - */ - int byteOffset(); + /** + * @return byte offset within the data block + */ + int byteOffset(); - /** - * @return byte size (required for STRING type) - */ - int size() default 0; + /** + * @return byte size (required for STRING type) + */ + int size() default 0; - /** - * @return the S7 data type - */ - S7Type type(); + /** + * @return the S7 data type + */ + S7Type type(); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7ConnectorFactory.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7ConnectorFactory.java index 80037efc3..671176e42 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7ConnectorFactory.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7ConnectorFactory.java @@ -28,104 +28,110 @@ import io.github.pnoker.driver.api.impl.S7TCPConnection; */ public class S7ConnectorFactory { - private S7ConnectorFactory() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private S7ConnectorFactory() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * @param type the Siemens PLC model - * @return a new TCP connection builder - */ - public static TCPConnectionBuilder buildTCPConnector(SiemensPLCS type) { - return new TCPConnectionBuilder(type); - } + /** + * @param type the Siemens PLC model + * @return a new TCP connection builder + */ + public static TCPConnectionBuilder buildTCPConnector(SiemensPLCS type) { + return new TCPConnectionBuilder(type); + } - /** - * @return a TCP connection builder defaulting to non-200 series - */ - public static TCPConnectionBuilder buildTCPConnector() { - return new TCPConnectionBuilder(SiemensPLCS.S_NON_200); - } + /** + * @return a TCP connection builder defaulting to non-200 series + */ + public static TCPConnectionBuilder buildTCPConnector() { + return new TCPConnectionBuilder(SiemensPLCS.S_NON_200); + } - /** - * Builder for configuring and creating S7 TCP connections. - */ - public static class TCPConnectionBuilder { + /** + * Builder for configuring and creating S7 TCP connections. + */ + public static class TCPConnectionBuilder { - private final SiemensPLCS plcsType; + private final SiemensPLCS plcsType; - private String host; + private String host; - private int rack = 0; + private int rack = 0; - private int slot = 2; + private int slot = 2; - private int port = 102; + private int port = 102; - private int timeout = 2000; + private int timeout = 2000; - TCPConnectionBuilder(SiemensPLCS type) { - this.plcsType = type; - } + TCPConnectionBuilder(SiemensPLCS type) { + this.plcsType = type; + } - /** - * Builds a connection with given params - * @return S7Connector - */ - public S7Connector build() { - return new S7TCPConnection(this.host, this.rack, this.slot, this.port, this.timeout, this.plcsType); - } + /** + * Builds a connection with given params + * + * @return S7Connector + */ + public S7Connector build() { + return new S7TCPConnection(this.host, this.rack, this.slot, this.port, this.timeout, this.plcsType); + } - /** - * use hostname/ip - * @param host Host - * @return TCPConnectionBuilder - */ - public TCPConnectionBuilder withHost(final String host) { - this.host = host; - return this; - } + /** + * use hostname/ip + * + * @param host Host + * @return TCPConnectionBuilder + */ + public TCPConnectionBuilder withHost(final String host) { + this.host = host; + return this; + } - /** - * use port, default is 102 - * @param port Port - * @return TCPConnectionBuilder - */ - public TCPConnectionBuilder withPort(final int port) { - this.port = port; - return this; - } + /** + * use port, default is 102 + * + * @param port Port + * @return TCPConnectionBuilder + */ + public TCPConnectionBuilder withPort(final int port) { + this.port = port; + return this; + } - /** - * use rack, default is 0 - * @param rack Rack - * @return TCPConnectionBuilder - */ - public TCPConnectionBuilder withRack(final int rack) { - this.rack = rack; - return this; - } + /** + * use rack, default is 0 + * + * @param rack Rack + * @return TCPConnectionBuilder + */ + public TCPConnectionBuilder withRack(final int rack) { + this.rack = rack; + return this; + } - /** - * use slot, default is 2 - * @param slot Slot - * @return TCPConnectionBuilder - */ - public TCPConnectionBuilder withSlot(final int slot) { - this.slot = slot; - return this; - } + /** + * use slot, default is 2 + * + * @param slot Slot + * @return TCPConnectionBuilder + */ + public TCPConnectionBuilder withSlot(final int slot) { + this.slot = slot; + return this; + } - /** - * use timeout, default is 2000 - * @param timeout Timeout - * @return TCPConnectionBuilder - */ - public TCPConnectionBuilder withTimeout(final int timeout) { - this.timeout = timeout; - return this; - } + /** + * use timeout, default is 2000 + * + * @param timeout Timeout + * @return TCPConnectionBuilder + */ + public TCPConnectionBuilder withTimeout(final int timeout) { + this.timeout = timeout; + return this; + } - } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7SerializerFactory.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7SerializerFactory.java index 6d84e8598..4a2876f6b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7SerializerFactory.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/factory/S7SerializerFactory.java @@ -28,17 +28,18 @@ import io.github.pnoker.driver.api.impl.serializer.S7SerializerImpl; */ public class S7SerializerFactory { - private S7SerializerFactory() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private S7SerializerFactory() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Builds a new serializer with given connector - * @param connector the connector to use - * @return a serializer instance - */ - public static S7Serializer buildSerializer(final S7Connector connector) { - return new S7SerializerImpl(connector); - } + /** + * Builds a new serializer with given connector + * + * @param connector the connector to use + * @return a serializer instance + */ + public static S7Serializer buildSerializer(final S7Connector connector) { + return new S7SerializerImpl(connector); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7BaseConnection.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7BaseConnection.java index 9d6f787b2..230bb854b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7BaseConnection.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7BaseConnection.java @@ -30,106 +30,107 @@ import io.github.pnoker.driver.api.impl.nodave.S7Connection; */ public abstract class S7BaseConnection implements S7Connector { - /** - * The Constant PROPERTY_AREA. - */ - public static final String PROPERTY_AREA = "area"; + /** + * The Constant PROPERTY_AREA. + */ + public static final String PROPERTY_AREA = "area"; - /** - * The Constant PROPERTY_AREANUMBER. - */ - public static final String PROPERTY_AREANUMBER = "areanumber"; + /** + * The Constant PROPERTY_AREANUMBER. + */ + public static final String PROPERTY_AREANUMBER = "areanumber"; - /** - * The Constant PROPERTY_BYTES. - */ - public static final String PROPERTY_BYTES = "bytes"; + /** + * The Constant PROPERTY_BYTES. + */ + public static final String PROPERTY_BYTES = "bytes"; - /** - * The Constant PROPERTY_OFFSET. - */ - public static final String PROPERTY_OFFSET = "offset"; + /** + * The Constant PROPERTY_OFFSET. + */ + public static final String PROPERTY_OFFSET = "offset"; - /** - * The Constant MAX_SIZE. - */ - private static final int MAX_SIZE = 96; + /** + * The Constant MAX_SIZE. + */ + private static final int MAX_SIZE = 96; - /** - * The dc. - */ - private S7Connection dc; + /** + * The dc. + */ + private S7Connection dc; - /** - * Checks the Result. - * @param libnodaveResult the libnodave result - */ - public static void checkResult(final int libnodaveResult) { - if (libnodaveResult != Nodave.RESULT_OK) { - final String msg = Nodave.strerror(libnodaveResult); - throw new IllegalArgumentException("Result: " + msg); - } - } + /** + * Checks the Result. + * + * @param libnodaveResult the libnodave result + */ + public static void checkResult(final int libnodaveResult) { + if (libnodaveResult != Nodave.RESULT_OK) { + final String msg = Nodave.strerror(libnodaveResult); + throw new IllegalArgumentException("Result: " + msg); + } + } - /** - * Dump data - * @param b the byte stream - */ - protected static void dump(final byte[] b) { - for (final byte element : b) { - System.out.print(Integer.toHexString(element & 0xFF) + ","); - } - } + /** + * Dump data + * + * @param b the byte stream + */ + protected static void dump(final byte[] b) { + for (final byte element : b) { + System.out.print(Integer.toHexString(element & 0xFF) + ","); + } + } - /** - * Initialize the connection - * @param dc the connection instance - */ - protected void init(final S7Connection dc) { - this.dc = dc; - } + /** + * Initialize the connection + * + * @param dc the connection instance + */ + protected void init(final S7Connection dc) { + this.dc = dc; + } - @Override - public synchronized byte[] read(final DaveArea area, final int areaNumber, final int bytes, final int offset) { - if (bytes > MAX_SIZE) { - final byte[] ret = new byte[bytes]; + @Override + public synchronized byte[] read(final DaveArea area, final int areaNumber, final int bytes, final int offset) { + if (bytes > MAX_SIZE) { + final byte[] ret = new byte[bytes]; - final byte[] currentBuffer = this.read(area, areaNumber, MAX_SIZE, offset); - System.arraycopy(currentBuffer, 0, ret, 0, currentBuffer.length); + final byte[] currentBuffer = this.read(area, areaNumber, MAX_SIZE, offset); + System.arraycopy(currentBuffer, 0, ret, 0, currentBuffer.length); - final byte[] nextBuffer = this.read(area, areaNumber, bytes - MAX_SIZE, offset + MAX_SIZE); - System.arraycopy(nextBuffer, 0, ret, currentBuffer.length, nextBuffer.length); + final byte[] nextBuffer = this.read(area, areaNumber, bytes - MAX_SIZE, offset + MAX_SIZE); + System.arraycopy(nextBuffer, 0, ret, currentBuffer.length, nextBuffer.length); - return ret; - } - else { - final byte[] buffer = new byte[bytes]; - final int ret = this.dc.readBytes(area, areaNumber, offset, bytes, buffer); + return ret; + } else { + final byte[] buffer = new byte[bytes]; + final int ret = this.dc.readBytes(area, areaNumber, offset, bytes, buffer); - checkResult(ret); - return buffer; - } - } + checkResult(ret); + return buffer; + } + } - @Override - public synchronized void write(final DaveArea area, final int areaNumber, final int offset, final byte[] buffer) { - if (buffer.length > MAX_SIZE) { - // Split buffer - final byte[] subBuffer = new byte[MAX_SIZE]; - final byte[] nextBuffer = new byte[buffer.length - subBuffer.length]; + @Override + public synchronized void write(final DaveArea area, final int areaNumber, final int offset, final byte[] buffer) { + if (buffer.length > MAX_SIZE) { + // Split buffer + final byte[] subBuffer = new byte[MAX_SIZE]; + final byte[] nextBuffer = new byte[buffer.length - subBuffer.length]; - System.arraycopy(buffer, 0, subBuffer, 0, subBuffer.length); - System.arraycopy(buffer, MAX_SIZE, nextBuffer, 0, nextBuffer.length); + System.arraycopy(buffer, 0, subBuffer, 0, subBuffer.length); + System.arraycopy(buffer, MAX_SIZE, nextBuffer, 0, nextBuffer.length); - this.write(area, areaNumber, offset, subBuffer); - this.write(area, areaNumber, offset + subBuffer.length, nextBuffer); - } - else { - // Size fits - final int ret = this.dc.writeBytes(area, areaNumber, offset, buffer.length, buffer); - // Check return-value - checkResult(ret); - } - } + this.write(area, areaNumber, offset, subBuffer); + this.write(area, areaNumber, offset + subBuffer.length, nextBuffer); + } else { + // Size fits + final int ret = this.dc.writeBytes(area, areaNumber, offset, buffer.length, buffer); + // Check return-value + checkResult(ret); + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7TCPConnection.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7TCPConnection.java index 396a9a8a2..972e37dec 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7TCPConnection.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/S7TCPConnection.java @@ -36,121 +36,120 @@ import java.net.Socket; */ public final class S7TCPConnection extends S7BaseConnection { - /** - * The Host to connect to - */ - private final String host; + /** + * The Host to connect to + */ + private final String host; - /** - * The port to connect to - */ - private final int port; + /** + * The port to connect to + */ + private final int port; - /** - * Rack number - */ - private final int rack; + /** + * Rack number + */ + private final int rack; - /** - * Slot number - */ - private final int slot; + /** + * Slot number + */ + private final int slot; - /** - * Timeout number - */ - private final int timeout; + /** + * Timeout number + */ + private final int timeout; - /** - * To connect device type,such as S200 - */ - private final SiemensPLCS siemensPLCS; + /** + * To connect device type,such as S200 + */ + private final SiemensPLCS siemensPLCS; - /** - * The Connection - */ - private TCPConnection tcpConnection; + /** + * The Connection + */ + private TCPConnection tcpConnection; - /** - * The Interface - */ - private PLCinterface plCinterface; + /** + * The Interface + */ + private PLCinterface plCinterface; - /** - * The Socket - */ - private Socket socket; + /** + * The Socket + */ + private Socket socket; - /** - * Creates a new Instance to the given host, rack, slot and port - * @param host Host - * @param rack Rack - * @param slot Slot - * @param port Port - * @param timeout Timeout - * @param siemensPLCS SiemensPLCS - * @throws S7Exception S7Exception - */ - public S7TCPConnection(final String host, final int rack, final int slot, final int port, final int timeout, - final SiemensPLCS siemensPLCS) throws S7Exception { - this.host = host; - this.rack = rack; - this.slot = slot; - this.port = port; - this.timeout = timeout; - this.siemensPLCS = siemensPLCS; - this.setupSocket(); - } + /** + * Creates a new Instance to the given host, rack, slot and port + * + * @param host Host + * @param rack Rack + * @param slot Slot + * @param port Port + * @param timeout Timeout + * @param siemensPLCS SiemensPLCS + * @throws S7Exception S7Exception + */ + public S7TCPConnection(final String host, final int rack, final int slot, final int port, final int timeout, + final SiemensPLCS siemensPLCS) throws S7Exception { + this.host = host; + this.rack = rack; + this.slot = slot; + this.port = port; + this.timeout = timeout; + this.siemensPLCS = siemensPLCS; + this.setupSocket(); + } - @Override - public void close() { - try { - this.socket.close(); - } - catch (final Exception e) { - e.printStackTrace(); - } - } + @Override + public void close() { + try { + this.socket.close(); + } catch (final Exception e) { + e.printStackTrace(); + } + } - /** - * Sets up the socket - */ - private void setupSocket() { - try { - this.socket = new Socket(); - this.socket.setSoTimeout(2000); - this.socket.connect(new InetSocketAddress(this.host, this.port), this.timeout); + /** + * Sets up the socket + */ + private void setupSocket() { + try { + this.socket = new Socket(); + this.socket.setSoTimeout(2000); + this.socket.connect(new InetSocketAddress(this.host, this.port), this.timeout); - // select the plc interface protocol by the plcsType - int protocol; - switch (this.siemensPLCS) { - case S_200: - protocol = Nodave.PROTOCOL_ISOTCP243; - break; - case S_NON_200: - case S_300: - case S_400: - case S_1200: - case S_1500: - case S_200_SMART: - default: - protocol = Nodave.PROTOCOL_ISOTCP; - break; - } - this.plCinterface = new PLCinterface(this.socket.getOutputStream(), this.socket.getInputStream(), "IF1", - DaveArea.LOCAL.getCode(), // TODO Local MPI-Address? - protocol); + // select the plc interface protocol by the plcsType + int protocol; + switch (this.siemensPLCS) { + case S_200: + protocol = Nodave.PROTOCOL_ISOTCP243; + break; + case S_NON_200: + case S_300: + case S_400: + case S_1200: + case S_1500: + case S_200_SMART: + default: + protocol = Nodave.PROTOCOL_ISOTCP; + break; + } + this.plCinterface = new PLCinterface(this.socket.getOutputStream(), this.socket.getInputStream(), "IF1", + DaveArea.LOCAL.getCode(), // TODO Local MPI-Address? + protocol); - this.tcpConnection = new TCPConnection(this.plCinterface, this.rack, this.slot); - final int res = this.tcpConnection.connectPLC(); - checkResult(res); + this.tcpConnection = new TCPConnection(this.plCinterface, this.rack, this.slot); + final int res = this.tcpConnection.connectPLC(); + checkResult(res); - super.init(this.tcpConnection); - } - catch (final Exception e) { - throw new S7Exception("constructor", e); - } + super.init(this.tcpConnection); + } catch (final Exception e) { + throw new S7Exception("constructor", e); + } - } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Nodave.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Nodave.java index b5338446f..7834fd5ca 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Nodave.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Nodave.java @@ -27,360 +27,362 @@ package io.github.pnoker.driver.api.impl.nodave; */ public final class Nodave { - public final static int MAX_RAW_LEN = 2048; + public final static int MAX_RAW_LEN = 2048; - public final static int MPIReachable = 0x30; + public final static int MPIReachable = 0x30; - public final static int MPIunused = 0x10; + public final static int MPIunused = 0x10; - public final static int OrderCodeSize = 21; + public final static int OrderCodeSize = 21; - public final static int PartnerListSize = 126; + public final static int PartnerListSize = 126; - public final static int PROTOCOL_ISOTCP = 4; + public final static int PROTOCOL_ISOTCP = 4; - public final static int PROTOCOL_ISOTCP243 = 5; + public final static int PROTOCOL_ISOTCP243 = 5; - public final static int PROTOCOL_MPI_IBH = 223; // MPI with IBH NetLink MPI + public final static int PROTOCOL_MPI_IBH = 223; // MPI with IBH NetLink MPI - // to ethernet gateway - public final static int PROTOCOL_MPI_NLPRO = 230; // MPI with IBH NetLink + // to ethernet gateway + public final static int PROTOCOL_MPI_NLPRO = 230; // MPI with IBH NetLink - // MPI to ethernet - // gateway - public final static int PROTOCOL_NLPRO = 230; // MPI with IBH NetLink MPI to + // MPI to ethernet + // gateway + public final static int PROTOCOL_NLPRO = 230; // MPI with IBH NetLink MPI to - // ethernet gateway - // to ethernet gateway - public final static int PROTOCOL_PPI_IBH = 224; // PPI with IBH NetLink MPI + // ethernet gateway + // to ethernet gateway + public final static int PROTOCOL_PPI_IBH = 224; // PPI with IBH NetLink MPI - public final static int RESULT_ADDRESS_OUT_OF_RANGE = 5; + public final static int RESULT_ADDRESS_OUT_OF_RANGE = 5; - /* means the write data size doesn't fit item size */ - public final static int RESULT_CANNOT_EVALUATE_PDU = -123; + /* means the write data size doesn't fit item size */ + public final static int RESULT_CANNOT_EVALUATE_PDU = -123; - public final static int RESULT_CPU_RETURNED_NO_DATA = -124; + public final static int RESULT_CPU_RETURNED_NO_DATA = -124; - public final static int RESULT_EMPTY_RESULT_ERROR = -126; + public final static int RESULT_EMPTY_RESULT_ERROR = -126; - public final static int RESULT_EMPTY_RESULT_SET_ERROR = -127; + public final static int RESULT_EMPTY_RESULT_SET_ERROR = -127; - public final static int RESULT_ITEM_NOT_AVAILABLE = 10; + public final static int RESULT_ITEM_NOT_AVAILABLE = 10; - /* means a a piece of data is not available in the CPU, e.g. */ - /* when trying to read a non existing DB */ - /* CPU tells it doesn't support to read a bit block with a */ - /* length other than 1 bit. */ - public final static int RESULT_ITEM_NOT_AVAILABLE200 = 3; + /* means a a piece of data is not available in the CPU, e.g. */ + /* when trying to read a non existing DB */ + /* CPU tells it doesn't support to read a bit block with a */ + /* length other than 1 bit. */ + public final static int RESULT_ITEM_NOT_AVAILABLE200 = 3; - /* means a a piece of data is not available in the CPU, e.g. */ - /* when trying to read a non existing DB or bit bloc of length<>1 */ - /* This code seems to be specific to 200 family. */ - /* CPU tells there is no peripheral at address */ - public final static int RESULT_MULTIPLE_BITS_NOT_SUPPORTED = 6; + /* means a a piece of data is not available in the CPU, e.g. */ + /* when trying to read a non existing DB or bit bloc of length<>1 */ + /* This code seems to be specific to 200 family. */ + /* CPU tells there is no peripheral at address */ + public final static int RESULT_MULTIPLE_BITS_NOT_SUPPORTED = 6; - public final static int RESULT_NO_PERIPHERAL_AT_ADDRESS = 1; + public final static int RESULT_NO_PERIPHERAL_AT_ADDRESS = 1; - public final static int RESULT_OK = 0; /* means all ok */ + public final static int RESULT_OK = 0; /* means all ok */ - public final static int RESULT_SHORT_PACKET = -1024; + public final static int RESULT_SHORT_PACKET = -1024; - public final static int RESULT_TIMEOUT = -1025; + public final static int RESULT_TIMEOUT = -1025; - public final static int RESULT_UNEXPECTED_FUNC = -128; + public final static int RESULT_UNEXPECTED_FUNC = -128; - public final static int RESULT_UNKNOWN_DATA_UNIT_SIZE = -129; + public final static int RESULT_UNKNOWN_DATA_UNIT_SIZE = -129; - public final static int RESULT_UNKNOWN_ERROR = -125; + public final static int RESULT_UNKNOWN_ERROR = -125; - /* means the data address is beyond the CPUs address range */ - public final static int RESULT_WRITE_DATA_SIZE_MISMATCH = 7; + /* means the data address is beyond the CPUs address range */ + public final static int RESULT_WRITE_DATA_SIZE_MISMATCH = 7; - private Nodave() { - // Not needed because of utility class - } + private Nodave() { + // Not needed because of utility class + } - public static float BEFloat(final byte[] b, final int pos) { - int i = 0; - // System.out.println("pos" + pos); + public static float BEFloat(final byte[] b, final int pos) { + int i = 0; + // System.out.println("pos" + pos); - i |= Nodave.USByte(b, pos); - i <<= 8; - i |= Nodave.USByte(b, pos + 1); - i <<= 8; - i |= Nodave.USByte(b, pos + 2); - i <<= 8; - i |= Nodave.USByte(b, pos + 3); - final float f = Float.intBitsToFloat(i); - return (f); - } + i |= Nodave.USByte(b, pos); + i <<= 8; + i |= Nodave.USByte(b, pos + 1); + i <<= 8; + i |= Nodave.USByte(b, pos + 2); + i <<= 8; + i |= Nodave.USByte(b, pos + 3); + final float f = Float.intBitsToFloat(i); + return (f); + } - public static byte[] bswap_16(int a) { - final byte[] b = new byte[2]; - b[1] = (byte) (a & 0xff); - a = a >> 8; - b[0] = (byte) (a & 0xff); - return b; - } + public static byte[] bswap_16(int a) { + final byte[] b = new byte[2]; + b[1] = (byte) (a & 0xff); + a = a >> 8; + b[0] = (byte) (a & 0xff); + return b; + } - public static byte[] bswap_32(int a) { - final byte[] b = new byte[4]; - b[3] = (byte) (a & 0xff); - a = a >> 8; - b[2] = (byte) (a & 0xff); - a = a >> 8; - b[1] = (byte) (a & 0xff); - a = a >> 8; - b[0] = (byte) (a & 0xff); - return b; - } + public static byte[] bswap_32(int a) { + final byte[] b = new byte[4]; + b[3] = (byte) (a & 0xff); + a = a >> 8; + b[2] = (byte) (a & 0xff); + a = a >> 8; + b[1] = (byte) (a & 0xff); + a = a >> 8; + b[0] = (byte) (a & 0xff); + return b; + } - public static byte[] bswap_32(long a) { - final byte[] b = new byte[4]; - b[3] = (byte) (a & 0xff); - a = a >> 8; - b[2] = (byte) (a & 0xff); - a = a >> 8; - b[1] = (byte) (a & 0xff); - a = a >> 8; - b[0] = (byte) (a & 0xff); - return b; - } + public static byte[] bswap_32(long a) { + final byte[] b = new byte[4]; + b[3] = (byte) (a & 0xff); + a = a >> 8; + b[2] = (byte) (a & 0xff); + a = a >> 8; + b[1] = (byte) (a & 0xff); + a = a >> 8; + b[0] = (byte) (a & 0xff); + return b; + } - /** - * This doesn't swap anything, but the name fits into the series - * @param a value - * @return Byte Array - */ - public static byte[] bswap_8(final int a) { - final byte[] b = new byte[1]; - b[0] = (byte) (a & 0xff); - return b; - } + /** + * This doesn't swap anything, but the name fits into the series + * + * @param a value + * @return Byte Array + */ + public static byte[] bswap_8(final int a) { + final byte[] b = new byte[1]; + b[0] = (byte) (a & 0xff); + return b; + } - /** - * Dumps len hex codes from byte array mem beginning at index start - * @param text Text - * @param mem Mem - * @param start Start - * @param len Length - */ - public static void dump(final String text, final byte[] mem, final int start, final int len) { - System.out.print(text + " "); - for (int i = start; i < (start + len); i++) { - int j = mem[i]; - if (j < 0) { - j += 256; - } - String s = Integer.toHexString(j); - if (s.length() < 2) { - s = "0" + s; - } - System.out.print(s + ","); - } - System.out.println(" "); - } + /** + * Dumps len hex codes from byte array mem beginning at index start + * + * @param text Text + * @param mem Mem + * @param start Start + * @param len Length + */ + public static void dump(final String text, final byte[] mem, final int start, final int len) { + System.out.print(text + " "); + for (int i = start; i < (start + len); i++) { + int j = mem[i]; + if (j < 0) { + j += 256; + } + String s = Integer.toHexString(j); + if (s.length() < 2) { + s = "0" + s; + } + System.out.print(s + ","); + } + System.out.println(" "); + } - public static long SBELong(final byte[] b, final int pos) { - final int i = b[pos]; - int j = b[pos + 1]; - int k = b[pos + 2]; - int l = b[pos + 3]; - // if (i < 0) - // i += 256; - if (j < 0) { - j += 256; - } - if (k < 0) { - k += 256; - } - if (l < 0) { - l += 256; - } - return ((256 * k) + l) + (65536L * ((256 * i) + j)); - } + public static long SBELong(final byte[] b, final int pos) { + final int i = b[pos]; + int j = b[pos + 1]; + int k = b[pos + 2]; + int l = b[pos + 3]; + // if (i < 0) + // i += 256; + if (j < 0) { + j += 256; + } + if (k < 0) { + k += 256; + } + if (l < 0) { + l += 256; + } + return ((256 * k) + l) + (65536L * ((256 * i) + j)); + } - public static int SBEWord(final byte[] b, final int pos) { - final int i = b[pos]; - int k = b[pos + 1]; - // if (i < 0) - // i += 256; - if (k < 0) { - k += 256; - } - return ((256 * i) + k); - } + public static int SBEWord(final byte[] b, final int pos) { + final int i = b[pos]; + int k = b[pos + 1]; + // if (i < 0) + // i += 256; + if (k < 0) { + k += 256; + } + return ((256 * i) + k); + } - public static int SByte(final byte[] b, final int pos) { - final int i = b[pos]; - return (i); - } + public static int SByte(final byte[] b, final int pos) { + final int i = b[pos]; + return (i); + } - public static void setBEFloat(final byte[] b, final int pos, final float f) { - int a = Float.floatToIntBits(f); - b[pos + 3] = (byte) (a & 0xff); - a = a >> 8; - b[pos + 2] = (byte) (a & 0xff); - a = a >> 8; - b[pos + 1] = (byte) (a & 0xff); - a = a >> 8; - b[pos] = (byte) (a & 0xff); - } + public static void setBEFloat(final byte[] b, final int pos, final float f) { + int a = Float.floatToIntBits(f); + b[pos + 3] = (byte) (a & 0xff); + a = a >> 8; + b[pos + 2] = (byte) (a & 0xff); + a = a >> 8; + b[pos + 1] = (byte) (a & 0xff); + a = a >> 8; + b[pos] = (byte) (a & 0xff); + } - public static void setUSBELong(final byte[] b, final int pos, long a) { - b[pos + 3] = (byte) (a & 0xff); - a = a >> 8; - b[pos + 2] = (byte) (a & 0xff); - a = a >> 8; - b[pos + 1] = (byte) (a & 0xff); - a = a >> 8; - b[pos] = (byte) (a & 0xff); - } + public static void setUSBELong(final byte[] b, final int pos, long a) { + b[pos + 3] = (byte) (a & 0xff); + a = a >> 8; + b[pos + 2] = (byte) (a & 0xff); + a = a >> 8; + b[pos + 1] = (byte) (a & 0xff); + a = a >> 8; + b[pos] = (byte) (a & 0xff); + } - public static void setUSBEWord(final byte[] b, final int pos, final int val) { - b[pos] = ((byte) (val / 0x100)); - b[pos + 1] = ((byte) (val % 0x100)); - } + public static void setUSBEWord(final byte[] b, final int pos, final int val) { + b[pos] = ((byte) (val / 0x100)); + b[pos + 1] = ((byte) (val % 0x100)); + } - public static void setUSByte(final byte[] b, final int pos, final int val) { - b[pos] = ((byte) (val & 0xff)); - } + public static void setUSByte(final byte[] b, final int pos, final int val) { + b[pos] = ((byte) (val & 0xff)); + } - public static String strerror(final int code) { - switch (code) { - case RESULT_OK: - return "ok"; - case RESULT_MULTIPLE_BITS_NOT_SUPPORTED: - return "the CPU doesn't support reading a bit block of length<>1"; - case RESULT_ITEM_NOT_AVAILABLE: - return "the desired item is not available in the PLC"; - case RESULT_ITEM_NOT_AVAILABLE200: - return "the desired item is not available in the PLC (200 family)"; - case RESULT_ADDRESS_OUT_OF_RANGE: - return "the desired address is beyond limit for this PLC"; - case RESULT_CPU_RETURNED_NO_DATA: - return "the PLC returned a packet with no result data"; - case Nodave.RESULT_UNKNOWN_ERROR: - return "the PLC returned an error code not understood by this library"; - case Nodave.RESULT_EMPTY_RESULT_ERROR: - return "this result contains no data"; - case Nodave.RESULT_EMPTY_RESULT_SET_ERROR: - return "can't work with an undefined result set"; - case Nodave.RESULT_CANNOT_EVALUATE_PDU: - return "can't evaluate the received PDU"; - case Nodave.RESULT_WRITE_DATA_SIZE_MISMATCH: - return "Write data size error"; - case Nodave.RESULT_NO_PERIPHERAL_AT_ADDRESS: - return "No data from I/O module"; - case Nodave.RESULT_UNEXPECTED_FUNC: - return "Unexpected function code in answer"; - case Nodave.RESULT_UNKNOWN_DATA_UNIT_SIZE: - return "PLC responds wit an unknown data type"; - case Nodave.RESULT_SHORT_PACKET: - return "Short packet from PLC"; - case Nodave.RESULT_TIMEOUT: - return "Timeout when waiting for PLC response"; - case 0x8000: - return "function already occupied."; - case 0x8001: - return "not allowed in current operating status."; - case 0x8101: - return "hardware fault."; - case 0x8103: - return "object access not allowed."; - case 0x8104: - return "context is not supported."; - case 0x8105: - return "invalid address."; - case 0x8106: - return "data type not supported."; - case 0x8107: - return "data type not consistent."; - case 0x810A: - return "object doesn't exist."; - case 0x8500: - return "incorrect PDU size."; - case 0x8702: - return "address invalid."; - case 0xd201: - return "block name syntax error."; - case 0xd202: - return "syntax error function parameter."; - case 0xd203: - return "syntax error block type."; - case 0xd204: - return "no linked block in storage medium."; - case 0xd205: - return "object already exists."; - case 0xd206: - return "object already exists."; - case 0xd207: - return "block exists in EPROM."; - case 0xd209: - return "block doesn't exist."; - case 0xd20e: - return "no block doesn't exist."; - case 0xd210: - return "block number too big."; - case 0xd240: - return "unfinished block transfer in progress?"; - case 0xd241: - return "protected by password."; - default: - return "no message defined for code: " + code + "!"; - } - } + public static String strerror(final int code) { + switch (code) { + case RESULT_OK: + return "ok"; + case RESULT_MULTIPLE_BITS_NOT_SUPPORTED: + return "the CPU doesn't support reading a bit block of length<>1"; + case RESULT_ITEM_NOT_AVAILABLE: + return "the desired item is not available in the PLC"; + case RESULT_ITEM_NOT_AVAILABLE200: + return "the desired item is not available in the PLC (200 family)"; + case RESULT_ADDRESS_OUT_OF_RANGE: + return "the desired address is beyond limit for this PLC"; + case RESULT_CPU_RETURNED_NO_DATA: + return "the PLC returned a packet with no result data"; + case Nodave.RESULT_UNKNOWN_ERROR: + return "the PLC returned an error code not understood by this library"; + case Nodave.RESULT_EMPTY_RESULT_ERROR: + return "this result contains no data"; + case Nodave.RESULT_EMPTY_RESULT_SET_ERROR: + return "can't work with an undefined result set"; + case Nodave.RESULT_CANNOT_EVALUATE_PDU: + return "can't evaluate the received PDU"; + case Nodave.RESULT_WRITE_DATA_SIZE_MISMATCH: + return "Write data size error"; + case Nodave.RESULT_NO_PERIPHERAL_AT_ADDRESS: + return "No data from I/O module"; + case Nodave.RESULT_UNEXPECTED_FUNC: + return "Unexpected function code in answer"; + case Nodave.RESULT_UNKNOWN_DATA_UNIT_SIZE: + return "PLC responds wit an unknown data type"; + case Nodave.RESULT_SHORT_PACKET: + return "Short packet from PLC"; + case Nodave.RESULT_TIMEOUT: + return "Timeout when waiting for PLC response"; + case 0x8000: + return "function already occupied."; + case 0x8001: + return "not allowed in current operating status."; + case 0x8101: + return "hardware fault."; + case 0x8103: + return "object access not allowed."; + case 0x8104: + return "context is not supported."; + case 0x8105: + return "invalid address."; + case 0x8106: + return "data type not supported."; + case 0x8107: + return "data type not consistent."; + case 0x810A: + return "object doesn't exist."; + case 0x8500: + return "incorrect PDU size."; + case 0x8702: + return "address invalid."; + case 0xd201: + return "block name syntax error."; + case 0xd202: + return "syntax error function parameter."; + case 0xd203: + return "syntax error block type."; + case 0xd204: + return "no linked block in storage medium."; + case 0xd205: + return "object already exists."; + case 0xd206: + return "object already exists."; + case 0xd207: + return "block exists in EPROM."; + case 0xd209: + return "block doesn't exist."; + case 0xd20e: + return "no block doesn't exist."; + case 0xd210: + return "block number too big."; + case 0xd240: + return "unfinished block transfer in progress?"; + case 0xd241: + return "protected by password."; + default: + return "no message defined for code: " + code + "!"; + } + } - public static byte[] toPLCfloat(final double d) { - final float f = (float) d; - return toPLCfloat(f); - } + public static byte[] toPLCfloat(final double d) { + final float f = (float) d; + return toPLCfloat(f); + } - public static byte[] toPLCfloat(final float f) { - final int i = Float.floatToIntBits(f); - return bswap_32(i); - } + public static byte[] toPLCfloat(final float f) { + final int i = Float.floatToIntBits(f); + return bswap_32(i); + } - public static long USBELong(final byte[] b, final int pos) { - int i = b[pos]; - int j = b[pos + 1]; - int k = b[pos + 2]; - int l = b[pos + 3]; - // System.out.println( - // pos + " 0:" + i + " 1:" + j + " 2:" + k + " 3:" + l); - if (i < 0) { - i += 256; - } - if (j < 0) { - j += 256; - } - if (k < 0) { - k += 256; - } - if (l < 0) { - l += 256; - } - return ((256 * k) + l) + (65536L * ((256 * i) + j)); - } + public static long USBELong(final byte[] b, final int pos) { + int i = b[pos]; + int j = b[pos + 1]; + int k = b[pos + 2]; + int l = b[pos + 3]; + // System.out.println( + // pos + " 0:" + i + " 1:" + j + " 2:" + k + " 3:" + l); + if (i < 0) { + i += 256; + } + if (j < 0) { + j += 256; + } + if (k < 0) { + k += 256; + } + if (l < 0) { + l += 256; + } + return ((256 * k) + l) + (65536L * ((256 * i) + j)); + } - public static int USBEWord(final byte[] b, final int pos) { - int i = b[pos]; - int k = b[pos + 1]; - if (i < 0) { - i += 256; - } - if (k < 0) { - k += 256; - } - return ((256 * i) + k); - } + public static int USBEWord(final byte[] b, final int pos) { + int i = b[pos]; + int k = b[pos + 1]; + if (i < 0) { + i += 256; + } + if (k < 0) { + k += 256; + } + return ((256 * i) + k); + } - public static int USByte(final byte[] b, final int pos) { - int i = b[pos]; - if (i < 0) { - i += 256; - } - return (i); - } + public static int USByte(final byte[] b, final int pos) { + int i = b[pos]; + if (i < 0) { + i += 256; + } + return (i); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PDU.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PDU.java index a49e8eafd..e84ee8374 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PDU.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PDU.java @@ -23,469 +23,461 @@ import io.github.pnoker.driver.api.DaveArea; */ public final class PDU { - /** - * known function codes - */ - public final static byte FUNC_READ = 4; + /** + * known function codes + */ + public final static byte FUNC_READ = 4; - public final static byte FUNC_WRITE = 5; + public final static byte FUNC_WRITE = 5; - public int data; + public int data; - public int param; // the position of the parameters; + public int param; // the position of the parameters; - public int plen; + public int plen; - public int udata; + public int udata; - public int udlen; + public int udlen; - int dlen; + int dlen; - int error; + int error; - int header; // the position of the header; + int header; // the position of the header; - int hlen; + int hlen; - byte[] mem; + byte[] mem; - /** - * set up the PDU information - * @param mem Mem - * @param pos Pos - */ - public PDU(final byte[] mem, final int pos) { - this.mem = mem; - this.header = pos; - } + /** + * set up the PDU information + * + * @param mem Mem + * @param pos Pos + */ + public PDU(final byte[] mem, final int pos) { + this.mem = mem; + this.header = pos; + } - public int addBitVarToReadRequest(final int area, final int DBnum, final int start, final int len) { - final byte pa[] = { 0x12, 0x0a, 0x10, 0x01, /* single bits */ - 0x00, 0x1A, /* insert length in bytes here */ - 0x00, 0x0B, /* insert DB number here */ - (byte) 0x84, /* change this to real area code */ - 0x00, 0x00, (byte) 0xC0 /* insert start address in bits */ - }; - Nodave.setUSBEWord(pa, 4, len); - Nodave.setUSBEWord(pa, 6, DBnum); - Nodave.setUSBELong(pa, 8, start); - Nodave.setUSByte(pa, 8, area); + public int addBitVarToReadRequest(final int area, final int DBnum, final int start, final int len) { + final byte pa[] = {0x12, 0x0a, 0x10, 0x01, /* single bits */ + 0x00, 0x1A, /* insert length in bytes here */ + 0x00, 0x0B, /* insert DB number here */ + (byte) 0x84, /* change this to real area code */ + 0x00, 0x00, (byte) 0xC0 /* insert start address in bits */ + }; + Nodave.setUSBEWord(pa, 4, len); + Nodave.setUSBEWord(pa, 6, DBnum); + Nodave.setUSBELong(pa, 8, start); + Nodave.setUSByte(pa, 8, area); - this.mem[this.param + 1]++; - System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); - this.plen += pa.length; - Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); - return 0; + this.mem[this.param + 1]++; + System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); + this.plen += pa.length; + Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); + return 0; - } + } - public void addBitVarToWriteRequest(final DaveArea area, final int DBnum, final int start, final int byteCount, - final byte[] buffer) { - final byte da[] = { 0, 3, 0, 0, }; - final byte pa[] = { 0x12, 0x0a, 0x10, 0x01, /* single bit */ - 0, 0, /* insert length in bytes here */ - 0, 0, /* insert DB number here */ - 0, /* change this to real area code */ - 0, 0, 0 /* insert start address in bits */ - }; - if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) - || (area == DaveArea.COUNTER200)) { - pa[3] = (byte) area.getCode(); - pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); - pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); - } - else if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { - pa[3] = 4; - pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); - pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); - } - else { - pa[4] = (byte) (byteCount / 0x100); - pa[5] = (byte) (byteCount & 0xff); - } - pa[6] = (byte) (DBnum / 256); - pa[7] = (byte) (DBnum & 0xff); - pa[8] = (byte) area.getCode(); - pa[11] = (byte) (start & 0xff); - pa[10] = (byte) ((start / 0x100) & 0xff); - pa[9] = (byte) (start / 0x10000); + public void addBitVarToWriteRequest(final DaveArea area, final int DBnum, final int start, final int byteCount, + final byte[] buffer) { + final byte da[] = {0, 3, 0, 0,}; + final byte pa[] = {0x12, 0x0a, 0x10, 0x01, /* single bit */ + 0, 0, /* insert length in bytes here */ + 0, 0, /* insert DB number here */ + 0, /* change this to real area code */ + 0, 0, 0 /* insert start address in bits */ + }; + if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) + || (area == DaveArea.COUNTER200)) { + pa[3] = (byte) area.getCode(); + pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); + pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); + } else if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { + pa[3] = 4; + pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); + pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); + } else { + pa[4] = (byte) (byteCount / 0x100); + pa[5] = (byte) (byteCount & 0xff); + } + pa[6] = (byte) (DBnum / 256); + pa[7] = (byte) (DBnum & 0xff); + pa[8] = (byte) area.getCode(); + pa[11] = (byte) (start & 0xff); + pa[10] = (byte) ((start / 0x100) & 0xff); + pa[9] = (byte) (start / 0x10000); - if ((this.dlen % 2) != 0) { - this.addData(da, 1); - } + if ((this.dlen % 2) != 0) { + this.addData(da, 1); + } - this.mem[this.param + 1]++; - if (this.dlen > 0) { - final byte[] saveData = new byte[this.dlen]; - System.arraycopy(this.mem, this.data, saveData, 0, this.dlen); - System.arraycopy(saveData, 0, this.mem, this.data + pa.length, this.dlen); - } - System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); - this.plen += pa.length; - Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); - this.data = this.param + this.plen; + this.mem[this.param + 1]++; + if (this.dlen > 0) { + final byte[] saveData = new byte[this.dlen]; + System.arraycopy(this.mem, this.data, saveData, 0, this.dlen); + System.arraycopy(saveData, 0, this.mem, this.data + pa.length, this.dlen); + } + System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); + this.plen += pa.length; + Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); + this.data = this.param + this.plen; - this.addData(da); - this.addValue(buffer); - } + this.addData(da); + this.addValue(buffer); + } - /** - * Add data after parameters, set dlen as needed. Needs valid header and parameters - */ - void addData(final byte[] newData) { - final int appPos = this.data + this.dlen; // append to this position - this.dlen += newData.length; - System.arraycopy(newData, 0, this.mem, appPos, newData.length); - Nodave.setUSBEWord(this.mem, this.header + 8, this.dlen); - } + /** + * Add data after parameters, set dlen as needed. Needs valid header and parameters + */ + void addData(final byte[] newData) { + final int appPos = this.data + this.dlen; // append to this position + this.dlen += newData.length; + System.arraycopy(newData, 0, this.mem, appPos, newData.length); + Nodave.setUSBEWord(this.mem, this.header + 8, this.dlen); + } - /** - * Add len bytes of len after parameters from a maybe longer block of bytes. Set dlen - * as needed. Needs valid header and parameters - * @param newData New Data - * @param len Length - */ - public void addData(final byte[] newData, final int len) { - final int appPos = this.data + this.dlen; // append to this position - this.dlen += len; - System.arraycopy(newData, 0, this.mem, appPos, len); - Nodave.setUSBEWord(this.mem, this.header + 8, this.dlen); - } + /** + * Add len bytes of len after parameters from a maybe longer block of bytes. Set dlen + * as needed. Needs valid header and parameters + * + * @param newData New Data + * @param len Length + */ + public void addData(final byte[] newData, final int len) { + final int appPos = this.data + this.dlen; // append to this position + this.dlen += len; + System.arraycopy(newData, 0, this.mem, appPos, len); + Nodave.setUSBEWord(this.mem, this.header + 8, this.dlen); + } - public void addParam(final byte[] pa) { - this.plen = pa.length; - System.arraycopy(pa, 0, this.mem, this.param, this.plen); - Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); - // mem[header + 6] = (byte) (pa.length / 256); - // mem[header + 7] = (byte) (pa.length % 256); - this.data = this.param + this.plen; - this.dlen = 0; - } + public void addParam(final byte[] pa) { + this.plen = pa.length; + System.arraycopy(pa, 0, this.mem, this.param, this.plen); + Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); + // mem[header + 6] = (byte) (pa.length / 256); + // mem[header + 7] = (byte) (pa.length % 256); + this.data = this.param + this.plen; + this.dlen = 0; + } - /* - * add data in user data. Add a user data header, if not yet present. - */ - public void addUserData(final byte[] da) { - final byte udh[] = { (byte) 0xff, 9, 0, 0 }; - if (this.dlen == 0) { - this.addData(udh); - } - this.addValue(da); - } + /* + * add data in user data. Add a user data header, if not yet present. + */ + public void addUserData(final byte[] da) { + final byte udh[] = {(byte) 0xff, 9, 0, 0}; + if (this.dlen == 0) { + this.addData(udh); + } + this.addValue(da); + } - /** - * Add values after value header in data, adjust dlen and data count. Needs valid - * header,parameters,data,dlen - */ - void addValue(final byte[] values) { - int valCount = (0x100 * this.mem[this.data + 2]) + this.mem[this.data + 3]; - if (this.mem[this.data + 1] == 4) { // bit data, length is in bits - valCount += 8 * values.length; - } - else if (this.mem[this.data + 1] == 9) { // byte data, length is in - // bytes - valCount += values.length; - } - else { - // XXX - } - if (this.udata == 0) { - this.udata = this.data + 4; - } - this.udlen += values.length; - Nodave.setUSBEWord(this.mem, this.data + 2, valCount); - this.addData(values); - } + /** + * Add values after value header in data, adjust dlen and data count. Needs valid + * header,parameters,data,dlen + */ + void addValue(final byte[] values) { + int valCount = (0x100 * this.mem[this.data + 2]) + this.mem[this.data + 3]; + if (this.mem[this.data + 1] == 4) { // bit data, length is in bits + valCount += 8 * values.length; + } else if (this.mem[this.data + 1] == 9) { // byte data, length is in + // bytes + valCount += values.length; + } else { + // XXX + } + if (this.udata == 0) { + this.udata = this.data + 4; + } + this.udlen += values.length; + Nodave.setUSBEWord(this.mem, this.data + 2, valCount); + this.addData(values); + } - public int addVarToReadRequest(final DaveArea area, final int DBnum, int start, final int len) { - final byte[] pa = { 0x12, 0x0a, 0x10, 0x02, /* 1=single bit, 2=byte, 4=word */ - 0x00, 0x1A, /* length in bytes */ - 0x00, 0x0B, /* DB number */ - (byte) 0x84, // * area code */ - 0x00, 0x00, (byte) 0xC0 /* start address in bits */ - }; + public int addVarToReadRequest(final DaveArea area, final int DBnum, int start, final int len) { + final byte[] pa = {0x12, 0x0a, 0x10, 0x02, /* 1=single bit, 2=byte, 4=word */ + 0x00, 0x1A, /* length in bytes */ + 0x00, 0x0B, /* DB number */ + (byte) 0x84, // * area code */ + 0x00, 0x00, (byte) 0xC0 /* start address in bits */ + }; - if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { - pa[3] = 4; - start *= 8; /* bits */ - } - else if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) - || (area == DaveArea.COUNTER200)) { - pa[3] = (byte) area.getCode(); - } - else { - start *= 8; /* bits */ - } + if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { + pa[3] = 4; + start *= 8; /* bits */ + } else if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) + || (area == DaveArea.COUNTER200)) { + pa[3] = (byte) area.getCode(); + } else { + start *= 8; /* bits */ + } - Nodave.setUSBEWord(pa, 4, len); - Nodave.setUSBEWord(pa, 6, DBnum); - Nodave.setUSBELong(pa, 8, start); - Nodave.setUSByte(pa, 8, area.getCode()); + Nodave.setUSBEWord(pa, 4, len); + Nodave.setUSBEWord(pa, 6, DBnum); + Nodave.setUSBELong(pa, 8, start); + Nodave.setUSByte(pa, 8, area.getCode()); - this.mem[this.param + 1]++; - System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); - this.plen += pa.length; - Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); - /** - * TODO calc length of result. Do not add variable if it would exceed max. result - * length. - */ - return 0; - } + this.mem[this.param + 1]++; + System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); + this.plen += pa.length; + Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); + /** + * TODO calc length of result. Do not add variable if it would exceed max. result + * length. + */ + return 0; + } - public void addVarToWriteRequest(final DaveArea area, final int DBnum, int start, final int byteCount, - final byte[] buffer) { - final byte da[] = { 0, 4, 0, 0, }; - final byte pa[] = { 0x12, 0x0a, 0x10, 0x02, - /* unit (for count?, for consistency?) byte */ - 0, 0, /* length in bytes */ - 0, 0, /* DB number */ - 0, /* area code */ - 0, 0, 0 /* start address in bits */ - }; - if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) - || (area == DaveArea.COUNTER200)) { - pa[3] = (byte) area.getCode(); - pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); - pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); - } - else if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { - pa[3] = 4; - pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); - pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); - } - else { - pa[4] = (byte) (byteCount / 0x100); - pa[5] = (byte) (byteCount & 0xff); - } - pa[6] = (byte) (DBnum / 256); - pa[7] = (byte) (DBnum & 0xff); - pa[8] = (byte) (area.getCode()); - start *= 8; /* number of bits */ - pa[11] = (byte) (start & 0xff); - pa[10] = (byte) ((start / 0x100) & 0xff); - pa[9] = (byte) (start / 0x10000); - if ((this.dlen % 2) != 0) { - this.addData(da, 1); - } - this.mem[this.param + 1]++; - if (this.dlen > 0) { - final byte[] saveData = new byte[this.dlen]; - System.arraycopy(this.mem, this.data, saveData, 0, this.dlen); - System.arraycopy(saveData, 0, this.mem, this.data + pa.length, this.dlen); - } - System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); - this.plen += pa.length; - Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); - this.data = this.param + this.plen; - this.addData(da); - this.addValue(buffer); - } + public void addVarToWriteRequest(final DaveArea area, final int DBnum, int start, final int byteCount, + final byte[] buffer) { + final byte da[] = {0, 4, 0, 0,}; + final byte pa[] = {0x12, 0x0a, 0x10, 0x02, + /* unit (for count?, for consistency?) byte */ + 0, 0, /* length in bytes */ + 0, 0, /* DB number */ + 0, /* area code */ + 0, 0, 0 /* start address in bits */ + }; + if ((area == DaveArea.TIMER) || (area == DaveArea.COUNTER) || (area == DaveArea.TIMER200) + || (area == DaveArea.COUNTER200)) { + pa[3] = (byte) area.getCode(); + pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); + pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); + } else if ((area == DaveArea.ANALOGINPUTS200) || (area == DaveArea.ANALOGOUTPUTS200)) { + pa[3] = 4; + pa[4] = (byte) (((byteCount + 1) / 2) / 0x100); + pa[5] = (byte) (((byteCount + 1) / 2) & 0xff); + } else { + pa[4] = (byte) (byteCount / 0x100); + pa[5] = (byte) (byteCount & 0xff); + } + pa[6] = (byte) (DBnum / 256); + pa[7] = (byte) (DBnum & 0xff); + pa[8] = (byte) (area.getCode()); + start *= 8; /* number of bits */ + pa[11] = (byte) (start & 0xff); + pa[10] = (byte) ((start / 0x100) & 0xff); + pa[9] = (byte) (start / 0x10000); + if ((this.dlen % 2) != 0) { + this.addData(da, 1); + } + this.mem[this.param + 1]++; + if (this.dlen > 0) { + final byte[] saveData = new byte[this.dlen]; + System.arraycopy(this.mem, this.data, saveData, 0, this.dlen); + System.arraycopy(saveData, 0, this.mem, this.data + pa.length, this.dlen); + } + System.arraycopy(pa, 0, this.mem, this.param + this.plen, pa.length); + this.plen += pa.length; + Nodave.setUSBEWord(this.mem, this.header + 6, this.plen); + this.data = this.param + this.plen; + this.addData(da); + this.addValue(buffer); + } - /** - * construct a write request for a single item in PLC memory. - */ - /* - * void constructWriteRequest( int area, int DBnum, int start, int len, byte[] buffer) - * { byte pa[] = new byte[14]; byte da[] = { 0, 4, 0, 0 }; pa[0] = PDU.FUNC_WRITE; - * pa[1] = (byte) 0x01; pa[2] = (byte) 0x12; pa[3] = (byte) 0x0a; pa[4] = (byte) 0x10; - * pa[5] = (byte) 0x02; - * - * Nodave.setUSBEWord(pa, 6, len); Nodave.setUSBEWord(pa, 8, DBnum); - * Nodave.setUSBELong(pa, 10, 8 * start); // the bit address Nodave.setUSByte(pa, 10, - * area); initHeader(1); addParam(pa); addData(da); addValue(buffer); if - * ((Nodave.Debug & Nodave.DEBUG_PDU) != 0) { dump(); } } - */ + /** + * construct a write request for a single item in PLC memory. + */ + /* + * void constructWriteRequest( int area, int DBnum, int start, int len, byte[] buffer) + * { byte pa[] = new byte[14]; byte da[] = { 0, 4, 0, 0 }; pa[0] = PDU.FUNC_WRITE; + * pa[1] = (byte) 0x01; pa[2] = (byte) 0x12; pa[3] = (byte) 0x0a; pa[4] = (byte) 0x10; + * pa[5] = (byte) 0x02; + * + * Nodave.setUSBEWord(pa, 6, len); Nodave.setUSBEWord(pa, 8, DBnum); + * Nodave.setUSBELong(pa, 10, 8 * start); // the bit address Nodave.setUSByte(pa, 10, + * area); initHeader(1); addParam(pa); addData(da); addValue(buffer); if + * ((Nodave.Debug & Nodave.DEBUG_PDU) != 0) { dump(); } } + */ - /** - * display information about a PDU - */ - public void dump() { - Nodave.dump("PDU header ", this.mem, this.header, this.hlen); - System.out.println("plen: " + this.plen + " dlen: " + this.dlen); - Nodave.dump("Parameter", this.mem, this.param, this.plen); - if (this.dlen > 0) { - Nodave.dump("Data ", this.mem, this.data, this.dlen); - } - if (this.udlen > 0) { - Nodave.dump("result Data ", this.mem, this.udata, this.udlen); - } - } + /** + * display information about a PDU + */ + public void dump() { + Nodave.dump("PDU header ", this.mem, this.header, this.hlen); + System.out.println("plen: " + this.plen + " dlen: " + this.dlen); + Nodave.dump("Parameter", this.mem, this.param, this.plen); + if (this.dlen > 0) { + Nodave.dump("Data ", this.mem, this.data, this.dlen); + } + if (this.udlen > 0) { + Nodave.dump("result Data ", this.mem, this.udata, this.udlen); + } + } - public int getError() { - return this.error; - } + public int getError() { + return this.error; + } - /** - * return the function code of the PDU - * @return Function Code Of PDU - */ - public int getFunc() { - return Nodave.USByte(this.mem, this.param + 0); - } + /** + * return the function code of the PDU + * + * @return Function Code Of PDU + */ + public int getFunc() { + return Nodave.USByte(this.mem, this.param + 0); + } - /* - * typedef struct { uc P; // allways 0x32 uc type; // a type? type 2 and 3 headers are - * two bytes longer. uc a,b; // currently unknown us number; // Number, can be used to - * identify answers corresponding to requests us plen; // length of parameters which - * follow this header us dlen; // length of data which follows the parameters uc x[2]; - * // only present in type 2 and 3 headers. This may contain error information. } - * PDUHeader; - */ + /* + * typedef struct { uc P; // allways 0x32 uc type; // a type? type 2 and 3 headers are + * two bytes longer. uc a,b; // currently unknown us number; // Number, can be used to + * identify answers corresponding to requests us plen; // length of parameters which + * follow this header us dlen; // length of data which follows the parameters uc x[2]; + * // only present in type 2 and 3 headers. This may contain error information. } + * PDUHeader; + */ - /** - * return the number of the PDU - * @return number - */ - public int getNumber() { - return Nodave.USBEWord(this.mem, this.header + 4); - } + /** + * return the number of the PDU + * + * @return number + */ + public int getNumber() { + return Nodave.USBEWord(this.mem, this.header + 4); + } - /** - * set the number of the PDU - * @param n number - */ - public void setNumber(final int n) { - Nodave.setUSBEWord(this.mem, this.header + 4, n); - } + /** + * set the number of the PDU + * + * @param n number + */ + public void setNumber(final int n) { + Nodave.setUSBEWord(this.mem, this.header + 4, n); + } - /** - * reserve space for the header of a new PDU - * @param type Type - */ - public void initHeader(final int type) { - if ((type == 2) || (type == 3)) { - this.hlen = 12; - } - else { - this.hlen = 10; - } - for (int i = 0; i < this.hlen; i++) { - this.mem[this.header + i] = 0; - } - this.param = this.header + this.hlen; - this.mem[this.header] = (byte) 0x32; - this.mem[this.header + 1] = (byte) type; - this.dlen = 0; - this.plen = 0; - this.udlen = 0; - this.data = 0; - this.udata = 0; - } + /** + * reserve space for the header of a new PDU + * + * @param type Type + */ + public void initHeader(final int type) { + if ((type == 2) || (type == 3)) { + this.hlen = 12; + } else { + this.hlen = 10; + } + for (int i = 0; i < this.hlen; i++) { + this.mem[this.header + i] = 0; + } + this.param = this.header + this.hlen; + this.mem[this.header] = (byte) 0x32; + this.mem[this.header + 1] = (byte) type; + this.dlen = 0; + this.plen = 0; + this.udlen = 0; + this.data = 0; + this.udata = 0; + } - public void initReadRequest() { - final byte pa[] = new byte[2]; - pa[0] = PDU.FUNC_READ; - pa[1] = (byte) 0x00; - this.initHeader(1); - this.addParam(pa); - } + public void initReadRequest() { + final byte pa[] = new byte[2]; + pa[0] = PDU.FUNC_READ; + pa[1] = (byte) 0x00; + this.initHeader(1); + this.addParam(pa); + } - /** - * prepare a read request with no item. - */ - public void prepareReadRequest() { - final byte pa[] = new byte[2]; - pa[0] = PDU.FUNC_READ; - pa[1] = (byte) 0x00; - this.initHeader(1); - this.addParam(pa); - } + /** + * prepare a read request with no item. + */ + public void prepareReadRequest() { + final byte pa[] = new byte[2]; + pa[0] = PDU.FUNC_READ; + pa[1] = (byte) 0x00; + this.initHeader(1); + this.addParam(pa); + } - /** - * prepare a write request with no item. - */ - public void prepareWriteRequest() { - final byte pa[] = new byte[2]; - pa[0] = PDU.FUNC_WRITE; - pa[1] = (byte) 0x00; - this.initHeader(1); - this.addParam(pa); - } + /** + * prepare a write request with no item. + */ + public void prepareWriteRequest() { + final byte pa[] = new byte[2]; + pa[0] = PDU.FUNC_WRITE; + pa[1] = (byte) 0x00; + this.initHeader(1); + this.addParam(pa); + } - /** - * Set up a PDU instance to reflect the structure of data present in the memory area - * given to initHeader. Needs valid header. - * @return Result - */ - public int setupReceivedPDU() { - int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; // just assume the worst - if ((this.mem[this.header + 1] == 2) || (this.mem[this.header + 1] == 3)) { - this.hlen = 12; - res = Nodave.USBEWord(this.mem, this.header + 10); - } - else { - this.error = 0; - this.hlen = 10; - res = 0; - } - this.param = this.header + this.hlen; - this.plen = Nodave.USBEWord(this.mem, this.header + 6); - this.data = this.param + this.plen; - this.dlen = Nodave.USBEWord(this.mem, this.header + 8); - this.udlen = 0; - this.udata = 0; - return res; - } + /** + * Set up a PDU instance to reflect the structure of data present in the memory area + * given to initHeader. Needs valid header. + * + * @return Result + */ + public int setupReceivedPDU() { + int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; // just assume the worst + if ((this.mem[this.header + 1] == 2) || (this.mem[this.header + 1] == 3)) { + this.hlen = 12; + res = Nodave.USBEWord(this.mem, this.header + 10); + } else { + this.error = 0; + this.hlen = 10; + res = 0; + } + this.param = this.header + this.hlen; + this.plen = Nodave.USBEWord(this.mem, this.header + 6); + this.data = this.param + this.plen; + this.dlen = Nodave.USBEWord(this.mem, this.header + 8); + this.udlen = 0; + this.udata = 0; + return res; + } - public int testPGReadResult() { - if (this.mem[this.param] != 0) { - return Nodave.RESULT_UNEXPECTED_FUNC; - } - return this.testResultData(); - } + public int testPGReadResult() { + if (this.mem[this.param] != 0) { + return Nodave.RESULT_UNEXPECTED_FUNC; + } + return this.testResultData(); + } - ; + ; - int testReadResult() { - if (this.mem[this.param] != FUNC_READ) { - return Nodave.RESULT_UNEXPECTED_FUNC; - } - return this.testResultData(); - } + int testReadResult() { + if (this.mem[this.param] != FUNC_READ) { + return Nodave.RESULT_UNEXPECTED_FUNC; + } + return this.testResultData(); + } - /* - - */ - int testResultData() { - int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; // just assume the worst - if ((this.mem[this.data] == (byte) 255) && (this.dlen > 4)) { - res = Nodave.RESULT_OK; - this.udata = this.data + 4; - // udlen=data[2]*0x100+data[3]; - this.udlen = Nodave.USBEWord(this.mem, this.data + 2); - if (this.mem[this.data + 1] == 4) { - this.udlen >>= 3; /* len is in bits, adjust */ - } - else if (this.mem[this.data + 1] == 9) { - /* len is already in bytes, ok */ - } - else if (this.mem[this.data + 1] == 3) { - /* len is in bits, but there is a byte per result bit, ok */ - } - else { - res = Nodave.RESULT_UNKNOWN_DATA_UNIT_SIZE; - } - } - else { - res = this.mem[this.data]; - } - return res; - } + /* - int testWriteResult() { - int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; - if (this.mem[this.param] != FUNC_WRITE) { - return Nodave.RESULT_UNEXPECTED_FUNC; - } - if ((this.mem[this.data] == 255)) { - res = Nodave.RESULT_OK; - } - else { - res = this.mem[this.data]; - } - return res; - } + */ + int testResultData() { + int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; // just assume the worst + if ((this.mem[this.data] == (byte) 255) && (this.dlen > 4)) { + res = Nodave.RESULT_OK; + this.udata = this.data + 4; + // udlen=data[2]*0x100+data[3]; + this.udlen = Nodave.USBEWord(this.mem, this.data + 2); + if (this.mem[this.data + 1] == 4) { + this.udlen >>= 3; /* len is in bits, adjust */ + } else if (this.mem[this.data + 1] == 9) { + /* len is already in bytes, ok */ + } else if (this.mem[this.data + 1] == 3) { + /* len is in bits, but there is a byte per result bit, ok */ + } else { + res = Nodave.RESULT_UNKNOWN_DATA_UNIT_SIZE; + } + } else { + res = this.mem[this.data]; + } + return res; + } + + int testWriteResult() { + int res = Nodave.RESULT_CANNOT_EVALUATE_PDU; + if (this.mem[this.param] != FUNC_WRITE) { + return Nodave.RESULT_UNEXPECTED_FUNC; + } + if ((this.mem[this.data] == 255)) { + res = Nodave.RESULT_OK; + } else { + res = this.mem[this.data]; + } + return res; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PLCinterface.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PLCinterface.java index 72ebe72e6..377b82aae 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PLCinterface.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/PLCinterface.java @@ -25,68 +25,65 @@ import java.io.OutputStream; */ public final class PLCinterface { - InputStream in; + InputStream in; - int localMPI; // the adapter's MPI address + int localMPI; // the adapter's MPI address - String name; + String name; - OutputStream out; + OutputStream out; - int protocol; // The kind of transport used on this interface. + int protocol; // The kind of transport used on this interface. - int wp, rp; + int wp, rp; - public PLCinterface(final OutputStream out, final InputStream in, final String name, final int localMPI, - final int protocol) { - this.init(out, in, name, localMPI, protocol); - } + public PLCinterface(final OutputStream out, final InputStream in, final String name, final int localMPI, + final int protocol) { + this.init(out, in, name, localMPI, protocol); + } - public void init(final OutputStream oStream, final InputStream iStream, final String name, final int localMPI, - final int protocol) { - this.out = oStream; - this.in = iStream; - this.name = name; - this.localMPI = localMPI; - this.protocol = protocol; - } + public void init(final OutputStream oStream, final InputStream iStream, final String name, final int localMPI, + final int protocol) { + this.out = oStream; + this.in = iStream; + this.name = name; + this.localMPI = localMPI; + this.protocol = protocol; + } - public int read(final byte[] b, int start, int len) { - int res; - try { - int retry = 0; - while ((this.in.available() <= 0) && (retry < 500)) { - try { - if (retry > 0) { - Thread.sleep(1); - } - retry++; - } - catch (final InterruptedException e) { - e.printStackTrace(); - } - } - res = 0; - while ((this.in.available() > 0) && (len > 0)) { - res = this.in.read(b, start, len); - start += res; - len -= res; - } - return res; - } - catch (final IOException e) { - e.printStackTrace(); - return 0; - } - } + public int read(final byte[] b, int start, int len) { + int res; + try { + int retry = 0; + while ((this.in.available() <= 0) && (retry < 500)) { + try { + if (retry > 0) { + Thread.sleep(1); + } + retry++; + } catch (final InterruptedException e) { + e.printStackTrace(); + } + } + res = 0; + while ((this.in.available() > 0) && (len > 0)) { + res = this.in.read(b, start, len); + start += res; + len -= res; + } + return res; + } catch (final IOException e) { + e.printStackTrace(); + return 0; + } + } - public void write(final byte[] b, final int start, final int len) { - try { - this.out.write(b, start, len); - } - catch (final IOException e) { - System.err.println("Interface.write: " + e); - } - } + public void write(final byte[] b, final int start, final int len) { + try { + this.out.write(b, start, len); + } catch (final IOException e) { + System.err.println("Interface.write: " + e); + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Result.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Result.java index a512aaec5..ff9835ee7 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Result.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/Result.java @@ -24,10 +24,10 @@ package io.github.pnoker.driver.api.impl.nodave; */ public final class Result { - public int bufferStart; + public int bufferStart; - public int error; + public int error; - public int length; + public int length; } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/ResultSet.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/ResultSet.java index ca61d69b3..698851808 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/ResultSet.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/ResultSet.java @@ -21,28 +21,28 @@ package io.github.pnoker.driver.api.impl.nodave; */ public final class ResultSet { - public Result[] results; + public Result[] results; - private int errorState, numResults; + private int errorState, numResults; - public int getErrorState() { - return this.errorState; - } + public int getErrorState() { + return this.errorState; + } - public void setErrorState(final int error) { - this.errorState = error; - } + public void setErrorState(final int error) { + this.errorState = error; + } - ; + ; - public int getNumResults() { - return this.numResults; - } + public int getNumResults() { + return this.numResults; + } - public void setNumResults(final int nr) { - this.numResults = nr; - } + public void setNumResults(final int nr) { + this.numResults = nr; + } - ; + ; } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/S7Connection.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/S7Connection.java index e1d3be1da..12662255f 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/S7Connection.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/S7Connection.java @@ -28,384 +28,388 @@ import java.util.concurrent.Semaphore; */ public abstract class S7Connection { - static int tmo_normal = 150; + static int tmo_normal = 150; - public int maxPDUlength; + public int maxPDUlength; - public byte messageNumber = 0; + public byte messageNumber = 0; - public byte[] msgIn; + public byte[] msgIn; - public byte[] msgOut; + public byte[] msgOut; - public int packetNumber = 0; // packetNumber in transport layer + public int packetNumber = 0; // packetNumber in transport layer - public int PDUstartIn; + public int PDUstartIn; - public int PDUstartOut; + public int PDUstartOut; - public Semaphore semaphore; + public Semaphore semaphore; - int answLen; // length of last message + int answLen; // length of last message - /** - * position in result data, incremented when variables are extracted without position - */ - int dataPointer; + /** + * position in result data, incremented when variables are extracted without position + */ + int dataPointer; - PLCinterface iface; // pointer to used interface + PLCinterface iface; // pointer to used interface - PDU rcvdPDU; + PDU rcvdPDU; - /** - * absolute begin of result data - */ - int udata; + /** + * absolute begin of result data + */ + int udata; - public S7Connection(final PLCinterface ifa) { - this.iface = ifa; - this.msgIn = new byte[Nodave.MAX_RAW_LEN]; - this.msgOut = new byte[Nodave.MAX_RAW_LEN]; - this.PDUstartIn = 0; - this.PDUstartOut = 0; - this.semaphore = new Semaphore(1); - } + public S7Connection(final PLCinterface ifa) { + this.iface = ifa; + this.msgIn = new byte[Nodave.MAX_RAW_LEN]; + this.msgOut = new byte[Nodave.MAX_RAW_LEN]; + this.PDUstartIn = 0; + this.PDUstartOut = 0; + this.semaphore = new Semaphore(1); + } - abstract public int exchange(PDU p1); + abstract public int exchange(PDU p1); - // int numResults; - /* - * class Result { int error; byte[] data; } - */ - /* - * Read a predefined set of values from the PLC. Return ok or an error state If a - * buffer pointer is provided, data will be copied into this buffer. If it's NULL you - * can get your data from the resultPointer in daveConnection long as you do not send - * further requests. - */ - public ResultSet execReadRequest(final PDU p) { - PDU p2; - int errorState; - errorState = this.exchange(p); + // int numResults; + /* + * class Result { int error; byte[] data; } + */ + /* + * Read a predefined set of values from the PLC. Return ok or an error state If a + * buffer pointer is provided, data will be copied into this buffer. If it's NULL you + * can get your data from the resultPointer in daveConnection long as you do not send + * further requests. + */ + public ResultSet execReadRequest(final PDU p) { + PDU p2; + int errorState; + errorState = this.exchange(p); - p2 = new PDU(this.msgIn, this.PDUstartIn); - p2.setupReceivedPDU(); - /* - * if (p2.udlen == 0) { dataPointer = 0; answLen = 0; return - * Nodave.RESULT_CPU_RETURNED_NO_DATA; } - */ - final ResultSet rs = new ResultSet(); - if (p2.mem[p2.param + 0] == PDU.FUNC_READ) { - int numResults = p2.mem[p2.param + 1]; - // System.out.println("Results " + numResults); - rs.results = new Result[numResults]; - int pos = p2.data; - for (int i = 0; i < numResults; i++) { - final Result r = new Result(); - r.error = Nodave.USByte(p2.mem, pos); - if (r.error == 255) { + p2 = new PDU(this.msgIn, this.PDUstartIn); + p2.setupReceivedPDU(); + /* + * if (p2.udlen == 0) { dataPointer = 0; answLen = 0; return + * Nodave.RESULT_CPU_RETURNED_NO_DATA; } + */ + final ResultSet rs = new ResultSet(); + if (p2.mem[p2.param + 0] == PDU.FUNC_READ) { + int numResults = p2.mem[p2.param + 1]; + // System.out.println("Results " + numResults); + rs.results = new Result[numResults]; + int pos = p2.data; + for (int i = 0; i < numResults; i++) { + final Result r = new Result(); + r.error = Nodave.USByte(p2.mem, pos); + if (r.error == 255) { - final int type = Nodave.USByte(p2.mem, pos + 1); - int len = Nodave.USBEWord(p2.mem, pos + 2); - r.error = 0; - // System.out.println("Raw length " + len); - if (type == 4) { - len /= 8; - } - else if (type == 3) { - ; // length is ok - } + final int type = Nodave.USByte(p2.mem, pos + 1); + int len = Nodave.USBEWord(p2.mem, pos + 2); + r.error = 0; + // System.out.println("Raw length " + len); + if (type == 4) { + len /= 8; + } else if (type == 3) { + ; // length is ok + } - // System.out.println("Byte length " + len); - // r.data = new byte[len]; + // System.out.println("Byte length " + len); + // r.data = new byte[len]; - // System.arraycopy(p2.mem, pos + 4, r.data, 0, len); - // Nodave.dump("Result " + i + ":", r.data, 0, len); - r.bufferStart = pos + 4; - pos += len; - if ((len % 2) == 1) { - pos++; - } - } - else { - System.out.println("Error " + r.error); - } - pos += 4; - rs.results[i] = r; - } - numResults = p2.mem[p2.param + 1]; - rs.setNumResults(numResults); - this.dataPointer = p2.udata; - this.answLen = p2.udlen; - // } - } - else { - errorState |= 2048; - } - this.semaphore.release(); - rs.setErrorState(errorState); - return rs; - } + // System.arraycopy(p2.mem, pos + 4, r.data, 0, len); + // Nodave.dump("Result " + i + ":", r.data, 0, len); + r.bufferStart = pos + 4; + pos += len; + if ((len % 2) == 1) { + pos++; + } + } else { + System.out.println("Error " + r.error); + } + pos += 4; + rs.results[i] = r; + } + numResults = p2.mem[p2.param + 1]; + rs.setNumResults(numResults); + this.dataPointer = p2.udata; + this.answLen = p2.udlen; + // } + } else { + errorState |= 2048; + } + this.semaphore.release(); + rs.setErrorState(errorState); + return rs; + } - public int getBYTE() { - this.dataPointer += 1; - return Nodave.SByte(this.msgIn, this.dataPointer - 1); - } + public int getBYTE() { + this.dataPointer += 1; + return Nodave.SByte(this.msgIn, this.dataPointer - 1); + } - public int getBYTE(final int pos) { - return Nodave.SByte(this.msgIn, this.udata + pos); - } + public int getBYTE(final int pos) { + return Nodave.SByte(this.msgIn, this.udata + pos); + } - public int getCHAR() { - this.dataPointer += 1; - return Nodave.SByte(this.msgIn, this.dataPointer - 1); - } + public int getCHAR() { + this.dataPointer += 1; + return Nodave.SByte(this.msgIn, this.dataPointer - 1); + } - public int getCHAR(final int pos) { - return Nodave.SByte(this.msgIn, this.udata + pos); - } + public int getCHAR(final int pos) { + return Nodave.SByte(this.msgIn, this.udata + pos); + } - /** - * get a signed 32bit value from the current position in result bytes - * @return value - */ - public long getDINT() { - this.dataPointer += 4; - return Nodave.SBELong(this.msgIn, this.dataPointer - 4); - } + /** + * get a signed 32bit value from the current position in result bytes + * + * @return value + */ + public long getDINT() { + this.dataPointer += 4; + return Nodave.SBELong(this.msgIn, this.dataPointer - 4); + } - /** - * get a signed 32bit value from the specified position in result bytes - * @param pos Pos - * @return Value - */ - public long getDINT(final int pos) { - return Nodave.SBELong(this.msgIn, this.udata + pos); - } + /** + * get a signed 32bit value from the specified position in result bytes + * + * @param pos Pos + * @return Value + */ + public long getDINT(final int pos) { + return Nodave.SBELong(this.msgIn, this.udata + pos); + } - /** - * get an unsigned 32bit value from the specified position in result bytes - * @param pos Pos - * @return value - */ - public long getDWORD(final int pos) { - // System.out.println("getDWORD pos " + pos); - return Nodave.USBELong(this.msgIn, this.udata + pos); - } + /** + * get an unsigned 32bit value from the specified position in result bytes + * + * @param pos Pos + * @return value + */ + public long getDWORD(final int pos) { + // System.out.println("getDWORD pos " + pos); + return Nodave.USBELong(this.msgIn, this.udata + pos); + } - /** - * get a float value from the current position in result bytes - * @return value - */ - public float getFloat() { - this.dataPointer += 4; - return Nodave.BEFloat(this.msgIn, this.dataPointer - 4); - } + /** + * get a float value from the current position in result bytes + * + * @return value + */ + public float getFloat() { + this.dataPointer += 4; + return Nodave.BEFloat(this.msgIn, this.dataPointer - 4); + } - /* - * The following methods are here to give Siemens users their usual data types: - */ + /* + * The following methods are here to give Siemens users their usual data types: + */ - /** - * get a float value from the specified position in result bytes - * @param pos Pos - * @return value - */ - public float getFloat(final int pos) { - // System.out.println("getFloat pos " + pos); - return Nodave.BEFloat(this.msgIn, this.udata + pos); - } + /** + * get a float value from the specified position in result bytes + * + * @param pos Pos + * @return value + */ + public float getFloat(final int pos) { + // System.out.println("getFloat pos " + pos); + return Nodave.BEFloat(this.msgIn, this.udata + pos); + } - public int getINT() { - this.dataPointer += 2; - return Nodave.SBEWord(this.msgIn, this.dataPointer - 2); - } + public int getINT() { + this.dataPointer += 2; + return Nodave.SBEWord(this.msgIn, this.dataPointer - 2); + } - public int getINT(final int pos) { - return Nodave.SBEWord(this.msgIn, this.udata + pos); - } + public int getINT(final int pos) { + return Nodave.SBEWord(this.msgIn, this.udata + pos); + } - public int getPPIresponse() { - return 0; - } + public int getPPIresponse() { + return 0; + } - /* - * public void sendYOURTURN() { } - */ - public int getResponse() { - return 0; - } + /* + * public void sendYOURTURN() { } + */ + public int getResponse() { + return 0; + } - public int getS16(final int pos) { - return Nodave.SBEWord(this.msgIn, this.udata + pos); - } + public int getS16(final int pos) { + return Nodave.SBEWord(this.msgIn, this.udata + pos); + } - public long getS32(final int pos) { - return Nodave.SBELong(this.msgIn, this.udata + pos); - } + public long getS32(final int pos) { + return Nodave.SBELong(this.msgIn, this.udata + pos); + } - public int getS8(final int pos) { - return Nodave.SByte(this.msgIn, this.udata + pos); - } + public int getS8(final int pos) { + return Nodave.SByte(this.msgIn, this.udata + pos); + } - /** - * get an unsigned 32bit value from the current position in result bytes - * @return value - */ - public long getU32() { - this.dataPointer += 4; - return Nodave.USBELong(this.msgIn, this.dataPointer - 4); - } + /** + * get an unsigned 32bit value from the current position in result bytes + * + * @return value + */ + public long getU32() { + this.dataPointer += 4; + return Nodave.USBELong(this.msgIn, this.dataPointer - 4); + } - public int getUS16(final int pos) { - return Nodave.USBEWord(this.msgIn, this.udata + pos); - } + public int getUS16(final int pos) { + return Nodave.USBEWord(this.msgIn, this.udata + pos); + } - public long getUS32(final int pos) { - return Nodave.USBELong(this.msgIn, this.udata + pos); - } + public long getUS32(final int pos) { + return Nodave.USBELong(this.msgIn, this.udata + pos); + } - public int getUS8(final int pos) { - return Nodave.USByte(this.msgIn, this.udata + pos); - } + public int getUS8(final int pos) { + return Nodave.USByte(this.msgIn, this.udata + pos); + } - /** - * get an unsigned 16bit value from the current position in result bytes - * @return word - */ - public int getWORD() { - this.dataPointer += 2; - return Nodave.USBEWord(this.msgIn, this.dataPointer - 2); - } + /** + * get an unsigned 16bit value from the current position in result bytes + * + * @return word + */ + public int getWORD() { + this.dataPointer += 2; + return Nodave.USBEWord(this.msgIn, this.dataPointer - 2); + } - /** - * get an unsigned 16bit value from the specified position in result bytes - * @param pos Pos - * @return word - */ - public int getWORD(final int pos) { - return Nodave.USBEWord(this.msgIn, this.udata + pos); - } + /** + * get an unsigned 16bit value from the specified position in result bytes + * + * @param pos Pos + * @return word + */ + public int getWORD(final int pos) { + return Nodave.USBEWord(this.msgIn, this.udata + pos); + } - /** - * build the PDU for a PDU length negotiation - * @return word - */ - public int negPDUlengthRequest() { - int res; - final PDU p = new PDU(this.msgOut, this.PDUstartOut); - final byte pa[] = { (byte) 0xF0, 0, 0x00, 0x01, 0x00, 0x01, 0x03, (byte) 0xC0, }; - p.initHeader(1); - p.addParam(pa); - res = this.exchange(p); - if (res != 0) { - return res; - } - final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); - res = p2.setupReceivedPDU(); - if (res != 0) { - return res; - } - this.maxPDUlength = Nodave.USBEWord(this.msgIn, p2.param + 6); - return res; - } + /** + * build the PDU for a PDU length negotiation + * + * @return word + */ + public int negPDUlengthRequest() { + int res; + final PDU p = new PDU(this.msgOut, this.PDUstartOut); + final byte pa[] = {(byte) 0xF0, 0, 0x00, 0x01, 0x00, 0x01, 0x03, (byte) 0xC0,}; + p.initHeader(1); + p.addParam(pa); + res = this.exchange(p); + if (res != 0) { + return res; + } + final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); + res = p2.setupReceivedPDU(); + if (res != 0) { + return res; + } + this.maxPDUlength = Nodave.USBEWord(this.msgIn, p2.param + 6); + return res; + } - public int readBytes(final DaveArea area, final int DBnum, final int start, final int len, final byte[] buffer) { - int res = 0; - try { - this.semaphore.acquire(); - } - catch (final InterruptedException e) { - e.printStackTrace(); - } - final PDU p1 = new PDU(this.msgOut, this.PDUstartOut); - p1.initReadRequest(); - p1.addVarToReadRequest(area, DBnum, start, len); + public int readBytes(final DaveArea area, final int DBnum, final int start, final int len, final byte[] buffer) { + int res = 0; + try { + this.semaphore.acquire(); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + final PDU p1 = new PDU(this.msgOut, this.PDUstartOut); + p1.initReadRequest(); + p1.addVarToReadRequest(area, DBnum, start, len); - res = this.exchange(p1); - if (res != Nodave.RESULT_OK) { - this.semaphore.release(); - return res; - } - final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); - res = p2.setupReceivedPDU(); - if (res != Nodave.RESULT_OK) { - this.semaphore.release(); - return res; - } + res = this.exchange(p1); + if (res != Nodave.RESULT_OK) { + this.semaphore.release(); + return res; + } + final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); + res = p2.setupReceivedPDU(); + if (res != Nodave.RESULT_OK) { + this.semaphore.release(); + return res; + } - res = p2.testReadResult(); - if (res != Nodave.RESULT_OK) { - this.semaphore.release(); - return res; - } - if (p2.udlen == 0) { - this.semaphore.release(); - return Nodave.RESULT_CPU_RETURNED_NO_DATA; - } - /* - * copy to user buffer and setup internal buffer pointers: - */ - if (buffer != null) { - System.arraycopy(p2.mem, p2.udata, buffer, 0, p2.udlen); - } + res = p2.testReadResult(); + if (res != Nodave.RESULT_OK) { + this.semaphore.release(); + return res; + } + if (p2.udlen == 0) { + this.semaphore.release(); + return Nodave.RESULT_CPU_RETURNED_NO_DATA; + } + /* + * copy to user buffer and setup internal buffer pointers: + */ + if (buffer != null) { + System.arraycopy(p2.mem, p2.udata, buffer, 0, p2.udlen); + } - this.dataPointer = p2.udata; - this.udata = p2.udata; - this.answLen = p2.udlen; - this.semaphore.release(); - return res; - } + this.dataPointer = p2.udata; + this.udata = p2.udata; + this.answLen = p2.udlen; + this.semaphore.release(); + return res; + } - public int sendMsg(final PDU p) { - return 0; - } + public int sendMsg(final PDU p) { + return 0; + } - public void sendRequestData(final int alt) { - } + public void sendRequestData(final int alt) { + } - public int useResult(final ResultSet rs, final int number) { - System.out.println("rs.getNumResults: " + rs.getNumResults() + " number: " + number); - if (rs.getNumResults() > number) { - this.dataPointer = rs.results[number].bufferStart; - return 0; - // udata=rs.results[number].bufferStart; - } - return -33; - } + public int useResult(final ResultSet rs, final int number) { + System.out.println("rs.getNumResults: " + rs.getNumResults() + " number: " + number); + if (rs.getNumResults() > number) { + this.dataPointer = rs.results[number].bufferStart; + return 0; + // udata=rs.results[number].bufferStart; + } + return -33; + } - ; + ; - /* - * Write len bytes to PLC memory area "area", data block DBnum. - */ - public int writeBytes(final DaveArea area, final int DBnum, final int start, final int len, final byte[] buffer) { - int errorState = 0; - this.semaphore.release(); - final PDU p1 = new PDU(this.msgOut, this.PDUstartOut); + /* + * Write len bytes to PLC memory area "area", data block DBnum. + */ + public int writeBytes(final DaveArea area, final int DBnum, final int start, final int len, final byte[] buffer) { + int errorState = 0; + this.semaphore.release(); + final PDU p1 = new PDU(this.msgOut, this.PDUstartOut); - // p1.constructWriteRequest(area, DBnum, start, len, buffer); - p1.prepareWriteRequest(); - p1.addVarToWriteRequest(area, DBnum, start, len, buffer); + // p1.constructWriteRequest(area, DBnum, start, len, buffer); + p1.prepareWriteRequest(); + p1.addVarToWriteRequest(area, DBnum, start, len, buffer); - errorState = this.exchange(p1); + errorState = this.exchange(p1); - if (errorState == 0) { - final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); - p2.setupReceivedPDU(); + if (errorState == 0) { + final PDU p2 = new PDU(this.msgIn, this.PDUstartIn); + p2.setupReceivedPDU(); - if (p2.mem[p2.param + 0] == PDU.FUNC_WRITE) { - if (p2.mem[p2.data + 0] == (byte) 0xFF) { - this.semaphore.release(); - return 0; - } - } - else { - errorState |= 4096; - } - } - this.semaphore.release(); - return errorState; - } + if (p2.mem[p2.param + 0] == PDU.FUNC_WRITE) { + if (p2.mem[p2.data + 0] == (byte) 0xFF) { + this.semaphore.release(); + return 0; + } + } else { + errorState |= 4096; + } + } + this.semaphore.release(); + return errorState; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/TCPConnection.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/TCPConnection.java index 53d097ce0..f09d768d6 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/TCPConnection.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/nodave/TCPConnection.java @@ -23,107 +23,109 @@ package io.github.pnoker.driver.api.impl.nodave; */ public final class TCPConnection extends S7Connection { - /** - * The rack. - */ - int rack; + /** + * The rack. + */ + int rack; - /** - * The slot. - */ - int slot; + /** + * The slot. + */ + int slot; - /** - * Instantiates a new TCP connection. - * @param ifa the plc interface - * @param rack the rack - * @param slot the slot - */ - public TCPConnection(final PLCinterface ifa, final int rack, final int slot) { - super(ifa); - this.rack = rack; - this.slot = slot; - this.PDUstartIn = 7; - this.PDUstartOut = 7; - } + /** + * Instantiates a new TCP connection. + * + * @param ifa the plc interface + * @param rack the rack + * @param slot the slot + */ + public TCPConnection(final PLCinterface ifa, final int rack, final int slot) { + super(ifa); + this.rack = rack; + this.slot = slot; + this.PDUstartIn = 7; + this.PDUstartOut = 7; + } - /** - * We have our own connectPLC(), but no disconnect() Open connection to a PLC. This - * assumes that dc is initialized by daveNewConnection and is not yet used. (or reused - * for the same PLC ?) - * @return the int - */ - public int connectPLC() { - int packetLength; - if (iface.protocol == Nodave.PROTOCOL_ISOTCP243) { - final byte[] b243 = { (byte) 0x11, (byte) 0xE0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0xC1, (byte) 0x02, (byte) 0x4D, (byte) 0x57, (byte) 0xC2, (byte) 0x02, - (byte) 0x4D, (byte) 0x57, (byte) 0xC0, (byte) 0x01, (byte) 0x09 }; - System.arraycopy(b243, 0, this.msgOut, 4, b243.length); - packetLength = b243.length; - } - else { - final byte[] b4 = { (byte) 0x11, (byte) 0xE0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, - (byte) 0x00, (byte) 0xC1, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0xC2, (byte) 0x02, - (byte) 0x01, (byte) 0x02, (byte) 0xC0, (byte) 0x01, (byte) 0x09 }; - System.arraycopy(b4, 0, this.msgOut, 4, b4.length); - this.msgOut[17] = (byte) (this.rack + 1); - this.msgOut[18] = (byte) this.slot; - packetLength = b4.length; - } - this.sendISOPacket(packetLength); - this.readISOPacket(); - /* - * PDU p = new PDU(msgOut, 7); p.initHeader(1); p.addParam(b61); exchange(p); - * return (0); - */ - return this.negPDUlengthRequest(); - } + /** + * We have our own connectPLC(), but no disconnect() Open connection to a PLC. This + * assumes that dc is initialized by daveNewConnection and is not yet used. (or reused + * for the same PLC ?) + * + * @return the int + */ + public int connectPLC() { + int packetLength; + if (iface.protocol == Nodave.PROTOCOL_ISOTCP243) { + final byte[] b243 = {(byte) 0x11, (byte) 0xE0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x00, (byte) 0xC1, (byte) 0x02, (byte) 0x4D, (byte) 0x57, (byte) 0xC2, (byte) 0x02, + (byte) 0x4D, (byte) 0x57, (byte) 0xC0, (byte) 0x01, (byte) 0x09}; + System.arraycopy(b243, 0, this.msgOut, 4, b243.length); + packetLength = b243.length; + } else { + final byte[] b4 = {(byte) 0x11, (byte) 0xE0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, + (byte) 0x00, (byte) 0xC1, (byte) 0x02, (byte) 0x01, (byte) 0x00, (byte) 0xC2, (byte) 0x02, + (byte) 0x01, (byte) 0x02, (byte) 0xC0, (byte) 0x01, (byte) 0x09}; + System.arraycopy(b4, 0, this.msgOut, 4, b4.length); + this.msgOut[17] = (byte) (this.rack + 1); + this.msgOut[18] = (byte) this.slot; + packetLength = b4.length; + } + this.sendISOPacket(packetLength); + this.readISOPacket(); + /* + * PDU p = new PDU(msgOut, 7); p.initHeader(1); p.addParam(b61); exchange(p); + * return (0); + */ + return this.negPDUlengthRequest(); + } - @Override - public int exchange(final PDU p1) { - this.msgOut[4] = (byte) 0x02; - this.msgOut[5] = (byte) 0xf0; - this.msgOut[6] = (byte) 0x80; - this.sendISOPacket(3 + p1.hlen + p1.plen + p1.dlen); - this.readISOPacket(); - return 0; - } + @Override + public int exchange(final PDU p1) { + this.msgOut[4] = (byte) 0x02; + this.msgOut[5] = (byte) 0xf0; + this.msgOut[6] = (byte) 0x80; + this.sendISOPacket(3 + p1.hlen + p1.plen + p1.dlen); + this.readISOPacket(); + return 0; + } - /** - * Read iso packet. - * @return the int - */ - protected int readISOPacket() { - int res = this.iface.read(this.msgIn, 0, 4); - if (res == 4) { - final int len = (0x100 * this.msgIn[2]) + this.msgIn[3]; - res += this.iface.read(this.msgIn, 4, len); - } - else { - return 0; - } - return res; - } + /** + * Read iso packet. + * + * @return the int + */ + protected int readISOPacket() { + int res = this.iface.read(this.msgIn, 0, 4); + if (res == 4) { + final int len = (0x100 * this.msgIn[2]) + this.msgIn[3]; + res += this.iface.read(this.msgIn, 4, len); + } else { + return 0; + } + return res; + } - /** - * Send iso packet. - * @param size the size - * @return the int - */ - protected int sendISOPacket(int size) { - size += 4; - this.msgOut[0] = (byte) 0x03; - this.msgOut[1] = (byte) 0x0; - this.msgOut[2] = (byte) (size / 0x100); - this.msgOut[3] = (byte) (size % 0x100); - /* - * if (messageNumber == 0) { messageNumber = 1; msgOut[11] = (byte) - * ((messageNumber + 1) & 0xff); messageNumber++; messageNumber &= 0xff; //!! } - */ + /** + * Send iso packet. + * + * @param size the size + * @return the int + */ + protected int sendISOPacket(int size) { + size += 4; + this.msgOut[0] = (byte) 0x03; + this.msgOut[1] = (byte) 0x0; + this.msgOut[2] = (byte) (size / 0x100); + this.msgOut[3] = (byte) (size % 0x100); + /* + * if (messageNumber == 0) { messageNumber = 1; msgOut[11] = (byte) + * ((messageNumber + 1) & 0xff); messageNumber++; messageNumber &= 0xff; //!! } + */ - this.iface.write(this.msgOut, 0, size); - return 0; - } + this.iface.write(this.msgOut, 0, size); + return 0; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/S7SerializerImpl.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/S7SerializerImpl.java index 98ce81658..b9c913112 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/S7SerializerImpl.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/S7SerializerImpl.java @@ -34,180 +34,174 @@ import java.lang.reflect.Array; @Slf4j public final class S7SerializerImpl implements S7Serializer { - /** - * The Connector. - */ - private final S7Connector connector; + /** + * The Connector. + */ + private final S7Connector connector; - /** - * Instantiates a new s7 serializer. - * @param connector the connector - */ - public S7SerializerImpl(final S7Connector connector) { - this.connector = connector; - } + /** + * Instantiates a new s7 serializer. + * + * @param connector the connector + */ + public S7SerializerImpl(final S7Connector connector) { + this.connector = connector; + } - public static Object extractBytes(PlcS7PointVariable plcs7PointVariable, final byte[] buffer, - final int byteOffset) { - try { - final BeanEntry entry = BeanParser.parse(plcs7PointVariable); - return entry.serializer.extract(entry.type, buffer, entry.byteOffset + byteOffset, entry.bitOffset); - } - catch (Exception e) { - throw new S7Exception("extractBytes", e); - } - } + public static Object extractBytes(PlcS7PointVariable plcs7PointVariable, final byte[] buffer, + final int byteOffset) { + try { + final BeanEntry entry = BeanParser.parse(plcs7PointVariable); + return entry.serializer.extract(entry.type, buffer, entry.byteOffset + byteOffset, entry.bitOffset); + } catch (Exception e) { + throw new S7Exception("extractBytes", e); + } + } - /** - * Extracts bytes from a buffer. - * @param the generic type - * @param beanClass the bean class - * @param buffer the buffer - * @param byteOffset the byte offset - * @return the t - */ - public static T extractBytes(final Class beanClass, final byte[] buffer, final int byteOffset) { - log.trace("Extracting type {} from buffer with size: {} at offset {}", beanClass.getName(), buffer.length, - byteOffset); + /** + * Extracts bytes from a buffer. + * + * @param the generic type + * @param beanClass the bean class + * @param buffer the buffer + * @param byteOffset the byte offset + * @return the t + */ + public static T extractBytes(final Class beanClass, final byte[] buffer, final int byteOffset) { + log.trace("Extracting type {} from buffer with size: {} at offset {}", beanClass.getName(), buffer.length, + byteOffset); - try { - final T obj = beanClass.newInstance(); - final BeanParseResult result = BeanParser.parse(beanClass); - for (final BeanEntry entry : result.entries) { - Object value = null; - if (entry.isArray) { - value = Array.newInstance(entry.type, entry.arraySize); - for (int i = 0; i < entry.arraySize; i++) { - final Object component = entry.serializer.extract(entry.type, buffer, - entry.byteOffset + byteOffset + (i * entry.s7type.getByteSize()), - entry.bitOffset + (i * entry.s7type.getBitSize())); - Array.set(value, i, component); - } - } - else { - value = entry.serializer.extract(entry.type, buffer, entry.byteOffset + byteOffset, - entry.bitOffset); - } + try { + final T obj = beanClass.newInstance(); + final BeanParseResult result = BeanParser.parse(beanClass); + for (final BeanEntry entry : result.entries) { + Object value = null; + if (entry.isArray) { + value = Array.newInstance(entry.type, entry.arraySize); + for (int i = 0; i < entry.arraySize; i++) { + final Object component = entry.serializer.extract(entry.type, buffer, + entry.byteOffset + byteOffset + (i * entry.s7type.getByteSize()), + entry.bitOffset + (i * entry.s7type.getBitSize())); + Array.set(value, i, component); + } + } else { + value = entry.serializer.extract(entry.type, buffer, entry.byteOffset + byteOffset, + entry.bitOffset); + } - if (entry.field.getType() == byte[].class) { - // Special case issue #45 - Byte[] oldValue = (Byte[]) value; + if (entry.field.getType() == byte[].class) { + // Special case issue #45 + Byte[] oldValue = (Byte[]) value; - value = new byte[oldValue.length]; + value = new byte[oldValue.length]; - for (int i = 0; i < oldValue.length; i++) { - ((byte[]) value)[i] = oldValue[i]; - } - } + for (int i = 0; i < oldValue.length; i++) { + ((byte[]) value)[i] = oldValue[i]; + } + } - entry.field.set(obj, value); - } + entry.field.set(obj, value); + } - return obj; - } - catch (final Exception e) { - throw new S7Exception("extractBytes", e); - } - } + return obj; + } catch (final Exception e) { + throw new S7Exception("extractBytes", e); + } + } - /** - * Inserts the bytes to the buffer. - * @param bean the bean - * @param buffer the buffer - * @param byteOffset the byte offset - */ - public static void insertBytes(final Object bean, final byte[] buffer, final int byteOffset) { - log.trace("Inerting buffer with size: {} at offset {} into bean: {}", buffer.length, byteOffset, bean); + /** + * Inserts the bytes to the buffer. + * + * @param bean the bean + * @param buffer the buffer + * @param byteOffset the byte offset + */ + public static void insertBytes(final Object bean, final byte[] buffer, final int byteOffset) { + log.trace("Inerting buffer with size: {} at offset {} into bean: {}", buffer.length, byteOffset, bean); - try { - final BeanParseResult result = BeanParser.parse(bean); + try { + final BeanParseResult result = BeanParser.parse(bean); - for (final BeanEntry entry : result.entries) { - final Object fieldValue = entry.field.get(bean); + for (final BeanEntry entry : result.entries) { + final Object fieldValue = entry.field.get(bean); - if (fieldValue != null) { - if (entry.isArray) { - for (int i = 0; i < entry.arraySize; i++) { - final Object arrayItem = Array.get(fieldValue, i); + if (fieldValue != null) { + if (entry.isArray) { + for (int i = 0; i < entry.arraySize; i++) { + final Object arrayItem = Array.get(fieldValue, i); - if (arrayItem != null) { - entry.serializer.insert(arrayItem, buffer, - entry.byteOffset + byteOffset + (i * entry.s7type.getByteSize()), - entry.bitOffset + (i * entry.s7type.getBitSize()), entry.size); - } - } - } - else { - entry.serializer.insert(fieldValue, buffer, entry.byteOffset + byteOffset, entry.bitOffset, - entry.size); - } - } - } - } - catch (final Exception e) { - throw new S7Exception("insertBytes", e); - } - } + if (arrayItem != null) { + entry.serializer.insert(arrayItem, buffer, + entry.byteOffset + byteOffset + (i * entry.s7type.getByteSize()), + entry.bitOffset + (i * entry.s7type.getBitSize()), entry.size); + } + } + } else { + entry.serializer.insert(fieldValue, buffer, entry.byteOffset + byteOffset, entry.bitOffset, + entry.size); + } + } + } + } catch (final Exception e) { + throw new S7Exception("insertBytes", e); + } + } - @Override - public synchronized T dispense(final Class beanClass, final int dbNum, final int byteOffset) - throws S7Exception { - try { - final BeanParseResult result = BeanParser.parse(beanClass); - final byte[] buffer = this.connector.read(DaveArea.DB, dbNum, result.blockSize, byteOffset); - return extractBytes(beanClass, buffer, 0); - } - catch (final Exception e) { - throw new S7Exception("dispense", e); - } - } + @Override + public synchronized T dispense(final Class beanClass, final int dbNum, final int byteOffset) + throws S7Exception { + try { + final BeanParseResult result = BeanParser.parse(beanClass); + final byte[] buffer = this.connector.read(DaveArea.DB, dbNum, result.blockSize, byteOffset); + return extractBytes(beanClass, buffer, 0); + } catch (final Exception e) { + throw new S7Exception("dispense", e); + } + } - @Override - public synchronized T dispense(final Class beanClass, final int dbNum, final int byteOffset, - final int blockSize) throws S7Exception { - try { - final byte[] buffer = this.connector.read(DaveArea.DB, dbNum, blockSize, byteOffset); - return extractBytes(beanClass, buffer, 0); - } - catch (final Exception e) { - throw new S7Exception( - "dispense dbnum(" + dbNum + ") byteoffset(" + byteOffset + ") blocksize(" + blockSize + ")", e); - } - } + @Override + public synchronized T dispense(final Class beanClass, final int dbNum, final int byteOffset, + final int blockSize) throws S7Exception { + try { + final byte[] buffer = this.connector.read(DaveArea.DB, dbNum, blockSize, byteOffset); + return extractBytes(beanClass, buffer, 0); + } catch (final Exception e) { + throw new S7Exception( + "dispense dbnum(" + dbNum + ") byteoffset(" + byteOffset + ") blocksize(" + blockSize + ")", e); + } + } - /** - * add by pnoker - */ - @Override - public Object dispense(PlcS7PointVariable plcs7PointVariable) throws S7Exception { - try { - final byte[] buffer = this.connector.read(DaveArea.DB, plcs7PointVariable.getDbNum(), - plcs7PointVariable.getSize(), plcs7PointVariable.getByteOffset()); - return extractBytes(plcs7PointVariable, buffer, 0); - } - catch (final Exception e) { - throw new S7Exception( - "dispense dbnum(" + plcs7PointVariable.getDbNum() + ") byteoffset(" - + plcs7PointVariable.getByteOffset() + ") blocksize(" + plcs7PointVariable.getSize() + ")", - e); - } - } + /** + * add by pnoker + */ + @Override + public Object dispense(PlcS7PointVariable plcs7PointVariable) throws S7Exception { + try { + final byte[] buffer = this.connector.read(DaveArea.DB, plcs7PointVariable.getDbNum(), + plcs7PointVariable.getSize(), plcs7PointVariable.getByteOffset()); + return extractBytes(plcs7PointVariable, buffer, 0); + } catch (final Exception e) { + throw new S7Exception( + "dispense dbnum(" + plcs7PointVariable.getDbNum() + ") byteoffset(" + + plcs7PointVariable.getByteOffset() + ") blocksize(" + plcs7PointVariable.getSize() + ")", + e); + } + } - @Override - public synchronized void store(final Object bean, final int dbNum, final int byteOffset) { - try { - final BeanParseResult result = BeanParser.parse(bean); + @Override + public synchronized void store(final Object bean, final int dbNum, final int byteOffset) { + try { + final BeanParseResult result = BeanParser.parse(bean); - final byte[] buffer = new byte[result.blockSize]; - log.trace("store-buffer-size: " + buffer.length); + final byte[] buffer = new byte[result.blockSize]; + log.trace("store-buffer-size: " + buffer.length); - insertBytes(bean, buffer, 0); + insertBytes(bean, buffer, 0); - this.connector.write(DaveArea.DB, dbNum, byteOffset, buffer); - } - catch (final Exception e) { - throw new S7Exception("store", e); - } - } + this.connector.write(DaveArea.DB, dbNum, byteOffset, buffer); + } catch (final Exception e) { + throw new S7Exception("store", e); + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/BitConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/BitConverter.java index 5a1d79f43..1d6927958 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/BitConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/BitConverter.java @@ -24,39 +24,38 @@ import io.github.pnoker.driver.api.S7Type; */ public final class BitConverter implements S7Serializable { - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final byte bufValue = buffer[byteOffset]; - return targetClass.cast(bufValue == (bufValue | (0x01 << bitOffset))); - } + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final byte bufValue = buffer[byteOffset]; + return targetClass.cast(bufValue == (bufValue | (0x01 << bitOffset))); + } - @Override - public S7Type getS7Type() { - return S7Type.BOOL; - } + @Override + public S7Type getS7Type() { + return S7Type.BOOL; + } - @Override - public int getSizeInBits() { - return 1; - } + @Override + public int getSizeInBits() { + return 1; + } - @Override - public int getSizeInBytes() { - return 0; - } + @Override + public int getSizeInBytes() { + return 0; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Boolean value = (Boolean) javaType; + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Boolean value = (Boolean) javaType; - // thx to @mfriedemann (https://github.com/mfriedemann) - if (value) { - buffer[byteOffset] |= (0x01 << bitOffset); - } - else { - buffer[byteOffset] &= ~(0x01 << bitOffset); - } - } + // thx to @mfriedemann (https://github.com/mfriedemann) + if (value) { + buffer[byteOffset] |= (0x01 << bitOffset); + } else { + buffer[byteOffset] &= ~(0x01 << bitOffset); + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ByteConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ByteConverter.java index 73a303538..493332ad4 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ByteConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ByteConverter.java @@ -29,31 +29,31 @@ import io.github.pnoker.driver.api.S7Type; public class ByteConverter implements S7Serializable { - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - return targetClass.cast(buffer[byteOffset]); - } + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + return targetClass.cast(buffer[byteOffset]); + } - @Override - public S7Type getS7Type() { - return S7Type.BYTE; - } + @Override + public S7Type getS7Type() { + return S7Type.BYTE; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 1; - } + @Override + public int getSizeInBytes() { + return 1; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Byte value = (Byte) javaType; - buffer[byteOffset] = value; - } + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Byte value = (Byte) javaType; + buffer[byteOffset] = value; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateAndTimeConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateAndTimeConverter.java index 5786c5b9d..2ba994111 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateAndTimeConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateAndTimeConverter.java @@ -31,169 +31,167 @@ import java.util.Date; public final class DateAndTimeConverter extends ByteConverter { - public static final int OFFSET_DAY = 2; + public static final int OFFSET_DAY = 2; - public static final int OFFSET_HOUR = 3; + public static final int OFFSET_HOUR = 3; - public static final int OFFSET_MILLIS_1_AND_DOW = 7; + public static final int OFFSET_MILLIS_1_AND_DOW = 7; - public static final int OFFSET_MILLIS_100_10 = 6; + public static final int OFFSET_MILLIS_100_10 = 6; - public static final int OFFSET_MINUTE = 4; + public static final int OFFSET_MINUTE = 4; - public static final int OFFSET_MONTH = 1; + public static final int OFFSET_MONTH = 1; - public static final int OFFSET_SECOND = 5; + public static final int OFFSET_SECOND = 5; - public static final int OFFSET_YEAR = 0; + public static final int OFFSET_YEAR = 0; - // 18, 1,16,16, 5,80,0,3, (dec) - // 12, 1,10,10, 5,50,0,3, (hex) - // 12-01-10 10:05:50.000 + // 18, 1,16,16, 5,80,0,3, (dec) + // 12, 1,10,10, 5,50,0,3, (hex) + // 12-01-10 10:05:50.000 - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final Calendar c = Calendar.getInstance(); - c.clear(); + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final Calendar c = Calendar.getInstance(); + c.clear(); - int year = this.getFromPLC(buffer, OFFSET_YEAR + byteOffset); + int year = this.getFromPLC(buffer, OFFSET_YEAR + byteOffset); - if (year < 90) { - // 1900 - 1989 - year += 2000; - } - else { - // 2000 - 2090 - year += 1900; - } + if (year < 90) { + // 1900 - 1989 + year += 2000; + } else { + // 2000 - 2090 + year += 1900; + } - int month = this.getFromPLC(buffer, OFFSET_MONTH + byteOffset); + int month = this.getFromPLC(buffer, OFFSET_MONTH + byteOffset); - if (month > 0) { - month--; - } + if (month > 0) { + month--; + } - c.set(Calendar.YEAR, year); - c.set(Calendar.MONTH, month); - c.set(Calendar.DAY_OF_MONTH, this.getFromPLC(buffer, OFFSET_DAY + byteOffset)); - c.set(Calendar.HOUR_OF_DAY, this.getFromPLC(buffer, OFFSET_HOUR + byteOffset)); - c.set(Calendar.MINUTE, this.getFromPLC(buffer, OFFSET_MINUTE + byteOffset)); - c.set(Calendar.SECOND, this.getFromPLC(buffer, OFFSET_SECOND + byteOffset)); + c.set(Calendar.YEAR, year); + c.set(Calendar.MONTH, month); + c.set(Calendar.DAY_OF_MONTH, this.getFromPLC(buffer, OFFSET_DAY + byteOffset)); + c.set(Calendar.HOUR_OF_DAY, this.getFromPLC(buffer, OFFSET_HOUR + byteOffset)); + c.set(Calendar.MINUTE, this.getFromPLC(buffer, OFFSET_MINUTE + byteOffset)); + c.set(Calendar.SECOND, this.getFromPLC(buffer, OFFSET_SECOND + byteOffset)); - /* - * TODO byte upperMillis = super.extract(Byte.class, buffer, - * OFFSET_MILLIS_100_10+byteOffset, bitOffset); byte lowerMillis = - * super.extract(Byte.class, buffer, OFFSET_MILLIS_1_AND_DOW+byteOffset, - * bitOffset); - * - * int ms100 = ( upperMillis >> 4 ); int ms10 = ( upperMillis & 0x0F ); int ms1 = - * ( lowerMillis >> 4 ); - * - * int millis = ms1 + ( 10*ms10 ) + ( 100*ms100 ); c.set(Calendar.MILLISECOND, - * millis); - * - * int dow = ( lowerMillis & 0x0F ); c.set(Calendar.DAY_OF_WEEK, dow); - */ + /* + * TODO byte upperMillis = super.extract(Byte.class, buffer, + * OFFSET_MILLIS_100_10+byteOffset, bitOffset); byte lowerMillis = + * super.extract(Byte.class, buffer, OFFSET_MILLIS_1_AND_DOW+byteOffset, + * bitOffset); + * + * int ms100 = ( upperMillis >> 4 ); int ms10 = ( upperMillis & 0x0F ); int ms1 = + * ( lowerMillis >> 4 ); + * + * int millis = ms1 + ( 10*ms10 ) + ( 100*ms100 ); c.set(Calendar.MILLISECOND, + * millis); + * + * int dow = ( lowerMillis & 0x0F ); c.set(Calendar.DAY_OF_WEEK, dow); + */ - return targetClass.cast(c.getTime()); - } + return targetClass.cast(c.getTime()); + } - /** - * Dec to Hex 10 = 0a 16 = 0f 17 = 10 - * @param buffer Byte Array - * @param offset Offset - * @return Byte - */ - public byte getFromPLC(final byte[] buffer, final int offset) { - try { - final byte ret = super.extract(Byte.class, buffer, offset, 0); - return (byte) Integer.parseInt(Integer.toHexString(ret & 0xFF)); - } - catch (final NumberFormatException e) { - return 0; - } - } + /** + * Dec to Hex 10 = 0a 16 = 0f 17 = 10 + * + * @param buffer Byte Array + * @param offset Offset + * @return Byte + */ + public byte getFromPLC(final byte[] buffer, final int offset) { + try { + final byte ret = super.extract(Byte.class, buffer, offset, 0); + return (byte) Integer.parseInt(Integer.toHexString(ret & 0xFF)); + } catch (final NumberFormatException e) { + return 0; + } + } - @Override - public S7Type getS7Type() { - return S7Type.DATE_AND_TIME; - } + @Override + public S7Type getS7Type() { + return S7Type.DATE_AND_TIME; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 8; - } + @Override + public int getSizeInBytes() { + return 8; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Date date = (Date) javaType; - final Calendar c = Calendar.getInstance(); - c.setTime(date); + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Date date = (Date) javaType; + final Calendar c = Calendar.getInstance(); + c.setTime(date); - int year = c.get(Calendar.YEAR); + int year = c.get(Calendar.YEAR); - /* - * if (year < 1990 || year > 2090) throw new S7Exception("Invalid year: " + year + - * " @ offset: " + byteOffset); - */ + /* + * if (year < 1990 || year > 2090) throw new S7Exception("Invalid year: " + year + + * " @ offset: " + byteOffset); + */ - if (year < 2000) { - // 1990 -1999 - year -= 1900; - } - else { - // 2000 - 2089 - year -= 2000; - } + if (year < 2000) { + // 1990 -1999 + year -= 1900; + } else { + // 2000 - 2089 + year -= 2000; + } - this.putToPLC(buffer, byteOffset + OFFSET_YEAR, year); - this.putToPLC(buffer, byteOffset + OFFSET_MONTH, c.get(Calendar.MONTH) + 1); - this.putToPLC(buffer, byteOffset + OFFSET_DAY, c.get(Calendar.DAY_OF_MONTH)); - this.putToPLC(buffer, byteOffset + OFFSET_HOUR, c.get(Calendar.HOUR_OF_DAY)); - this.putToPLC(buffer, byteOffset + OFFSET_MINUTE, c.get(Calendar.MINUTE)); - this.putToPLC(buffer, byteOffset + OFFSET_SECOND, c.get(Calendar.SECOND)); + this.putToPLC(buffer, byteOffset + OFFSET_YEAR, year); + this.putToPLC(buffer, byteOffset + OFFSET_MONTH, c.get(Calendar.MONTH) + 1); + this.putToPLC(buffer, byteOffset + OFFSET_DAY, c.get(Calendar.DAY_OF_MONTH)); + this.putToPLC(buffer, byteOffset + OFFSET_HOUR, c.get(Calendar.HOUR_OF_DAY)); + this.putToPLC(buffer, byteOffset + OFFSET_MINUTE, c.get(Calendar.MINUTE)); + this.putToPLC(buffer, byteOffset + OFFSET_SECOND, c.get(Calendar.SECOND)); - /* - * TODO int msec1 = 0, msec10 = 0, msec100 = 0; Integer millis = - * c.get(Calendar.MILLISECOND); String mStr = millis.toString(); - * - * if (mStr.length() > 2) { msec100 = Integer.parseInt( mStr.substring(0, 1) ); - * msec10 = Integer.parseInt( mStr.substring(1, 2) ); msec1 = Integer.parseInt( - * mStr.substring(2, 3) ); } else if (mStr.length() > 1) { msec10 = - * Integer.parseInt( mStr.substring(0, 1) ); msec1 = Integer.parseInt( - * mStr.substring(1, 2) ); } else { msec1 = Integer.parseInt( mStr.substring(0, 1) - * ); } - * - * super.insert( (byte)( (byte)msec10 | (byte)(msec100 << 4) ), buffer, - * OFFSET_MILLIS_100_10+byteOffset, 0, 1); - * - * int dow = c.get(Calendar.DAY_OF_WEEK); - * - * super.insert( (byte)( (byte)dow | (byte)(msec1 << 4) ), buffer, - * OFFSET_MILLIS_1_AND_DOW+byteOffset, 0, 1); - */ - } + /* + * TODO int msec1 = 0, msec10 = 0, msec100 = 0; Integer millis = + * c.get(Calendar.MILLISECOND); String mStr = millis.toString(); + * + * if (mStr.length() > 2) { msec100 = Integer.parseInt( mStr.substring(0, 1) ); + * msec10 = Integer.parseInt( mStr.substring(1, 2) ); msec1 = Integer.parseInt( + * mStr.substring(2, 3) ); } else if (mStr.length() > 1) { msec10 = + * Integer.parseInt( mStr.substring(0, 1) ); msec1 = Integer.parseInt( + * mStr.substring(1, 2) ); } else { msec1 = Integer.parseInt( mStr.substring(0, 1) + * ); } + * + * super.insert( (byte)( (byte)msec10 | (byte)(msec100 << 4) ), buffer, + * OFFSET_MILLIS_100_10+byteOffset, 0, 1); + * + * int dow = c.get(Calendar.DAY_OF_WEEK); + * + * super.insert( (byte)( (byte)dow | (byte)(msec1 << 4) ), buffer, + * OFFSET_MILLIS_1_AND_DOW+byteOffset, 0, 1); + */ + } - /** - * Hex to dec 0a = 10 0f = 16 10 = 17 - * @param buffer Byte Array - * @param offset Offset - * @param i int - */ - public void putToPLC(final byte[] buffer, final int offset, final int i) { - try { - final int ret = Integer.parseInt("" + i, 16); - buffer[offset] = (byte) ret; - } - catch (final NumberFormatException e) { - return; - } - } + /** + * Hex to dec 0a = 10 0f = 16 10 = 17 + * + * @param buffer Byte Array + * @param offset Offset + * @param i int + */ + public void putToPLC(final byte[] buffer, final int offset, final int i) { + try { + final int ret = Integer.parseInt("" + i, 16); + buffer[offset] = (byte) ret; + } catch (final NumberFormatException e) { + return; + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateConverter.java index cdf1a6212..79604d5af 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/DateConverter.java @@ -31,71 +31,70 @@ import java.util.Date; public final class DateConverter extends IntegerConverter { - private static final long MILLI_TO_DAY_FACTOR = 24 * 60 * 60 * 1000; + private static final long MILLI_TO_DAY_FACTOR = 24 * 60 * 60 * 1000; - /** - * 1.1.1990 - */ - private static final long OFFSET_1990; + /** + * 1.1.1990 + */ + private static final long OFFSET_1990; - static { - final Calendar c = Calendar.getInstance(); - c.clear(); - c.set(Calendar.HOUR_OF_DAY, 0); - c.set(Calendar.YEAR, 1990); + static { + final Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.HOUR_OF_DAY, 0); + c.set(Calendar.YEAR, 1990); - OFFSET_1990 = c.getTime().getTime(); - } + OFFSET_1990 = c.getTime().getTime(); + } - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final long days = super.extract(Integer.class, buffer, byteOffset, bitOffset); + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final long days = super.extract(Integer.class, buffer, byteOffset, bitOffset); - long millis = days * MILLI_TO_DAY_FACTOR; + long millis = days * MILLI_TO_DAY_FACTOR; - millis += OFFSET_1990; + millis += OFFSET_1990; - final Calendar c = Calendar.getInstance(); - c.setTimeInMillis(millis); - c.set(Calendar.MILLISECOND, 0); - c.set(Calendar.SECOND, 0); - c.set(Calendar.MINUTE, 0); - c.set(Calendar.HOUR_OF_DAY, 0); + final Calendar c = Calendar.getInstance(); + c.setTimeInMillis(millis); + c.set(Calendar.MILLISECOND, 0); + c.set(Calendar.SECOND, 0); + c.set(Calendar.MINUTE, 0); + c.set(Calendar.HOUR_OF_DAY, 0); - return targetClass.cast(c.getTime()); - } + return targetClass.cast(c.getTime()); + } - @Override - public S7Type getS7Type() { - return S7Type.DATE; - } + @Override + public S7Type getS7Type() { + return S7Type.DATE; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Date d = (Date) javaType; + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Date d = (Date) javaType; - long millis = d.getTime(); + long millis = d.getTime(); - millis -= OFFSET_1990; + millis -= OFFSET_1990; - final double days = (double) millis / (double) MILLI_TO_DAY_FACTOR; + final double days = (double) millis / (double) MILLI_TO_DAY_FACTOR; - final long ROUND = 1000; + final long ROUND = 1000; - final long expected = (long) ((days * MILLI_TO_DAY_FACTOR) / ROUND); - final long actual = millis / ROUND; + final long expected = (long) ((days * MILLI_TO_DAY_FACTOR) / ROUND); + final long actual = millis / ROUND; - if (expected != actual) { - throw new IllegalArgumentException("Expected: " + expected + " got: " + actual); - } + if (expected != actual) { + throw new IllegalArgumentException("Expected: " + expected + " got: " + actual); + } - if (millis < 0) { - super.insert(0, buffer, byteOffset, bitOffset, 2); - } - else { - super.insert((int) Math.round(days), buffer, byteOffset, bitOffset, 2); - } - } + if (millis < 0) { + super.insert(0, buffer, byteOffset, bitOffset, 2); + } else { + super.insert((int) Math.round(days), buffer, byteOffset, bitOffset, 2); + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/IntegerConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/IntegerConverter.java index 1424db286..c7fc6d2e8 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/IntegerConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/IntegerConverter.java @@ -29,43 +29,43 @@ import io.github.pnoker.driver.api.S7Type; public class IntegerConverter implements S7Serializable { - private static final int OFFSET_HIGH_BYTE = 0; + private static final int OFFSET_HIGH_BYTE = 0; - private static final int OFFSET_LOW_BYTE = 1; + private static final int OFFSET_LOW_BYTE = 1; - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final byte lower = buffer[byteOffset + OFFSET_LOW_BYTE]; - final byte higher = buffer[byteOffset + OFFSET_HIGH_BYTE]; + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final byte lower = buffer[byteOffset + OFFSET_LOW_BYTE]; + final byte higher = buffer[byteOffset + OFFSET_HIGH_BYTE]; - final Integer i = (lower & 0xFF) | ((higher << 8) & 0xFF00); + final Integer i = (lower & 0xFF) | ((higher << 8) & 0xFF00); - return targetClass.cast(i); - } + return targetClass.cast(i); + } - @Override - public S7Type getS7Type() { - return S7Type.WORD; - } + @Override + public S7Type getS7Type() { + return S7Type.WORD; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 2; - } + @Override + public int getSizeInBytes() { + return 2; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Integer value = (Integer) javaType; - final byte lower = (byte) ((value) & 0xFF); - final byte higher = (byte) ((value >> 8) & 0xFF); - buffer[byteOffset + OFFSET_LOW_BYTE] = lower; - buffer[byteOffset + OFFSET_HIGH_BYTE] = higher; - } + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Integer value = (Integer) javaType; + final byte lower = (byte) ((value) & 0xFF); + final byte higher = (byte) ((value >> 8) & 0xFF); + buffer[byteOffset + OFFSET_LOW_BYTE] = lower; + buffer[byteOffset + OFFSET_HIGH_BYTE] = higher; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/LongConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/LongConverter.java index aa3dfd7fd..9fde58c1b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/LongConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/LongConverter.java @@ -29,46 +29,46 @@ import io.github.pnoker.driver.api.S7Type; public final class LongConverter implements S7Serializable { - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final byte b1 = buffer[byteOffset]; - final byte b2 = buffer[byteOffset + 1]; - final byte b3 = buffer[byteOffset + 2]; - final byte b4 = buffer[byteOffset + 3]; + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final byte b1 = buffer[byteOffset]; + final byte b2 = buffer[byteOffset + 1]; + final byte b3 = buffer[byteOffset + 2]; + final byte b4 = buffer[byteOffset + 3]; - final Integer i = ((b4) & 0x000000FF) | ((b3 << 8) & 0x0000FF00) | ((b2 << 16) & 0x00FF0000) - | ((b1 << 24) & 0xFF000000); + final Integer i = ((b4) & 0x000000FF) | ((b3 << 8) & 0x0000FF00) | ((b2 << 16) & 0x00FF0000) + | ((b1 << 24) & 0xFF000000); - return targetClass.cast(i.longValue()); - } + return targetClass.cast(i.longValue()); + } - @Override - public S7Type getS7Type() { - return S7Type.DWORD; - } + @Override + public S7Type getS7Type() { + return S7Type.DWORD; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 4; - } + @Override + public int getSizeInBytes() { + return 4; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Long value = (Long) javaType; - final byte b4 = (byte) ((value) & 0xFF); - final byte b3 = (byte) ((value >> 8) & 0xFF); - final byte b2 = (byte) ((value >> 16) & 0xFF); - final byte b1 = (byte) ((value >> 24) & 0xFF); - buffer[byteOffset] = b1; - buffer[byteOffset + 1] = b2; - buffer[byteOffset + 2] = b3; - buffer[byteOffset + 3] = b4; - } + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Long value = (Long) javaType; + final byte b4 = (byte) ((value) & 0xFF); + final byte b3 = (byte) ((value >> 8) & 0xFF); + final byte b2 = (byte) ((value >> 16) & 0xFF); + final byte b1 = (byte) ((value >> 24) & 0xFF); + buffer[byteOffset] = b1; + buffer[byteOffset + 1] = b2; + buffer[byteOffset + 2] = b3; + buffer[byteOffset + 3] = b4; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/RealConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/RealConverter.java index fe4257b27..e731917dd 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/RealConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/RealConverter.java @@ -29,57 +29,57 @@ import io.github.pnoker.driver.api.S7Type; public final class RealConverter implements S7Serializable { - private static final int OFFSET_POS1 = 0; + private static final int OFFSET_POS1 = 0; - private static final int OFFSET_POS2 = 1; + private static final int OFFSET_POS2 = 1; - private static final int OFFSET_POS3 = 2; + private static final int OFFSET_POS3 = 2; - private static final int OFFSET_POS4 = 3; + private static final int OFFSET_POS4 = 3; - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final int iValue = ((buffer[byteOffset + OFFSET_POS4] & 0xFF)) - | ((buffer[byteOffset + OFFSET_POS3] & 0xFF) << 8) | ((buffer[byteOffset + OFFSET_POS2] & 0xFF) << 16) - | ((buffer[byteOffset + OFFSET_POS1] & 0xFF) << 24); + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final int iValue = ((buffer[byteOffset + OFFSET_POS4] & 0xFF)) + | ((buffer[byteOffset + OFFSET_POS3] & 0xFF) << 8) | ((buffer[byteOffset + OFFSET_POS2] & 0xFF) << 16) + | ((buffer[byteOffset + OFFSET_POS1] & 0xFF) << 24); - final Float fValue = Float.intBitsToFloat(iValue); + final Float fValue = Float.intBitsToFloat(iValue); - Object ret = fValue; + Object ret = fValue; - if (targetClass == Double.class) { - ret = Double.parseDouble(fValue.toString()); - } + if (targetClass == Double.class) { + ret = Double.parseDouble(fValue.toString()); + } - return targetClass.cast(ret); - } + return targetClass.cast(ret); + } - @Override - public S7Type getS7Type() { - return S7Type.REAL; - } + @Override + public S7Type getS7Type() { + return S7Type.REAL; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 4; - } + @Override + public int getSizeInBytes() { + return 4; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final float fValue = Float.parseFloat(javaType.toString()); + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final float fValue = Float.parseFloat(javaType.toString()); - final int iValue = Float.floatToIntBits(fValue); + final int iValue = Float.floatToIntBits(fValue); - buffer[byteOffset + OFFSET_POS4] = (byte) ((iValue) & 0xFF); - buffer[byteOffset + OFFSET_POS3] = (byte) ((iValue >> 8) & 0xFF); - buffer[byteOffset + OFFSET_POS2] = (byte) ((iValue >> 16) & 0xFF); - buffer[byteOffset + OFFSET_POS1] = (byte) ((iValue >> 24) & 0xFF); - } + buffer[byteOffset + OFFSET_POS4] = (byte) ((iValue) & 0xFF); + buffer[byteOffset + OFFSET_POS3] = (byte) ((iValue >> 8) & 0xFF); + buffer[byteOffset + OFFSET_POS2] = (byte) ((iValue >> 16) & 0xFF); + buffer[byteOffset + OFFSET_POS1] = (byte) ((iValue >> 24) & 0xFF); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ShortConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ShortConverter.java index 97dea3196..5c098ff40 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ShortConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/ShortConverter.java @@ -29,44 +29,44 @@ import io.github.pnoker.driver.api.S7Type; public class ShortConverter implements S7Serializable { - private static final short OFFSET_HIGH_BYTE = 0; + private static final short OFFSET_HIGH_BYTE = 0; - private static final short OFFSET_LOW_BYTE = 1; + private static final short OFFSET_LOW_BYTE = 1; - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final byte lower = buffer[byteOffset + OFFSET_LOW_BYTE]; - final byte higher = buffer[byteOffset + OFFSET_HIGH_BYTE]; + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final byte lower = buffer[byteOffset + OFFSET_LOW_BYTE]; + final byte higher = buffer[byteOffset + OFFSET_HIGH_BYTE]; - final Integer i = (lower & 0xFF) | ((higher << 8) & 0xFF00); + final Integer i = (lower & 0xFF) | ((higher << 8) & 0xFF00); - return targetClass.cast(i.shortValue()); + return targetClass.cast(i.shortValue()); - } + } - @Override - public S7Type getS7Type() { - return S7Type.INT; - } + @Override + public S7Type getS7Type() { + return S7Type.INT; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 2; - } + @Override + public int getSizeInBytes() { + return 2; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final Short value = (Short) javaType; - final byte lower = (byte) ((value) & 0xFF); - final byte higher = (byte) ((value >> 8) & 0xFF); - buffer[byteOffset + OFFSET_LOW_BYTE] = lower; - buffer[byteOffset + OFFSET_HIGH_BYTE] = higher; - } + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final Short value = (Short) javaType; + final byte lower = (byte) ((value) & 0xFF); + final byte higher = (byte) ((value >> 8) & 0xFF); + buffer[byteOffset + OFFSET_LOW_BYTE] = lower; + buffer[byteOffset + OFFSET_HIGH_BYTE] = higher; + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StringConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StringConverter.java index 57c542b4c..5257f7db1 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StringConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StringConverter.java @@ -30,52 +30,52 @@ import io.github.pnoker.driver.api.S7Type; public final class StringConverter implements S7Serializable { - private static final int OFFSET_CURRENT_LENGTH = 1; + private static final int OFFSET_CURRENT_LENGTH = 1; - private static final int OFFSET_OVERALL_LENGTH = 0; + private static final int OFFSET_OVERALL_LENGTH = 0; - private static final int OFFSET_START = 2; + private static final int OFFSET_START = 2; - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final int len = buffer[byteOffset + OFFSET_CURRENT_LENGTH] & 0xFF; + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final int len = buffer[byteOffset + OFFSET_CURRENT_LENGTH] & 0xFF; - return targetClass.cast(new String(buffer, byteOffset + OFFSET_START, len)); - } + return targetClass.cast(new String(buffer, byteOffset + OFFSET_START, len)); + } - @Override - public S7Type getS7Type() { - return S7Type.STRING; - } + @Override + public S7Type getS7Type() { + return S7Type.STRING; + } - @Override - public int getSizeInBits() { - // Not static - return 0; - } + @Override + public int getSizeInBits() { + // Not static + return 0; + } - @Override - public int getSizeInBytes() { - // Not static - return 2; // 2 bytes overhead - } + @Override + public int getSizeInBytes() { + // Not static + return 2; // 2 bytes overhead + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final String value = (String) javaType; + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final String value = (String) javaType; - final int len = value.length(); + final int len = value.length(); - if (len > size) { - throw new IllegalArgumentException("String to big: " + len); - } + if (len > size) { + throw new IllegalArgumentException("String to big: " + len); + } - buffer[byteOffset + OFFSET_OVERALL_LENGTH] = (byte) size; - buffer[byteOffset + OFFSET_CURRENT_LENGTH] = (byte) len; + buffer[byteOffset + OFFSET_OVERALL_LENGTH] = (byte) size; + buffer[byteOffset + OFFSET_CURRENT_LENGTH] = (byte) len; - final byte[] strBytes = DecodeUtil.stringToByte(value); - System.arraycopy(strBytes, 0, buffer, byteOffset + OFFSET_START, len); - } + final byte[] strBytes = DecodeUtil.stringToByte(value); + System.arraycopy(strBytes, 0, buffer, byteOffset + OFFSET_START, len); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StructConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StructConverter.java index 078a7e861..1736eb48b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StructConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/StructConverter.java @@ -30,30 +30,30 @@ import io.github.pnoker.driver.api.impl.serializer.S7SerializerImpl; public final class StructConverter implements S7Serializable { - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - return S7SerializerImpl.extractBytes(targetClass, buffer, byteOffset); - } + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + return S7SerializerImpl.extractBytes(targetClass, buffer, byteOffset); + } - @Override - public S7Type getS7Type() { - return null; - } + @Override + public S7Type getS7Type() { + return null; + } - @Override - public int getSizeInBits() { - return 0; - } + @Override + public int getSizeInBits() { + return 0; + } - @Override - public int getSizeInBytes() { - return 0; - } + @Override + public int getSizeInBytes() { + return 0; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - S7SerializerImpl.insertBytes(javaType, buffer, byteOffset); - } + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + S7SerializerImpl.insertBytes(javaType, buffer, byteOffset); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/TimeConverter.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/TimeConverter.java index e7cba2b93..1f6c04ed6 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/TimeConverter.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/converter/TimeConverter.java @@ -28,43 +28,43 @@ import io.github.pnoker.driver.api.S7Type; public final class TimeConverter extends ByteConverter { - @Override - public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { - final byte b1 = super.extract(Byte.class, buffer, byteOffset + 3, bitOffset); - final byte b2 = super.extract(Byte.class, buffer, byteOffset + 2, bitOffset); - final byte b3 = super.extract(Byte.class, buffer, byteOffset + 1, bitOffset); - final byte b4 = super.extract(Byte.class, buffer, byteOffset, bitOffset); + @Override + public T extract(final Class targetClass, final byte[] buffer, final int byteOffset, final int bitOffset) { + final byte b1 = super.extract(Byte.class, buffer, byteOffset + 3, bitOffset); + final byte b2 = super.extract(Byte.class, buffer, byteOffset + 2, bitOffset); + final byte b3 = super.extract(Byte.class, buffer, byteOffset + 1, bitOffset); + final byte b4 = super.extract(Byte.class, buffer, byteOffset, bitOffset); - final long l = ((long) b1 & 0xFF) | ((long) b2 & 0xFF) << 8 | ((long) b3 & 0xFF) << 16 - | ((long) b4 & 0xFF) << 24; + final long l = ((long) b1 & 0xFF) | ((long) b2 & 0xFF) << 8 | ((long) b3 & 0xFF) << 16 + | ((long) b4 & 0xFF) << 24; - return targetClass.cast(l); - } + return targetClass.cast(l); + } - @Override - public S7Type getS7Type() { - return S7Type.TIME; - } + @Override + public S7Type getS7Type() { + return S7Type.TIME; + } - @Override - public int getSizeInBytes() { - return 4; - } + @Override + public int getSizeInBytes() { + return 4; + } - @Override - public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, - final int size) { - final long l = (Long) javaType; + @Override + public void insert(final Object javaType, final byte[] buffer, final int byteOffset, final int bitOffset, + final int size) { + final long l = (Long) javaType; - final byte b1 = (byte) ((byte) (l) & 0xFF); - final byte b2 = (byte) ((byte) (l >> 8) & 0xFF); - final byte b3 = (byte) ((byte) (l >> 16) & 0xFF); - final byte b4 = (byte) ((byte) (l >> 24) & 0xFF); + final byte b1 = (byte) ((byte) (l) & 0xFF); + final byte b2 = (byte) ((byte) (l >> 8) & 0xFF); + final byte b3 = (byte) ((byte) (l >> 16) & 0xFF); + final byte b4 = (byte) ((byte) (l >> 24) & 0xFF); - super.insert(b1, buffer, byteOffset + 3, bitOffset, 1); - super.insert(b2, buffer, byteOffset + 2, bitOffset, 1); - super.insert(b3, buffer, byteOffset + 1, bitOffset, 1); - super.insert(b4, buffer, byteOffset, bitOffset, 1); - } + super.insert(b1, buffer, byteOffset + 3, bitOffset, 1); + super.insert(b2, buffer, byteOffset + 2, bitOffset, 1); + super.insert(b3, buffer, byteOffset + 1, bitOffset, 1); + super.insert(b4, buffer, byteOffset, bitOffset, 1); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanEntry.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanEntry.java index b5b84b57f..16e707b3b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanEntry.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanEntry.java @@ -28,43 +28,43 @@ import java.lang.reflect.Field; */ public final class BeanEntry { - /** - * The Array size - */ - public int arraySize; + /** + * The Array size + */ + public int arraySize; - /** - * Offsets and size - */ - public int byteOffset; + /** + * Offsets and size + */ + public int byteOffset; - public int bitOffset; + public int bitOffset; - public int size; + public int size; - /** - * The corresponding field - */ - public Field field; + /** + * The corresponding field + */ + public Field field; - /** - * Array type - */ - public boolean isArray; + /** + * Array type + */ + public boolean isArray; - /** - * The S7 Type - */ - public S7Type s7type; + /** + * The S7 Type + */ + public S7Type s7type; - /** - * The corresponding serializer - */ - public S7Serializable serializer; + /** + * The corresponding serializer + */ + public S7Serializable serializer; - /** - * The Java type - */ - public Class type; + /** + * The Java type + */ + public Class type; } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParseResult.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParseResult.java index 4b30cdf85..c266f34b3 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParseResult.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParseResult.java @@ -28,14 +28,14 @@ import java.util.Vector; public final class BeanParseResult { - /** - * The needed blocksize - */ - public int blockSize; + /** + * The needed blocksize + */ + public int blockSize; - /** - * The Bean entries - */ - public Vector entries = new Vector(); + /** + * The Bean entries + */ + public Vector entries = new Vector(); } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParser.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParser.java index 327f11ba8..e5918210b 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParser.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/api/impl/serializer/parser/BeanParser.java @@ -36,144 +36,141 @@ import java.lang.reflect.Field; @Slf4j public final class BeanParser { - private BeanParser() { - throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); - } + private BeanParser() { + throw new IllegalStateException(ExceptionConstant.UTILITY_CLASS); + } - /** - * Returns the wrapper for the primitive type - * @param primitiveType Class - * @return Class - */ - private static Class getWrapperForPrimitiveType(final Class primitiveType) { - if (primitiveType == boolean.class) { - return Boolean.class; - } - else if (primitiveType == byte.class) { - return Byte.class; - } - else if (primitiveType == int.class) { - return Integer.class; - } - else if (primitiveType == float.class) { - return Float.class; - } - else if (primitiveType == double.class) { - return Double.class; - } - else if (primitiveType == long.class) { - return Long.class; - } - else { - // Fallback - return primitiveType; - } - } + /** + * Returns the wrapper for the primitive type + * + * @param primitiveType Class + * @return Class + */ + private static Class getWrapperForPrimitiveType(final Class primitiveType) { + if (primitiveType == boolean.class) { + return Boolean.class; + } else if (primitiveType == byte.class) { + return Byte.class; + } else if (primitiveType == int.class) { + return Integer.class; + } else if (primitiveType == float.class) { + return Float.class; + } else if (primitiveType == double.class) { + return Double.class; + } else if (primitiveType == long.class) { + return Long.class; + } else { + // Fallback + return primitiveType; + } + } - public static BeanEntry parse(PlcS7PointVariable plcs7PointVariable) throws Exception { - final BeanEntry entry = new BeanEntry(); - entry.byteOffset = plcs7PointVariable.getByteOffset(); - entry.bitOffset = plcs7PointVariable.getBitOffset(); - entry.size = plcs7PointVariable.getSize(); - entry.s7type = plcs7PointVariable.getType(); - entry.type = getWrapperForPrimitiveType(plcs7PointVariable.getFieldType()); - entry.serializer = entry.s7type.getSerializer().getDeclaredConstructor().newInstance(); + public static BeanEntry parse(PlcS7PointVariable plcs7PointVariable) throws Exception { + final BeanEntry entry = new BeanEntry(); + entry.byteOffset = plcs7PointVariable.getByteOffset(); + entry.bitOffset = plcs7PointVariable.getBitOffset(); + entry.size = plcs7PointVariable.getSize(); + entry.s7type = plcs7PointVariable.getType(); + entry.type = getWrapperForPrimitiveType(plcs7PointVariable.getFieldType()); + entry.serializer = entry.s7type.getSerializer().getDeclaredConstructor().newInstance(); - return entry; - } + return entry; + } - /** - * Parses a Class - * @param jclass Class - * @return BeanParseResult - * @throws Exception Exception - */ - public static BeanParseResult parse(final Class jclass) throws Exception { - final BeanParseResult res = new BeanParseResult(); - log.trace("Parsing: " + jclass.getName()); + /** + * Parses a Class + * + * @param jclass Class + * @return BeanParseResult + * @throws Exception Exception + */ + public static BeanParseResult parse(final Class jclass) throws Exception { + final BeanParseResult res = new BeanParseResult(); + log.trace("Parsing: " + jclass.getName()); - for (final Field field : jclass.getFields()) { - final S7Variable dataAnnotation = field.getAnnotation(S7Variable.class); + for (final Field field : jclass.getFields()) { + final S7Variable dataAnnotation = field.getAnnotation(S7Variable.class); - if (dataAnnotation != null) { - log.trace("Parsing field: " + field.getName()); - log.trace(" type: " + dataAnnotation.type()); - log.trace(" byteOffset: " + dataAnnotation.byteOffset()); - log.trace(" bitOffset: " + dataAnnotation.bitOffset()); - log.trace(" size: " + dataAnnotation.size()); - log.trace(" arraySize: " + dataAnnotation.arraySize()); + if (dataAnnotation != null) { + log.trace("Parsing field: " + field.getName()); + log.trace(" type: " + dataAnnotation.type()); + log.trace(" byteOffset: " + dataAnnotation.byteOffset()); + log.trace(" bitOffset: " + dataAnnotation.bitOffset()); + log.trace(" size: " + dataAnnotation.size()); + log.trace(" arraySize: " + dataAnnotation.arraySize()); - final int offset = dataAnnotation.byteOffset(); + final int offset = dataAnnotation.byteOffset(); - // update max offset - if (offset > res.blockSize) { - res.blockSize = offset; - } + // update max offset + if (offset > res.blockSize) { + res.blockSize = offset; + } - if (dataAnnotation.type() == S7Type.STRUCT) { - // recurse - log.trace("Recursing..."); - final BeanParseResult subResult = parse(field.getType()); - res.blockSize += subResult.blockSize; - log.trace(" New blocksize: " + res.blockSize); - } + if (dataAnnotation.type() == S7Type.STRUCT) { + // recurse + log.trace("Recursing..."); + final BeanParseResult subResult = parse(field.getType()); + res.blockSize += subResult.blockSize; + log.trace(" New blocksize: " + res.blockSize); + } - log.trace(" New blocksize (+offset): " + res.blockSize); + log.trace(" New blocksize (+offset): " + res.blockSize); - // Add dynamic size - res.blockSize += dataAnnotation.size(); + // Add dynamic size + res.blockSize += dataAnnotation.size(); - // Plain element - final BeanEntry entry = new BeanEntry(); - entry.byteOffset = dataAnnotation.byteOffset(); - entry.bitOffset = dataAnnotation.bitOffset(); - entry.field = field; - entry.type = getWrapperForPrimitiveType(field.getType()); - entry.size = dataAnnotation.size(); - entry.s7type = dataAnnotation.type(); - entry.isArray = field.getType().isArray(); - entry.arraySize = dataAnnotation.arraySize(); + // Plain element + final BeanEntry entry = new BeanEntry(); + entry.byteOffset = dataAnnotation.byteOffset(); + entry.bitOffset = dataAnnotation.bitOffset(); + entry.field = field; + entry.type = getWrapperForPrimitiveType(field.getType()); + entry.size = dataAnnotation.size(); + entry.s7type = dataAnnotation.type(); + entry.isArray = field.getType().isArray(); + entry.arraySize = dataAnnotation.arraySize(); - if (entry.isArray) { - entry.type = getWrapperForPrimitiveType(entry.type.getComponentType()); - } + if (entry.isArray) { + entry.type = getWrapperForPrimitiveType(entry.type.getComponentType()); + } - // Create new serializer - final S7Serializable s = entry.s7type.getSerializer().getDeclaredConstructor().newInstance(); - entry.serializer = s; + // Create new serializer + final S7Serializable s = entry.s7type.getSerializer().getDeclaredConstructor().newInstance(); + entry.serializer = s; - res.blockSize += (s.getSizeInBytes() * dataAnnotation.arraySize()); - log.trace(" New blocksize (+array): " + res.blockSize); + res.blockSize += (s.getSizeInBytes() * dataAnnotation.arraySize()); + log.trace(" New blocksize (+array): " + res.blockSize); - if (s.getSizeInBits() > 0) { - boolean offsetOfBitAlreadyKnown = false; - for (final BeanEntry parsedEntry : res.entries) { - if (parsedEntry.byteOffset == entry.byteOffset) { - offsetOfBitAlreadyKnown = true; - } - } - if (!offsetOfBitAlreadyKnown) { - res.blockSize++; - } - } + if (s.getSizeInBits() > 0) { + boolean offsetOfBitAlreadyKnown = false; + for (final BeanEntry parsedEntry : res.entries) { + if (parsedEntry.byteOffset == entry.byteOffset) { + offsetOfBitAlreadyKnown = true; + } + } + if (!offsetOfBitAlreadyKnown) { + res.blockSize++; + } + } - res.entries.add(entry); - } - } + res.entries.add(entry); + } + } - log.trace("Parsing done, overall size: " + res.blockSize); + log.trace("Parsing done, overall size: " + res.blockSize); - return res; - } + return res; + } - /** - * Parses an Object - * @param obj Object - * @return BeanParseResult - * @throws Exception Exception - */ - public static BeanParseResult parse(final Object obj) throws Exception { - return parse(obj.getClass()); - } + /** + * Parses an Object + * + * @param obj Object + * @return BeanParseResult + * @throws Exception Exception + */ + public static BeanParseResult parse(final Object obj) throws Exception { + return parse(obj.getClass()); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/bean/PlcS7PointVariable.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/bean/PlcS7PointVariable.java index cc92824ab..8a52a17de 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/bean/PlcS7PointVariable.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/bean/PlcS7PointVariable.java @@ -32,77 +32,77 @@ import java.util.Date; @Setter public class PlcS7PointVariable { - private int dbNum; + private int dbNum; - private int byteOffset; + private int byteOffset; - private int bitOffset; + private int bitOffset; - /** - * Data block size, the number of bytes occupied by point data. - */ - private int size; + /** + * Data block size, the number of bytes occupied by point data. + */ + private int size; - private S7Type type; + private S7Type type; - private Class fieldType; + private Class fieldType; - public PlcS7PointVariable(int dbNum, int byteOffset, int bitOffset, int size, String s7Type) { - this.dbNum = dbNum; - this.byteOffset = byteOffset; - this.bitOffset = bitOffset; - this.size = size; - getS7TypeAndType(s7Type); + public PlcS7PointVariable(int dbNum, int byteOffset, int bitOffset, int size, String s7Type) { + this.dbNum = dbNum; + this.byteOffset = byteOffset; + this.bitOffset = bitOffset; + this.size = size; + getS7TypeAndType(s7Type); - } + } - private void getS7TypeAndType(String s7Type) { - switch (s7Type) { - case "bool": - this.type = S7Type.BOOL; - this.fieldType = Boolean.class; - break; - case "byte": - this.type = S7Type.BYTE; - this.fieldType = Byte.class; - break; - case "int": - this.type = S7Type.INT; - this.fieldType = Short.class; - break; - case "dint": - this.type = S7Type.DINT; - this.fieldType = Long.class; - break; - case "word": - this.type = S7Type.WORD; - this.fieldType = Integer.class; - break; - case "dword": - this.type = S7Type.DWORD; - this.fieldType = Long.class; - break; - case "real": - this.type = S7Type.REAL; - this.fieldType = Float.class; - break; - case "date": - this.type = S7Type.DATE; - this.fieldType = Date.class; - break; - case "time": - this.type = S7Type.TIME; - this.fieldType = Long.class; - break; - case "datetime": - this.type = S7Type.DATE_AND_TIME; - this.fieldType = Long.class; - break; - default: - this.type = S7Type.STRING; - this.fieldType = Boolean.class; - break; - } - } + private void getS7TypeAndType(String s7Type) { + switch (s7Type) { + case "bool": + this.type = S7Type.BOOL; + this.fieldType = Boolean.class; + break; + case "byte": + this.type = S7Type.BYTE; + this.fieldType = Byte.class; + break; + case "int": + this.type = S7Type.INT; + this.fieldType = Short.class; + break; + case "dint": + this.type = S7Type.DINT; + this.fieldType = Long.class; + break; + case "word": + this.type = S7Type.WORD; + this.fieldType = Integer.class; + break; + case "dword": + this.type = S7Type.DWORD; + this.fieldType = Long.class; + break; + case "real": + this.type = S7Type.REAL; + this.fieldType = Float.class; + break; + case "date": + this.type = S7Type.DATE; + this.fieldType = Date.class; + break; + case "time": + this.type = S7Type.TIME; + this.fieldType = Long.class; + break; + case "datetime": + this.type = S7Type.DATE_AND_TIME; + this.fieldType = Long.class; + break; + default: + this.type = S7Type.STRING; + this.fieldType = Boolean.class; + break; + } + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/exception/S7Exception.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/exception/S7Exception.java index b2058a674..96bd71928 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/exception/S7Exception.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/exception/S7Exception.java @@ -27,40 +27,43 @@ package io.github.pnoker.driver.exception; */ public final class S7Exception extends RuntimeException { - /** - * The Constant serialVersionUID. - */ - private static final long serialVersionUID = 1L; + /** + * The Constant serialVersionUID. + */ + private static final long serialVersionUID = 1L; - /** - * Instantiates a new s7 exception. - */ - public S7Exception() { - } + /** + * Instantiates a new s7 exception. + */ + public S7Exception() { + } - /** - * Instantiates a new s7 exception. - * @param message the message - */ - public S7Exception(final String message) { - super(message); - } + /** + * Instantiates a new s7 exception. + * + * @param message the message + */ + public S7Exception(final String message) { + super(message); + } - /** - * Instantiates a new s7 exception. - * @param message the message - * @param cause the cause - */ - public S7Exception(final String message, final Throwable cause) { - super(message, cause); - } + /** + * Instantiates a new s7 exception. + * + * @param message the message + * @param cause the cause + */ + public S7Exception(final String message, final Throwable cause) { + super(message, cause); + } - /** - * Instantiates a new s7 exception. - * @param cause the cause - */ - public S7Exception(final Throwable cause) { - super(cause); - } + /** + * Instantiates a new s7 exception. + * + * @param cause the cause + */ + public S7Exception(final Throwable cause) { + super(cause); + } } diff --git a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 1cc3781c6..fad9e8caa 100644 --- a/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-plcs7/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -69,192 +69,189 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Cache of device ID to S7 connector instances. - */ - private Map connectMap; + /** + * Cache of device ID to S7 connector instances. + */ + private Map connectMap; - @Override - public void initial() { - connectMap = new ConcurrentHashMap<>(16); - } + @Override + public void initial() { + connectMap = new ConcurrentHashMap<>(16); + } - @Override - public void schedule() { - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + @Override + public void schedule() { + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - @Override - public void event(MetadataEventDTO metadataEvent) { - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + @Override + public void event(MetadataEventDTO metadataEvent) { + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - // Remove stale connection when device is updated or deleted - if (MetadataOperateTypeEnum.DELETE.equals(operateType) - || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { - connectMap.remove(metadataEvent.getId()); - } - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + // Remove stale connection when device is updated or deleted + if (MetadataOperateTypeEnum.DELETE.equals(operateType) + || MetadataOperateTypeEnum.UPDATE.equals(operateType)) { + connectMap.remove(metadataEvent.getId()); + } + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - log.debug("Plc S7 Read, device: {}, point: {}", JsonUtil.toJsonString(device), JsonUtil.toJsonString(point)); - MyS7Connector myS7Connector = getS7Connector(device.getId(), driverConfig); + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + log.debug("Plc S7 Read, device: {}, point: {}", JsonUtil.toJsonString(device), JsonUtil.toJsonString(point)); + MyS7Connector myS7Connector = getS7Connector(device.getId(), driverConfig); - try { - myS7Connector.lock.writeLock().lock(); - S7Serializer serializer = S7SerializerFactory.buildSerializer(myS7Connector.getConnector()); - PlcS7PointVariable plcs7PointVariable = getPointVariable(pointConfig, point.getPointTypeFlag().getCode()); - return new RValue(device, point, String.valueOf(serializer.dispense(plcs7PointVariable))); - } - catch (Exception e) { - log.error("Plc S7 Read Error: {}", e.getMessage()); - return null; - } - finally { - myS7Connector.lock.writeLock().unlock(); - } - } + try { + myS7Connector.lock.writeLock().lock(); + S7Serializer serializer = S7SerializerFactory.buildSerializer(myS7Connector.getConnector()); + PlcS7PointVariable plcs7PointVariable = getPointVariable(pointConfig, point.getPointTypeFlag().getCode()); + return new RValue(device, point, String.valueOf(serializer.dispense(plcs7PointVariable))); + } catch (Exception e) { + log.error("Plc S7 Read Error: {}", e.getMessage()); + return null; + } finally { + myS7Connector.lock.writeLock().unlock(); + } + } - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - log.debug("Plc S7 Write, device: {}, value: {}", JsonUtil.toJsonString(device), JsonUtil.toJsonString(wValue)); - MyS7Connector myS7Connector = getS7Connector(device.getId(), driverConfig); - myS7Connector.lock.writeLock().lock(); - S7Serializer serializer = S7SerializerFactory.buildSerializer(myS7Connector.getConnector()); - PlcS7PointVariable plcs7PointVariable = getPointVariable(pointConfig, wValue.getType().getCode()); + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + log.debug("Plc S7 Write, device: {}, value: {}", JsonUtil.toJsonString(device), JsonUtil.toJsonString(wValue)); + MyS7Connector myS7Connector = getS7Connector(device.getId(), driverConfig); + myS7Connector.lock.writeLock().lock(); + S7Serializer serializer = S7SerializerFactory.buildSerializer(myS7Connector.getConnector()); + PlcS7PointVariable plcs7PointVariable = getPointVariable(pointConfig, wValue.getType().getCode()); - try { - store(serializer, plcs7PointVariable, wValue.getType().getCode(), wValue.getValue()); - return true; - } - catch (Exception e) { - log.error("Plc S7 Write Error: {}", e.getMessage()); - return false; - } - finally { - myS7Connector.lock.writeLock().unlock(); - } - } + try { + store(serializer, plcs7PointVariable, wValue.getType().getCode(), wValue.getValue()); + return true; + } catch (Exception e) { + log.error("Plc S7 Write Error: {}", e.getMessage()); + return false; + } finally { + myS7Connector.lock.writeLock().unlock(); + } + } - /** - * Get or create an S7 TCP connector for the given device. - * @param deviceId unique device identifier - * @param driverConfig driver configuration (host, port) - * @return wrapper containing the connector and its read-write lock - * @throws ServiceException if connector creation fails - */ - private MyS7Connector getS7Connector(Long deviceId, Map driverConfig) { - MyS7Connector myS7Connector = connectMap.get(deviceId); - if (Objects.isNull(myS7Connector)) { - myS7Connector = new MyS7Connector(); + /** + * Get or create an S7 TCP connector for the given device. + * + * @param deviceId unique device identifier + * @param driverConfig driver configuration (host, port) + * @return wrapper containing the connector and its read-write lock + * @throws ServiceException if connector creation fails + */ + private MyS7Connector getS7Connector(Long deviceId, Map driverConfig) { + MyS7Connector myS7Connector = connectMap.get(deviceId); + if (Objects.isNull(myS7Connector)) { + myS7Connector = new MyS7Connector(); - log.debug("Plc S7 Connection Info {}", JsonUtil.toJsonString(driverConfig)); - try { - S7Connector s7Connector = S7ConnectorFactory.buildTCPConnector() - .withHost(driverConfig.get("host").getValue(String.class)) - .withPort(driverConfig.get("port").getValue(Integer.class)) - .build(); - myS7Connector.setLock(new ReentrantReadWriteLock()); - myS7Connector.setConnector(s7Connector); - } - catch (Exception e) { - throw new ServiceException("new s7connector fail" + e.getMessage()); - } - connectMap.put(deviceId, myS7Connector); - } - return myS7Connector; - } + log.debug("Plc S7 Connection Info {}", JsonUtil.toJsonString(driverConfig)); + try { + S7Connector s7Connector = S7ConnectorFactory.buildTCPConnector() + .withHost(driverConfig.get("host").getValue(String.class)) + .withPort(driverConfig.get("port").getValue(Integer.class)) + .build(); + myS7Connector.setLock(new ReentrantReadWriteLock()); + myS7Connector.setConnector(s7Connector); + } catch (Exception e) { + throw new ServiceException("new s7connector fail" + e.getMessage()); + } + connectMap.put(deviceId, myS7Connector); + } + return myS7Connector; + } - /** - * Build a PlcS7PointVariable from point configuration attributes. - * @param pointConfig point attributes (dbNum, byteOffset, bitOffset, blockSize) - * @param type S7 data type code - * @return the point variable definition - */ - private PlcS7PointVariable getPointVariable(Map pointConfig, String type) { - log.debug("Plc S7 Point Attribute Config {}", JsonUtil.toJsonString(pointConfig)); - return new PlcS7PointVariable(pointConfig.get("dbNum").getValue(Integer.class), - pointConfig.get("byteOffset").getValue(Integer.class), - pointConfig.get("bitOffset").getValue(Integer.class), - pointConfig.get("blockSize").getValue(Integer.class), type); - } + /** + * Build a PlcS7PointVariable from point configuration attributes. + * + * @param pointConfig point attributes (dbNum, byteOffset, bitOffset, blockSize) + * @param type S7 data type code + * @return the point variable definition + */ + private PlcS7PointVariable getPointVariable(Map pointConfig, String type) { + log.debug("Plc S7 Point Attribute Config {}", JsonUtil.toJsonString(pointConfig)); + return new PlcS7PointVariable(pointConfig.get("dbNum").getValue(Integer.class), + pointConfig.get("byteOffset").getValue(Integer.class), + pointConfig.get("bitOffset").getValue(Integer.class), + pointConfig.get("blockSize").getValue(Integer.class), type); + } - /** - * Write a typed value to an S7 data block. - *

- * Supports INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. - * @param serializer active S7 serializer - * @param plcS7PointVariable target point variable (DB number, offsets) - * @param type data type code - * @param value string representation of the value to write - * @throws UnSupportException if the type is unsupported - */ - private void store(S7Serializer serializer, PlcS7PointVariable plcS7PointVariable, String type, String value) { - AttributeTypeFlagEnum valueType = AttributeTypeFlagEnum.ofCode(type); - if (Objects.isNull(valueType)) { - throw new UnSupportException("Unsupported type of " + type); - } - AttributeBO attributeBOConfig = new AttributeBO(value, valueType); + /** + * Write a typed value to an S7 data block. + *

+ * Supports INT, LONG, FLOAT, DOUBLE, BOOLEAN, STRING. + * + * @param serializer active S7 serializer + * @param plcS7PointVariable target point variable (DB number, offsets) + * @param type data type code + * @param value string representation of the value to write + * @throws UnSupportException if the type is unsupported + */ + private void store(S7Serializer serializer, PlcS7PointVariable plcS7PointVariable, String type, String value) { + AttributeTypeFlagEnum valueType = AttributeTypeFlagEnum.ofCode(type); + if (Objects.isNull(valueType)) { + throw new UnSupportException("Unsupported type of " + type); + } + AttributeBO attributeBOConfig = new AttributeBO(value, valueType); - switch (valueType) { - case INT: - int intValue = attributeBOConfig.getValue(Integer.class); - serializer.store(intValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - case LONG: - long longValue = attributeBOConfig.getValue(Long.class); - serializer.store(longValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - case FLOAT: - float floatValue = attributeBOConfig.getValue(Float.class); - serializer.store(floatValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - case DOUBLE: - double doubleValue = attributeBOConfig.getValue(Double.class); - serializer.store(doubleValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - case BOOLEAN: - boolean booleanValue = attributeBOConfig.getValue(Boolean.class); - serializer.store(booleanValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - case STRING: - serializer.store(value, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); - break; - default: - break; - } - } + switch (valueType) { + case INT: + int intValue = attributeBOConfig.getValue(Integer.class); + serializer.store(intValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + case LONG: + long longValue = attributeBOConfig.getValue(Long.class); + serializer.store(longValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + case FLOAT: + float floatValue = attributeBOConfig.getValue(Float.class); + serializer.store(floatValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + case DOUBLE: + double doubleValue = attributeBOConfig.getValue(Double.class); + serializer.store(doubleValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + case BOOLEAN: + boolean booleanValue = attributeBOConfig.getValue(Boolean.class); + serializer.store(booleanValue, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + case STRING: + serializer.store(value, plcS7PointVariable.getDbNum(), plcS7PointVariable.getByteOffset()); + break; + default: + break; + } + } - /** - * Wrapper holding an S7 connector and its thread-safety lock. - */ - @Getter - @Setter - @NoArgsConstructor - @AllArgsConstructor - private static class MyS7Connector { + /** + * Wrapper holding an S7 connector and its thread-safety lock. + */ + @Getter + @Setter + @NoArgsConstructor + @AllArgsConstructor + private static class MyS7Connector { - private ReentrantReadWriteLock lock; + private ReentrantReadWriteLock lock; - private S7Connector connector; + private S7Connector connector; - } + } } diff --git a/dc3-driver/dc3-driver-virtual/README.md b/dc3-driver/dc3-driver-virtual/README.md index 2b11ebc48..3e4abc463 100644 --- a/dc3-driver/dc3-driver-virtual/README.md +++ b/dc3-driver/dc3-driver-virtual/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-driver-virtual` is the Virtual Driver of the IoT DC3 platform, designed for testing and development purposes. It simulates device communication by generating random point +`dc3-driver-virtual` is the Virtual Driver of the IoT DC3 platform, designed for testing and development purposes. It +simulates device communication by generating random point values on a configurable schedule without connecting to real hardware. ## Module Information diff --git a/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/VirtualDriverApplication.java b/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/VirtualDriverApplication.java index a245c8372..e967f2c0d 100644 --- a/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/VirtualDriverApplication.java +++ b/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/VirtualDriverApplication.java @@ -33,13 +33,14 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class VirtualDriverApplication { - /** - * Virtual Driver Application Main Method Start the Spring Boot application by passing - * the VirtualDriverApplication class and command line arguments - * @param args Command line arguments passed to the application - */ - public static void main(String[] args) { - SpringApplication.run(VirtualDriverApplication.class, args); - } + /** + * Virtual Driver Application Main Method Start the Spring Boot application by passing + * the VirtualDriverApplication class and command line arguments + * + * @param args Command line arguments passed to the application + */ + public static void main(String[] args) { + SpringApplication.run(VirtualDriverApplication.class, args); + } } diff --git a/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java b/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java index 70e759f16..52129cfc5 100644 --- a/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java +++ b/dc3-driver/dc3-driver-virtual/src/main/java/io/github/pnoker/driver/service/impl/DriverCustomServiceImpl.java @@ -54,167 +54,169 @@ import java.util.concurrent.TimeUnit; @Service public class DriverCustomServiceImpl implements DriverCustomService { - @Resource - DriverMetadata driverMetadata; + @Resource + DriverMetadata driverMetadata; - @Resource - private DriverSenderService driverSenderService; + @Resource + private DriverSenderService driverSenderService; - /** - * Initializes the virtual driver. - *

- * This method is called when the driver starts. Override this method to implement - * custom initialization logic specific to your virtual device simulation. - *

- */ - @Override - public void initial() { - /* - * Driver initialization logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. This method is automatically executed when the - * driver starts, and you can perform specific initialization operations here. - * - */ - } + /** + * Initializes the virtual driver. + *

+ * This method is called when the driver starts. Override this method to implement + * custom initialization logic specific to your virtual device simulation. + *

+ */ + @Override + public void initial() { + /* + * Driver initialization logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. This method is automatically executed when the + * driver starts, and you can perform specific initialization operations here. + * + */ + } - /** - * Scheduled task to report device status. - *

- * This method is called periodically to update device status. By default, all virtual - * devices are reported as ONLINE with a 25-second validity period. Override this - * method to implement custom status reporting logic. - *

- */ - @Override - public void schedule() { - /* - * Device status upload logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. Device status upload can be flexibly implemented - * based on specific requirements. Here are some common approaches: - Determine - * device status based on read data in the `read` method; - Periodically check - * device status in a custom scheduled task; - Trigger device status judgment - * based on specific business logic or events. - * - * Finally, submit the device status to the SDK management through the {@link - * DriverSenderService#deviceStatusSender(Long, DeviceStatusEnum)} interface. The - * device status enumeration {@link DeviceStatusEnum} includes the following - * states: - ONLINE: Device online - OFFLINE: Device offline - MAINTAIN: Device - * under maintenance - FAULT: Device fault - * - * In the following example, all devices are set to {@link - * DeviceStatusEnum#ONLINE}, with a status validity period of 25 {@link - * TimeUnit#SECONDS}. - */ - driverMetadata.getDeviceIds() - .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); - } + /** + * Scheduled task to report device status. + *

+ * This method is called periodically to update device status. By default, all virtual + * devices are reported as ONLINE with a 25-second validity period. Override this + * method to implement custom status reporting logic. + *

+ */ + @Override + public void schedule() { + /* + * Device status upload logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. Device status upload can be flexibly implemented + * based on specific requirements. Here are some common approaches: - Determine + * device status based on read data in the `read` method; - Periodically check + * device status in a custom scheduled task; - Trigger device status judgment + * based on specific business logic or events. + * + * Finally, submit the device status to the SDK management through the {@link + * DriverSenderService#deviceStatusSender(Long, DeviceStatusEnum)} interface. The + * device status enumeration {@link DeviceStatusEnum} includes the following + * states: - ONLINE: Device online - OFFLINE: Device offline - MAINTAIN: Device + * under maintenance - FAULT: Device fault + * + * In the following example, all devices are set to {@link + * DeviceStatusEnum#ONLINE}, with a status validity period of 25 {@link + * TimeUnit#SECONDS}. + */ + driverMetadata.getDeviceIds() + .forEach(id -> driverSenderService.deviceStatusSender(id, DeviceStatusEnum.ONLINE, 25, TimeUnit.SECONDS)); + } - /** - * Handles metadata change events for drivers, devices, and points. - *

- * This method is called when metadata is created, updated, or deleted. Override this - * method to implement custom event handling logic. - *

- * @param metadataEvent the metadata event containing type, operation, and ID - * information - */ - @Override - public void event(MetadataEventDTO metadataEvent) { - /* - * Receive metadata events for driver, device, and point creation, update, and - * deletion. - * - * Metadata type: {@link MetadataTypeEnum} (DRIVER, DEVICE, POINT) Metadata - * operation type: {@link MetadataOperateTypeEnum} (ADD, DELETE, UPDATE) - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. - */ - MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); - MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); - if (MetadataTypeEnum.DEVICE.equals(metadataType)) { - // to do something for device event - log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); - } - else if (MetadataTypeEnum.POINT.equals(metadataType)) { - // to do something for point event - log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); - } - } + /** + * Handles metadata change events for drivers, devices, and points. + *

+ * This method is called when metadata is created, updated, or deleted. Override this + * method to implement custom event handling logic. + *

+ * + * @param metadataEvent the metadata event containing type, operation, and ID + * information + */ + @Override + public void event(MetadataEventDTO metadataEvent) { + /* + * Receive metadata events for driver, device, and point creation, update, and + * deletion. + * + * Metadata type: {@link MetadataTypeEnum} (DRIVER, DEVICE, POINT) Metadata + * operation type: {@link MetadataOperateTypeEnum} (ADD, DELETE, UPDATE) + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. + */ + MetadataTypeEnum metadataType = metadataEvent.getMetadataType(); + MetadataOperateTypeEnum operateType = metadataEvent.getOperateType(); + if (MetadataTypeEnum.DEVICE.equals(metadataType)) { + // to do something for device event + log.info("Device metadata event: deviceId: {}, operate: {}", metadataEvent.getId(), operateType); + } else if (MetadataTypeEnum.POINT.equals(metadataType)) { + // to do something for point event + log.info("Point metadata event: pointId: {}, operate: {}", metadataEvent.getId(), operateType); + } + } - /** - * Reads data from a virtual device point. - *

- * This method generates simulated data based on the point type: - *

    - *
  • STRING type: returns "abcd1234"
  • - *
  • BOOLEAN type: returns a random boolean value
  • - *
  • Other types: returns a random float between 0 and 100
  • - *
- * Override this method to implement custom data generation logic. - *

- * @param driverConfig driver configuration attributes - * @param pointConfig point configuration attributes - * @param device the device to read from - * @param point the point to read - * @return the read value wrapped in an RValue object - */ - @Override - public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point) { - /* - * Read device point data logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. Generate random data based on point type: - If the - * point type is STRING, generate a random string of length 8; - If the point type - * is BOOLEAN, generate a random boolean value; - Otherwise, generate a random - * float between 0 and 100. - */ - if (PointTypeFlagEnum.STRING.equals(point.getPointTypeFlag())) { - return new RValue(device, point, "abcd1234"); - } - if (PointTypeFlagEnum.BOOLEAN.equals(point.getPointTypeFlag())) { - Random random = new Random(); - boolean b = random.nextBoolean(); - return new RValue(device, point, String.valueOf(b)); - } + /** + * Reads data from a virtual device point. + *

+ * This method generates simulated data based on the point type: + *

    + *
  • STRING type: returns "abcd1234"
  • + *
  • BOOLEAN type: returns a random boolean value
  • + *
  • Other types: returns a random float between 0 and 100
  • + *
+ * Override this method to implement custom data generation logic. + *

+ * + * @param driverConfig driver configuration attributes + * @param pointConfig point configuration attributes + * @param device the device to read from + * @param point the point to read + * @return the read value wrapped in an RValue object + */ + @Override + public RValue read(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point) { + /* + * Read device point data logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. Generate random data based on point type: - If the + * point type is STRING, generate a random string of length 8; - If the point type + * is BOOLEAN, generate a random boolean value; - Otherwise, generate a random + * float between 0 and 100. + */ + if (PointTypeFlagEnum.STRING.equals(point.getPointTypeFlag())) { + return new RValue(device, point, "abcd1234"); + } + if (PointTypeFlagEnum.BOOLEAN.equals(point.getPointTypeFlag())) { + Random random = new Random(); + boolean b = random.nextBoolean(); + return new RValue(device, point, String.valueOf(b)); + } - Random random = new Random(); - double value = random.nextDouble() * 100; - return new RValue(device, point, String.valueOf(value)); - } + Random random = new Random(); + double value = random.nextDouble() * 100; + return new RValue(device, point, String.valueOf(value)); + } - /** - * Writes data to a virtual device point. - *

- * By default, this method returns false indicating the write operation is not - * supported. Override this method to implement custom write logic for virtual - * devices. - *

- * @param driverConfig driver configuration attributes - * @param pointConfig point configuration attributes - * @param device the device to write to - * @param point the point to write - * @param wValue the value to write - * @return true if the write operation succeeded, false otherwise - */ - @Override - public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, - PointBO point, WValue wValue) { - /* - * Write device point data logic - * - * Hint: The logic here is for reference only; please modify it according to the - * actual application scenario. You can implement the point data write logic based - * on specific business requirements. By default, this method returns false, - * indicating that the write operation was not executed or failed. - */ - return false; - } + /** + * Writes data to a virtual device point. + *

+ * By default, this method returns false indicating the write operation is not + * supported. Override this method to implement custom write logic for virtual + * devices. + *

+ * + * @param driverConfig driver configuration attributes + * @param pointConfig point configuration attributes + * @param device the device to write to + * @param point the point to write + * @param wValue the value to write + * @return true if the write operation succeeded, false otherwise + */ + @Override + public Boolean write(Map driverConfig, Map pointConfig, DeviceBO device, + PointBO point, WValue wValue) { + /* + * Write device point data logic + * + * Hint: The logic here is for reference only; please modify it according to the + * actual application scenario. You can implement the point data write logic based + * on specific business requirements. By default, this method returns false, + * indicating that the write operation was not executed or failed. + */ + return false; + } } diff --git a/dc3-gateway/README.md b/dc3-gateway/README.md index 1310502f5..27bdaa9f6 100644 --- a/dc3-gateway/README.md +++ b/dc3-gateway/README.md @@ -2,7 +2,8 @@ ## Overview -`dc3-gateway` is the API Gateway of the IoT DC3 platform, built on Spring Cloud Gateway (WebFlux). It serves as the single ingress point for all external HTTP traffic, providing +`dc3-gateway` is the API Gateway of the IoT DC3 platform, built on Spring Cloud Gateway (WebFlux). It serves as the +single ingress point for all external HTTP traffic, providing rate limiting, authentication verification, service routing, and reverse proxying. ## Module Information @@ -21,7 +22,8 @@ rate limiting, authentication verification, service routing, and reverse proxyin ## Key Responsibilities - **Request Routing**: Routes `/api/v3/{service}/**` requests to the corresponding center service via `StripPrefix=2` -- **Authentication Filter**: `Authentic` filter validates Bearer tokens with the Auth Center before forwarding protected routes +- **Authentication Filter**: `Authentic` filter validates Bearer tokens with the Auth Center before forwarding protected + routes - **Load Balancing**: Uses Nacos or static addresses (dev mode) for backend service discovery - **gRPC Client**: Connects to `dc3-center-auth` (port `9300`) for token validation diff --git a/dc3-gateway/src/main/java/io/github/pnoker/gateway/GatewayApplication.java b/dc3-gateway/src/main/java/io/github/pnoker/gateway/GatewayApplication.java index 0cb955500..e465704c7 100644 --- a/dc3-gateway/src/main/java/io/github/pnoker/gateway/GatewayApplication.java +++ b/dc3-gateway/src/main/java/io/github/pnoker/gateway/GatewayApplication.java @@ -33,12 +33,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GatewayApplication { - /** - * Main method to launch Spring Boot application - * @param args Command line arguments - */ - public static void main(String[] args) { - SpringApplication.run(GatewayApplication.class, args); - } + /** + * Main method to launch Spring Boot application + * + * @param args Command line arguments + */ + public static void main(String[] args) { + SpringApplication.run(GatewayApplication.class, args); + } } diff --git a/docs/MODULES.md b/docs/MODULES.md index 5acd98963..9219388a7 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -15,78 +15,78 @@ iot-dc3 (root pom) ## dc3-api - gRPC Contract Layer -| Module | Description | -|--------|-------------| -| dc3-api-auth | Auth protobuf: tenant, user, token | -| dc3-api-data | Data protobuf: point value read/write | -| dc3-api-driver | Driver protobuf: register, command | +| Module | Description | +|-----------------|------------------------------------------------------| +| dc3-api-auth | Auth protobuf: tenant, user, token | +| dc3-api-data | Data protobuf: point value read/write | +| dc3-api-driver | Driver protobuf: register, command | | dc3-api-manager | Manager protobuf: device, profile, driver management | ## dc3-common - Shared Business Libraries ### Foundation Layer -| Module | Purpose | -|--------|--------| -| dc3-common-constant | Enums, constants, value objects | +| Module | Purpose | +|----------------------|------------------------------------------| +| dc3-common-constant | Enums, constants, value objects | | dc3-common-exception | Custom exception hierarchy (24+ classes) | -| dc3-common-public | R wrapper, utility classes | -| dc3-common-model | BO/VO/DTO entity definitions | -| dc3-common-web | BaseController, WebFlux config | -| dc3-common-log | Request/response logging filter | -| dc3-common-thread | Thread pool configuration | +| dc3-common-public | R wrapper, utility classes | +| dc3-common-model | BO/VO/DTO entity definitions | +| dc3-common-web | BaseController, WebFlux config | +| dc3-common-log | Request/response logging filter | +| dc3-common-thread | Thread pool configuration | ### Data Access Layer -| Module | Purpose | -|--------|--------| -| dc3-common-dal | MyBatis-Plus mapper/repository | -| dc3-common-postgres | PostgreSQL datasource (dynamic multi-schema) | -| dc3-common-redis | Redis cache configuration | -| dc3-common-repository | File/blob storage abstraction | +| Module | Purpose | +|-----------------------|----------------------------------------------| +| dc3-common-dal | MyBatis-Plus mapper/repository | +| dc3-common-postgres | PostgreSQL datasource (dynamic multi-schema) | +| dc3-common-redis | Redis cache configuration | +| dc3-common-repository | File/blob storage abstraction | ### Communication Layer -| Module | Purpose | -|--------|--------| -| dc3-common-facade-api | Facade interfaces for cross-service calls | -| dc3-common-facade-grpc | gRPC client/server auto-configuration | -| dc3-common-facade-local | Local facade for dc3-center-single | -| dc3-common-rabbitmq | RabbitMQ exchange/queue config | -| dc3-common-mqtt | MQTT client configuration | +| Module | Purpose | +|-------------------------|-------------------------------------------| +| dc3-common-facade-api | Facade interfaces for cross-service calls | +| dc3-common-facade-grpc | gRPC client/server auto-configuration | +| dc3-common-facade-local | Local facade for dc3-center-single | +| dc3-common-rabbitmq | RabbitMQ exchange/queue config | +| dc3-common-mqtt | MQTT client configuration | ### Domain Layer -| Module | Purpose | Key Dependencies | -|--------|---------|------------------| -| dc3-common-auth | Auth business logic | dc3-api-auth, dal, postgres, web | -| dc3-common-manager | Manager business logic | dc3-api-*, dal, facade-api, postgres, rabbitmq, quartz, web | -| dc3-common-data | Data business logic | dc3-api-*, dal, facade-api, postgres, rabbitmq, redis, repository, quartz, web | -| dc3-common-driver | Driver SDK | dc3-api-driver, constant, exception, log, model, public, quartz, rabbitmq, thread | -| dc3-common-gateway | Gateway filter | facade-api, log, model, public, web | +| Module | Purpose | Key Dependencies | +|--------------------|------------------------|-----------------------------------------------------------------------------------| +| dc3-common-auth | Auth business logic | dc3-api-auth, dal, postgres, web | +| dc3-common-manager | Manager business logic | dc3-api-*, dal, facade-api, postgres, rabbitmq, quartz, web | +| dc3-common-data | Data business logic | dc3-api-*, dal, facade-api, postgres, rabbitmq, redis, repository, quartz, web | +| dc3-common-driver | Driver SDK | dc3-api-driver, constant, exception, log, model, public, quartz, rabbitmq, thread | +| dc3-common-gateway | Gateway filter | facade-api, log, model, public, web | ## dc3-center - Deployable Services -| Service | Depends On | HTTP | gRPC | -|---------|-----------|------|------| -| dc3-center-auth | dc3-common-auth | 8300 | 9300 | -| dc3-center-data | dc3-common-data, facade-grpc | 8500 | 9500 | -| dc3-center-manager | dc3-common-manager, facade-grpc | 8400 | 9400 | -| dc3-center-single | auth+manager+data (facade-local) | 8200 | 9200 | +| Service | Depends On | HTTP | gRPC | +|--------------------|----------------------------------|------|------| +| dc3-center-auth | dc3-common-auth | 8300 | 9300 | +| dc3-center-data | dc3-common-data, facade-grpc | 8500 | 9500 | +| dc3-center-manager | dc3-common-manager, facade-grpc | 8400 | 9400 | +| dc3-center-single | auth+manager+data (facade-local) | 8200 | 9200 | ## dc3-driver - Protocol Drivers All drivers depend on dc3-common-driver. Communicate with Manager via gRPC + RabbitMQ. -| Driver | Protocol | -|--------|----------| -| dc3-driver-virtual | Virtual device simulator (HTTP push) | -| dc3-driver-listening-virtual | Listening virtual driver (MQTT) | -| dc3-driver-modbus-tcp | Modbus TCP | -| dc3-driver-mqtt | MQTT (generic) | -| dc3-driver-opc-da | OPC DA (DCOM) | -| dc3-driver-opc-ua | OPC UA | -| dc3-driver-plcs7 | Siemens S7 (PLC) | +| Driver | Protocol | +|------------------------------|--------------------------------------| +| dc3-driver-virtual | Virtual device simulator (HTTP push) | +| dc3-driver-listening-virtual | Listening virtual driver (MQTT) | +| dc3-driver-modbus-tcp | Modbus TCP | +| dc3-driver-mqtt | MQTT (generic) | +| dc3-driver-opc-da | OPC DA (DCOM) | +| dc3-driver-opc-ua | OPC UA | +| dc3-driver-plcs7 | Siemens S7 (PLC) | ## dc3-gateway diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index d09f839d0..c1c401876 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -101,12 +101,12 @@ make compose-restart STACK=dev ## 8. Service default endpoints -| Service | HTTP | gRPC | -|---------|------|------| -| Gateway | 8000 | - | -| Auth Center | 8300 | 9300 | +| Service | HTTP | gRPC | +|----------------|------|------| +| Gateway | 8000 | - | +| Auth Center | 8300 | 9300 | | Manager Center | 8400 | 9400 | -| Data Center | 8500 | 9500 | +| Data Center | 8500 | 9500 | ## 9. Recommended local workflow diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 84055e0cd..1f40fd5e4 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -7,6 +7,7 @@ Common local development and runtime issues in IoT DC3 and how to resolve them. **Cause**: Parallelism not enabled / JVM heap too small. **Resolution**: Already configured in this repo: + - `.mvn/maven.config` contains `-T 1C` - `.mvn/jvm.config` contains `-Xms512m -Xmx1024m` @@ -17,10 +18,12 @@ If still slow, increase heap or reduce background CPU load. **Cause**: Project requires JDK 21. **Resolution**: + ```bash java -version mvn -version ``` + The build now enforces JDK 21 via `maven-enforcer-plugin`. ## 3. spring-javaformat:validate fails @@ -28,9 +31,11 @@ The build now enforces JDK 21 via `maven-enforcer-plugin`. **Cause**: Code formatting does not match Spring Java Format rules. **Resolution**: + ```bash mvn -s .mvn/settings.xml io.spring.javaformat:spring-javaformat-maven-plugin:apply ``` + Then rebuild. ## 4. Ports already in use @@ -40,6 +45,7 @@ Then rebuild. **Resolution**: Override ports using environment variables or `.env` values. Common overrides: + - `SERVER_PORT` - `GRPC_SERVER_PORT` - `DC3_GATEWAY_PORT` @@ -52,10 +58,12 @@ Common overrides: **Cause**: Postgres container not started / custom .env changed published ports. **Resolution**: + ```bash make compose-ps STACK=db make compose-file STACK=db ``` + Confirm the published port matches the application config. ## 6. RabbitMQ connection failures @@ -63,6 +71,7 @@ Confirm the published port matches the application config. **Cause**: Container not ready / wrong virtual host or credentials. **Resolution**: Wait until healthcheck passes, then restart dependent services. + ```bash make compose-logs STACK=db ``` @@ -90,6 +99,7 @@ make compose-logs STACK=db **Cause**: `mvn package` failed inside image build. **Resolution**: + ```bash make package make build @@ -100,6 +110,7 @@ make build **Cause**: `REGISTRY` was set to `domestic` / `aliyun` / `cn`. **Resolution**: Use `REGISTRY=global` for Docker Hub images. + ```bash make dev-db REGISTRY=global ``` @@ -107,6 +118,7 @@ make dev-db REGISTRY=global ## 12. Want faster debugging in one JVM Use `dc3-center-single` to combine Auth/Manager/Data into one process. + ```bash java -jar dc3-center/dc3-center-single/target/dc3-center-single.jar ``` diff --git a/pom.xml b/pom.xml index 282cc814b..c16ff9b88 100644 --- a/pom.xml +++ b/pom.xml @@ -33,8 +33,10 @@ https://github.com/pnoker/iot-dc3 IoT DC3 is a fully open-source distributed Internet of Things (IoT) platform built on Spring Cloud. - It accelerates IoT project development and simplifies IoT device management, providing comprehensive solutions for building robust IoT systems. - It is AI-ready, enabling seamless integration of AI capabilities for intelligent device connectivity, automation, and data-driven operations. + It accelerates IoT project development and simplifies IoT device management, providing comprehensive solutions + for building robust IoT systems. + It is AI-ready, enabling seamless integration of AI capabilities for intelligent device connectivity, + automation, and data-driven operations. All components and code are open-source, ensuring transparency, flexibility, and community-driven innovation. @@ -300,53 +302,6 @@ - - - io.spring.javaformat - spring-javaformat-maven-plugin - 0.0.47 - - - validate - validate - - validate - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.1 - - - com.puppycrawl.tools - checkstyle - 9.3 - - - io.spring.javaformat - spring-javaformat-checkstyle - 0.0.47 - - - - - checkstyle-validation - validate - true - - ${maven.multiModuleProjectDirectory}/checkstyle.xml - true - - - check - - - -