From d89e3b63dce6539d52e0f54b7609bea752dca72f Mon Sep 17 00:00:00 2001 From: George Date: Wed, 24 Dec 2025 20:36:15 +0800 Subject: [PATCH] =?UTF-8?q?20251224:=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fastbee/common/annotation/DataScope.java | 5 +- .../com/fastbee/common/utils/ip/IpUtils.java | 134 +- fastbee-framework/pom.xml | 6 +- .../framework/aspect/WebLogAspect.java | 13 +- .../framework/aspectj/DataScopeAspect.java | 162 +- .../framework/aspectj/DataSourceAspect.java | 36 +- .../fastbee/framework/aspectj/LogAspect.java | 134 +- .../framework/aspectj/RateLimiterAspect.java | 51 +- .../framework/config/ApplicationConfig.java | 9 +- .../framework/config/CaptchaConfig.java | 19 +- .../framework/config/DataSourceConfig.java | 4 +- .../fastbee/framework/config/DruidConfig.java | 19 +- .../config/FastJson2JsonRedisSerializer.java | 27 +- .../framework/config/FilterConfig.java | 26 +- .../framework/config/KaptchaTextCreator.java | 34 +- .../framework/config/OtaThreadPoolConfig.java | 10 +- .../fastbee/framework/config/RedisConfig.java | 14 +- .../framework/config/RedissonConfig.java | 53 +- .../framework/config/ResourcesConfig.java | 26 +- .../framework/config/SecurityConfig.java | 35 +- .../framework/config/ServerConfig.java | 34 +- .../config/SqlFilterArgumentResolver.java | 13 +- .../framework/config/ThreadPoolConfig.java | 16 +- .../config/properties/DruidProperties.java | 3 +- .../properties/PermitAllUrlProperties.java | 35 +- .../config/properties/RedissonProperties.java | 1 - .../sharding/ShardingAlgorithmTool.java | 33 +- .../sharding/ShardingTablesLoadRunner.java | 1 - .../sharding/TimeShardingAlgorithm.java | 18 +- .../enums/ShardingTableCacheEnum.java | 22 +- .../datasource/DynamicDataSource.java | 9 +- .../DynamicDataSourceContextHolder.java | 28 +- .../interceptor/LanguageInterceptor.java | 8 +- .../interceptor/RepeatSubmitInterceptor.java | 20 +- .../interceptor/TraceIdInterceptor.java | 10 +- .../impl/SameUrlDataInterceptor.java | 33 +- .../framework/manager/AsyncManager.java | 28 +- .../manager/CaffeineCacheDecorator.java | 4 +- .../framework/manager/ShutdownManager.java | 17 +- .../framework/manager/SpringCacheManager.java | 52 +- .../manager/factory/AsyncFactory.java | 47 +- .../framework/mybatis/QueryWrapperX.java | 8 +- .../mybatis/config/MybatisPlusConfig.java | 3 + .../config/MybatisPlusMetaObjectHandler.java | 52 +- .../framework/mybatis/utils/MyBatisUtils.java | 12 +- .../context/AuthenticationContextHolder.java | 14 +- .../context/PermissionContextHolder.java | 19 +- .../filter/JwtAuthenticationTokenFilter.java | 12 +- .../handle/AuthenticationEntryPointImpl.java | 32 +- .../handle/LogoutSuccessHandlerImpl.java | 14 +- .../fastbee/framework/web/domain/Server.java | 133 +- .../framework/web/domain/server/Cpu.java | 41 +- .../framework/web/domain/server/Jvm.java | 56 +- .../framework/web/domain/server/Mem.java | 26 +- .../framework/web/domain/server/Sys.java | 35 +- .../framework/web/domain/server/SysFile.java | 47 +- .../web/exception/GlobalExceptionHandler.java | 42 +- .../web/service/PermissionService.java | 91 +- .../web/service/SysPasswordService.java | 70 +- .../web/service/SysPermissionService.java | 37 +- .../web/service/SysRegisterService.java | 64 +- .../framework/web/service/TokenService.java | 12 +- .../web/service/UserDetailsServiceImpl.java | 34 +- fastbee-iot-data/pom.xml | 54 +- .../java/com/fastbee/iot/data/StartBoot.java | 2 +- .../iot/data/aspect/DeviceDebugLogAspect.java | 123 +- .../data/consumer/DeviceOtherMsgConsumer.java | 8 +- .../consumer/DevicePropFetchConsumer.java | 31 +- .../data/consumer/DeviceStatusConsumer.java | 2 +- .../iot/data/consumer/DeviceTestConsumer.java | 6 +- .../iot/data/emq/subscribeCallback.java | 2 +- .../iot/data/job/DeviceAbstractQuartzJob.java | 55 +- .../DeviceDisallowConcurrentExecution.java | 7 +- .../iot/data/job/DeviceJobExecution.java | 7 +- .../fastbee/iot/data/job/DeviceJobInvoke.java | 1 + .../iot/data/job/DeviceScheduleUtils.java | 28 +- .../iot/data/job/SyncDeviceStatusJob.java | 5 +- .../iot/data/listen/DeviceOtherListen.java | 6 +- .../iot/data/listen/DeviceStatusListen.java | 1 + .../iot/data/listen/DeviceTestListen.java | 6 +- .../iot/data/listen/UpGradeListener.java | 19 +- .../iot/data/ruleEngine/SceneContext.java | 35 +- .../iot/data/service/IDataHandler.java | 4 + .../data/service/IDeviceMessageService.java | 1 + .../service/IDeviceReportMessageService.java | 5 + .../service/IFirmwareTaskDetailService.java | 6 +- .../data/service/IFirmwareTaskService.java | 4 +- .../iot/data/service/IFunctionInvoke.java | 3 + .../data/service/IMessagePublishService.java | 4 +- .../iot/data/service/IMqttMessagePublish.java | 2 +- .../data/service/IOtaTaskUpgradeService.java | 1 + .../iot/data/service/IOtaUpgradeService.java | 2 + .../fastbee/iot/data/service/IRuleEngine.java | 3 + .../data/service/impl/DataHandlerImpl.java | 16 +- .../iot/data/service/impl/DeviceJob.java | 4 +- .../service/impl/DeviceJobServiceImpl.java | 108 +- .../impl/DeviceMessageServiceImpl.java | 36 +- .../impl/DeviceReportMessageServiceImpl.java | 35 +- .../data/service/impl/DeviceTestHandler.java | 7 +- .../impl/FirmwareTaskDetailServiceImpl.java | 15 +- .../service/impl/FirmwareTaskServiceImpl.java | 23 +- .../data/service/impl/FunctionInvokeImpl.java | 24 +- .../iot/data/service/impl/MessageManager.java | 30 +- .../service/impl/MqttMessagePublishImpl.java | 18 +- .../impl/OtaTaskUpgradeServiceImpl.java | 11 +- .../service/impl/OtaUpgradeServiceImpl.java | 1 - .../data/service/impl/RuleEngineHandler.java | 4 +- fastbee-mq/pom.xml | 92 +- .../mq/producer/EmqxMessageProducer.java | 2 +- .../fastbee/mq/producer/MessageProducer.java | 21 +- .../fastbee/mq/queue/DeviceOtherQueue.java | 5 +- .../mq/queue/DevicePropFetchQueue.java | 6 +- .../fastbee/mq/queue/DeviceReplyQueue.java | 6 +- .../fastbee/mq/queue/DeviceReportQueue.java | 5 +- .../fastbee/mq/queue/DeviceStatusQueue.java | 6 +- .../com/fastbee/mq/queue/DeviceTestQueue.java | 5 +- .../fastbee/mq/queue/FunctionInvokeQueue.java | 6 +- .../com/fastbee/mq/queue/OtaUpgradeQueue.java | 6 +- fastbee-notify/fastbee-notify-core/pom.xml | 4 +- .../core/controller/NotifyController.java | 17 +- .../dingtalk/service/DingTalkService.java | 8 +- .../service/impl/DingTalkServiceImpl.java | 10 +- .../core/email/service/EmailService.java | 6 +- .../core/service/NotifySendService.java | 14 +- .../service/impl/NotifySendServiceImpl.java | 9 +- .../notify/core/sms/service/ISmsService.java | 29 +- .../core/sms/service/Impl/SmsServiceImpl.java | 9 +- .../notify/core/voice/config/VoiceConfig.java | 1 + .../core/voice/service/VoiceService.java | 5 +- .../voice/service/impl/VoiceServiceImpl.java | 6 +- .../wechat/service/WeChatPushService.java | 5 +- .../service/impl/WeChatPushServiceImpl.java | 24 +- .../notify/core/wechat/vo/WxMssVo.java | 1 + fastbee-notify/fastbee-notify-web/pom.xml | 4 +- .../controller/NotifyChannelController.java | 27 +- .../controller/NotifyLogController.java | 25 +- .../fastbee/notify/domain/NotifyChannel.java | 35 +- .../com/fastbee/notify/domain/NotifyLog.java | 57 +- .../fastbee/notify/domain/NotifyTemplate.java | 43 +- .../notify/mapper/NotifyChannelMapper.java | 6 +- .../notify/mapper/NotifyLogMapper.java | 3 +- .../notify/mapper/NotifyTemplateMapper.java | 8 +- .../notify/service/INotifyChannelService.java | 7 +- .../notify/service/INotifyLogService.java | 17 +- .../service/INotifyTemplateService.java | 8 +- .../impl/NotifyChannelServiceImpl.java | 21 +- .../service/impl/NotifyLogServiceImpl.java | 21 +- .../impl/NotifyTemplateServiceImpl.java | 11 +- .../fastbee/notify/vo/ChannelProviderVO.java | 3 +- .../java/com/fastbee/notify/vo/NotifyVO.java | 2 +- .../resources/mapper/NotifyChannelMapper.xml | 60 +- .../main/resources/mapper/NotifyLogMapper.xml | 77 +- .../resources/mapper/NotifyTemplateMapper.xml | 83 +- fastbee-notify/pom.xml | 4 +- fastbee-open-api/pom.xml | 59 +- .../datacenter/DataCenterController.java | 72 +- .../device/DeviceAlertUserController.java | 17 +- .../controller/device/DeviceController.java | 88 +- .../device/DeviceJobController.java | 33 +- .../device/DeviceRecordController.java | 17 +- .../device/DeviceShareController.java | 31 +- .../device/DeviceUserController.java | 33 +- .../deviceConfig/CategoryController.java | 30 +- .../CommandPreferencesController.java | 33 +- .../deviceConfig/GroupController.java | 29 +- .../deviceConfig/OrderControlController.java | 36 +- .../ProductAuthorizeController.java | 26 +- .../deviceConfig/ProductController.java | 46 +- .../deviceConfig/ThingsModelController.java | 66 +- .../ThingsModelTemplateController.java | 5 +- .../deviceLog/AlertLogController.java | 25 +- .../deviceLog/DeviceLogController.java | 32 +- .../deviceLog/EventLogController.java | 21 +- .../deviceLog/FunctionLogController.java | 23 +- .../firmware/FirmwareController.java | 23 +- .../firmware/FirmwareTaskController.java | 22 +- .../firmware/ViewConfigController.java | 25 +- .../gateway/SubGatewayController.java | 29 +- .../goview/GoviewProjectController.java | 24 +- .../goview/GoviewProjectDataController.java | 2 + .../media/MediaServerController.java | 37 +- .../controller/media/PlayerController.java | 9 +- .../controller/media/PtzController.java | 4 + .../controller/media/RecordController.java | 14 +- .../media/SipDeviceChannelController.java | 21 +- .../controller/media/SipDeviceController.java | 27 +- .../controller/media/TalkController.java | 5 +- .../controller/media/ZmlHookController.java | 59 +- .../modbus/ModbusConfigController.java | 44 +- .../modbus/ModbusParamsController.java | 33 +- .../modbus/ProductModbusJobController.java | 2 +- .../modbus/ProductSubGatewayController.java | 2 +- .../netty/NettyManagerController.java | 21 +- .../protocol/ProtocolController.java | 23 +- .../ruleEngine/AlertController.java | 35 +- .../ruleEngine/BridgeController.java | 5 +- .../ruleEngine/HttpBridgeController.java | 20 +- .../runtime/DeviceRuntimeController.java | 10 +- .../sceneModel/SceneModelController.java | 23 +- .../sceneModel/SceneModelDataController.java | 29 +- .../SceneModelDeviceController.java | 26 +- .../sceneModel/SceneModelTagController.java | 23 +- .../socialUser/SocialLoginController.java | 1 + .../tool/AuthResourceController.java | 3 +- .../tool/NewsCategoryController.java | 26 +- .../controller/tool/NewsController.java | 38 +- .../controller/tool/TestRuleController.java | 4 +- .../controller/tool/ToolController.java | 59 +- .../translate/AppLanguageController.java | 23 +- .../translate/AppPreferencesController.java | 24 +- .../controller/wechat/WeChatController.java | 16 +- fastbee-plugs/fastbee-generator/pom.xml | 2 +- .../fastbee/generator/config/GenConfig.java | 47 +- .../generator/controller/GenController.java | 44 +- .../fastbee/generator/domain/GenTable.java | 562 +- .../generator/domain/GenTableColumn.java | 576 +- .../mapper/GenTableColumnMapper.java | 3 +- .../generator/mapper/GenTableMapper.java | 3 +- .../service/GenTableColumnServiceImpl.java | 71 +- .../service/GenTableServiceImpl.java | 247 +- .../service/IGenTableColumnService.java | 13 +- .../generator/service/IGenTableService.java | 33 +- .../com/fastbee/generator/util/GenUtils.java | 125 +- .../generator/util/VelocityInitializer.java | 15 +- .../fastbee/generator/util/VelocityUtils.java | 183 +- .../mapper/generator/GenTableColumnMapper.xml | 188 +- .../mapper/generator/GenTableMapper.xml | 441 +- .../main/resources/vm/java/controller.java.vm | 12 +- .../main/resources/vm/java/convert.java.vm | 9 +- .../src/main/resources/vm/java/domain.java.vm | 88 +- .../src/main/resources/vm/java/mapper.java.vm | 5 +- .../main/resources/vm/java/service.java.vm | 13 +- .../resources/vm/java/serviceImpl.java.vm | 45 +- .../main/resources/vm/java/sub-domain.java.vm | 121 +- .../src/main/resources/vm/java/vo.java.vm | 60 +- .../src/main/resources/vm/js/api.js.vm | 46 +- .../main/resources/vm/vue/index-tree.vue.vm | 962 +- .../src/main/resources/vm/vue/index.vue.vm | 1252 ++- .../resources/vm/vue/v3/index-tree.vue.vm | 912 +- .../src/main/resources/vm/vue/v3/index.vue.vm | 1219 ++- .../src/main/resources/vm/xml/mapper.xml.vm | 34 +- fastbee-plugs/fastbee-http/pom.xml | 4 +- .../java/com/fastbee/http/client/Amap.java | 16 +- .../fastbee/http/client/DownloadClient.java | 2 + .../http/controller/TestUploadController.java | 5 +- .../com/fastbee/http/model/Coordinate.java | 2 +- .../java/com/fastbee/http/model/Location.java | 8 +- .../java/com/fastbee/http/utils/PathUtil.java | 10 +- fastbee-plugs/fastbee-mqtt-client/pom.xml | 18 +- .../fastbee/mqttclient/MqttClientConfig.java | 16 +- .../com/fastbee/mqttclient/PubMqttClient.java | 4 +- fastbee-plugs/fastbee-oauth/pom.xml | 4 +- .../config/AuthorizationServerConfig.java | 9 +- .../oauth/config/ResourceServerConfig.java | 4 +- .../oauth/config/SpeakerApprovalHandler.java | 11 +- .../controller/ConfirmAccessController.java | 4 +- .../oauth/controller/LoginController.java | 6 +- .../OauthClientDetailsController.java | 23 +- .../oauth/controller/OauthController.java | 30 +- .../fastbee/oauth/domain/OauthApprovals.java | 27 +- .../oauth/domain/OauthClientDetails.java | 198 +- .../com/fastbee/oauth/domain/OauthCode.java | 55 +- .../oauth/mapper/OauthAccessTokenMapper.java | 2 +- .../oauth/mapper/OauthApprovalsMapper.java | 3 +- .../mapper/OauthClientDetailsMapper.java | 4 +- .../fastbee/oauth/mapper/OauthCodeMapper.java | 3 +- .../oauth/service/IOauthApprovalsService.java | 3 +- .../service/IOauthClientDetailsService.java | 3 +- .../oauth/service/IOauthCodeService.java | 3 +- .../impl/OauthAccessTokenServiceImpl.java | 8 +- .../impl/OauthApprovalsServiceImpl.java | 21 +- .../impl/OauthClientDetailsServiceImpl.java | 21 +- .../service/impl/OauthCodeServiceImpl.java | 21 +- .../com/fastbee/oauth/utils/HttpUtils.java | 18 +- .../com/fastbee/oauth/utils/OAuth2Utils.java | 18 +- .../mapper/OauthAccessTokenMapper.xml | 12 +- .../resources/mapper/OauthApprovalsMapper.xml | 47 +- .../mapper/OauthClientDetailsMapper.xml | 87 +- .../main/resources/mapper/OauthCodeMapper.xml | 27 +- .../static/oauth/css/bootstrap-theme.css | 671 +- .../resources/static/oauth/css/bootstrap.css | 8682 ++++++++++------- .../fonts/glyphicons-halflings-regular.svg | 825 +- .../resources/static/oauth/js/bootstrap.js | 4260 ++++---- .../templates/oauth/access_confirmation.html | 18 +- .../templates/oauth/clientDetails.html | 28 +- .../main/resources/templates/oauth/index.html | 8 +- .../main/resources/templates/oauth/login.html | 16 +- fastbee-plugs/fastbee-oss/pom.xml | 4 +- .../oss/controller/OssConfigController.java | 25 +- .../java/com/fastbee/oss/core/OssClient.java | 82 +- .../com/fastbee/oss/domain/OssConfig.java | 262 +- .../com/fastbee/oss/domain/OssDetail.java | 125 +- .../com/fastbee/oss/entity/OssConstant.java | 3 +- .../com/fastbee/oss/entity/UploadResult.java | 1 - .../fastbee/oss/enums/AccessPolicyType.java | 3 +- .../com/fastbee/oss/enums/PlatformType.java | 4 +- .../com/fastbee/oss/enums/PolicyType.java | 1 - .../fastbee/oss/mapper/OssConfigMapper.java | 3 +- .../fastbee/oss/mapper/OssDetailMapper.java | 3 +- .../oss/service/IOssConfigService.java | 18 +- .../oss/service/IOssDetailService.java | 17 +- .../com/fastbee/oss/service/OssClient.java | 85 +- .../service/impl/OssConfigServiceImpl.java | 38 +- .../service/impl/OssDetailServiceImpl.java | 17 +- .../main/resources/mapper/OssConfigMapper.xml | 111 +- .../main/resources/mapper/OssDetailMapper.xml | 86 +- .../fastbee-oss/src/main/resources/oss.sql | 78 +- .../fastbee-pay/fastbee-pay-api/pom.xml | 4 +- .../pay/api/enums/ErrorCodeConstants.java | 4 +- .../api/enums/order/PayOrderStatusEnum.java | 10 +- .../fastbee-pay/fastbee-pay-core/pom.xml | 4 +- .../controller/admin/app/vo/PayAppBaseVO.java | 6 +- .../admin/channel/vo/PayChannelBaseVO.java | 6 +- .../admin/demo/vo/OrderInfoRespVO.java | 6 +- .../admin/notify/PayNotifyController.java | 4 +- .../notify/vo/PayNotifyTaskDetailRespVO.java | 1 - .../admin/notify/vo/PayNotifyTaskRespVO.java | 2 +- .../admin/order/PayOrderController.java | 2 +- .../admin/order/vo/PayOrderBaseVO.java | 1 + .../order/vo/PayOrderPageItemRespVO.java | 2 +- .../admin/refund/PayRefundController.java | 2 +- .../admin/refund/vo/PayRefundBaseVO.java | 6 +- .../refund/vo/PayRefundPageItemRespVO.java | 2 +- .../app/order/vo/AppPayOrderSubmitReqVO.java | 2 +- .../pay/core/convert/app/PayAppConvert.java | 2 +- .../convert/channel/PayChannelConvert.java | 4 +- .../convert/notify/PayNotifyTaskConvert.java | 4 +- .../core/convert/order/PayOrderConvert.java | 4 + .../core/convert/refund/PayRefundConvert.java | 4 + .../dataobject/notify/PayNotifyTask.java | 2 +- .../dataobject/order/PayOrderExtension.java | 2 +- .../core/domain/redis/RedisKeyConstants.java | 4 +- .../pay/core/job/order/PayOrderSyncJob.java | 6 +- .../pay/core/service/app/PayAppService.java | 4 +- .../core/service/app/PayAppServiceImpl.java | 2 +- .../service/channel/PayChannelService.java | 10 +- .../channel/PayChannelServiceImpl.java | 2 +- .../core/service/demo/OrderInfoService.java | 6 +- .../service/demo/OrderInfoServiceImpl.java | 2 +- .../core/service/notify/PayNotifyService.java | 3 +- .../service/notify/PayNotifyServiceImpl.java | 5 +- .../core/service/order/PayOrderService.java | 6 +- .../service/order/PayOrderServiceImpl.java | 11 +- .../core/service/refund/PayRefundService.java | 4 +- .../service/refund/PayRefundServiceImpl.java | 7 +- .../com/fastbee/pay/core/util/MoneyUtils.java | 2 +- .../fastbee/pay/core/util/PaySeqUtils.java | 4 + .../fastbee-pay/fastbee-pay-framework/pom.xml | 4 +- .../pay/framework/client/PayClient.java | 8 +- .../framework/client/PayClientFactory.java | 6 +- .../client/dto/refund/PayRefundRespDTO.java | 8 +- .../client/impl/PayClientFactoryImpl.java | 33 +- .../impl/alipay/AbstractAlipayPayClient.java | 18 +- .../impl/alipay/AlipayAppPayClient.java | 4 +- .../impl/alipay/AlipayPayClientConfig.java | 12 +- .../client/impl/alipay/AlipayPcPayClient.java | 2 +- .../client/impl/mock/MockPayClientConfig.java | 2 +- .../impl/weixin/AbstractWxPayClient.java | 128 +- .../client/impl/weixin/WxBarPayClient.java | 22 +- .../client/impl/weixin/WxPayClientConfig.java | 26 +- .../client/impl/weixin/WxPubPayClient.java | 20 +- .../enums/channel/PayChannelEnum.java | 19 +- fastbee-plugs/fastbee-pay/pom.xml | 4 +- fastbee-plugs/fastbee-quartz/pom.xml | 4 +- .../fastbee/quartz/config/ScheduleConfig.java | 2 +- .../quartz/controller/SysJobController.java | 73 +- .../controller/SysJobLogController.java | 22 +- .../com/fastbee/quartz/domain/SysJob.java | 121 +- .../com/fastbee/quartz/domain/SysJobLog.java | 117 +- .../quartz/mapper/SysJobLogMapper.java | 3 +- .../fastbee/quartz/mapper/SysJobMapper.java | 3 +- .../quartz/service/ISysJobLogService.java | 15 +- .../quartz/service/ISysJobService.java | 27 +- .../service/impl/SysJobLogServiceImpl.java | 33 +- .../service/impl/SysJobServiceImpl.java | 104 +- .../java/com/fastbee/quartz/task/RyTask.java | 14 +- .../quartz/util/AbstractQuartzJob.java | 35 +- .../com/fastbee/quartz/util/CronUtils.java | 29 +- .../fastbee/quartz/util/JobInvokeUtil.java | 94 +- .../QuartzDisallowConcurrentExecution.java | 9 +- .../quartz/util/QuartzJobExecution.java | 9 +- .../fastbee/quartz/util/ScheduleUtils.java | 41 +- .../mapper/quartz/SysJobLogMapper.xml | 177 +- .../resources/mapper/quartz/SysJobMapper.xml | 220 +- fastbee-plugs/fastbee-ruleEngine/pom.xml | 4 +- .../config/MainExecutorBuilder.java | 1 + .../config/WhenExecutorBuilder.java | 1 + fastbee-plugs/pom.xml | 2 +- .../fastbee-protocol-base/pom.xml | 3 +- .../fastbee/protocol/ProtocolLoadUtils.java | 4 +- .../protocol/base/annotation/Column.java | 33 +- .../base/annotation/MergeSubClass.java | 1 + .../protocol/base/annotation/Protocol.java | 1 + .../protocol/base/message/MessageBody.java | 5 +- .../protocol/base/message/MessageHead.java | 6 + .../protocol/base/model/ActiveModel.java | 3 +- .../protocol/base/model/BufferModel.java | 2 +- .../fastbee/protocol/base/model/MapModel.java | 2 +- .../protocol/base/model/NumberPModel.java | 2 +- .../fastbee/protocol/base/model/WModel.java | 6 +- .../protocol/base/protocol/IProtocol.java | 3 +- .../protocol/base/struc/BaseStructure.java | 4 +- .../base/struc/CollectionStructure.java | 1 + .../protocol/base/struc/LengthStructure.java | 1 + .../struc/LengthUnitCollectionStructure.java | 1 + .../base/struc/LengthUnitStructure.java | 1 + .../protocol/base/struc/MapStructure.java | 6 +- .../base/struc/TotalArrayObjectStructure.java | 1 + .../struc/TotalArrayPrimitiveStructure.java | 2 +- .../base/struc/TotalCollectionStructure.java | 7 +- .../base/struc/TotalMapStructure.java | 2 +- .../protocol/domain/DeviceProtocol.java | 13 +- .../protocol/enums/ModbusBitStatus.java | 4 +- .../protocol/enums/ModbusCoilStatus.java | 6 +- .../fastbee/protocol/enums/ModbusErrCode.java | 37 +- .../service/IProtocolManagerService.java | 10 +- .../impl/ProtocolManagerServiceImpl.java | 23 +- .../com/fastbee/protocol/util/ArrayMap.java | 1 + .../fastbee/protocol/util/ByteToHexUtil.java | 46 +- .../java/com/fastbee/protocol/util/Cache.java | 2 +- .../fastbee/protocol/util/CharsBuilder.java | 26 +- .../com/fastbee/protocol/util/DateTool.java | 39 +- .../com/fastbee/protocol/util/IntTool.java | 57 +- .../protocol/util/IntegerToByteUtil.java | 20 +- .../fastbee/protocol/util/KeyValuePair.java | 1 + .../protocol/util/SingleVersionUtils.java | 1 + .../protocol/util/ToStringBuilder.java | 18 +- .../fastbee-protocol-collect/pom.xml | 2 +- .../com/fastbee/ch/ChProtocolService.java | 225 +- .../fastbee/common/ProtocolDeCodeService.java | 12 +- .../fastbee/flowdev/codec/FlowDevDecoder.java | 20 +- .../fastbee/flowdev/codec/FlowDevEncoder.java | 6 +- .../flowdev/codec/FlowDevProtocol.java | 34 +- .../com/fastbee/flowdev/model/FlowDev.java | 28 +- .../fastbee/flowdev/model/FlowEndPoint.java | 4 +- .../hp/ModbusToJsonHPProtocolService.java | 99 +- .../java/com/fastbee/hp/modbusToJson-HP.json | 82 +- .../com/fastbee/json/JsonProtocolService.java | 16 +- .../jsonPak/JsonPakProtocolService.java | 22 +- .../com/fastbee/jsonPak/pak/JsonEndPoint.java | 4 +- .../jsonchenyi/JsonChenYiProtocolService.java | 4 +- .../fastbee/modbus/codec/MessageAdapter.java | 20 +- .../fastbee/modbus/codec/ModbusDecoder.java | 4 +- .../fastbee/modbus/codec/ModbusEncoder.java | 4 +- .../com/fastbee/modbus/model/ModbusRtu.java | 33 +- .../fastbee/modbus/pak/ModbusEndPoint.java | 7 +- .../java/com/fastbee/modbus/pak/TcpDtu.java | 1 + .../com/fastbee/modbus/test/ModbusTest.java | 13 +- .../ModbusToJsonProtocolService.java | 15 +- .../modbustcp/codec/ModbusTcpDecoder.java | 2 +- .../modbustcp/codec/ModbusTcpEncoder.java | 4 +- .../modbustcp/codec/ModbusTcpProtocol.java | 15 +- .../fastbee/modbustcp/model/ModbusTcp.java | 30 +- .../fastbee/ota/codec/OtaPackageDecoder.java | 10 +- .../com/fastbee/ota/model/OtaCheckUtils.java | 2 + .../com/fastbee/ota/model/OtaPackage.java | 4 +- .../ota/test/OtaPackageProtocolTest.java | 3 +- .../pakModbus/codec/ModbusRtu-pak.JSON | 37 +- .../pakModbus/codec/ModbusRtuPakDecoder.java | 35 +- .../pakModbus/codec/ModbusRtuPakEncoder.java | 11 +- .../pakModbus/codec/ModbusRtuPakProtocol.java | 24 +- .../pakModbus/model/CombineFactory.java | 16 +- .../fastbee/pakModbus/model/PakModbusRtu.java | 73 +- .../fastbee/pakModbus/test/PakModbusTest.java | 4 +- .../com/fastbee/rj45/Rj45ProtocolService.java | 16 +- .../java/com/fastbee/sgz/SgzEndPoint.java | 24 +- .../java/com/fastbee/sgz/SgzMessageType.java | 16 +- .../yinerda/YiDaErProtocolService.java | 16 +- .../zqwl/GEC6100ToZqwlProtocolService.java | 25 +- .../zqwl/ModbusToJsonZQWLProtocolService.java | 121 +- .../java/com/fastbee/zqwl/ZQWLDIDORet.java | 3 +- fastbee-protocol/pom.xml | 3 +- fastbee-record/pom.xml | 2 +- .../fastbee/record/ZlmRecordApplication.java | 2 +- .../config/FastJson2JsonRedisSerializer.java | 20 +- .../config/FastJsonRedisSerializer.java | 3 +- .../record/config/GlobalExceptionHandler.java | 2 + .../record/config/GlobalResponseAdvice.java | 3 +- .../fastbee/record/config/RedisConfig.java | 84 +- .../record/config/SpringDocConfig.java | 1 + .../fastbee/record/config/StartConfig.java | 10 +- .../record/config/ThreadPoolTaskConfig.java | 2 +- .../record/controller/DownController.java | 2 +- .../record/controller/DownloadController.java | 10 +- .../record/controller/RecordController.java | 84 +- .../controller/bean/ControllerException.java | 3 +- .../record/controller/bean/Result.java | 9 +- .../record/service/FFmpegExecUtils.java | 22 +- .../record/service/FileManagerTimer.java | 24 +- .../record/service/VideoFileService.java | 16 +- .../com/fastbee/record/utils/DateUtils.java | 7 +- .../com/fastbee/record/utils/PageInfo.java | 4 +- .../com/fastbee/record/utils/RedisUtil.java | 127 +- .../src/main/resources/all-application.yml | 92 +- .../src/main/resources/application-dev.yml | 104 +- .../src/main/resources/application-prod.yml | 104 +- .../src/main/resources/static/download.html | 6 +- fastbee-server/base-server/pom.xml | 18 +- .../com/fastbee/base/codec/Delimiter.java | 1 + .../com/fastbee/base/codec/LengthField.java | 5 +- .../fastbee/base/codec/MessageEncoder.java | 2 +- .../base/core/DefaultHandlerMapping.java | 1 + .../fastbee/base/core/HandlerInterceptor.java | 8 +- .../com/fastbee/base/core/HandlerMapping.java | 1 + .../base/core/SpringHandlerMapping.java | 1 - .../fastbee/base/core/annotation/Node.java | 1 + .../base/core/annotation/PakMapping.java | 1 + .../base/core/hanler/AsyncBatchHandler.java | 33 +- .../fastbee/base/core/hanler/SyncHandler.java | 5 +- .../com/fastbee/base/core/model/Response.java | 5 +- .../com/fastbee/base/model/SessionKey.java | 4 +- .../fastbee/base/service/ISessionStore.java | 15 +- .../base/service/impl/SessionStoreImpl.java | 17 +- .../java/com/fastbee/base/session/Packet.java | 13 +- .../com/fastbee/base/session/Session.java | 83 +- .../fastbee/base/session/SessionListener.java | 9 +- .../fastbee/base/session/SessionManager.java | 46 +- .../com/fastbee/base/util/AttributeUtils.java | 9 +- .../com/fastbee/base/util/ByteBufUtils.java | 1 + .../com/fastbee/base/util/ClassUtils.java | 1 + .../fastbee/base/util/ConcurrentStorage.java | 13 +- .../com/fastbee/base/util/DeviceUtils.java | 5 +- .../java/com/fastbee/base/util/Stopwatch.java | 18 +- .../java/com/fastbee/base/util/Storage.java | 3 +- fastbee-server/boot-strap/pom.xml | 2 +- .../fastbee/bootstrap/coap/CoapBootStrap.java | 5 +- .../fastbee/bootstrap/http/HttpBootStrap.java | 4 +- .../fastbee/bootstrap/mqtt/MQTTBootStrap.java | 10 +- .../fastbee/bootstrap/tcp/TCPBootStrap.java | 11 +- .../bootstrap/tcp/config/TcpBeanConfig.java | 10 +- .../tcp/config/TcpHandlerInterceptor.java | 9 +- .../tcp/config/TcpSessionListener.java | 16 +- .../fastbee/bootstrap/udp/UDPBootStrap.java | 7 +- fastbee-server/coap-server/pom.xml | 42 +- .../src/main/java/com/fastbee/coap/README.md | 6 +- .../coap/codec/CoapMessageDecoder.java | 42 +- .../coap/codec/CoapMessageEncoder.java | 17 +- .../coap/codec/HeaderDecodingException.java | 2 +- .../coap/codec/OptionCodecException.java | 1 + .../coap/handler/AbstractResourceHandler.java | 2 +- .../fastbee/coap/handler/ReqDispatcher.java | 4 +- .../fastbee/coap/handler/RequestConsumer.java | 3 +- .../coap/handler/TimeResourceHandler.java | 3 +- .../com/fastbee/coap/model/BlockSize.java | 23 +- .../com/fastbee/coap/model/CoapMessage.java | 119 +- .../com/fastbee/coap/model/CoapRequest.java | 54 +- .../com/fastbee/coap/model/CoapResponse.java | 96 +- .../com/fastbee/coap/model/MessageCode.java | 67 +- .../com/fastbee/coap/model/MessageType.java | 15 +- .../java/com/fastbee/coap/model/Token.java | 28 +- .../coap/model/linkformat/LinkParam.java | 437 +- .../coap/model/linkformat/LinkValue.java | 51 +- .../coap/model/linkformat/LinkValueList.java | 62 +- .../coap/model/options/ContentFormat.java | 22 +- .../coap/model/options/EmptyOptionValue.java | 7 +- .../coap/model/options/OpaqueOptionValue.java | 37 +- .../fastbee/coap/model/options/Option.java | 417 +- .../coap/model/options/OptionValue.java | 162 +- .../coap/model/options/StringOptionValue.java | 50 +- .../coap/model/options/UintOptionValue.java | 15 +- .../fastbee/coap/server/ResourceRegistry.java | 8 +- fastbee-server/http-server/pom.xml | 4 +- .../java/com/fastbee/http/auth/BasicAuth.java | 2 +- .../http/handler/req/EventHttpReqHandler.java | 2 +- .../http/handler/req/InfoHttpReqHandler.java | 1 + .../handler/req/MonitorHttpReqHandler.java | 3 +- .../http/manager/HttpSessionManager.java | 3 +- .../http/manager/NettyHttpSession.java | 10 +- .../fastbee/http/utils/DigestAuthUtil.java | 26 +- fastbee-server/iot-server-core/pom.xml | 2 +- .../main/java/com/fastbee/server/Server.java | 5 +- .../fastbee/server/config/NettyConfig.java | 31 +- .../handler/DelimiterBasedFrameDecoder.java | 9 +- .../server/handler/DispatcherHandler.java | 50 +- .../LengthFieldAndDelimiterFrameDecoder.java | 33 +- .../server/handler/MessageDecoderWrapper.java | 2 +- .../server/handler/MessageEncoderWrapper.java | 3 +- .../server/handler/TCPMessageAdapter.java | 30 +- .../server/handler/UDPMessageAdapter.java | 15 +- fastbee-server/mqtt-broker/pom.xml | 38 +- .../com/fastbee/mqtt/annotation/Process.java | 1 + .../com/fastbee/mqtt/auth/AuthService.java | 12 +- .../mqtt/codec/WebSocketMqttCodec.java | 1 + .../com/fastbee/mqtt/handler/MqttConnect.java | 8 +- .../com/fastbee/mqtt/handler/MqttPingreq.java | 4 +- .../com/fastbee/mqtt/handler/MqttPubRel.java | 5 +- .../com/fastbee/mqtt/handler/MqttPubcomp.java | 3 +- .../fastbee/mqtt/handler/MqttSubscribe.java | 2 +- .../handler/adapter/MqttMessageAdapter.java | 8 +- .../handler/adapter/MqttMessageDelegate.java | 19 +- .../fastbee/mqtt/manager/ClientManager.java | 7 +- .../mqtt/manager/MqttRemoteManager.java | 13 +- .../fastbee/mqtt/manager/ResponseManager.java | 2 +- .../mqtt/manager/RetainMsgManager.java | 1 + .../fastbee/mqtt/manager/SessionManger.java | 38 +- .../mqtt/manager/WillMessageManager.java | 13 +- .../com/fastbee/mqtt/model/ClientMessage.java | 8 +- .../com/fastbee/mqtt/model/RetainMessage.java | 1 + .../com/fastbee/mqtt/model/Subscribe.java | 1 + .../mqtt/service/ISubscriptionService.java | 7 +- .../mqtt/service/impl/MessageStoreImpl.java | 20 +- .../service/impl/SubscriptionServiceImpl.java | 2 +- .../fastbee/mqtt/utils/MqttMessageUtils.java | 9 +- fastbee-server/sip-server/README.md | 9 +- fastbee-server/sip-server/pom.xml | 104 +- .../fastbee/sip/conf/ServerLoggerImpl.java | 18 +- .../com/fastbee/sip/conf/StackLoggerImpl.java | 201 +- .../sip/conf/ThreadPoolTaskConfig.java | 2 +- .../com/fastbee/sip/domain/MediaServer.java | 63 +- .../com/fastbee/sip/domain/SipConfig.java | 31 +- .../com/fastbee/sip/domain/SipDevice.java | 242 +- .../fastbee/sip/domain/SipDeviceChannel.java | 24 +- .../java/com/fastbee/sip/enums/AlarmType.java | 10 +- .../com/fastbee/sip/enums/ChannelType.java | 4 +- .../java/com/fastbee/sip/enums/Direct.java | 16 +- .../com/fastbee/sip/enums/FunctionType.java | 1 + .../com/fastbee/sip/enums/InviteType.java | 2 +- .../sip/handler/req/NotifyReqHandler.java | 5 +- .../sip/handler/req/RegisterReqHandler.java | 8 +- .../sip/handler/req/ReqAbstractHandler.java | 22 +- .../handler/req/message/IMessageHandler.java | 1 + .../req/message/MessageRequestProcessor.java | 14 +- .../message/notify/cmdType/AlarmHandler.java | 1 + .../response/cmdType/AlarmRHandler.java | 1 + .../response/cmdType/BroadcastHandler.java | 2 +- .../response/cmdType/CatalogHandler.java | 12 +- .../cmdType/ConfigDownloadHandler.java | 1 + .../response/cmdType/DeviceConfigHandler.java | 1 + .../cmdType/DeviceControlHandler.java | 1 + .../response/cmdType/DeviceInfoHandler.java | 1 + .../response/cmdType/DeviceStatusHandler.java | 1 + .../cmdType/MobilePositionRHandler.java | 1 + .../response/cmdType/RecordInfoHandler.java | 2 + .../sip/handler/res/ByeResHandler.java | 4 +- .../sip/handler/res/CancelResHandler.java | 5 +- .../sip/handler/res/InviteResHandler.java | 14 +- .../fastbee/sip/mapper/MediaServerMapper.java | 6 +- .../fastbee/sip/mapper/SipConfigMapper.java | 4 +- .../sip/mapper/SipDeviceChannelMapper.java | 7 +- .../fastbee/sip/mapper/SipDeviceMapper.java | 5 +- .../java/com/fastbee/sip/model/BaseTree.java | 10 +- .../com/fastbee/sip/model/PtzscaleInput.java | 2 +- .../com/fastbee/sip/model/RecordItem.java | 9 +- .../java/com/fastbee/sip/model/SipDate.java | 4 +- .../fastbee/sip/model/SipDeviceSummary.java | 12 +- .../java/com/fastbee/sip/model/Stream.java | 4 +- .../java/com/fastbee/sip/model/StreamURL.java | 4 +- .../fastbee/sip/model/VideoSessionInfo.java | 9 +- .../com/fastbee/sip/server/GBMsgParser.java | 282 +- .../com/fastbee/sip/server/IGBListener.java | 1 + .../java/com/fastbee/sip/server/IRtspCmd.java | 4 + .../java/com/fastbee/sip/server/ISipCmd.java | 6 + .../fastbee/sip/server/NullSipProvider.java | 8 +- .../sip/server/RecordCacheManager.java | 10 +- .../sip/server/ReqMsgHeaderBuilder.java | 11 +- .../com/fastbee/sip/server/SIPSender.java | 62 +- .../java/com/fastbee/sip/server/SipLayer.java | 51 +- .../sip/server/VideoSessionManager.java | 3 +- .../sip/server/impl/GBListenerImpl.java | 8 +- .../sip/server/impl/MessageInvokerImpl.java | 43 +- .../sip/server/impl/RequestBuilderImpl.java | 3 +- .../fastbee/sip/server/impl/RtspCmdImpl.java | 21 +- .../fastbee/sip/server/impl/SipCmdImpl.java | 19 +- .../com/fastbee/sip/server/msg/Alarm.java | 20 +- .../sip/server/msg/ConfigDownload.java | 76 +- .../fastbee/sip/server/msg/DeviceControl.java | 118 +- .../fastbee/sip/server/msg/GB28181Device.java | 8 +- .../fastbee/sip/service/IGatewayService.java | 5 +- .../sip/service/IMediaServerService.java | 13 +- .../com/fastbee/sip/service/IMqttService.java | 5 + .../fastbee/sip/service/IRecordService.java | 15 +- .../sip/service/ISipConfigService.java | 10 +- .../sip/service/ISipDeviceChannelService.java | 8 +- .../sip/service/ISipDeviceService.java | 10 +- .../com/fastbee/sip/service/ITalkService.java | 2 + .../fastbee/sip/service/IZmlHookService.java | 14 + .../sip/service/impl/GatewayServiceImpl.java | 2 +- .../sip/service/impl/SendRtpServiceInpl.java | 12 +- .../service/impl/SipConfigServiceImpl.java | 6 +- .../service/impl/SipDeviceServiceImpl.java | 32 +- .../sip/service/impl/TalkServiceImpl.java | 2 +- .../sip/service/impl/VideoMqttService.java | 24 +- .../sip/service/impl/ZmlHookServiceImpl.java | 6 +- .../com/fastbee/sip/util/DigestAuthUtil.java | 28 +- .../com/fastbee/sip/util/RecordApiUtils.java | 14 +- .../java/com/fastbee/sip/util/SipUtil.java | 36 +- .../java/com/fastbee/sip/util/XmlUtil.java | 51 +- .../resources/mapper/MediaServerMapper.xml | 101 +- .../main/resources/mapper/SipConfigMapper.xml | 32 +- .../mapper/SipDeviceChannelMapper.xml | 121 +- .../main/resources/mapper/SipDeviceMapper.xml | 44 +- .../iot/service/impl/DeviceServiceImpl.java | 32 +- .../views/iot/device/device-modbus-task.vue | 2 +- .../views/iot/product/product-modbus-task.vue | 2 +- .../iot/product/product-things-model.vue | 2 +- 695 files changed, 19767 insertions(+), 17863 deletions(-) diff --git a/fastbee-common/src/main/java/com/fastbee/common/annotation/DataScope.java b/fastbee-common/src/main/java/com/fastbee/common/annotation/DataScope.java index ee5bb173..675c4636 100644 --- a/fastbee-common/src/main/java/com/fastbee/common/annotation/DataScope.java +++ b/fastbee-common/src/main/java/com/fastbee/common/annotation/DataScope.java @@ -8,14 +8,13 @@ import java.lang.annotation.Target; /** * 数据权限过滤注解 - * + * * @author ruoyi */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface DataScope -{ +public @interface DataScope { /** * 部门表的别名 */ diff --git a/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java b/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java index 7aad829d..ed81e99a 100644 --- a/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java +++ b/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java @@ -8,43 +8,35 @@ import java.net.UnknownHostException; /** * 获取IP方法 - * + * * @author ruoyi */ -public class IpUtils -{ +public class IpUtils { /** * 获取客户端IP - * + * * @param request 请求对象 * @return IP地址 */ - public static String getIpAddr(HttpServletRequest request) - { - if (request == null) - { + public static String getIpAddr(HttpServletRequest request) { + if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } - if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) - { + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } @@ -53,26 +45,23 @@ public class IpUtils /** * 检查是否为内部IP地址 - * + * * @param ip IP地址 * @return 结果 */ - public static boolean internalIp(String ip) - { + public static boolean internalIp(String ip) { byte[] addr = textToNumericFormatV4(ip); return internalIp(addr) || "127.0.0.1".equals(ip); } /** * 检查是否为内部IP地址 - * + * * @param addr byte地址 * @return 结果 */ - private static boolean internalIp(byte[] addr) - { - if (StringUtils.isNull(addr) || addr.length < 2) - { + private static boolean internalIp(byte[] addr) { + if (StringUtils.isNull(addr) || addr.length < 2) { return true; } final byte b0 = addr[0]; @@ -86,20 +75,16 @@ public class IpUtils // 192.168.x.x/16 final byte SECTION_5 = (byte) 0xC0; final byte SECTION_6 = (byte) 0xA8; - switch (b0) - { + switch (b0) { case SECTION_1: return true; case SECTION_2: - if (b1 >= SECTION_3 && b1 <= SECTION_4) - { + if (b1 >= SECTION_3 && b1 <= SECTION_4) { return true; } case SECTION_5: - switch (b1) - { - case SECTION_6: - return true; + if (b1 == SECTION_6) { + return true; } default: return false; @@ -108,29 +93,24 @@ public class IpUtils /** * 将IPv4地址转换成字节 - * + * * @param text IPv4地址 * @return byte 字节 */ - public static byte[] textToNumericFormatV4(String text) - { - if (text.length() == 0) - { + public static byte[] textToNumericFormatV4(String text) { + if (text.length() == 0) { return null; } byte[] bytes = new byte[4]; String[] elements = text.split("\\.", -1); - try - { + try { long l; int i; - switch (elements.length) - { + switch (elements.length) { case 1: l = Long.parseLong(elements[0]); - if ((l < 0L) || (l > 4294967295L)) - { + if ((l < 0L) || (l > 4294967295L)) { return null; } bytes[0] = (byte) (int) (l >> 24 & 0xFF); @@ -140,14 +120,12 @@ public class IpUtils break; case 2: l = Integer.parseInt(elements[0]); - if ((l < 0L) || (l > 255L)) - { + if ((l < 0L) || (l > 255L)) { return null; } bytes[0] = (byte) (int) (l & 0xFF); l = Integer.parseInt(elements[1]); - if ((l < 0L) || (l > 16777215L)) - { + if ((l < 0L) || (l > 16777215L)) { return null; } bytes[1] = (byte) (int) (l >> 16 & 0xFF); @@ -155,29 +133,24 @@ public class IpUtils bytes[3] = (byte) (int) (l & 0xFF); break; case 3: - for (i = 0; i < 2; ++i) - { + for (i = 0; i < 2; ++i) { l = Integer.parseInt(elements[i]); - if ((l < 0L) || (l > 255L)) - { + if ((l < 0L) || (l > 255L)) { return null; } bytes[i] = (byte) (int) (l & 0xFF); } l = Integer.parseInt(elements[2]); - if ((l < 0L) || (l > 65535L)) - { + if ((l < 0L) || (l > 65535L)) { return null; } bytes[2] = (byte) (int) (l >> 8 & 0xFF); bytes[3] = (byte) (int) (l & 0xFF); break; case 4: - for (i = 0; i < 4; ++i) - { + for (i = 0; i < 4; ++i) { l = Integer.parseInt(elements[i]); - if ((l < 0L) || (l > 255L)) - { + if ((l < 0L) || (l > 255L)) { return null; } bytes[i] = (byte) (int) (l & 0xFF); @@ -186,9 +159,7 @@ public class IpUtils default: return null; } - } - catch (NumberFormatException e) - { + } catch (NumberFormatException e) { return null; } return bytes; @@ -196,34 +167,26 @@ public class IpUtils /** * 获取IP地址 - * + * * @return 本地IP地址 */ - public static String getHostIp() - { - try - { + public static String getHostIp() { + try { return InetAddress.getLocalHost().getHostAddress(); - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { } return "127.0.0.1"; } /** * 获取主机名 - * + * * @return 本地主机名 */ - public static String getHostName() - { - try - { + public static String getHostName() { + try { return InetAddress.getLocalHost().getHostName(); - } - catch (UnknownHostException e) - { + } catch (UnknownHostException e) { } return "未知"; } @@ -234,16 +197,12 @@ public class IpUtils * @param ip 获得的IP地址 * @return 第一个非unknown IP地址 */ - public static String getMultistageReverseProxyIp(String ip) - { + public static String getMultistageReverseProxyIp(String ip) { // 多级反向代理检测 - if (ip != null && ip.indexOf(",") > 0) - { + if (ip != null && ip.indexOf(",") > 0) { final String[] ips = ip.trim().split(","); - for (String subIp : ips) - { - if (false == isUnknown(subIp)) - { + for (String subIp : ips) { + if (false == isUnknown(subIp)) { ip = subIp; break; } @@ -258,8 +217,7 @@ public class IpUtils * @param checkString 被检测的字符串 * @return 是否未知 */ - public static boolean isUnknown(String checkString) - { + public static boolean isUnknown(String checkString) { return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString); } } \ No newline at end of file diff --git a/fastbee-framework/pom.xml b/fastbee-framework/pom.xml index e841b93e..4dc2e15f 100644 --- a/fastbee-framework/pom.xml +++ b/fastbee-framework/pom.xml @@ -1,6 +1,6 @@ - fastbee @@ -18,7 +18,7 @@ - + org.springframework.boot spring-boot-starter-web diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/aspect/WebLogAspect.java b/fastbee-framework/src/main/java/com/fastbee/framework/aspect/WebLogAspect.java index a6927574..85341652 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/aspect/WebLogAspect.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/aspect/WebLogAspect.java @@ -1,16 +1,5 @@ package com.fastbee.framework.aspect; -import com.google.gson.Gson; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import javax.servlet.http.HttpServletRequest; - //@Aspect //@Component public class WebLogAspect { @@ -48,7 +37,7 @@ public class WebLogAspect { // @After("webLog()") // public void doAfter() throws Throwable { // logger.info("=========================================== End ==========================================="); - // 每个请求之间空一行 + // 每个请求之间空一行 // logger.info(""); // } // /** diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataScopeAspect.java b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataScopeAspect.java index 813d9d3f..2bbddf49 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataScopeAspect.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataScopeAspect.java @@ -1,11 +1,5 @@ package com.fastbee.framework.aspectj; -import java.util.ArrayList; -import java.util.List; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Before; -import org.springframework.stereotype.Component; import com.fastbee.common.annotation.DataScope; import com.fastbee.common.core.domain.BaseEntity; import com.fastbee.common.core.domain.entity.SysRole; @@ -15,6 +9,13 @@ import com.fastbee.common.core.text.Convert; import com.fastbee.common.utils.SecurityUtils; import com.fastbee.common.utils.StringUtils; import com.fastbee.framework.security.context.PermissionContextHolder; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; /** * 数据过滤处理 @@ -23,8 +24,7 @@ import com.fastbee.framework.security.context.PermissionContextHolder; */ @Aspect @Component -public class DataScopeAspect -{ +public class DataScopeAspect { /** * 全部数据权限 */ @@ -55,23 +55,74 @@ public class DataScopeAspect */ public static final String DATA_SCOPE = "dataScope"; + /** + * 数据范围过滤 + * + * @param joinPoint 切点 + * @param user 用户 + * @param deptAlias 部门别名 + * @param userAlias 用户别名 + * @param permission 权限字符 + */ + public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission) { + StringBuilder sqlString = new StringBuilder(); + List conditions = new ArrayList(); + + for (SysRole role : user.getRoles()) { + String dataScope = role.getDataScope(); + if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) { + continue; + } + if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions()) + && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) { + continue; + } + if (DATA_SCOPE_ALL.equals(dataScope)) { + sqlString = new StringBuilder(); + break; + } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { + sqlString.append(StringUtils.format( + " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, + role.getRoleId())); + } else if (DATA_SCOPE_DEPT.equals(dataScope)) { + sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); + } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { + sqlString.append(StringUtils.format( + " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", + deptAlias, user.getDeptId(), user.getDeptId())); + } else if (DATA_SCOPE_SELF.equals(dataScope)) { + if (StringUtils.isNotBlank(userAlias)) { + sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); + } else { + // 数据权限为仅本人且没有userAlias别名不查询任何数据 + sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias)); + } + } + conditions.add(dataScope); + } + + if (StringUtils.isNotBlank(sqlString.toString())) { + Object params = joinPoint.getArgs()[0]; + if (StringUtils.isNotNull(params) && params instanceof BaseEntity) { + BaseEntity baseEntity = (BaseEntity) params; + baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); + } + } + } + @Before("@annotation(controllerDataScope)") - public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable - { + public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable { clearDataScope(point); handleDataScope(point, controllerDataScope); } - protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) - { + protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) { // 获取当前的用户 LoginUser loginUser = SecurityUtils.getLoginUser(); - if (StringUtils.isNotNull(loginUser)) - { + if (StringUtils.isNotNull(loginUser)) { SysUser currentUser = loginUser.getUser(); // 如果是超级管理员,则不过滤数据 - if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) - { + if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) { String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext()); dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias(), permission); @@ -79,87 +130,12 @@ public class DataScopeAspect } } - /** - * 数据范围过滤 - * - * @param joinPoint 切点 - * @param user 用户 - * @param deptAlias 部门别名 - * @param userAlias 用户别名 - * @param permission 权限字符 - */ - public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission) - { - StringBuilder sqlString = new StringBuilder(); - List conditions = new ArrayList(); - - for (SysRole role : user.getRoles()) - { - String dataScope = role.getDataScope(); - if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) - { - continue; - } - if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions()) - && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) - { - continue; - } - if (DATA_SCOPE_ALL.equals(dataScope)) - { - sqlString = new StringBuilder(); - break; - } - else if (DATA_SCOPE_CUSTOM.equals(dataScope)) - { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, - role.getRoleId())); - } - else if (DATA_SCOPE_DEPT.equals(dataScope)) - { - sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); - } - else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) - { - sqlString.append(StringUtils.format( - " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", - deptAlias, user.getDeptId(), user.getDeptId())); - } - else if (DATA_SCOPE_SELF.equals(dataScope)) - { - if (StringUtils.isNotBlank(userAlias)) - { - sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); - } - else - { - // 数据权限为仅本人且没有userAlias别名不查询任何数据 - sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias)); - } - } - conditions.add(dataScope); - } - - if (StringUtils.isNotBlank(sqlString.toString())) - { - Object params = joinPoint.getArgs()[0]; - if (StringUtils.isNotNull(params) && params instanceof BaseEntity) - { - BaseEntity baseEntity = (BaseEntity) params; - baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); - } - } - } - /** * 拼接权限sql前先清空params.dataScope参数防止注入 */ - private void clearDataScope(final JoinPoint joinPoint) - { + private void clearDataScope(final JoinPoint joinPoint) { Object params = joinPoint.getArgs()[0]; - if (StringUtils.isNotNull(params) && params instanceof BaseEntity) - { + if (StringUtils.isNotNull(params) && params instanceof BaseEntity) { BaseEntity baseEntity = (BaseEntity) params; baseEntity.getParams().put(DATA_SCOPE, ""); } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataSourceAspect.java b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataSourceAspect.java index 9a31e44b..a9b053d1 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataSourceAspect.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/DataSourceAspect.java @@ -1,6 +1,8 @@ package com.fastbee.framework.aspectj; -import java.util.Objects; +import com.fastbee.common.annotation.DataSource; +import com.fastbee.common.utils.StringUtils; +import com.fastbee.framework.datasource.DynamicDataSourceContextHolder; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -11,45 +13,37 @@ import org.slf4j.LoggerFactory; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; -import com.fastbee.common.annotation.DataSource; -import com.fastbee.common.utils.StringUtils; -import com.fastbee.framework.datasource.DynamicDataSourceContextHolder; + +import java.util.Objects; /** * 多数据源处理 - * + * * @author ruoyi */ @Aspect @Order(1) @Component -public class DataSourceAspect -{ +public class DataSourceAspect { protected Logger logger = LoggerFactory.getLogger(getClass()); @Pointcut("@annotation(com.fastbee.common.annotation.DataSource)" + "|| @within(com.fastbee.common.annotation.DataSource)") - public void dsPointCut() - { + public void dsPointCut() { } @Around("dsPointCut()") - public Object around(ProceedingJoinPoint point) throws Throwable - { + public Object around(ProceedingJoinPoint point) throws Throwable { DataSource dataSource = getDataSource(point); - if (StringUtils.isNotNull(dataSource)) - { + if (StringUtils.isNotNull(dataSource)) { DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name()); } - try - { + try { return point.proceed(); - } - finally - { + } finally { // 销毁数据源 在执行方法之后 DynamicDataSourceContextHolder.clearDataSourceType(); } @@ -58,12 +52,10 @@ public class DataSourceAspect /** * 获取需要切换的数据源 */ - public DataSource getDataSource(ProceedingJoinPoint point) - { + public DataSource getDataSource(ProceedingJoinPoint point) { MethodSignature signature = (MethodSignature) point.getSignature(); DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class); - if (Objects.nonNull(dataSource)) - { + if (Objects.nonNull(dataSource)) { return dataSource; } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java index bd03f3f7..73c2cbb5 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java @@ -1,18 +1,5 @@ package com.fastbee.framework.aspectj; -import java.util.Collection; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.AfterThrowing; -import org.aspectj.lang.annotation.Aspect; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.validation.BindingResult; -import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson2.JSON; import com.fastbee.common.annotation.Log; import com.fastbee.common.core.domain.model.LoginUser; @@ -26,48 +13,58 @@ import com.fastbee.common.utils.ip.IpUtils; import com.fastbee.framework.manager.AsyncManager; import com.fastbee.framework.manager.factory.AsyncFactory; import com.fastbee.system.domain.SysOperLog; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.validation.BindingResult; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Collection; +import java.util.Map; /** * 操作日志记录处理 - * + * * @author ruoyi */ @Aspect @Component -public class LogAspect -{ +public class LogAspect { + /** + * 排除敏感属性字段 + */ + public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"}; private static final Logger log = LoggerFactory.getLogger(LogAspect.class); - /** 排除敏感属性字段 */ - public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" }; - /** * 处理完请求后执行 * * @param joinPoint 切点 */ @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult") - public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) - { + public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) { handleLog(joinPoint, controllerLog, null, jsonResult); } /** * 拦截异常操作 - * + * * @param joinPoint 切点 - * @param e 异常 + * @param e 异常 */ @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e") - public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) - { + public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) { handleLog(joinPoint, controllerLog, e, null); } - protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) - { - try - { + protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) { + try { // 获取当前的用户 LoginUser loginUser = SecurityUtils.getLoginUser(); @@ -78,13 +75,11 @@ public class LogAspect String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); operLog.setOperIp(ip); operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255)); - if (loginUser != null) - { + if (loginUser != null) { operLog.setOperName(loginUser.getUsername()); } - if (e != null) - { + if (e != null) { operLog.setStatus(BusinessStatus.FAIL.ordinal()); operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); } @@ -98,9 +93,7 @@ public class LogAspect getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult); // 保存数据库 AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); - } - catch (Exception exp) - { + } catch (Exception exp) { // 记录本地异常日志 log.error("异常信息:{}", exp.getMessage()); exp.printStackTrace(); @@ -109,13 +102,12 @@ public class LogAspect /** * 获取注解中对方法的描述信息 用于Controller层注解 - * - * @param log 日志 + * + * @param log 日志 * @param operLog 操作日志 * @throws Exception */ - public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception - { + public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception { // 设置action动作 operLog.setBusinessType(log.businessType().ordinal()); // 设置标题 @@ -123,34 +115,28 @@ public class LogAspect // 设置操作人类别 operLog.setOperatorType(log.operatorType().ordinal()); // 是否需要保存request,参数和值 - if (log.isSaveRequestData()) - { + if (log.isSaveRequestData()) { // 获取参数的信息,传入到数据库中。 setRequestValue(joinPoint, operLog); } // 是否需要保存response,参数和值 - if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) - { + if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) { operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000)); } } /** * 获取请求的参数,放到log中 - * + * * @param operLog 操作日志 * @throws Exception 异常 */ - private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception - { + private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception { String requestMethod = operLog.getRequestMethod(); - if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) - { + if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) { String params = argsArrayToString(joinPoint.getArgs()); operLog.setOperParam(StringUtils.substring(params, 0, 2000)); - } - else - { + } else { Map paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest()); operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter()), 0, 2000)); } @@ -159,22 +145,15 @@ public class LogAspect /** * 参数拼装 */ - private String argsArrayToString(Object[] paramsArray) - { + private String argsArrayToString(Object[] paramsArray) { String params = ""; - if (paramsArray != null && paramsArray.length > 0) - { - for (Object o : paramsArray) - { - if (StringUtils.isNotNull(o) && !isFilterObject(o)) - { - try - { + if (paramsArray != null && paramsArray.length > 0) { + for (Object o : paramsArray) { + if (StringUtils.isNotNull(o) && !isFilterObject(o)) { + try { String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter()); params += jsonObj.toString() + " "; - } - catch (Exception e) - { + } catch (Exception e) { } } } @@ -185,38 +164,29 @@ public class LogAspect /** * 忽略敏感属性 */ - public PropertyPreExcludeFilter excludePropertyPreFilter() - { + public PropertyPreExcludeFilter excludePropertyPreFilter() { return new PropertyPreExcludeFilter().addExcludes(EXCLUDE_PROPERTIES); } /** * 判断是否需要过滤的对象。 - * + * * @param o 对象信息。 * @return 如果是需要过滤的对象,则返回true;否则返回false。 */ @SuppressWarnings("rawtypes") - public boolean isFilterObject(final Object o) - { + public boolean isFilterObject(final Object o) { Class clazz = o.getClass(); - if (clazz.isArray()) - { + if (clazz.isArray()) { return clazz.getComponentType().isAssignableFrom(MultipartFile.class); - } - else if (Collection.class.isAssignableFrom(clazz)) - { + } else if (Collection.class.isAssignableFrom(clazz)) { Collection collection = (Collection) o; - for (Object value : collection) - { + for (Object value : collection) { return value instanceof MultipartFile; } - } - else if (Map.class.isAssignableFrom(clazz)) - { + } else if (Map.class.isAssignableFrom(clazz)) { Map map = (Map) o; - for (Object value : map.entrySet()) - { + for (Object value : map.entrySet()) { Map.Entry entry = (Map.Entry) value; return entry.getValue() instanceof MultipartFile; } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/RateLimiterAspect.java b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/RateLimiterAspect.java index caed1bd1..aae88b30 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/RateLimiterAspect.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/RateLimiterAspect.java @@ -1,8 +1,11 @@ package com.fastbee.framework.aspectj; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.List; +import com.fastbee.common.annotation.RateLimiter; +import com.fastbee.common.enums.LimitType; +import com.fastbee.common.exception.ServiceException; +import com.fastbee.common.utils.ServletUtils; +import com.fastbee.common.utils.StringUtils; +import com.fastbee.common.utils.ip.IpUtils; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @@ -13,12 +16,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; -import com.fastbee.common.annotation.RateLimiter; -import com.fastbee.common.enums.LimitType; -import com.fastbee.common.exception.ServiceException; -import com.fastbee.common.utils.ServletUtils; -import com.fastbee.common.utils.StringUtils; -import com.fastbee.common.utils.ip.IpUtils; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; /** * 限流处理 @@ -27,8 +28,7 @@ import com.fastbee.common.utils.ip.IpUtils; */ @Aspect @Component -public class RateLimiterAspect -{ +public class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); private RedisTemplate redisTemplate; @@ -36,49 +36,38 @@ public class RateLimiterAspect private RedisScript limitScript; @Autowired - public void setRedisTemplate1(RedisTemplate redisTemplate) - { + public void setRedisTemplate1(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } @Autowired - public void setLimitScript(RedisScript limitScript) - { + public void setLimitScript(RedisScript limitScript) { this.limitScript = limitScript; } @Before("@annotation(rateLimiter)") - public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable - { + public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable { int time = rateLimiter.time(); int count = rateLimiter.count(); String combineKey = getCombineKey(rateLimiter, point); List keys = Collections.singletonList(combineKey); - try - { + try { Long number = redisTemplate.execute(limitScript, keys, count, time); - if (StringUtils.isNull(number) || number.intValue() > count) - { + if (StringUtils.isNull(number) || number.intValue() > count) { throw new ServiceException("访问过于频繁,请稍候再试"); } log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey); - } - catch (ServiceException e) - { + } catch (ServiceException e) { throw e; - } - catch (Exception e) - { + } catch (Exception e) { throw new RuntimeException("服务器限流异常,请稍候再试"); } } - public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) - { + public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) { StringBuffer stringBuffer = new StringBuffer(rateLimiter.key()); - if (rateLimiter.limitType() == LimitType.IP) - { + if (rateLimiter.limitType() == LimitType.IP) { stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-"); } MethodSignature signature = (MethodSignature) point.getSignature(); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/ApplicationConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/ApplicationConfig.java index be28f9a1..e084d7ea 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/ApplicationConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/ApplicationConfig.java @@ -1,11 +1,12 @@ package com.fastbee.framework.config; -import java.util.TimeZone; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; +import java.util.TimeZone; + /** * 程序注解配置 * @@ -14,14 +15,12 @@ import org.springframework.context.annotation.EnableAspectJAutoProxy; @Configuration // 表示通过aop框架暴露该代理对象,AopContext能够访问 @EnableAspectJAutoProxy(exposeProxy = true) -public class ApplicationConfig -{ +public class ApplicationConfig { /** * 时区配置 */ @Bean - public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() - { + public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() { return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault()); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/CaptchaConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/CaptchaConfig.java index 26f4d0f0..0436cba5 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/CaptchaConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/CaptchaConfig.java @@ -1,23 +1,23 @@ package com.fastbee.framework.config; -import java.util.Properties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.Properties; + import static com.google.code.kaptcha.Constants.*; /** * 验证码配置 - * + * * @author ruoyi */ @Configuration -public class CaptchaConfig -{ +public class CaptchaConfig { @Bean(name = "captchaProducer") - public DefaultKaptcha getKaptchaBean() - { + public DefaultKaptcha getKaptchaBean() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); // 是否有边框 默认为true 我们可以自己设置yes,no @@ -44,8 +44,7 @@ public class CaptchaConfig } @Bean(name = "captchaProducerMath") - public DefaultKaptcha getKaptchaBeanMath() - { + public DefaultKaptcha getKaptchaBeanMath() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); // 是否有边框 默认为true 我们可以自己设置yes,no diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java index 399eabd8..f9196162 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java @@ -31,8 +31,8 @@ public class DataSourceConfig { private final DataSource shardingSphereDataSource; public DataSourceConfig(DynamicDataSourceProperties properties, - DefaultDataSourceCreator dataSourceCreator, - @Qualifier("shardingSphereDataSource") DataSource shardingSphereDataSource) { + DefaultDataSourceCreator dataSourceCreator, + @Qualifier("shardingSphereDataSource") DataSource shardingSphereDataSource) { this.properties = properties; this.dataSourceCreator = dataSourceCreator; this.shardingSphereDataSource = shardingSphereDataSource; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java index 367e693f..945832af 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java @@ -15,11 +15,10 @@ public class DruidConfig { /** * 去除监控页面底部的广告 */ - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Bean @ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true") - public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) - { + public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) { // 获取web监控页面的参数 DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); // 提取common.js的配置路径 @@ -27,16 +26,14 @@ public class DruidConfig { String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); final String filePath = "support/http/resources/js/common.js"; // 创建filter进行过滤 - Filter filter = new Filter() - { + Filter filter = new Filter() { @Override - public void init(javax.servlet.FilterConfig filterConfig) throws ServletException - { + public void init(javax.servlet.FilterConfig filterConfig) throws ServletException { } + @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException - { + throws IOException, ServletException { chain.doFilter(request, response); // 重置缓冲区,响应头不会被重置 response.resetBuffer(); @@ -47,9 +44,9 @@ public class DruidConfig { text = text.replaceAll("powered.*?shrek.wang", ""); response.getWriter().write(text); } + @Override - public void destroy() - { + public void destroy() { } }; FilterRegistrationBean registrationBean = new FilterRegistrationBean(); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java index 43f1889d..a8813e56 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java @@ -1,44 +1,39 @@ package com.fastbee.framework.config; -import java.nio.charset.Charset; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +import java.nio.charset.Charset; /** * Redis使用FastJson序列化 - * + * * @author ruoyi */ -public class FastJson2JsonRedisSerializer implements RedisSerializer -{ +public class FastJson2JsonRedisSerializer implements RedisSerializer { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class clazz; - public FastJson2JsonRedisSerializer(Class clazz) - { + public FastJson2JsonRedisSerializer(Class clazz) { super(); this.clazz = clazz; } @Override - public byte[] serialize(T t) throws SerializationException - { - if (t == null) - { + public byte[] serialize(T t) throws SerializationException { + if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override - public T deserialize(byte[] bytes) throws SerializationException - { - if (bytes == null || bytes.length <= 0) - { + public T deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java index 8e0e76ef..f486cb33 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java @@ -1,16 +1,17 @@ package com.fastbee.framework.config; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.DispatcherType; +import com.fastbee.common.filter.RepeatableFilter; +import com.fastbee.common.filter.XssFilter; +import com.fastbee.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.fastbee.common.filter.RepeatableFilter; -import com.fastbee.common.filter.XssFilter; -import com.fastbee.common.utils.StringUtils; + +import javax.servlet.DispatcherType; +import java.util.HashMap; +import java.util.Map; /** * Filter配置 @@ -18,19 +19,17 @@ import com.fastbee.common.utils.StringUtils; * @author ruoyi */ @Configuration -public class FilterConfig -{ +public class FilterConfig { @Value("${xss.excludes}") private String excludes; @Value("${xss.urlPatterns}") private String urlPatterns; - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Bean @ConditionalOnProperty(value = "xss.enabled", havingValue = "true") - public FilterRegistrationBean xssFilterRegistration() - { + public FilterRegistrationBean xssFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setDispatcherTypes(DispatcherType.REQUEST); registration.setFilter(new XssFilter()); @@ -43,10 +42,9 @@ public class FilterConfig return registration; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Bean - public FilterRegistrationBean someFilterRegistration() - { + public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new RepeatableFilter()); registration.addUrlPatterns("/*"); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/KaptchaTextCreator.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/KaptchaTextCreator.java index a468e30c..0f7edf4c 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/KaptchaTextCreator.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/KaptchaTextCreator.java @@ -1,61 +1,49 @@ package com.fastbee.framework.config; -import java.util.Random; import com.google.code.kaptcha.text.impl.DefaultTextCreator; +import java.util.Random; + /** * 验证码文本生成器 * * @author ruoyi */ -public class KaptchaTextCreator extends DefaultTextCreator -{ +public class KaptchaTextCreator extends DefaultTextCreator { private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); @Override - public String getText() - { + public String getText() { Integer result = 0; Random random = new Random(); int x = random.nextInt(10); int y = random.nextInt(10); StringBuilder suChinese = new StringBuilder(); int randomoperands = random.nextInt(3); - if (randomoperands == 0) - { + if (randomoperands == 0) { result = x * y; suChinese.append(CNUMBERS[x]); suChinese.append("*"); suChinese.append(CNUMBERS[y]); - } - else if (randomoperands == 1) - { - if ((x != 0) && y % x == 0) - { + } else if (randomoperands == 1) { + if ((x != 0) && y % x == 0) { result = y / x; suChinese.append(CNUMBERS[y]); suChinese.append("/"); suChinese.append(CNUMBERS[x]); - } - else - { + } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } - } - else - { - if (x >= y) - { + } else { + if (x >= y) { result = x - y; suChinese.append(CNUMBERS[x]); suChinese.append("-"); suChinese.append(CNUMBERS[y]); - } - else - { + } else { result = y - x; suChinese.append(CNUMBERS[y]); suChinese.append("-"); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/OtaThreadPoolConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/OtaThreadPoolConfig.java index 5cf9f895..d460de10 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/OtaThreadPoolConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/OtaThreadPoolConfig.java @@ -8,8 +8,9 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ThreadPoolExecutor; @Configuration -public class OtaThreadPoolConfig -{ +public class OtaThreadPoolConfig { + // 配置线程池的前缀 + private static final String threadNamePrefix = "ota-"; // 核心线程池大小 private int corePoolSize = 10; // 最大可创建的线程数 @@ -18,12 +19,9 @@ public class OtaThreadPoolConfig private int queueCapacity = 10000; // 线程池维护线程所允许的空闲时间 private int keepAliveSeconds = 30; - // 配置线程池的前缀 - private static final String threadNamePrefix = "ota-"; @Bean(name = FastBeeConstant.TASK.OTA_THREAD_POOL) - public ThreadPoolTaskExecutor threadPoolTaskExecutor() - { + public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/RedisConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/RedisConfig.java index 70e9783d..61cca777 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/RedisConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/RedisConfig.java @@ -14,12 +14,10 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; * @author ruoyi */ @Configuration -public class RedisConfig extends CachingConfigurerSupport -{ +public class RedisConfig extends CachingConfigurerSupport { @Bean - @SuppressWarnings(value = { "unchecked", "rawtypes" }) - public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) - { + @SuppressWarnings(value = {"unchecked", "rawtypes"}) + public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); @@ -38,8 +36,7 @@ public class RedisConfig extends CachingConfigurerSupport } @Bean - public DefaultRedisScript limitScript() - { + public DefaultRedisScript limitScript() { DefaultRedisScript redisScript = new DefaultRedisScript<>(); redisScript.setScriptText(limitScriptText()); redisScript.setResultType(Long.class); @@ -49,8 +46,7 @@ public class RedisConfig extends CachingConfigurerSupport /** * 限流脚本 */ - private String limitScriptText() - { + private String limitScriptText() { return "local key = KEYS[1]\n" + "local count = tonumber(ARGV[1])\n" + "local time = tonumber(ARGV[2])\n" + diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/RedissonConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/RedissonConfig.java index cf2637a7..c286d8bc 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/RedissonConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/RedissonConfig.java @@ -1,6 +1,8 @@ package com.fastbee.framework.config; import cn.hutool.core.util.ObjectUtil; +import com.fastbee.framework.config.properties.RedissonProperties; +import com.fastbee.framework.handler.KeyPrefixHandler; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; @@ -9,7 +11,6 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import lombok.extern.slf4j.Slf4j; -import com.fastbee.framework.config.properties.RedissonProperties; import org.redisson.client.codec.StringCodec; import org.redisson.codec.CompositeCodec; import org.redisson.codec.TypedJsonJacksonCodec; @@ -18,8 +19,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.fastbee.framework.handler.KeyPrefixHandler; - import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -53,39 +52,39 @@ public class RedissonConfig { // 组合序列化 key 使用 String 内容使用通用 json 格式 CompositeCodec codec = new CompositeCodec(StringCodec.INSTANCE, jsonCodec, jsonCodec); config.setThreads(redissonProperties.getThreads()) - .setNettyThreads(redissonProperties.getNettyThreads()) - // 缓存 Lua 脚本 减少网络传输(redisson 大部分的功能都是基于 Lua 脚本实现) - .setUseScriptCache(true) - .setCodec(codec); + .setNettyThreads(redissonProperties.getNettyThreads()) + // 缓存 Lua 脚本 减少网络传输(redisson 大部分的功能都是基于 Lua 脚本实现) + .setUseScriptCache(true) + .setCodec(codec); RedissonProperties.SingleServerConfig singleServerConfig = redissonProperties.getSingleServerConfig(); if (ObjectUtil.isNotNull(singleServerConfig)) { // 使用单机模式 config.useSingleServer() - //设置redis key前缀 - .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix())) - .setTimeout(singleServerConfig.getTimeout()) - .setClientName(singleServerConfig.getClientName()) - .setIdleConnectionTimeout(singleServerConfig.getIdleConnectionTimeout()) - .setSubscriptionConnectionPoolSize(singleServerConfig.getSubscriptionConnectionPoolSize()) - .setConnectionMinimumIdleSize(singleServerConfig.getConnectionMinimumIdleSize()) - .setConnectionPoolSize(singleServerConfig.getConnectionPoolSize()); + //设置redis key前缀 + .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix())) + .setTimeout(singleServerConfig.getTimeout()) + .setClientName(singleServerConfig.getClientName()) + .setIdleConnectionTimeout(singleServerConfig.getIdleConnectionTimeout()) + .setSubscriptionConnectionPoolSize(singleServerConfig.getSubscriptionConnectionPoolSize()) + .setConnectionMinimumIdleSize(singleServerConfig.getConnectionMinimumIdleSize()) + .setConnectionPoolSize(singleServerConfig.getConnectionPoolSize()); } // 集群配置方式 参考下方注释 RedissonProperties.ClusterServersConfig clusterServersConfig = redissonProperties.getClusterServersConfig(); if (ObjectUtil.isNotNull(clusterServersConfig)) { config.useClusterServers() - //设置redis key前缀 - .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix())) - .setTimeout(clusterServersConfig.getTimeout()) - .setClientName(clusterServersConfig.getClientName()) - .setIdleConnectionTimeout(clusterServersConfig.getIdleConnectionTimeout()) - .setSubscriptionConnectionPoolSize(clusterServersConfig.getSubscriptionConnectionPoolSize()) - .setMasterConnectionMinimumIdleSize(clusterServersConfig.getMasterConnectionMinimumIdleSize()) - .setMasterConnectionPoolSize(clusterServersConfig.getMasterConnectionPoolSize()) - .setSlaveConnectionMinimumIdleSize(clusterServersConfig.getSlaveConnectionMinimumIdleSize()) - .setSlaveConnectionPoolSize(clusterServersConfig.getSlaveConnectionPoolSize()) - .setReadMode(clusterServersConfig.getReadMode()) - .setSubscriptionMode(clusterServersConfig.getSubscriptionMode()); + //设置redis key前缀 + .setNameMapper(new KeyPrefixHandler(redissonProperties.getKeyPrefix())) + .setTimeout(clusterServersConfig.getTimeout()) + .setClientName(clusterServersConfig.getClientName()) + .setIdleConnectionTimeout(clusterServersConfig.getIdleConnectionTimeout()) + .setSubscriptionConnectionPoolSize(clusterServersConfig.getSubscriptionConnectionPoolSize()) + .setMasterConnectionMinimumIdleSize(clusterServersConfig.getMasterConnectionMinimumIdleSize()) + .setMasterConnectionPoolSize(clusterServersConfig.getMasterConnectionPoolSize()) + .setSlaveConnectionMinimumIdleSize(clusterServersConfig.getSlaveConnectionMinimumIdleSize()) + .setSlaveConnectionPoolSize(clusterServersConfig.getSlaveConnectionPoolSize()) + .setReadMode(clusterServersConfig.getReadMode()) + .setSubscriptionMode(clusterServersConfig.getSubscriptionMode()); } log.info("初始化 redis 配置"); }; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/ResourcesConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/ResourcesConfig.java index d37d184c..2ade13aa 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/ResourcesConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/ResourcesConfig.java @@ -1,8 +1,9 @@ package com.fastbee.framework.config; -import java.util.concurrent.TimeUnit; - +import com.fastbee.common.config.RuoYiConfig; +import com.fastbee.common.constant.Constants; import com.fastbee.framework.interceptor.LanguageInterceptor; +import com.fastbee.framework.interceptor.RepeatSubmitInterceptor; import com.fastbee.framework.interceptor.TraceIdInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; @@ -14,20 +15,17 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import com.fastbee.common.config.RuoYiConfig; -import com.fastbee.common.constant.Constants; -import com.fastbee.framework.interceptor.RepeatSubmitInterceptor; import javax.annotation.Resource; +import java.util.concurrent.TimeUnit; /** * 通用配置 - * + * * @author ruoyi */ @Configuration -public class ResourcesConfig implements WebMvcConfigurer -{ +public class ResourcesConfig implements WebMvcConfigurer { @Autowired private RepeatSubmitInterceptor repeatSubmitInterceptor; @Resource @@ -36,8 +34,7 @@ public class ResourcesConfig implements WebMvcConfigurer private TraceIdInterceptor traceIdInterceptor; @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) - { + public void addResourceHandlers(ResourceHandlerRegistry registry) { /** 本地文件上传路径 */ registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**") .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/"); @@ -45,15 +42,15 @@ public class ResourcesConfig implements WebMvcConfigurer /** swagger配置 */ registry.addResourceHandler("/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/") - .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic());; + .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic()); + ; } /** * 自定义拦截规则 */ @Override - public void addInterceptors(InterceptorRegistry registry) - { + public void addInterceptors(InterceptorRegistry registry) { // TraceId拦截器放在最前面,确保所有请求都有TraceId registry.addInterceptor(traceIdInterceptor).addPathPatterns("/**").order(0); registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); @@ -66,8 +63,7 @@ public class ResourcesConfig implements WebMvcConfigurer * 跨域配置 */ @Bean - public CorsFilter corsFilter() - { + public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 设置访问源地址 diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java index 3a87bde1..f0691eb9 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java @@ -1,5 +1,9 @@ package com.fastbee.framework.config; +import com.fastbee.framework.config.properties.PermitAllUrlProperties; +import com.fastbee.framework.security.filter.JwtAuthenticationTokenFilter; +import com.fastbee.framework.security.handle.AuthenticationEntryPointImpl; +import com.fastbee.framework.security.handle.LogoutSuccessHandlerImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; @@ -15,10 +19,6 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.filter.CorsFilter; -import com.fastbee.framework.config.properties.PermitAllUrlProperties; -import com.fastbee.framework.security.filter.JwtAuthenticationTokenFilter; -import com.fastbee.framework.security.handle.AuthenticationEntryPointImpl; -import com.fastbee.framework.security.handle.LogoutSuccessHandlerImpl; /** * spring security配置 @@ -27,8 +27,7 @@ import com.fastbee.framework.security.handle.LogoutSuccessHandlerImpl; */ //@EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter -{ +public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 自定义用户认证逻辑 */ @@ -73,8 +72,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter */ @Bean @Override - public AuthenticationManager authenticationManagerBean() throws Exception - { + public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @@ -94,8 +92,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * authenticated | 用户登录后可访问 */ @Override - protected void configure(HttpSecurity httpSecurity) throws Exception - { + protected void configure(HttpSecurity httpSecurity) throws Exception { // 注解标记允许匿名访问的url ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests(); permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll()); @@ -113,17 +110,17 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter // 过滤请求 .authorizeRequests() // 对于登录login 注册register 验证码captchaImage 允许匿名访问 - .antMatchers("/login", "/register", "/captchaImage","/iot/tool/register","/iot/tool/ntp", - "/iot/tool/mqtt/auth","/iot/tool/mqtt/authv5","/iot/tool/mqtt/webhook","/iot/tool/mqtt/webhookv5","/auth/**/**", + .antMatchers("/login", "/register", "/captchaImage", "/iot/tool/register", "/iot/tool/ntp", + "/iot/tool/mqtt/auth", "/iot/tool/mqtt/authv5", "/iot/tool/mqtt/webhook", "/iot/tool/mqtt/webhookv5", "/auth/**/**", "/wechat/mobileLogin", "/wechat/miniLogin", "/wechat/wxBind/callback").permitAll() .antMatchers("/zlmhook/**").permitAll() //.antMatchers("/sip/player/getBigScreenUrl/**").permitAll() .antMatchers("/ruleengine/rulemanager/**").permitAll() - .antMatchers("/goview/sys/login","/goview/project/getData").permitAll() - .antMatchers("/notify/smsLoginCaptcha","/auth/sms/login", "/notify/weComVerifyUrl" - ,"/wechat/publicAccount/callback","/notify/smsRegisterCaptcha").permitAll() + .antMatchers("/goview/sys/login", "/goview/project/getData").permitAll() + .antMatchers("/notify/smsLoginCaptcha", "/auth/sms/login", "/notify/weComVerifyUrl" + , "/wechat/publicAccount/callback", "/notify/smsRegisterCaptcha").permitAll() .antMatchers("/app/language/list").permitAll() - .antMatchers("/iot/news/bannerList","/iot/news/topList", "/iot/news/getDetail").permitAll() + .antMatchers("/iot/news/bannerList", "/iot/news/topList", "/iot/news/getDetail").permitAll() // 静态资源,可匿名访问 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() @@ -161,8 +158,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * 强散列哈希加密实现 */ @Bean - public BCryptPasswordEncoder bCryptPasswordEncoder() - { + public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @@ -170,8 +166,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * 身份认证接口 */ @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception - { + protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java index a07d6e0a..2ecff0c2 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java @@ -1,32 +1,30 @@ package com.fastbee.framework.config; -import javax.servlet.http.HttpServletRequest; -import org.springframework.stereotype.Component; import com.fastbee.common.utils.ServletUtils; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; /** * 服务相关配置 - * + * * @author ruoyi */ @Component -public class ServerConfig -{ - /** - * 获取完整的请求路径,包括:域名,端口,上下文访问路径 - * - * @return 服务地址 - */ - public String getUrl() - { - HttpServletRequest request = ServletUtils.getRequest(); - return getDomain(request); - } - - public static String getDomain(HttpServletRequest request) - { +public class ServerConfig { + public static String getDomain(HttpServletRequest request) { StringBuffer url = request.getRequestURL(); String contextPath = request.getServletContext().getContextPath(); return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString(); } + + /** + * 获取完整的请求路径,包括:域名,端口,上下文访问路径 + * + * @return 服务地址 + */ + public String getUrl() { + HttpServletRequest request = ServletUtils.getRequest(); + return getDomain(request); + } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/SqlFilterArgumentResolver.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/SqlFilterArgumentResolver.java index f1acaa53..2498e2dc 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/SqlFilterArgumentResolver.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/SqlFilterArgumentResolver.java @@ -20,16 +20,18 @@ import java.util.stream.Collectors; /** * 解决Mybatis Plus Order By SQL注入问题 + * * @author admin */ @Slf4j public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver { - private final static String[] KEYWORDS = { "master", "truncate", "insert", "select", "delete", "update", "declare", - "alter", "drop", "sleep" }; + private final static String[] KEYWORDS = {"master", "truncate", "insert", "select", "delete", "update", "declare", + "alter", "drop", "sleep"}; /** * 判断Controller是否包含page 参数 + * * @param parameter 参数 * @return 是否过滤 */ @@ -39,9 +41,9 @@ public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver } /** - * @param parameter 入参集合 - * @param mavContainer model 和 view - * @param webRequest web相关 + * @param parameter 入参集合 + * @param mavContainer model 和 view + * @param webRequest web相关 * @param binderFactory 入参解析 * @return 检查后新的page对象 *

@@ -77,6 +79,7 @@ public class SqlFilterArgumentResolver implements HandlerMethodArgumentResolver /** * 判断用户输入里面有没有关键字 + * * @return Predicate */ private Predicate sqlInjectPredicate() { diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/ThreadPoolConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/ThreadPoolConfig.java index 8560f0f6..6b25dd4c 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/ThreadPoolConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/ThreadPoolConfig.java @@ -5,6 +5,7 @@ import org.apache.commons.lang3.concurrent.BasicThreadFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; @@ -15,8 +16,7 @@ import java.util.concurrent.ThreadPoolExecutor; * @author ruoyi **/ @Configuration -public class ThreadPoolConfig -{ +public class ThreadPoolConfig { // 核心线程池大小 private int corePoolSize = 50; @@ -30,8 +30,7 @@ public class ThreadPoolConfig private int keepAliveSeconds = 300; @Bean(name = "threadPoolTaskExecutor") - public ThreadPoolTaskExecutor threadPoolTaskExecutor() - { + public ThreadPoolTaskExecutor threadPoolTaskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); @@ -46,15 +45,12 @@ public class ThreadPoolConfig * 执行周期性或定时任务 */ @Bean(name = "scheduledExecutorService") - protected ScheduledExecutorService scheduledExecutorService() - { + protected ScheduledExecutorService scheduledExecutorService() { return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(), - new ThreadPoolExecutor.CallerRunsPolicy()) - { + new ThreadPoolExecutor.CallerRunsPolicy()) { @Override - protected void afterExecute(Runnable r, Throwable t) - { + protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); Threads.printException(r, t); } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/DruidProperties.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/DruidProperties.java index dca60d5a..d8aace14 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/DruidProperties.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/DruidProperties.java @@ -8,8 +8,7 @@ import org.springframework.context.annotation.Configuration; * @author ruoyi */ @Configuration -public class DruidProperties -{ +public class DruidProperties { // @Value("${spring.datasource.druid.initialSize}") // private int initialSize; // diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/PermitAllUrlProperties.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/PermitAllUrlProperties.java index 71baae88..640f3ab9 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/PermitAllUrlProperties.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/PermitAllUrlProperties.java @@ -1,10 +1,6 @@ package com.fastbee.framework.config.properties; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.regex.Pattern; +import com.fastbee.common.annotation.Anonymous; import org.apache.commons.lang3.RegExUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; @@ -15,27 +11,27 @@ import org.springframework.core.annotation.AnnotationUtils; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.mvc.method.RequestMappingInfo; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import com.fastbee.common.annotation.Anonymous; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; /** * 设置Anonymous注解允许匿名访问的url - * + * * @author ruoyi */ @Configuration -public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware -{ +public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware { private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); - + public String ASTERISK = "*"; private ApplicationContext applicationContext; - private List urls = new ArrayList<>(); - public String ASTERISK = "*"; - @Override - public void afterPropertiesSet() - { + public void afterPropertiesSet() { RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class); Map map = mapping.getHandlerMethods(); @@ -55,18 +51,15 @@ public class PermitAllUrlProperties implements InitializingBean, ApplicationCont } @Override - public void setApplicationContext(ApplicationContext context) throws BeansException - { + public void setApplicationContext(ApplicationContext context) throws BeansException { this.applicationContext = context; } - public List getUrls() - { + public List getUrls() { return urls; } - public void setUrls(List urls) - { + public void setUrls(List urls) { this.urls = urls; } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/RedissonProperties.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/RedissonProperties.java index 7df7ab9c..3cae7c40 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/RedissonProperties.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/properties/RedissonProperties.java @@ -8,7 +8,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** * Redisson 配置属性 - * */ @Data @ConfigurationProperties(prefix = "redisson") diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingAlgorithmTool.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingAlgorithmTool.java index 391d8d1f..7da965f8 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingAlgorithmTool.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingAlgorithmTool.java @@ -21,15 +21,18 @@ import java.util.stream.Collectors; /** *

@Title ShardingAlgorithmTool *

@Description 按月分片算法工具 - * */ @Slf4j public class ShardingAlgorithmTool { - /** 表分片符号,例:siot_device_log_202201 中,分片符号为 "_" */ + /** + * 表分片符号,例:siot_device_log_202201 中,分片符号为 "_" + */ private static final String TABLE_SPLIT_SYMBOL = "_"; - /** 数据库配置 */ + /** + * 数据库配置 + */ private static final Environment ENV = SpringUtil.getApplicationContext().getEnvironment(); private static final String DATASOURCE_URL = ENV.getProperty("spring.shardingsphere.datasource.ds0.url"); private static final String DATASOURCE_USERNAME = ENV.getProperty("spring.shardingsphere.datasource.ds0.username"); @@ -38,7 +41,8 @@ public class ShardingAlgorithmTool { /** * 检查分表获取的表名是否存在,不存在则自动建表 - * @param logicTable 逻辑表 + * + * @param logicTable 逻辑表 * @param resultTableNames 真实表名,例:iot_device_log_202201 * @return 存在于数据库中的真实表名集合 */ @@ -48,7 +52,8 @@ public class ShardingAlgorithmTool { /** * 检查分表获取的表名是否存在,不存在则自动建表 - * @param logicTable 逻辑表 + * + * @param logicTable 逻辑表 * @param resultTableName 真实表名,例:iot_device_log_202201 * @return 确认存在于数据库中的真实表名 */ @@ -72,6 +77,7 @@ public class ShardingAlgorithmTool { /** * 重载指定分表缓存 + * * @param logicTable 逻辑表 */ public static void tableNameCacheReload(ShardingTableCacheEnum logicTable) { @@ -89,8 +95,9 @@ public class ShardingAlgorithmTool { /** * 获取所有表名 - * @return 表名集合 + * * @param logicTable 逻辑表 + * @return 表名集合 */ public static List getAllTableNameBySchema(ShardingTableCacheEnum logicTable) { List tableNames = new ArrayList<>(); @@ -102,10 +109,10 @@ public class ShardingAlgorithmTool { Statement st = conn.createStatement()) { String logicTableName = logicTable.logicTableName(); try (ResultSet rs = st.executeQuery("show TABLES like '" + logicTableName + TABLE_SPLIT_SYMBOL + "%'")) { - log.info("查询数据库所有表:{}","show TABLES like '" + logicTableName + TABLE_SPLIT_SYMBOL + "%'"); + log.info("查询数据库所有表:{}", "show TABLES like '" + logicTableName + TABLE_SPLIT_SYMBOL + "%'"); while (rs.next()) { String tableName = rs.getString(1); - log.info("分表格式:{}",String.format("^(%s\\d{6})$", logicTableName + TABLE_SPLIT_SYMBOL)); + log.info("分表格式:{}", String.format("^(%s\\d{6})$", logicTableName + TABLE_SPLIT_SYMBOL)); // 匹配分表格式 例:^(t\_contract_\d{6})$ if (org.apache.commons.lang3.StringUtils.isNotBlank(tableName) && tableName.matches(String.format("^(%s\\d{6})$", logicTableName + TABLE_SPLIT_SYMBOL))) { tableNames.add(rs.getString(1)); @@ -125,7 +132,7 @@ public class ShardingAlgorithmTool { * @param logicTableName 逻辑表名 * @param tableNamesCache 真实表名集合 */ - public static void actualDataNodesRefresh(String logicTableName, List tableNamesCache) { + public static void actualDataNodesRefresh(String logicTableName, List tableNamesCache) { try { if (CollectionUtils.isEmpty(tableNamesCache)) { return; @@ -138,7 +145,7 @@ public class ShardingAlgorithmTool { String newActualDataNodes = tableNamesCache.stream().map(o -> String.format("%s.%s", dbName, o)).collect(Collectors.joining(",")); ShardingSphereDataSource shardingSphereDataSource = SpringUtil.getBean(ShardingSphereDataSource.class); updateShardRuleActualDataNodes(shardingSphereDataSource, logicTableName, newActualDataNodes); - }catch (Exception e){ + } catch (Exception e) { log.error("初始化 动态表单失败,原因:{}", e.getMessage(), e); } } @@ -209,13 +216,14 @@ public class ShardingAlgorithmTool { /** * 创建分表 - * @param logicTable 逻辑表 + * + * @param logicTable 逻辑表 * @param resultTableName 真实表名,例:sys_user_behavior_202201 * @return 创建结果(true创建成功,false未创建) */ private static boolean createShardingTable(ShardingTableCacheEnum logicTable, String resultTableName) { // 根据日期判断,当前月份之后分表不提前创建 - String month = resultTableName.replace(logicTable.logicTableName() + TABLE_SPLIT_SYMBOL,""); + String month = resultTableName.replace(logicTable.logicTableName() + TABLE_SPLIT_SYMBOL, ""); YearMonth shardingMonth = YearMonth.parse(month, DateTimeFormatter.ofPattern("yyyyMM")); if (shardingMonth.isAfter(YearMonth.now())) { return false; @@ -236,6 +244,7 @@ public class ShardingAlgorithmTool { /** * 执行SQL + * * @param sqlList SQL集合 */ private static void executeSql(List sqlList) { diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingTablesLoadRunner.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingTablesLoadRunner.java index 4723c3be..3ad093bc 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingTablesLoadRunner.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/ShardingTablesLoadRunner.java @@ -7,7 +7,6 @@ import org.springframework.stereotype.Component; /** *

@Title ShardingTablesLoadRunner *

@Description 项目启动后,读取已有分表,进行缓存 - * */ @Order(value = 1) // 数字越小,越先执行 @Component diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/TimeShardingAlgorithm.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/TimeShardingAlgorithm.java index ff0d717e..8e2616d3 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/TimeShardingAlgorithm.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/TimeShardingAlgorithm.java @@ -20,7 +20,6 @@ import java.util.function.Function; /** *

@Title TimeShardingAlgorithm *

@Description 分片算法,按月分片 - * */ @Slf4j public class TimeShardingAlgorithm implements StandardShardingAlgorithm { @@ -51,7 +50,8 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { /** * 精准分片 - * @param tableNames 对应分片库中所有分片表的集合 + * + * @param tableNames 对应分片库中所有分片表的集合 * @param preciseShardingValue 分片键值,其中 logicTableName 为逻辑表,columnName 分片键,value 为从 SQL 中解析出来的分片键的值 * @return 表名 */ @@ -69,7 +69,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); String resultTableName = logicTableName + "_" + TABLE_SHARD_TIME_FORMATTER.format(localDateTime); // 检查分表获取的表名是否存在,不存在则自动建表 - if (!tableNames.contains(resultTableName)){ + if (!tableNames.contains(resultTableName)) { tableNames.add(resultTableName); } return ShardingAlgorithmTool.getShardingTableAndCreate(logicTable, resultTableName); @@ -77,13 +77,14 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { /** * 范围分片 - * @param tableNames 对应分片库中所有分片表的集合 + * + * @param tableNames 对应分片库中所有分片表的集合 * @param rangeShardingValue 分片范围 * @return 表名集合 */ @Override public Collection doSharding(Collection tableNames, RangeShardingValue rangeShardingValue) { - log.info("开始分表查询开始:{}",System.currentTimeMillis()); + log.info("开始分表查询开始:{}", System.currentTimeMillis()); String logicTableName = rangeShardingValue.getLogicTableName(); ShardingTableCacheEnum logicTable = ShardingTableCacheEnum.of(logicTableName); createAllTable(logicTable, tableNames); @@ -113,7 +114,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { calendar.add(Calendar.DAY_OF_MONTH, 1); // 给日期加一天 minDate = calendar.getTime(); } - log.info("开始分表查询结束:{}",System.currentTimeMillis()); + log.info("开始分表查询结束:{}", System.currentTimeMillis()); return ShardingAlgorithmTool.getShardingTablesAndCreate(logicTable, resultTableNames); } catch (Exception e) { return ShardingAlgorithmTool.getShardingTablesAndCreate(logicTable, logicTable.resultTableNamesCache()); @@ -137,6 +138,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { /** * 获取 最小分片值 + * * @param tableNames 表名集合 * @return 最小分片值 */ @@ -156,6 +158,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { /** * 获取 最大分片值 + * * @param tableNames 表名集合 * @return 最大分片值 */ @@ -175,6 +178,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { /** * 根据分片规则获取的表,创建所有的表 + * * @param logicTable * @param tableNames */ @@ -184,7 +188,7 @@ public class TimeShardingAlgorithm implements StandardShardingAlgorithm { return; } //根据分片规则创建表 - ShardingAlgorithmTool.getShardingTablesAndCreate(logicTable,tableNames); + ShardingAlgorithmTool.getShardingTablesAndCreate(logicTable, tableNames); //刷新缓存 ShardingAlgorithmTool.tableNameCacheReload(logicTable); } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/enums/ShardingTableCacheEnum.java b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/enums/ShardingTableCacheEnum.java index 54246d49..2fa0cad0 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/enums/ShardingTableCacheEnum.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/config/sharding/enums/ShardingTableCacheEnum.java @@ -1,6 +1,7 @@ package com.fastbee.framework.config.sharding.enums; import com.baomidou.mybatisplus.core.toolkit.CollectionUtils; + import java.util.*; import static com.fastbee.framework.config.sharding.ShardingAlgorithmTool.actualDataNodesRefresh; @@ -9,7 +10,6 @@ import static com.fastbee.framework.config.sharding.ShardingAlgorithmTool.actual /** *

@Title ShardingTableCacheEnum *

@Description 分片表缓存枚举 - * */ public enum ShardingTableCacheEnum { @@ -18,6 +18,12 @@ public enum ShardingTableCacheEnum { */ DEVICE_LOG("iot_device_log", new HashSet<>()); + private static Map valueMap = new HashMap<>(); + + static { + Arrays.stream(ShardingTableCacheEnum.values()).forEach(o -> valueMap.put(o.logicTableName, o)); + } + /** * 逻辑表名 */ @@ -27,12 +33,6 @@ public enum ShardingTableCacheEnum { */ private final Set resultTableNamesCache; - private static Map valueMap = new HashMap<>(); - - static { - Arrays.stream(ShardingTableCacheEnum.values()).forEach(o -> valueMap.put(o.logicTableName, o)); - } - ShardingTableCacheEnum(String logicTableName, Set resultTableNamesCache) { this.logicTableName = logicTableName; this.resultTableNamesCache = resultTableNamesCache; @@ -42,6 +42,10 @@ public enum ShardingTableCacheEnum { return valueMap.get(value); } + public static Set logicTableNames() { + return valueMap.keySet(); + } + public String logicTableName() { return logicTableName; } @@ -69,10 +73,6 @@ public enum ShardingTableCacheEnum { } } - public static Set logicTableNames() { - return valueMap.keySet(); - } - @Override public String toString() { return "ShardingTableCacheEnum{" + diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSource.java b/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSource.java index 03feff0c..2830ffdc 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSource.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSource.java @@ -12,18 +12,15 @@ import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; * @author ruoyi */ @Slf4j -public class DynamicDataSource extends AbstractRoutingDataSource -{ - public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) - { +public class DynamicDataSource extends AbstractRoutingDataSource { + public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) { super.setDefaultTargetDataSource(defaultTargetDataSource); super.setTargetDataSources(targetDataSources); super.afterPropertiesSet(); } @Override - protected Object determineCurrentLookupKey() - { + protected Object determineCurrentLookupKey() { //log.debug("数据源:" + DynamicDataSourceContextHolder.getDataSourceType()); return DynamicDataSourceContextHolder.getDataSourceType(); } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSourceContextHolder.java b/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSourceContextHolder.java index 04e5877f..2e77de04 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSourceContextHolder.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/datasource/DynamicDataSourceContextHolder.java @@ -5,41 +5,37 @@ import org.slf4j.LoggerFactory; /** * 数据源切换处理 - * + * * @author ruoyi */ -public class DynamicDataSourceContextHolder -{ +public class DynamicDataSourceContextHolder { public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); /** * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, - * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 + * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 */ private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>(); + /** + * 获得数据源的变量 + */ + public static String getDataSourceType() { + return CONTEXT_HOLDER.get(); + } + /** * 设置数据源的变量 */ - public static void setDataSourceType(String dsType) - { + public static void setDataSourceType(String dsType) { log.info("切换到{}数据源", dsType); CONTEXT_HOLDER.set(dsType); } - /** - * 获得数据源的变量 - */ - public static String getDataSourceType() - { - return CONTEXT_HOLDER.get(); - } - /** * 清空数据源变量 */ - public static void clearDataSourceType() - { + public static void clearDataSourceType() { CONTEXT_HOLDER.remove(); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/LanguageInterceptor.java b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/LanguageInterceptor.java index db0bf430..fff0ec21 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/LanguageInterceptor.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/LanguageInterceptor.java @@ -27,14 +27,14 @@ public class LanguageInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String language = request.getHeader(LANGUAGE); if (StringUtils.isEmpty(language) || language.equals("undefined") - || language.equals("")|| language.equals("null")){ + || language.equals("") || language.equals("null")) { //针对有些接口没有增加语言字段,先去token获取 language = SecurityUtils.getLanguage(); - }else if (!language.contains("-")){ - language = Language.matches(language); + } else if (!language.contains("-")) { + language = Language.matches(language); } // 前端传递的language必须是zh-CN格式的,中间的-必须要完整,不能只传递zh或en - Locale locale = new Locale(language.split("-")[0],language.split("-")[1]); + Locale locale = new Locale(language.split("-")[0], language.split("-")[1]); // 这样赋值以后,MessageUtils.message方法就不用修改了 LocaleContextHolder.setLocale(locale); return true; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/RepeatSubmitInterceptor.java b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/RepeatSubmitInterceptor.java index 7ce4bc2b..0a5b875e 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/RepeatSubmitInterceptor.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/RepeatSubmitInterceptor.java @@ -3,6 +3,7 @@ package com.fastbee.framework.interceptor; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; @@ -17,29 +18,22 @@ import com.fastbee.common.utils.ServletUtils; * @author ruoyi */ @Component -public abstract class RepeatSubmitInterceptor implements HandlerInterceptor -{ +public abstract class RepeatSubmitInterceptor implements HandlerInterceptor { @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception - { - if (handler instanceof HandlerMethod) - { + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class); - if (annotation != null) - { - if (this.isRepeatSubmit(request, annotation)) - { + if (annotation != null) { + if (this.isRepeatSubmit(request, annotation)) { AjaxResult ajaxResult = AjaxResult.error(annotation.message()); ServletUtils.renderString(response, JSON.toJSONString(ajaxResult)); return false; } } return true; - } - else - { + } else { return true; } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/TraceIdInterceptor.java b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/TraceIdInterceptor.java index 541f8d19..a5698fa1 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/TraceIdInterceptor.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/TraceIdInterceptor.java @@ -20,10 +20,10 @@ public class TraceIdInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 获取请求URI String requestURI = request.getRequestURI(); - + // 尝试从请求头中获取TraceId(支持分布式追踪) String traceId = request.getHeader("X-Trace-Id"); - + // 如果请求头中没有TraceId,则生成一个新的 if (traceId == null || traceId.isEmpty()) { traceId = TraceIdUtils.generateTraceIdString(); @@ -31,14 +31,14 @@ public class TraceIdInterceptor implements HandlerInterceptor { // 如果请求头中有TraceId,设置到MDC TraceIdUtils.setTraceId(traceId); } - + // 将TraceId放入响应头,方便前端获取 response.setHeader("X-Trace-Id", traceId); - + // 打印请求路径日志 org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TraceIdInterceptor.class); log.info("拦截请求路径: {}", requestURI); - + return true; } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/impl/SameUrlDataInterceptor.java b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/impl/SameUrlDataInterceptor.java index fabf4f9e..4ef709c7 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/impl/SameUrlDataInterceptor.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/interceptor/impl/SameUrlDataInterceptor.java @@ -4,6 +4,7 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.servlet.http.HttpServletRequest; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -19,12 +20,11 @@ import com.fastbee.framework.interceptor.RepeatSubmitInterceptor; /** * 判断请求url和数据是否和上一次相同, * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 - * + * * @author ruoyi */ @Component -public class SameUrlDataInterceptor extends RepeatSubmitInterceptor -{ +public class SameUrlDataInterceptor extends RepeatSubmitInterceptor { public final String REPEAT_PARAMS = "repeatParams"; public final String REPEAT_TIME = "repeatTime"; @@ -38,18 +38,15 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor @SuppressWarnings("unchecked") @Override - public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) - { + public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) { String nowParams = ""; - if (request instanceof RepeatedlyRequestWrapper) - { + if (request instanceof RepeatedlyRequestWrapper) { RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request; nowParams = HttpHelper.getBodyString(repeatedlyRequest); } // body参数为空,获取Parameter的数据 - if (StringUtils.isEmpty(nowParams)) - { + if (StringUtils.isEmpty(nowParams)) { nowParams = JSON.toJSONString(request.getParameterMap()); } Map nowDataMap = new HashMap(); @@ -66,14 +63,11 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey; Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); - if (sessionObj != null) - { + if (sessionObj != null) { Map sessionMap = (Map) sessionObj; - if (sessionMap.containsKey(url)) - { + if (sessionMap.containsKey(url)) { Map preDataMap = (Map) sessionMap.get(url); - if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) - { + if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) { return true; } } @@ -87,8 +81,7 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 判断参数是否相同 */ - private boolean compareParams(Map nowMap, Map preMap) - { + private boolean compareParams(Map nowMap, Map preMap) { String nowParams = (String) nowMap.get(REPEAT_PARAMS); String preParams = (String) preMap.get(REPEAT_PARAMS); return nowParams.equals(preParams); @@ -97,12 +90,10 @@ public class SameUrlDataInterceptor extends RepeatSubmitInterceptor /** * 判断两次间隔时间 */ - private boolean compareTime(Map nowMap, Map preMap, int interval) - { + private boolean compareTime(Map nowMap, Map preMap, int interval) { long time1 = (Long) nowMap.get(REPEAT_TIME); long time2 = (Long) preMap.get(REPEAT_TIME); - if ((time1 - time2) < interval) - { + if ((time1 - time2) < interval) { return true; } return false; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/manager/AsyncManager.java b/fastbee-framework/src/main/java/com/fastbee/framework/manager/AsyncManager.java index 12d73e51..cfdb3f7e 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/manager/AsyncManager.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/manager/AsyncManager.java @@ -1,23 +1,23 @@ package com.fastbee.framework.manager; +import com.fastbee.common.utils.Threads; +import com.fastbee.common.utils.spring.SpringUtils; + import java.util.TimerTask; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import com.fastbee.common.utils.Threads; -import com.fastbee.common.utils.spring.SpringUtils; /** * 异步任务管理器 - * + * * @author ruoyi */ -public class AsyncManager -{ +public class AsyncManager { + private static AsyncManager me = new AsyncManager(); /** * 操作延迟10毫秒 */ private final int OPERATE_DELAY_TIME = 10; - /** * 异步操作任务调度线程池 */ @@ -26,30 +26,26 @@ public class AsyncManager /** * 单例模式 */ - private AsyncManager(){} + private AsyncManager() { + } - private static AsyncManager me = new AsyncManager(); - - public static AsyncManager me() - { + public static AsyncManager me() { return me; } /** * 执行任务 - * + * * @param task 任务 */ - public void execute(TimerTask task) - { + public void execute(TimerTask task) { executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); } /** * 停止任务线程池 */ - public void shutdown() - { + public void shutdown() { Threads.shutdownAndAwaitTermination(executor); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/manager/CaffeineCacheDecorator.java b/fastbee-framework/src/main/java/com/fastbee/framework/manager/CaffeineCacheDecorator.java index 4bb47cb5..8ad49357 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/manager/CaffeineCacheDecorator.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/manager/CaffeineCacheDecorator.java @@ -2,16 +2,16 @@ package com.fastbee.framework.manager; import org.springframework.cache.Cache; import com.fastbee.common.utils.spring.SpringUtils; + import java.util.concurrent.Callable; /** * Cache 装饰器模式(用于扩展 Caffeine 一级缓存) - * */ public class CaffeineCacheDecorator implements Cache { private static final com.github.benmanes.caffeine.cache.Cache - CAFFEINE = SpringUtils.getBean("caffeine"); + CAFFEINE = SpringUtils.getBean("caffeine"); private final Cache cache; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/manager/ShutdownManager.java b/fastbee-framework/src/main/java/com/fastbee/framework/manager/ShutdownManager.java index a4e6efdd..27bf5017 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/manager/ShutdownManager.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/manager/ShutdownManager.java @@ -3,6 +3,7 @@ package com.fastbee.framework.manager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; + import javax.annotation.PreDestroy; /** @@ -11,28 +12,22 @@ import javax.annotation.PreDestroy; * @author ruoyi */ @Component -public class ShutdownManager -{ +public class ShutdownManager { private static final Logger logger = LoggerFactory.getLogger("sys-user"); @PreDestroy - public void destroy() - { + public void destroy() { shutdownAsyncManager(); } /** * 停止异步执行任务 */ - private void shutdownAsyncManager() - { - try - { + private void shutdownAsyncManager() { + try { logger.info("====关闭后台任务任务线程池===="); AsyncManager.me().shutdown(); - } - catch (Exception e) - { + } catch (Exception e) { logger.error(e.getMessage(), e); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/manager/SpringCacheManager.java b/fastbee-framework/src/main/java/com/fastbee/framework/manager/SpringCacheManager.java index c59ab9b3..12f78e91 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/manager/SpringCacheManager.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/manager/SpringCacheManager.java @@ -23,22 +23,16 @@ import java.util.concurrent.ConcurrentMap; *

* 修改 RedissonSpringCacheManager 源码 * 重写 cacheName 处理方法 支持多参数 - * - * */ @SuppressWarnings("unchecked") public class SpringCacheManager implements CacheManager { - private boolean dynamic = true; - - private boolean allowNullValues = true; - - private boolean transactionAware = true; - - private Long ttl; - Map configMap = new ConcurrentHashMap<>(); ConcurrentMap instanceMap = new ConcurrentHashMap<>(); + private boolean dynamic = true; + private boolean allowNullValues = true; + private boolean transactionAware = true; + private Long ttl; /** * Creates CacheManager supplied by Redisson instance @@ -74,25 +68,6 @@ public class SpringCacheManager implements CacheManager { this.transactionAware = transactionAware; } - /** - * Defines 'fixed' cache names. - * A new cache instance will not be created in dynamic for non-defined names. - *

- * `null` parameter setups dynamic mode - * - * @param names of caches - */ - public void setCacheNames(Collection names) { - if (names != null) { - for (String name : names) { - getCache(name); - } - dynamic = false; - } else { - dynamic = true; - } - } - /** * Set cache config mapped by cache name * @@ -182,5 +157,24 @@ public class SpringCacheManager implements CacheManager { return Collections.unmodifiableSet(configMap.keySet()); } + /** + * Defines 'fixed' cache names. + * A new cache instance will not be created in dynamic for non-defined names. + *

+ * `null` parameter setups dynamic mode + * + * @param names of caches + */ + public void setCacheNames(Collection names) { + if (names != null) { + for (String name : names) { + getCache(name); + } + dynamic = false; + } else { + dynamic = true; + } + } + } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/manager/factory/AsyncFactory.java b/fastbee-framework/src/main/java/com/fastbee/framework/manager/factory/AsyncFactory.java index 34bd8098..2bb48900 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/manager/factory/AsyncFactory.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/manager/factory/AsyncFactory.java @@ -1,8 +1,5 @@ package com.fastbee.framework.manager.factory; -import java.util.TimerTask; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fastbee.common.constant.Constants; import com.fastbee.common.utils.LogUtils; import com.fastbee.common.utils.ServletUtils; @@ -15,35 +12,35 @@ import com.fastbee.system.domain.SysOperLog; import com.fastbee.system.service.ISysLogininforService; import com.fastbee.system.service.ISysOperLogService; import eu.bitwalker.useragentutils.UserAgent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.TimerTask; /** * 异步工厂(产生任务用) - * + * * @author ruoyi */ -public class AsyncFactory -{ +public class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** * 记录登录信息 - * + * * @param username 用户名 - * @param status 状态 - * @param message 消息 - * @param args 列表 + * @param status 状态 + * @param message 消息 + * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, - final Object... args) - { + final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); - return new TimerTask() - { + return new TimerTask() { @Override - public void run() - { + public void run() { String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); @@ -66,12 +63,9 @@ public class AsyncFactory logininfor.setOs(os); logininfor.setMsg(message); // 日志状态 - if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) - { + if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) { logininfor.setStatus(Constants.SUCCESS); - } - else if (Constants.LOGIN_FAIL.equals(status)) - { + } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus(Constants.FAIL); } // 插入数据 @@ -82,17 +76,14 @@ public class AsyncFactory /** * 操作日志记录 - * + * * @param operLog 操作日志信息 * @return 任务task */ - public static TimerTask recordOper(final SysOperLog operLog) - { - return new TimerTask() - { + public static TimerTask recordOper(final SysOperLog operLog) { + return new TimerTask() { @Override - public void run() - { + public void run() { // 远程查询操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/QueryWrapperX.java b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/QueryWrapperX.java index 44ba9f7d..9816bfc0 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/QueryWrapperX.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/QueryWrapperX.java @@ -9,7 +9,7 @@ import java.util.Collection; /** * 拓展 MyBatis Plus QueryWrapper 类,主要增加如下功能: - * + *

* 1. 拼接条件的方法,增加 xxxIfPresent 方法,用于判断值不存在的时候,不要拼接到条件中。 * * @param 数据类型 @@ -93,13 +93,13 @@ public class QueryWrapperX extends QueryWrapper { } public QueryWrapperX betweenIfPresent(String column, Object[] values) { - if (values!= null && values.length != 0 && values[0] != null && values[1] != null) { + if (values != null && values.length != 0 && values[0] != null && values[1] != null) { return (QueryWrapperX) super.between(column, values[0], values[1]); } - if (values!= null && values.length != 0 && values[0] != null) { + if (values != null && values.length != 0 && values[0] != null) { return (QueryWrapperX) ge(column, values[0]); } - if (values!= null && values.length != 0 && values[1] != null) { + if (values != null && values.length != 0 && values[1] != null) { return (QueryWrapperX) le(column, values[1]); } return this; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusConfig.java b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusConfig.java index 4bd659e3..c2d37bf4 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusConfig.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusConfig.java @@ -24,6 +24,7 @@ public class MybatisPlusConfig implements WebMvcConfigurer { /** * SQL 过滤器避免SQL 注入 + * * @param argumentResolvers */ @Override @@ -49,8 +50,10 @@ public class MybatisPlusConfig implements WebMvcConfigurer { public IdentifierGenerator idGenerator() { return new DefaultIdentifierGenerator(NetUtil.getLocalhost()); } + /** * 审计字段自动填充 + * * @return {@link MybatisPlusMetaObjectHandler} */ @Bean diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusMetaObjectHandler.java b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusMetaObjectHandler.java index a599a9a5..3ebd2a18 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusMetaObjectHandler.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/config/MybatisPlusMetaObjectHandler.java @@ -19,6 +19,32 @@ import java.util.Date; @Slf4j public class MybatisPlusMetaObjectHandler implements MetaObjectHandler { + /** + * 填充值,先判断是否有手动设置,优先手动设置的值,例如:job必须手动设置 + * + * @param fieldName 属性名 + * @param fieldVal 属性值 + * @param metaObject MetaObject + * @param isCover 是否覆盖原有值,避免更新操作手动入参 + */ + private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) { + // 1. 没有 get 方法 + if (!metaObject.hasSetter(fieldName)) { + return; + } + // 2. 如果用户有手动设置的值 + Object userSetValue = metaObject.getValue(fieldName); + String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset()); + if (StrUtil.isNotBlank(setValueStr) && !isCover) { + return; + } + // 3. field 类型相同时设置 + Class getterType = metaObject.getGetterType(fieldName); + if (ClassUtils.isAssignableValue(getterType, fieldVal)) { + metaObject.setValue(fieldName, fieldVal); + } + } + @Override public void insertFill(MetaObject metaObject) { log.debug("mybatisPlus插入填充--------------"); @@ -38,33 +64,9 @@ public class MybatisPlusMetaObjectHandler implements MetaObjectHandler { fillValIfNullByName("updateBy", getUserName(), metaObject, true); } - /** - * 填充值,先判断是否有手动设置,优先手动设置的值,例如:job必须手动设置 - * @param fieldName 属性名 - * @param fieldVal 属性值 - * @param metaObject MetaObject - * @param isCover 是否覆盖原有值,避免更新操作手动入参 - */ - private static void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCover) { - // 1. 没有 get 方法 - if (!metaObject.hasSetter(fieldName)) { - return; - } - // 2. 如果用户有手动设置的值 - Object userSetValue = metaObject.getValue(fieldName); - String setValueStr = StrUtil.str(userSetValue, Charset.defaultCharset()); - if (StrUtil.isNotBlank(setValueStr) && !isCover) { - return; - } - // 3. field 类型相同时设置 - Class getterType = metaObject.getGetterType(fieldName); - if (ClassUtils.isAssignableValue(getterType, fieldVal)) { - metaObject.setValue(fieldName, fieldVal); - } - } - /** * 获取 spring security 当前的用户名 + * * @return 当前用户名 */ private String getUserName() { diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/utils/MyBatisUtils.java b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/utils/MyBatisUtils.java index 9493e76a..3cd53f3d 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/utils/MyBatisUtils.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/utils/MyBatisUtils.java @@ -34,7 +34,7 @@ public class MyBatisUtils { // 排序字段 if (!CollectionUtil.isEmpty(sortingFields)) { page.addOrder(sortingFields.stream().map(sortingField -> SortingField.ORDER_ASC.equals(sortingField.getOrder()) ? - OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField())) + OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField())) .collect(Collectors.toList())); } return page; @@ -45,8 +45,8 @@ public class MyBatisUtils { * 由于 MybatisPlusInterceptor 不支持添加拦截器,所以只能全量设置 * * @param interceptor 链 - * @param inner 拦截器 - * @param index 位置 + * @param inner 拦截器 + * @param index 位置 */ public static void addInterceptor(MybatisPlusInterceptor interceptor, InnerInterceptor inner, int index) { List inners = new ArrayList<>(interceptor.getInterceptors()); @@ -56,7 +56,7 @@ public class MyBatisUtils { /** * 获得 Table 对应的表名 - * + *

* 兼容 MySQL 转义表名 `t_xxx` * * @param table 表 @@ -73,9 +73,9 @@ public class MyBatisUtils { /** * 构建 Column 对象 * - * @param tableName 表名 + * @param tableName 表名 * @param tableAlias 别名 - * @param column 字段名 + * @param column 字段名 * @return Column 对象 */ public static Column buildColumn(String tableName, Alias tableAlias, String column) { diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/security/context/AuthenticationContextHolder.java b/fastbee-framework/src/main/java/com/fastbee/framework/security/context/AuthenticationContextHolder.java index 1fb2ed6b..80992ed1 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/security/context/AuthenticationContextHolder.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/security/context/AuthenticationContextHolder.java @@ -4,25 +4,21 @@ import org.springframework.security.core.Authentication; /** * 身份验证信息 - * + * * @author ruoyi */ -public class AuthenticationContextHolder -{ +public class AuthenticationContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal<>(); - public static Authentication getContext() - { + public static Authentication getContext() { return contextHolder.get(); } - public static void setContext(Authentication context) - { + public static void setContext(Authentication context) { contextHolder.set(context); } - public static void clearContext() - { + public static void clearContext() { contextHolder.remove(); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/security/context/PermissionContextHolder.java b/fastbee-framework/src/main/java/com/fastbee/framework/security/context/PermissionContextHolder.java index 85a95b22..99032482 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/security/context/PermissionContextHolder.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/security/context/PermissionContextHolder.java @@ -6,22 +6,19 @@ import com.fastbee.common.core.text.Convert; /** * 权限信息 - * + * * @author ruoyi */ -public class PermissionContextHolder -{ +public class PermissionContextHolder { private static final String PERMISSION_CONTEXT_ATTRIBUTES = "PERMISSION_CONTEXT"; - public static void setContext(String permission) - { - RequestContextHolder.currentRequestAttributes().setAttribute(PERMISSION_CONTEXT_ATTRIBUTES, permission, - RequestAttributes.SCOPE_REQUEST); - } - - public static String getContext() - { + public static String getContext() { return Convert.toStr(RequestContextHolder.currentRequestAttributes().getAttribute(PERMISSION_CONTEXT_ATTRIBUTES, RequestAttributes.SCOPE_REQUEST)); } + + public static void setContext(String permission) { + RequestContextHolder.currentRequestAttributes().setAttribute(PERMISSION_CONTEXT_ATTRIBUTES, permission, + RequestAttributes.SCOPE_REQUEST); + } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/security/filter/JwtAuthenticationTokenFilter.java b/fastbee-framework/src/main/java/com/fastbee/framework/security/filter/JwtAuthenticationTokenFilter.java index 6d190782..62beb477 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/security/filter/JwtAuthenticationTokenFilter.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/security/filter/JwtAuthenticationTokenFilter.java @@ -5,6 +5,7 @@ import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; @@ -18,22 +19,19 @@ import com.fastbee.framework.web.service.TokenService; /** * token过滤器 验证token有效性 - * + * * @author ruoyi */ @Component -public class JwtAuthenticationTokenFilter extends OncePerRequestFilter -{ +public class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private TokenService tokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws ServletException, IOException - { + throws ServletException, IOException { LoginUser loginUser = tokenService.getLoginUser(request); - if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) - { + if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) { tokenService.verifyToken(loginUser); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/AuthenticationEntryPointImpl.java b/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/AuthenticationEntryPointImpl.java index f6509e6b..ea4b40ab 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/AuthenticationEntryPointImpl.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/AuthenticationEntryPointImpl.java @@ -4,6 +4,7 @@ import java.io.IOException; import java.io.Serializable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; @@ -15,30 +16,27 @@ import com.fastbee.common.utils.StringUtils; /** * 认证失败处理类 返回未授权 - * + * * @author ruoyi */ @Component -public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable -{ +public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; - @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) - throws IOException - { -// if (isAjaxRequest(request)){ - int code = HttpStatus.UNAUTHORIZED; - String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI()); - ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg))); -// }else { -// response.sendRedirect("/oauth/login"); -// } - } - - public static boolean isAjaxRequest(HttpServletRequest request) { String ajaxFlag = request.getHeader("X-Requested-With"); return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag); } + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) + throws IOException { +// if (isAjaxRequest(request)){ + int code = HttpStatus.UNAUTHORIZED; + String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI()); + ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg))); +// }else { +// response.sendRedirect("/oauth/login"); +// } + } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/LogoutSuccessHandlerImpl.java b/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/LogoutSuccessHandlerImpl.java index 65ad50f5..49fbcddd 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/LogoutSuccessHandlerImpl.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/security/handle/LogoutSuccessHandlerImpl.java @@ -4,6 +4,7 @@ import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.Authentication; @@ -20,27 +21,24 @@ import com.fastbee.framework.web.service.TokenService; /** * 自定义退出处理类 返回成功 - * + * * @author ruoyi */ @Configuration -public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler -{ +public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler { @Autowired private TokenService tokenService; /** * 退出处理 - * + * * @return */ @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) - throws IOException, ServletException - { + throws IOException, ServletException { LoginUser loginUser = tokenService.getLoginUser(request); - if (StringUtils.isNotNull(loginUser)) - { + if (StringUtils.isNotNull(loginUser)) { String userName = loginUser.getUsername(); // 删除用户缓存记录 tokenService.delLoginUser(loginUser.getToken()); diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/Server.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/Server.java index b9173e00..18011192 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/Server.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/Server.java @@ -1,16 +1,8 @@ package com.fastbee.framework.web.domain; -import java.net.UnknownHostException; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; import com.fastbee.common.utils.Arith; import com.fastbee.common.utils.ip.IpUtils; -import com.fastbee.framework.web.domain.server.Cpu; -import com.fastbee.framework.web.domain.server.Jvm; -import com.fastbee.framework.web.domain.server.Mem; -import com.fastbee.framework.web.domain.server.Sys; -import com.fastbee.framework.web.domain.server.SysFile; +import com.fastbee.framework.web.domain.server.*; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.CentralProcessor.TickType; @@ -21,15 +13,19 @@ import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; +import java.net.UnknownHostException; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; + /** * 服务器相关信息 - * + * * @author ruoyi */ -public class Server -{ +public class Server { private static final int OSHI_WAIT_SECOND = 1000; - + /** * CPU相关信息 */ @@ -55,58 +51,69 @@ public class Server */ private List sysFiles = new LinkedList(); - public Cpu getCpu() - { + public Cpu getCpu() { return cpu; } - public void setCpu(Cpu cpu) - { + public void setCpu(Cpu cpu) { this.cpu = cpu; } - public Mem getMem() - { + public Mem getMem() { return mem; } - public void setMem(Mem mem) - { + public void setMem(Mem mem) { this.mem = mem; } - public Jvm getJvm() - { + public Jvm getJvm() { return jvm; } - public void setJvm(Jvm jvm) - { + public void setJvm(Jvm jvm) { this.jvm = jvm; } - public Sys getSys() - { + public Sys getSys() { return sys; } - public void setSys(Sys sys) - { + public void setSys(Sys sys) { this.sys = sys; } - public List getSysFiles() - { + public List getSysFiles() { return sysFiles; } - public void setSysFiles(List sysFiles) - { + public void setSysFiles(List sysFiles) { this.sysFiles = sysFiles; } - public void copyTo() throws Exception - { + /** + * 设置磁盘信息 + */ + private void setSysFiles(OperatingSystem os) { + FileSystem fileSystem = os.getFileSystem(); + List fsArray = fileSystem.getFileStores(); + for (OSFileStore fs : fsArray) { + long free = fs.getUsableSpace(); + long total = fs.getTotalSpace(); + long used = total - free; + SysFile sysFile = new SysFile(); + sysFile.setDirName(fs.getMount()); + sysFile.setSysTypeName(fs.getType()); + sysFile.setTypeName(fs.getName()); + sysFile.setTotal(convertFileSize(total)); + sysFile.setFree(convertFileSize(free)); + sysFile.setUsed(convertFileSize(used)); + sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100)); + sysFiles.add(sysFile); + } + } + + public void copyTo() throws Exception { SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); @@ -124,8 +131,7 @@ public class Server /** * 设置CPU信息 */ - private void setCpuInfo(CentralProcessor processor) - { + private void setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(OSHI_WAIT_SECOND); @@ -150,8 +156,7 @@ public class Server /** * 设置内存信息 */ - private void setMemInfo(GlobalMemory memory) - { + private void setMemInfo(GlobalMemory memory) { mem.setTotal(memory.getTotal()); mem.setUsed(memory.getTotal() - memory.getAvailable()); mem.setFree(memory.getAvailable()); @@ -160,8 +165,7 @@ public class Server /** * 设置服务器信息 */ - private void setSysInfo() - { + private void setSysInfo() { Properties props = System.getProperties(); sys.setComputerName(IpUtils.getHostName()); sys.setComputerIp(IpUtils.getHostIp()); @@ -173,8 +177,7 @@ public class Server /** * 设置Java虚拟机 */ - private void setJvmInfo() throws UnknownHostException - { + private void setJvmInfo() throws UnknownHostException { Properties props = System.getProperties(); jvm.setTotal(Runtime.getRuntime().totalMemory()); jvm.setMax(Runtime.getRuntime().maxMemory()); @@ -183,57 +186,25 @@ public class Server jvm.setHome(props.getProperty("java.home")); } - /** - * 设置磁盘信息 - */ - private void setSysFiles(OperatingSystem os) - { - FileSystem fileSystem = os.getFileSystem(); - List fsArray = fileSystem.getFileStores(); - for (OSFileStore fs : fsArray) - { - long free = fs.getUsableSpace(); - long total = fs.getTotalSpace(); - long used = total - free; - SysFile sysFile = new SysFile(); - sysFile.setDirName(fs.getMount()); - sysFile.setSysTypeName(fs.getType()); - sysFile.setTypeName(fs.getName()); - sysFile.setTotal(convertFileSize(total)); - sysFile.setFree(convertFileSize(free)); - sysFile.setUsed(convertFileSize(used)); - sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100)); - sysFiles.add(sysFile); - } - } - /** * 字节转换 - * + * * @param size 字节大小 * @return 转换后值 */ - public String convertFileSize(long size) - { + public String convertFileSize(long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; - if (size >= gb) - { + if (size >= gb) { return String.format("%.1f GB", (float) size / gb); - } - else if (size >= mb) - { + } else if (size >= mb) { float f = (float) size / mb; return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); - } - else if (size >= kb) - { + } else if (size >= kb) { float f = (float) size / kb; return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); - } - else - { + } else { return String.format("%d B", size); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Cpu.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Cpu.java index 705b2825..a35674b3 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Cpu.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Cpu.java @@ -4,11 +4,10 @@ import com.fastbee.common.utils.Arith; /** * CPU相关信息 - * + * * @author ruoyi */ -public class Cpu -{ +public class Cpu { /** * 核心数 */ @@ -39,63 +38,51 @@ public class Cpu */ private double free; - public int getCpuNum() - { + public int getCpuNum() { return cpuNum; } - public void setCpuNum(int cpuNum) - { + public void setCpuNum(int cpuNum) { this.cpuNum = cpuNum; } - public double getTotal() - { + public double getTotal() { return Arith.round(Arith.mul(total, 100), 2); } - public void setTotal(double total) - { + public void setTotal(double total) { this.total = total; } - public double getSys() - { + public double getSys() { return Arith.round(Arith.mul(sys / total, 100), 2); } - public void setSys(double sys) - { + public void setSys(double sys) { this.sys = sys; } - public double getUsed() - { + public double getUsed() { return Arith.round(Arith.mul(used / total, 100), 2); } - public void setUsed(double used) - { + public void setUsed(double used) { this.used = used; } - public double getWait() - { + public double getWait() { return Arith.round(Arith.mul(wait / total, 100), 2); } - public void setWait(double wait) - { + public void setWait(double wait) { this.wait = wait; } - public double getFree() - { + public double getFree() { return Arith.round(Arith.mul(free / total, 100), 2); } - public void setFree(double free) - { + public void setFree(double free) { this.free = free; } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Jvm.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Jvm.java index 5d45a7b5..1cad6823 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Jvm.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Jvm.java @@ -1,16 +1,16 @@ package com.fastbee.framework.web.domain.server; -import java.lang.management.ManagementFactory; import com.fastbee.common.utils.Arith; import com.fastbee.common.utils.DateUtils; +import java.lang.management.ManagementFactory; + /** * JVM相关信息 - * + * * @author ruoyi */ -public class Jvm -{ +public class Jvm { /** * 当前JVM占用的内存总数(M) */ @@ -36,95 +36,79 @@ public class Jvm */ private String home; - public double getTotal() - { + public double getTotal() { return Arith.div(total, (1024 * 1024), 2); } - public void setTotal(double total) - { + public void setTotal(double total) { this.total = total; } - public double getMax() - { + public double getMax() { return Arith.div(max, (1024 * 1024), 2); } - public void setMax(double max) - { + public void setMax(double max) { this.max = max; } - public double getFree() - { + public double getFree() { return Arith.div(free, (1024 * 1024), 2); } - public void setFree(double free) - { + public void setFree(double free) { this.free = free; } - public double getUsed() - { + public double getUsed() { return Arith.div(total - free, (1024 * 1024), 2); } - public double getUsage() - { + public double getUsage() { return Arith.mul(Arith.div(total - free, total, 4), 100); } /** * 获取JDK名称 */ - public String getName() - { + public String getName() { return ManagementFactory.getRuntimeMXBean().getVmName(); } - public String getVersion() - { + public String getVersion() { return version; } - public void setVersion(String version) - { + public void setVersion(String version) { this.version = version; } - public String getHome() - { + public String getHome() { return home; } - public void setHome(String home) - { + public void setHome(String home) { this.home = home; } /** * JDK启动时间 */ - public String getStartTime() - { + public String getStartTime() { return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate()); } /** * JDK运行时间 */ - public String getRunTime() - { + public String getRunTime() { return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate()); } /** * 运行参数 */ - public String getInputArgs() - { + public String getInputArgs() { return ManagementFactory.getRuntimeMXBean().getInputArguments().toString(); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Mem.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Mem.java index 44074dfa..cd20a993 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Mem.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Mem.java @@ -4,11 +4,10 @@ import com.fastbee.common.utils.Arith; /** * 內存相关信息 - * + * * @author ruoyi */ -public class Mem -{ +public class Mem { /** * 内存总量 */ @@ -24,38 +23,31 @@ public class Mem */ private double free; - public double getTotal() - { + public double getTotal() { return Arith.div(total, (1024 * 1024 * 1024), 2); } - public void setTotal(long total) - { + public void setTotal(long total) { this.total = total; } - public double getUsed() - { + public double getUsed() { return Arith.div(used, (1024 * 1024 * 1024), 2); } - public void setUsed(long used) - { + public void setUsed(long used) { this.used = used; } - public double getFree() - { + public double getFree() { return Arith.div(free, (1024 * 1024 * 1024), 2); } - public void setFree(long free) - { + public void setFree(long free) { this.free = free; } - public double getUsage() - { + public double getUsage() { return Arith.mul(Arith.div(used, total, 4), 100); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Sys.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Sys.java index c7b2f257..78b104d3 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Sys.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/Sys.java @@ -2,11 +2,10 @@ package com.fastbee.framework.web.domain.server; /** * 系统相关信息 - * + * * @author ruoyi */ -public class Sys -{ +public class Sys { /** * 服务器名称 */ @@ -32,53 +31,43 @@ public class Sys */ private String osArch; - public String getComputerName() - { + public String getComputerName() { return computerName; } - public void setComputerName(String computerName) - { + public void setComputerName(String computerName) { this.computerName = computerName; } - public String getComputerIp() - { + public String getComputerIp() { return computerIp; } - public void setComputerIp(String computerIp) - { + public void setComputerIp(String computerIp) { this.computerIp = computerIp; } - public String getUserDir() - { + public String getUserDir() { return userDir; } - public void setUserDir(String userDir) - { + public void setUserDir(String userDir) { this.userDir = userDir; } - public String getOsName() - { + public String getOsName() { return osName; } - public void setOsName(String osName) - { + public void setOsName(String osName) { this.osName = osName; } - public String getOsArch() - { + public String getOsArch() { return osArch; } - public void setOsArch(String osArch) - { + public void setOsArch(String osArch) { this.osArch = osArch; } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/SysFile.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/SysFile.java index 80edd964..73036654 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/SysFile.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/domain/server/SysFile.java @@ -2,11 +2,10 @@ package com.fastbee.framework.web.domain.server; /** * 系统文件相关信息 - * + * * @author ruoyi */ -public class SysFile -{ +public class SysFile { /** * 盘符路径 */ @@ -42,73 +41,59 @@ public class SysFile */ private double usage; - public String getDirName() - { + public String getDirName() { return dirName; } - public void setDirName(String dirName) - { + public void setDirName(String dirName) { this.dirName = dirName; } - public String getSysTypeName() - { + public String getSysTypeName() { return sysTypeName; } - public void setSysTypeName(String sysTypeName) - { + public void setSysTypeName(String sysTypeName) { this.sysTypeName = sysTypeName; } - public String getTypeName() - { + public String getTypeName() { return typeName; } - public void setTypeName(String typeName) - { + public void setTypeName(String typeName) { this.typeName = typeName; } - public String getTotal() - { + public String getTotal() { return total; } - public void setTotal(String total) - { + public void setTotal(String total) { this.total = total; } - public String getFree() - { + public String getFree() { return free; } - public void setFree(String free) - { + public void setFree(String free) { this.free = free; } - public String getUsed() - { + public String getUsed() { return used; } - public void setUsed(String used) - { + public void setUsed(String used) { this.used = used; } - public double getUsage() - { + public double getUsage() { return usage; } - public void setUsage(double usage) - { + public void setUsage(double usage) { this.usage = usage; } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/exception/GlobalExceptionHandler.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/exception/GlobalExceptionHandler.java index a848827f..a07f474d 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/exception/GlobalExceptionHandler.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/exception/GlobalExceptionHandler.java @@ -1,6 +1,10 @@ package com.fastbee.framework.web.exception; -import javax.servlet.http.HttpServletRequest; +import com.fastbee.common.constant.HttpStatus; +import com.fastbee.common.core.domain.AjaxResult; +import com.fastbee.common.exception.DemoModeException; +import com.fastbee.common.exception.ServiceException; +import com.fastbee.common.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; @@ -9,28 +13,23 @@ import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; -import com.fastbee.common.constant.HttpStatus; -import com.fastbee.common.core.domain.AjaxResult; -import com.fastbee.common.exception.DemoModeException; -import com.fastbee.common.exception.ServiceException; -import com.fastbee.common.utils.StringUtils; + +import javax.servlet.http.HttpServletRequest; /** * 全局异常处理器 - * + * * @author ruoyi */ @RestControllerAdvice -public class GlobalExceptionHandler -{ +public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 权限校验异常 */ @ExceptionHandler(AccessDeniedException.class) - public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) - { + public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage()); return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权"); @@ -41,8 +40,7 @@ public class GlobalExceptionHandler */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, - HttpServletRequest request) - { + HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()); return AjaxResult.error(e.getMessage()); @@ -52,8 +50,7 @@ public class GlobalExceptionHandler * 业务异常 */ @ExceptionHandler(ServiceException.class) - public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) - { + public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) { log.error(e.getMessage(), e); Integer code = e.getCode(); return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage()); @@ -63,8 +60,7 @@ public class GlobalExceptionHandler * 拦截未知的运行时异常 */ @ExceptionHandler(RuntimeException.class) - public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) - { + public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',发生未知异常.", requestURI, e); return AjaxResult.error(e.getMessage()); @@ -74,8 +70,7 @@ public class GlobalExceptionHandler * 系统异常 */ @ExceptionHandler(Exception.class) - public AjaxResult handleException(Exception e, HttpServletRequest request) - { + public AjaxResult handleException(Exception e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',发生系统异常.", requestURI, e); return AjaxResult.error(e.getMessage()); @@ -85,8 +80,7 @@ public class GlobalExceptionHandler * 自定义验证异常 */ @ExceptionHandler(BindException.class) - public AjaxResult handleBindException(BindException e) - { + public AjaxResult handleBindException(BindException e) { log.error(e.getMessage(), e); String message = e.getAllErrors().get(0).getDefaultMessage(); return AjaxResult.error(message); @@ -96,8 +90,7 @@ public class GlobalExceptionHandler * 自定义验证异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) - public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) - { + public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error(e.getMessage(), e); String message = e.getBindingResult().getFieldError().getDefaultMessage(); return AjaxResult.error(message); @@ -107,8 +100,7 @@ public class GlobalExceptionHandler * 演示模式异常 */ @ExceptionHandler(DemoModeException.class) - public AjaxResult handleDemoModeException(DemoModeException e) - { + public AjaxResult handleDemoModeException(DemoModeException e) { return AjaxResult.error("演示模式,不允许操作"); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/PermissionService.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/PermissionService.java index 16061890..5816e773 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/PermissionService.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/PermissionService.java @@ -1,26 +1,30 @@ package com.fastbee.framework.web.service; -import java.util.Set; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; import com.fastbee.common.core.domain.entity.SysRole; import com.fastbee.common.core.domain.model.LoginUser; import com.fastbee.common.utils.SecurityUtils; import com.fastbee.common.utils.StringUtils; import com.fastbee.framework.security.context.PermissionContextHolder; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +import java.util.Set; /** * RuoYi首创 自定义权限实现,ss取自SpringSecurity首字母 - * + * * @author ruoyi */ @Service("ss") -public class PermissionService -{ - /** 所有权限标识 */ +public class PermissionService { + /** + * 所有权限标识 + */ private static final String ALL_PERMISSION = "*:*:*"; - /** 管理员角色权限标识 */ + /** + * 管理员角色权限标识 + */ private static final String SUPER_ADMIN = "admin"; private static final String ROLE_DELIMETER = ","; @@ -29,19 +33,16 @@ public class PermissionService /** * 验证用户是否具备某权限 - * + * * @param permission 权限字符串 * @return 用户是否具备某权限 */ - public boolean hasPermi(String permission) - { - if (StringUtils.isEmpty(permission)) - { + public boolean hasPermi(String permission) { + if (StringUtils.isEmpty(permission)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); - if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) - { + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) { return false; } PermissionContextHolder.setContext(permission); @@ -54,8 +55,7 @@ public class PermissionService * @param permission 权限字符串 * @return 用户是否不具备某权限 */ - public boolean lacksPermi(String permission) - { + public boolean lacksPermi(String permission) { return hasPermi(permission) != true; } @@ -65,23 +65,18 @@ public class PermissionService * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 * @return 用户是否具有以下任意一个权限 */ - public boolean hasAnyPermi(String permissions) - { - if (StringUtils.isEmpty(permissions)) - { + public boolean hasAnyPermi(String permissions) { + if (StringUtils.isEmpty(permissions)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); - if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) - { + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) { return false; } PermissionContextHolder.setContext(permissions); Set authorities = loginUser.getPermissions(); - for (String permission : permissions.split(PERMISSION_DELIMETER)) - { - if (permission != null && hasPermissions(authorities, permission)) - { + for (String permission : permissions.split(PERMISSION_DELIMETER)) { + if (permission != null && hasPermissions(authorities, permission)) { return true; } } @@ -90,26 +85,21 @@ public class PermissionService /** * 判断用户是否拥有某个角色 - * + * * @param role 角色字符串 * @return 用户是否具备某角色 */ - public boolean hasRole(String role) - { - if (StringUtils.isEmpty(role)) - { + public boolean hasRole(String role) { + if (StringUtils.isEmpty(role)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); - if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) - { + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) { return false; } - for (SysRole sysRole : loginUser.getUser().getRoles()) - { + for (SysRole sysRole : loginUser.getUser().getRoles()) { String roleKey = sysRole.getRoleKey(); - if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) - { + if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) { return true; } } @@ -122,8 +112,7 @@ public class PermissionService * @param role 角色名称 * @return 用户是否不具备某角色 */ - public boolean lacksRole(String role) - { + public boolean lacksRole(String role) { return hasRole(role) != true; } @@ -133,21 +122,16 @@ public class PermissionService * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 * @return 用户是否具有以下任意一个角色 */ - public boolean hasAnyRoles(String roles) - { - if (StringUtils.isEmpty(roles)) - { + public boolean hasAnyRoles(String roles) { + if (StringUtils.isEmpty(roles)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); - if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) - { + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) { return false; } - for (String role : roles.split(ROLE_DELIMETER)) - { - if (hasRole(role)) - { + for (String role : roles.split(ROLE_DELIMETER)) { + if (hasRole(role)) { return true; } } @@ -156,13 +140,12 @@ public class PermissionService /** * 判断是否包含权限 - * + * * @param permissions 权限列表 - * @param permission 权限字符串 + * @param permission 权限字符串 * @return 用户是否具备某权限 */ - private boolean hasPermissions(Set permissions, String permission) - { + private boolean hasPermissions(Set permissions, String permission) { return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission)); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPasswordService.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPasswordService.java index 7fd63448..0be1d18e 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPasswordService.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPasswordService.java @@ -1,10 +1,5 @@ package com.fastbee.framework.web.service; -import java.util.concurrent.TimeUnit; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; import com.fastbee.common.constant.CacheConstants; import com.fastbee.common.constant.Constants; import com.fastbee.common.core.domain.entity.SysUser; @@ -16,6 +11,12 @@ import com.fastbee.common.utils.SecurityUtils; import com.fastbee.framework.manager.AsyncManager; import com.fastbee.framework.manager.factory.AsyncFactory; import com.fastbee.framework.security.context.AuthenticationContextHolder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; /** * 登录密码方法 @@ -23,8 +24,7 @@ import com.fastbee.framework.security.context.AuthenticationContextHolder; * @author ruoyi */ @Component -public class SysPasswordService -{ +public class SysPasswordService { @Autowired private RedisCache redisCache; @@ -40,86 +40,71 @@ public class SysPasswordService * @param username 用户名 * @return 缓存键key */ - private String getCacheKey(String username) - { + private String getCacheKey(String username) { return CacheConstants.PWD_ERR_CNT_KEY + username; } - public void validate(SysUser user) - { + public void validate(SysUser user) { Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext(); String username = usernamePasswordAuthenticationToken.getName(); String password = usernamePasswordAuthenticationToken.getCredentials().toString(); Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); - if (retryCount == null) - { + if (retryCount == null) { retryCount = 0; } - if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) - { + if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime))); throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime); } - if (!matches(user, password)) - { + if (!matches(user, password)) { retryCount = retryCount + 1; AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); throw new UserPasswordNotMatchException(); - } - else - { + } else { clearLoginRecordCache(username); } } - public void socialValidate(SysUser user, String encodePwd) - { + public void socialValidate(SysUser user, String encodePwd) { String username = user.getUserName(); String password = user.getPassword(); Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); - if (retryCount == null) - { + if (retryCount == null) { retryCount = 0; } - if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) - { + if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime))); throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime); } - if(!password.equals(encodePwd)){ + if (!password.equals(encodePwd)) { retryCount = retryCount + 1; AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); throw new UserPasswordNotMatchException(); - } - else - { + } else { clearLoginRecordCache(username); } } - public boolean matches(SysUser user, String rawPassword) - { + public boolean matches(SysUser user, String rawPassword) { return SecurityUtils.matchesPassword(rawPassword, user.getPassword()); } - public void clearLoginRecordCache(String loginName) - { - if (redisCache.hasKey(getCacheKey(loginName))) - { + public void clearLoginRecordCache(String loginName) { + if (redisCache.hasKey(getCacheKey(loginName))) { redisCache.deleteObject(getCacheKey(loginName)); } } @@ -130,28 +115,23 @@ public class SysPasswordService Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); - if (retryCount == null) - { + if (retryCount == null) { retryCount = 0; } - if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) - { + if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime))); throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime); } - if (!matches(user, encodePwd)) - { + if (!matches(user, encodePwd)) { retryCount = retryCount + 1; AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.retry.limit.count", retryCount))); redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); throw new UserPasswordNotMatchException(); - } - else - { + } else { clearLoginRecordCache(username); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPermissionService.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPermissionService.java index bb465a76..a6fda339 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPermissionService.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysPermissionService.java @@ -1,14 +1,15 @@ package com.fastbee.framework.web.service; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import com.fastbee.common.core.domain.entity.SysRole; import com.fastbee.common.core.domain.entity.SysUser; import com.fastbee.system.service.ISysMenuService; import com.fastbee.system.service.ISysRoleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; /** * 用户权限处理 @@ -16,8 +17,7 @@ import com.fastbee.system.service.ISysRoleService; * @author ruoyi */ @Component -public class SysPermissionService -{ +public class SysPermissionService { @Autowired private ISysRoleService roleService; @@ -30,16 +30,12 @@ public class SysPermissionService * @param user 用户信息 * @return 角色权限信息 */ - public Set getRolePermission(SysUser user) - { + public Set getRolePermission(SysUser user) { Set roles = new HashSet(); // 管理员拥有所有权限 - if (user.isAdmin()) - { + if (user.isAdmin()) { roles.add("admin"); - } - else - { + } else { roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId())); } return roles; @@ -51,26 +47,21 @@ public class SysPermissionService * @param user 用户信息 * @return 菜单权限信息 */ - public Set getMenuPermission(SysUser user) - { + public Set getMenuPermission(SysUser user) { Set perms = new HashSet(); // 管理员拥有所有权限 if (user.isAdmin()) { perms.add("*:*:*"); } else { List roles = user.getRoles(); - if (!roles.isEmpty() && roles.size() > 1) - { + if (!roles.isEmpty() && roles.size() > 1) { // 多角色设置permissions属性,以便数据权限匹配权限 - for (SysRole role : roles) - { + for (SysRole role : roles) { Set rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId()); role.setPermissions(rolePerms); perms.addAll(rolePerms); } - } - else - { + } else { perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId())); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java index dcf3255b..754ffcfd 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java @@ -1,7 +1,5 @@ package com.fastbee.framework.web.service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import com.fastbee.common.constant.CacheConstants; import com.fastbee.common.constant.Constants; import com.fastbee.common.constant.UserConstants; @@ -17,15 +15,16 @@ import com.fastbee.framework.manager.AsyncManager; import com.fastbee.framework.manager.factory.AsyncFactory; import com.fastbee.system.service.ISysConfigService; import com.fastbee.system.service.ISysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * 注册校验方法 - * + * * @author ruoyi */ @Component -public class SysRegisterService -{ +public class SysRegisterService { @Autowired private ISysUserService userService; @@ -38,52 +37,36 @@ public class SysRegisterService /** * 注册 */ - public String register(RegisterBody registerBody) - { + public String register(RegisterBody registerBody) { String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(); SysUser sysUser = new SysUser(); sysUser.setUserName(username); // 验证码开关 boolean captchaEnabled = configService.selectCaptchaEnabled(); - if (captchaEnabled) - { + if (captchaEnabled) { validateCaptcha(username, registerBody.getCode(), registerBody.getUuid()); } - if (StringUtils.isEmpty(username)) - { + if (StringUtils.isEmpty(username)) { msg = "用户名不能为空"; - } - else if (StringUtils.isEmpty(password)) - { + } else if (StringUtils.isEmpty(password)) { msg = "用户密码不能为空"; - } - else if (username.length() < UserConstants.USERNAME_MIN_LENGTH - || username.length() > UserConstants.USERNAME_MAX_LENGTH) - { + } else if (username.length() < UserConstants.USERNAME_MIN_LENGTH + || username.length() > UserConstants.USERNAME_MAX_LENGTH) { msg = "账户长度必须在2到20个字符之间"; - } - else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH - || password.length() > UserConstants.PASSWORD_MAX_LENGTH) - { + } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH + || password.length() > UserConstants.PASSWORD_MAX_LENGTH) { msg = "密码长度必须在5到20个字符之间"; - } - else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) - { + } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) { msg = "保存用户'" + username + "'失败,注册账号已存在"; - } - else - { + } else { sysUser.setNickName(username); sysUser.setPassword(SecurityUtils.encryptPassword(password)); boolean regFlag = userService.registerUser(sysUser); - if (!regFlag) - { + if (!regFlag) { msg = "注册失败,请联系系统管理人员"; - } - else - { + } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success"))); } } @@ -92,23 +75,20 @@ public class SysRegisterService /** * 校验验证码 - * + * * @param username 用户名 - * @param code 验证码 - * @param uuid 唯一标识 + * @param code 验证码 + * @param uuid 唯一标识 * @return 结果 */ - public void validateCaptcha(String username, String code, String uuid) - { + public void validateCaptcha(String username, String code, String uuid) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); - if (captcha == null) - { + if (captcha == null) { throw new CaptchaExpireException(); } - if (!code.equalsIgnoreCase(captcha)) - { + if (!code.equalsIgnoreCase(captcha)) { throw new CaptchaException(); } } diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/TokenService.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/TokenService.java index 0553fd6e..01f44e09 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/TokenService.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/TokenService.java @@ -35,24 +35,18 @@ import java.util.concurrent.TimeUnit; */ @Component public class TokenService { + protected static final long MILLIS_SECOND = 1000; + protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND; + private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L; // 令牌自定义标识 @Value("${token.header}") private String header; - // 令牌秘钥 @Value("${token.secret}") private String secret; - // 令牌有效期(默认30分钟) @Value("${token.expireTime}") private int expireTime; - - protected static final long MILLIS_SECOND = 1000; - - protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND; - - private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L; - @Autowired private RedisCache redisCache; diff --git a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/UserDetailsServiceImpl.java b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/UserDetailsServiceImpl.java index 650c74b8..6c0794d4 100644 --- a/fastbee-framework/src/main/java/com/fastbee/framework/web/service/UserDetailsServiceImpl.java +++ b/fastbee-framework/src/main/java/com/fastbee/framework/web/service/UserDetailsServiceImpl.java @@ -1,5 +1,11 @@ package com.fastbee.framework.web.service; +import com.fastbee.common.core.domain.entity.SysUser; +import com.fastbee.common.core.domain.model.LoginUser; +import com.fastbee.common.enums.UserStatus; +import com.fastbee.common.exception.ServiceException; +import com.fastbee.common.utils.StringUtils; +import com.fastbee.system.service.ISysUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -7,12 +13,6 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; -import com.fastbee.common.core.domain.entity.SysUser; -import com.fastbee.common.core.domain.model.LoginUser; -import com.fastbee.common.enums.UserStatus; -import com.fastbee.common.exception.ServiceException; -import com.fastbee.common.utils.StringUtils; -import com.fastbee.system.service.ISysUserService; /** * 用户验证处理 @@ -20,13 +20,12 @@ import com.fastbee.system.service.ISysUserService; * @author ruoyi */ @Service -public class UserDetailsServiceImpl implements UserDetailsService -{ +public class UserDetailsServiceImpl implements UserDetailsService { private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); @Autowired private ISysUserService userService; - + @Autowired private SysPasswordService passwordService; @@ -34,21 +33,15 @@ public class UserDetailsServiceImpl implements UserDetailsService private SysPermissionService permissionService; @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException - { + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { SysUser user = userService.selectUserByUserName(username); - if (StringUtils.isNull(user)) - { + if (StringUtils.isNull(user)) { log.info("登录用户:{} 不存在.", username); throw new ServiceException("登录用户:" + username + " 不存在"); - } - else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) - { + } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) { log.info("登录用户:{} 已被删除.", username); throw new ServiceException("对不起,您的账号:" + username + " 已被删除"); - } - else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) - { + } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) { log.info("登录用户:{} 已被停用.", username); throw new ServiceException("对不起,您的账号:" + username + " 已停用"); } @@ -58,8 +51,7 @@ public class UserDetailsServiceImpl implements UserDetailsService return createLoginUser(user); } - public UserDetails createLoginUser(SysUser user) - { + public UserDetails createLoginUser(SysUser user) { return new LoginUser(user.getUserId(), user.getDeptId(), user.getLanguage(), user, permissionService.getMenuPermission(user)); } } diff --git a/fastbee-iot-data/pom.xml b/fastbee-iot-data/pom.xml index 87f3cebe..c8f0196b 100644 --- a/fastbee-iot-data/pom.xml +++ b/fastbee-iot-data/pom.xml @@ -1,34 +1,34 @@ - - 4.0.0 - - fastbee - com.fastbee - 3.8.5 - - fastbee-iot-data + + 4.0.0 + + fastbee + com.fastbee + 3.8.5 + + fastbee-iot-data - - - com.fastbee - mqtt-broker - + + + com.fastbee + mqtt-broker + - - com.fastbee - fastbee-mq - + + com.fastbee + fastbee-mq + - - com.fastbee - fastbee-quartz - + + com.fastbee + fastbee-quartz + - - com.fastbee - fastbee-mqtt-client - - + + com.fastbee + fastbee-mqtt-client + + diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/StartBoot.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/StartBoot.java index 4083e544..e70b8e64 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/StartBoot.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/StartBoot.java @@ -65,7 +65,7 @@ public class StartBoot implements ApplicationRunner { log.info("=>设备监听队列启动成功"); }).start(); } catch (Exception e) { - log.error("=>客户端启动失败:{}", e.getMessage(),e); + log.error("=>客户端启动失败:{}", e.getMessage(), e); } } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/aspect/DeviceDebugLogAspect.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/aspect/DeviceDebugLogAspect.java index 565c940c..d3ab9686 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/aspect/DeviceDebugLogAspect.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/aspect/DeviceDebugLogAspect.java @@ -14,11 +14,11 @@ import com.fastbee.common.utils.StringUtils; import com.fastbee.common.utils.gateway.mq.TopicsUtils; import com.fastbee.iot.domain.Device; import com.fastbee.iot.domain.DeviceLog; -import com.fastbee.iot.service.IDeviceService; -import com.fastbee.iot.service.IProductService; -import com.fastbee.iot.service.IProductAuthorizeService; -import com.fastbee.iot.domain.ProductAuthorize; import com.fastbee.iot.domain.Product; +import com.fastbee.iot.domain.ProductAuthorize; +import com.fastbee.iot.service.IDeviceService; +import com.fastbee.iot.service.IProductAuthorizeService; +import com.fastbee.iot.service.IProductService; import com.fastbee.iot.tdengine.service.ILogService; import com.fastbee.mqtt.manager.MqttRemoteManager; import com.fastbee.mqtt.model.PushMessageBo; @@ -41,7 +41,7 @@ import java.util.Objects; /** * 设备调试错误日志AOP切面 * 用于拦截数据解析和指令发送的异常,自动记录错误日志并推送到前端页面 - * + *

* 功能: * 1. 拦截设备数据解析异常(parseReportMsg) * 2. 拦截指令发送异常(messagePost) @@ -58,13 +58,21 @@ import java.util.Objects; @Slf4j public class DeviceDebugLogAspect { - /** 日志值最大长度 */ + /** + * 日志值最大长度 + */ private static final int MAX_LOG_VALUE_LENGTH = 64; - /** 备注最大长度 */ + /** + * 备注最大长度 + */ private static final int MAX_REMARK_LENGTH = 200; - /** 错误信息显示最大长度 */ + /** + * 错误信息显示最大长度 + */ private static final int MAX_ERROR_MSG_DISPLAY_LENGTH = 50; - /** 其他模式 */ + /** + * 其他模式 + */ private static final int MODE_OTHER = 3; @Resource @@ -121,7 +129,7 @@ public class DeviceDebugLogAspect { String sourceData = extractSourceDataFromReportBo(bo); String errorMsg = getErrorMessage(e); Long productId = bo.getProductId(); - return new ErrorLogContext(serialNumber, sourceData, errorMsg, + return new ErrorLogContext(serialNumber, sourceData, errorMsg, DeviceLogTypeEnum.DATA_PARSE_ERROR.getType(), "DEBUG_ERROR", productId); } return null; @@ -223,7 +231,7 @@ public class DeviceDebugLogAspect { /** * 统一异常处理入口 */ - private void handleException(JoinPoint joinPoint, Throwable e, + private void handleException(JoinPoint joinPoint, Throwable e, java.util.function.Function contextExtractor, String errorLogPrefix) { try { @@ -371,7 +379,7 @@ public class DeviceDebugLogAspect { DeviceLog deviceLog = buildDeviceLog(device, context); logService.saveDeviceLog(deviceLog); log.info("已保存错误日志到数据库 - 设备: {}, 错误类型: {}, 错误信息: {}", - serialNumber, context.getIdentity(), + serialNumber, context.getIdentity(), StringUtils.substring(context.getErrorMsg(), 0, MAX_ERROR_MSG_DISPLAY_LENGTH)); // 推送错误信息到前端页面 @@ -430,7 +438,7 @@ public class DeviceDebugLogAspect { // 构建错误消息的物模型数据 ThingsModelSimpleItem errorItem = new ThingsModelSimpleItem(); errorItem.setId("ERROR_" + context.getIdentity()); - errorItem.setName(Objects.equals(context.getLogType(), DeviceLogTypeEnum.DATA_PARSE_ERROR.getType()) + errorItem.setName(Objects.equals(context.getLogType(), DeviceLogTypeEnum.DATA_PARSE_ERROR.getType()) ? "数据解析错误" : "指令发送错误"); errorItem.setValue(context.getErrorMsg()); errorItem.setRemark(context.getErrorMsg()); @@ -441,7 +449,7 @@ public class DeviceDebugLogAspect { // 构建推送消息 PushMessageBo messageBo = new PushMessageBo(); messageBo.setTopic(topicsUtils.buildTopic(productId, serialNumber.toUpperCase(), TopicType.WS_SERVICE_INVOKE)); - + String sourceAscii = hexToAscii(context.getSourceData()); JSONObject pushObj = new JSONObject(); pushObj.put("message", errorItems); @@ -449,49 +457,21 @@ public class DeviceDebugLogAspect { pushObj.put("sourcesAscii", sourceAscii); pushObj.put("errorType", context.getIdentity()); pushObj.put("isError", true); - + messageBo.setMessage(JSON.toJSONString(pushObj)); - + // 推送消息到MQTT mqttRemoteManager.pushCommon(messageBo); - log.info("已推送错误信息到前端 - 设备: {}, 产品ID: {}, 错误类型: {}", + log.info("已推送错误信息到前端 - 设备: {}, 产品ID: {}, 错误类型: {}", serialNumber, productId, context.getIdentity()); } catch (Exception ex) { log.error("推送错误信息到前端失败: {}", ex.getMessage(), ex); } } - /** - * 错误日志上下文对象 - */ - private static class ErrorLogContext { - private final String serialNumber; - private final String sourceData; - private final String errorMsg; - private final Integer logType; - private final String identity; - private final Long productId; - - public ErrorLogContext(String serialNumber, String sourceData, String errorMsg, - Integer logType, String identity, Long productId) { - this.serialNumber = serialNumber; - this.sourceData = sourceData; - this.errorMsg = errorMsg; - this.logType = logType; - this.identity = identity; - this.productId = productId; - } - - public String getSerialNumber() { return serialNumber; } - public String getSourceData() { return sourceData; } - public String getErrorMsg() { return errorMsg; } - public Integer getLogType() { return logType; } - public String getIdentity() { return identity; } - public Long getProductId() { return productId; } - } - /** * 将ASCII字符串转换为HEX字符串 + * * @param asciiStr ASCII字符串 * @return HEX字符串(大写,每两个字符一组,用空格分隔) */ @@ -515,7 +495,7 @@ public class DeviceDebugLogAspect { } return hex.toString(); } catch (Exception e) { - log.warn("ASCII转HEX失败: {}, ASCII字符串: {}", e.getMessage(), + log.warn("ASCII转HEX失败: {}, ASCII字符串: {}", e.getMessage(), StringUtils.isNotEmpty(asciiStr) ? StringUtils.substring(asciiStr, 0, 50) : ""); return ""; } @@ -523,6 +503,7 @@ public class DeviceDebugLogAspect { /** * 将16进制字符串转换为ASCII字符串 + * * @param hexStr 16进制字符串(可能包含空格) * @return ASCII字符串,保留换行符和回车符,其他不可打印字符显示为点号 */ @@ -565,9 +546,55 @@ public class DeviceDebugLogAspect { } return ascii.toString(); } catch (Exception e) { - log.warn("HEX转ASCII失败: {}, HEX字符串: {}", e.getMessage(), + log.warn("HEX转ASCII失败: {}, HEX字符串: {}", e.getMessage(), StringUtils.isNotEmpty(hexStr) ? StringUtils.substring(hexStr, 0, 50) : ""); return ""; } } + + /** + * 错误日志上下文对象 + */ + private static class ErrorLogContext { + private final String serialNumber; + private final String sourceData; + private final String errorMsg; + private final Integer logType; + private final String identity; + private final Long productId; + + public ErrorLogContext(String serialNumber, String sourceData, String errorMsg, + Integer logType, String identity, Long productId) { + this.serialNumber = serialNumber; + this.sourceData = sourceData; + this.errorMsg = errorMsg; + this.logType = logType; + this.identity = identity; + this.productId = productId; + } + + public String getSerialNumber() { + return serialNumber; + } + + public String getSourceData() { + return sourceData; + } + + public String getErrorMsg() { + return errorMsg; + } + + public Integer getLogType() { + return logType; + } + + public String getIdentity() { + return identity; + } + + public Long getProductId() { + return productId; + } + } } \ No newline at end of file diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceOtherMsgConsumer.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceOtherMsgConsumer.java index f75ad672..3e89525f 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceOtherMsgConsumer.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceOtherMsgConsumer.java @@ -21,12 +21,12 @@ public class DeviceOtherMsgConsumer { private DeviceOtherMsgHandler otherMsgHandler; @Async(FastBeeConstant.TASK.DEVICE_OTHER_TASK) - public void consume(DeviceReportBo bo){ + public void consume(DeviceReportBo bo) { try { - //处理emq订阅的非 property/post 属性上报的消息 ,因为其他消息量小,放在一起处理 + //处理emq订阅的非 property/post 属性上报的消息 ,因为其他消息量小,放在一起处理 otherMsgHandler.messageHandler(bo); - }catch (Exception e){ - log.error("=>设备其他消息处理出错",e); + } catch (Exception e) { + log.error("=>设备其他消息处理出错", e); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DevicePropFetchConsumer.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DevicePropFetchConsumer.java index a6d986a2..5011158b 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DevicePropFetchConsumer.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DevicePropFetchConsumer.java @@ -55,6 +55,8 @@ import java.util.stream.Collectors; public class DevicePropFetchConsumer { + //锁集合 + private final ConcurrentHashMap taskLocks = new ConcurrentHashMap<>(); @Autowired private PubMqttClient pubMqttClient; @Autowired @@ -71,11 +73,8 @@ public class DevicePropFetchConsumer { private ISessionStore sessionStore; @Resource private IModbusParamsService modbusParamsService; - @Value("${server.broker.enabled}") private Boolean enabled; - //锁集合 - private final ConcurrentHashMap taskLocks = new ConcurrentHashMap<>(); @Async(FastBeeConstant.TASK.DEVICE_FETCH_PROP_TASK) public void consume(ModbusPollJob job) { @@ -83,7 +82,7 @@ public class DevicePropFetchConsumer { DeviceJob deviceJob = job.getDeviceJob(); // type 1:手动下发 2:定时任务执行 ModbusPollMsg task = type == 1 ? job.getPollMsg() : getCommandList(deviceJob); - if (CollectionUtils.isEmpty(task.getCommandList()))return; + if (CollectionUtils.isEmpty(task.getCommandList())) return; String serialNumber = task.getSerialNumber(); //获取一个线程锁 Lock lock = taskLocks.computeIfAbsent(serialNumber, k -> new ReentrantLock()); @@ -132,21 +131,21 @@ public class DevicePropFetchConsumer { modbusJob.setJobId(jobId); modbusJob.setStatus("0"); List modbusJobList = modbusJobService.selectModbusJobList(modbusJob); - if (CollectionUtils.isEmpty(modbusJobList))return modbusPollMsg; + if (CollectionUtils.isEmpty(modbusJobList)) return modbusPollMsg; //处理子设备情况 handleSubDeviceStatus(modbusJobList); List commandList = modbusJobList.stream().map(ModbusJob::getCommand).collect(Collectors.toList()); - + // 检查是否有设备上电触发任务(cycleType=3) boolean hasPowerOnTrigger = modbusJobList.stream() .anyMatch(job -> job.getCycleType() != null && job.getCycleType() == 3); - + // modbus-tcp 重新处理事务标识符 String subSerialNumber = modbusJobList.get(0).getSubSerialNumber(); String tcpKey = RedisKeyBuilder.buildModbusTcpCacheKey(subSerialNumber); String tcpObject = redisCache.getStrCacheObject(tcpKey); List tcpCommandList = new ArrayList<>(); - + // 如果是设备上电触发任务(cycleType=3),跳过事务ID处理,直接使用原始指令 if (hasPowerOnTrigger) { log.info("检测到设备上电触发任务(cycleType=3),跳过事务ID处理,使用原始指令"); @@ -179,8 +178,8 @@ public class DevicePropFetchConsumer { DeviceStatusVO deviceStatusVO = deviceService.selectDeviceStatusAndTransportStatus(modbusPollMsg.getSerialNumber()); modbusPollMsg.setTransport(deviceStatusVO.getTransport()); Session session = sessionStore.getSession(modbusPollMsg.getSerialNumber()); - if (enabled && Objects.isNull(session)){ - log.info("设备:[{}],不在线",modbusPollMsg.getSerialNumber()); + if (enabled && Objects.isNull(session)) { + log.info("设备:[{}],不在线", modbusPollMsg.getSerialNumber()); return modbusPollMsg; } log.info("执行modbus轮询指令:[{}]", JSON.toJSONString(commandList)); @@ -190,30 +189,30 @@ public class DevicePropFetchConsumer { /** * 处理子设备根据设备数据定时更新状态 */ - public void handleSubDeviceStatus(List modbusJobList){ + public void handleSubDeviceStatus(List modbusJobList) { for (ModbusJob modbusJob : modbusJobList) { String subSerialNumber = modbusJob.getSubSerialNumber(); Session session = sessionStore.getSession(subSerialNumber); - if (Objects.isNull(session))continue; + if (Objects.isNull(session)) continue; //如果是网关子设备,则检测子设备是否在特定时间内有数据上报 - if (modbusJob.getDeviceType() == DeviceType.SUB_GATEWAY.getCode()){ + if (modbusJob.getDeviceType() == DeviceType.SUB_GATEWAY.getCode()) { long deterTime = 300L; //这里默认使用5分钟,如果轮询时间大于5分钟,请在配置参数设置更长时间 ModbusParams params = modbusParamsService.getModbusParamsByDeviceId(modbusJob.getSubDeviceId()); - if (!Objects.isNull(params)){ + if (!Objects.isNull(params)) { deterTime = Long.parseLong(params.getDeterTimer()); } long lastAccessTime = session.getLastAccessTime(); //如果现在的时间 - 最后访问时间 > 判断时间则更新为离线 long time = (System.currentTimeMillis() - lastAccessTime - 20) / 1000; - if (time > deterTime){ + if (time > deterTime) { //处理设备离线 DeviceStatusBo statusBo = DeviceStatusBo.builder().status(DeviceStatus.OFFLINE) .serialNumber(subSerialNumber) .timestamp(DateUtils.getNowDate()).build(); MessageProducer.sendStatusMsg(statusBo); sessionStore.cleanSession(subSerialNumber); - log.info("设备[{}],超过:[{}],未上报数据,更新为离线",subSerialNumber,deterTime); + log.info("设备[{}],超过:[{}],未上报数据,更新为离线", subSerialNumber, deterTime); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceStatusConsumer.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceStatusConsumer.java index 2a824898..b465291d 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceStatusConsumer.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceStatusConsumer.java @@ -63,7 +63,7 @@ public class DeviceStatusConsumer { try { List list = new ArrayList<>(); List subDeviceList = subGatewayService.getSubDeviceListByGw(bo.getSerialNumber()); - if (!CollectionUtils.isEmpty(subDeviceList) && bo.getStatus()== DeviceStatus.OFFLINE){ + if (!CollectionUtils.isEmpty(subDeviceList) && bo.getStatus() == DeviceStatus.OFFLINE) { for (SubDeviceBo subDeviceBo : subDeviceList) { DeviceStatusBo deviceStatusBo = new DeviceStatusBo(); BeanUtils.copyProperties(bo, deviceStatusBo); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceTestConsumer.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceTestConsumer.java index 5bb57df9..150423bb 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceTestConsumer.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/consumer/DeviceTestConsumer.java @@ -20,12 +20,12 @@ public class DeviceTestConsumer { private IDeviceTestService testHandler; @Async(FastBeeConstant.TASK.DEVICE_TEST_TASK) - public void consume(DeviceTestReportBo bo){ + public void consume(DeviceTestReportBo bo) { try { //处理emq订阅的非 property/post 属性上报的消息 ,因为其他消息量小,放在一起处理 testHandler.messageHandler(bo); - }catch (Exception e){ - log.error("=>设备其他消息处理出错",e); + } catch (Exception e) { + log.error("=>设备其他消息处理出错", e); } } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/emq/subscribeCallback.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/emq/subscribeCallback.java index 047969c5..a7079a9a 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/emq/subscribeCallback.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/emq/subscribeCallback.java @@ -64,6 +64,6 @@ public class subscribeCallback implements IMqttMessageListener { .serverType(ServerType.MQTT) .build(); /*将mqtt的消息发送至MQ队列处理消息 ,减轻mqtt客户端消息压力*/ - emqxMessageSerice.sendEmqxMessage(name,reportBo); + emqxMessageSerice.sendEmqxMessage(name, reportBo); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceAbstractQuartzJob.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceAbstractQuartzJob.java index 63aca795..51fedb2e 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceAbstractQuartzJob.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceAbstractQuartzJob.java @@ -4,12 +4,12 @@ import com.fastbee.common.constant.Constants; import com.fastbee.common.constant.ScheduleConstants; import com.fastbee.common.utils.ExceptionUtil; import com.fastbee.common.utils.StringUtils; +import com.fastbee.common.utils.TraceIdUtils; import com.fastbee.common.utils.bean.BeanUtils; import com.fastbee.common.utils.spring.SpringUtils; import com.fastbee.iot.domain.DeviceJob; import com.fastbee.quartz.domain.SysJobLog; import com.fastbee.quartz.service.ISysJobLogService; -import com.fastbee.common.utils.TraceIdUtils; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; @@ -23,8 +23,7 @@ import java.util.Date; * * @author ruoyi */ -public abstract class DeviceAbstractQuartzJob implements Job -{ +public abstract class DeviceAbstractQuartzJob implements Job { private static final Logger log = LoggerFactory.getLogger(DeviceAbstractQuartzJob.class); /** @@ -33,21 +32,16 @@ public abstract class DeviceAbstractQuartzJob implements Job private static ThreadLocal threadLocal = new ThreadLocal<>(); @Override - public void execute(JobExecutionContext context) throws JobExecutionException - { + public void execute(JobExecutionContext context) throws JobExecutionException { DeviceJob deviceJob = new DeviceJob(); BeanUtils.copyBeanProp(deviceJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); - try - { + try { before(context, deviceJob); - if (deviceJob != null) - { + if (deviceJob != null) { doExecute(context, deviceJob); } after(context, deviceJob, null); - } - catch (Exception e) - { + } catch (Exception e) { log.error("任务执行异常 - :", e); after(context, deviceJob, e); } @@ -56,44 +50,42 @@ public abstract class DeviceAbstractQuartzJob implements Job /** * 执行前 * - * @param context 工作执行上下文对象 + * @param context 工作执行上下文对象 * @param deviceJob 系统计划任务 */ - protected void before(JobExecutionContext context, DeviceJob deviceJob) - { + protected void before(JobExecutionContext context, DeviceJob deviceJob) { threadLocal.set(new Date()); - + // 为设备定时任务生成TraceId,使用统一的生成逻辑 TraceIdUtils.generateTraceId(); - + log.info("设备定时任务开始执行: {} - {}", deviceJob.getJobName(), deviceJob.getJobGroup()); } /** * 执行后 * - * @param context 工作执行上下文对象 + * @param context 工作执行上下文对象 * @param deviceJob 系统计划任务 */ - protected void after(JobExecutionContext context, DeviceJob deviceJob, Exception e) - { + protected void after(JobExecutionContext context, DeviceJob deviceJob, Exception e) { Date startTime = threadLocal.get(); threadLocal.remove(); final SysJobLog sysJobLog = new SysJobLog(); sysJobLog.setJobName(deviceJob.getJobName()); sysJobLog.setJobGroup(deviceJob.getJobGroup()); - + // 设置 invokeTarget,确保不为空(数据库字段是 NOT NULL) String invokeTarget = deviceJob.getDeviceName(); if (StringUtils.isEmpty(invokeTarget)) { // 如果设备名称为空,使用设备编号或任务名称作为默认值 - invokeTarget = StringUtils.isNotEmpty(deviceJob.getSerialNumber()) - ? deviceJob.getSerialNumber() - : deviceJob.getJobName(); + invokeTarget = StringUtils.isNotEmpty(deviceJob.getSerialNumber()) + ? deviceJob.getSerialNumber() + : deviceJob.getJobName(); } sysJobLog.setInvokeTarget(invokeTarget); - + // 确保 startTime 不为 null if (startTime == null) { startTime = new Date(); @@ -103,30 +95,27 @@ public abstract class DeviceAbstractQuartzJob implements Job sysJobLog.setStopTime(stopTime); long runMs = stopTime.getTime() - startTime.getTime(); sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); - if (e != null) - { + if (e != null) { sysJobLog.setStatus(Constants.FAIL); String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); sysJobLog.setExceptionInfo(errorMsg); - } - else - { + } else { sysJobLog.setStatus(Constants.SUCCESS); } // 写入数据库当中 SpringUtils.getBean(ISysJobLogService.class).addJobLog(sysJobLog); - + // 清除TraceId,避免内存泄漏 TraceIdUtils.clearTraceId(); - + log.info("设备定时任务执行完成: {} - {}, 耗时: {}ms", deviceJob.getJobName(), deviceJob.getJobGroup(), runMs); } /** * 执行方法,由子类重载 * - * @param context 工作执行上下文对象 + * @param context 工作执行上下文对象 * @param deviceJob 系统计划任务 * @throws Exception 执行过程中的异常 */ diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceDisallowConcurrentExecution.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceDisallowConcurrentExecution.java index f88aa462..83397cdb 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceDisallowConcurrentExecution.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceDisallowConcurrentExecution.java @@ -8,14 +8,11 @@ import org.quartz.JobExecutionContext; * 定时任务处理(禁止并发执行) * * @author ruoyi - * */ @DisallowConcurrentExecution -public class DeviceDisallowConcurrentExecution extends DeviceAbstractQuartzJob -{ +public class DeviceDisallowConcurrentExecution extends DeviceAbstractQuartzJob { @Override - protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception - { + protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception { DeviceJobInvoke.invokeMethod(deviceJob); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobExecution.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobExecution.java index cc8ad35f..3962bef8 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobExecution.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobExecution.java @@ -7,13 +7,10 @@ import org.quartz.JobExecutionContext; * 定时任务处理(允许并发执行) * * @author ruoyi - * */ -public class DeviceJobExecution extends DeviceAbstractQuartzJob -{ +public class DeviceJobExecution extends DeviceAbstractQuartzJob { @Override - protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception - { + protected void doExecute(JobExecutionContext context, DeviceJob deviceJob) throws Exception { DeviceJobInvoke.invokeMethod(deviceJob); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobInvoke.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobInvoke.java index d6649562..eab87456 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobInvoke.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceJobInvoke.java @@ -36,6 +36,7 @@ public class DeviceJobInvoke { private static FlowLogExecutor flowExecutor = SpringUtils.getBean(FlowLogExecutor.class); private static IDataHandler dataHandler = SpringUtils.getBean(IDataHandler.class); + /** * 执行方法 * diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceScheduleUtils.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceScheduleUtils.java index 95ba3778..5d3de40c 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceScheduleUtils.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/DeviceScheduleUtils.java @@ -10,18 +10,15 @@ import org.quartz.*; * 定时任务工具类 * * @author ruoyi - * */ -public class DeviceScheduleUtils -{ +public class DeviceScheduleUtils { /** * 得到quartz任务类 * * @param deviceJob 执行计划 * @return 具体执行任务类 */ - private static Class getQuartzJobClass(DeviceJob deviceJob) - { + private static Class getQuartzJobClass(DeviceJob deviceJob) { boolean isConcurrent = "0".equals(deviceJob.getConcurrent()); return isConcurrent ? DeviceJobExecution.class : DeviceDisallowConcurrentExecution.class; } @@ -29,24 +26,21 @@ public class DeviceScheduleUtils /** * 构建任务触发对象 */ - public static TriggerKey getTriggerKey(Long jobId, String jobGroup) - { + public static TriggerKey getTriggerKey(Long jobId, String jobGroup) { return TriggerKey.triggerKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); } /** * 构建任务键对象 */ - public static JobKey getJobKey(Long jobId, String jobGroup) - { + public static JobKey getJobKey(Long jobId, String jobGroup) { return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); } /** * 创建定时任务 */ - public static void createScheduleJob(Scheduler scheduler, DeviceJob job) throws SchedulerException, TaskException - { + public static void createScheduleJob(Scheduler scheduler, DeviceJob job) throws SchedulerException, TaskException { Class jobClass = getQuartzJobClass(job); // 1.创建任务 Long jobId = job.getJobId(); @@ -65,8 +59,7 @@ public class DeviceScheduleUtils jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); // 判断是否存在 - if (scheduler.checkExists(getJobKey(jobId, jobGroup))) - { + if (scheduler.checkExists(getJobKey(jobId, jobGroup))) { // 防止创建时存在数据问题 先移除,然后在执行创建操作 scheduler.deleteJob(getJobKey(jobId, jobGroup)); } @@ -75,8 +68,7 @@ public class DeviceScheduleUtils scheduler.scheduleJob(jobDetail, trigger); // 暂停任务 - if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) - { + if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) { scheduler.pauseJob(DeviceScheduleUtils.getJobKey(jobId, jobGroup)); } } @@ -85,10 +77,8 @@ public class DeviceScheduleUtils * 设置定时任务策略 */ public static CronScheduleBuilder handleCronScheduleMisfirePolicy(DeviceJob job, CronScheduleBuilder cb) - throws TaskException - { - switch (job.getMisfirePolicy()) - { + throws TaskException { + switch (job.getMisfirePolicy()) { case ScheduleConstants.MISFIRE_DEFAULT: return cb; case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/SyncDeviceStatusJob.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/SyncDeviceStatusJob.java index f90e5d61..06474af9 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/SyncDeviceStatusJob.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/job/SyncDeviceStatusJob.java @@ -17,6 +17,7 @@ import java.util.Objects; /** * 定时同步设备状态 -- netty版本mqtt使用 + * * @author gsb * @date 2024/4/11 10:33 */ @@ -32,8 +33,8 @@ public class SyncDeviceStatusJob { /** * 定期同步设备状态 - * 1.将异常在线设备变更为离线状态 - * 2.将离线设备但实际在线设备变更为在线 + * 1.将异常在线设备变更为离线状态 + * 2.将离线设备但实际在线设备变更为在线 */ public void syncDeviceStatus() { if (enabled) { diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceOtherListen.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceOtherListen.java index 4c907caf..f352620a 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceOtherListen.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceOtherListen.java @@ -22,12 +22,12 @@ public class DeviceOtherListen { private DeviceOtherMsgConsumer otherMsgConsumer; @Async(FastBeeConstant.TASK.DEVICE_OTHER_TASK) - public void listen(){ - while (true){ + public void listen() { + while (true) { try { DeviceReportBo reportBo = DeviceOtherQueue.take(); otherMsgConsumer.consume(reportBo); - }catch (Exception e){ + } catch (Exception e) { log.error("=>emq数据转发异常"); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceStatusListen.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceStatusListen.java index 0c187b25..d67f8239 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceStatusListen.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceStatusListen.java @@ -11,6 +11,7 @@ import org.springframework.stereotype.Component; /** * 设备状态监听 + * * @author bill */ @Slf4j diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceTestListen.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceTestListen.java index 52a4c8cb..91147170 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceTestListen.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/DeviceTestListen.java @@ -21,13 +21,13 @@ public class DeviceTestListen { private DeviceTestConsumer deviceTestConsumer; @Async(FastBeeConstant.TASK.DEVICE_TEST_TASK) - public void listen(){ - while (true){ + public void listen() { + while (true) { try { DeviceTestReportBo take = DeviceTestQueue.take(); deviceTestConsumer.consume(take); - }catch (Exception e){ + } catch (Exception e) { log.error("=>emq数据转发异常"); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/UpGradeListener.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/UpGradeListener.java index e78b1324..e0392944 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/UpGradeListener.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/listen/UpGradeListener.java @@ -22,6 +22,7 @@ import java.util.Date; /** * OTA升级监听 + * * @author bill */ @Slf4j @@ -41,18 +42,18 @@ public class UpGradeListener implements ApplicationRunner { @Async(FastBeeConstant.TASK.DELAY_UPGRADE_TASK) - public void listen(){ - while (true){ + public void listen() { + while (true) { try { OtaUpgradeDelayTask task = DelayUpgradeQueue.task(); - if (StringUtils.isNotNull(task)){ + if (StringUtils.isNotNull(task)) { Date startTime = task.getStartTime(); otaUpgradeService.upgrade(task); - log.info("=>开始OTA升级时间{}",startTime); + log.info("=>开始OTA升级时间{}", startTime); } continue; - }catch (Exception e){ - log.error("=>OTA升级监听异常",e); + } catch (Exception e) { + log.error("=>OTA升级监听异常", e); } } } @@ -68,14 +69,14 @@ public class UpGradeListener implements ApplicationRunner { /** * 切换菜单中Emqx控制台和netty管理 */ - public void updateMenu(){ + public void updateMenu() { SysMenu sysMenu = new SysMenu(); - if (enabled){ + if (enabled) { sysMenu.setMenuId(2104L); sysMenu.setVisible("1"); menuService.updateMenu(sysMenu); sysMenu.setMenuId(3031L); - }else { + } else { sysMenu.setMenuId(3031L); sysMenu.setVisible("1"); menuService.updateMenu(sysMenu); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/ruleEngine/SceneContext.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/ruleEngine/SceneContext.java index 44002bd2..394925ae 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/ruleEngine/SceneContext.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/ruleEngine/SceneContext.java @@ -45,52 +45,37 @@ import static java.util.regex.Pattern.compile; @Slf4j public class SceneContext { private static Logger scene_logger = LoggerFactory.getLogger("scene"); + private static IFunctionInvoke functionInvoke = SpringUtils.getBean(IFunctionInvoke.class); + private static IDeviceService deviceService = SpringUtils.getBean(IDeviceService.class); + private static IAlertService alertService = SpringUtils.getBean(IAlertService.class); + private static NotifySendService notifySendService = SpringUtils.getBean(NotifySendService.class); + private static RedisCache redisCache = SpringUtils.getBean(RedisCache.class); + private static IAlertLogService alertLogService = SpringUtils.getBean(IAlertLogService.class); + private static IDeviceUserService deviceUserService = SpringUtils.getBean(IDeviceUserService.class); + private static ISceneService sceneService = SpringUtils.getBean(ISceneService.class); + private static IRuleEngine ruleService = SpringUtils.getBean(IRuleEngine.class); + private static IDeviceAlertUserService deviceAlertUserService = SpringUtils.getBean(IDeviceAlertUserService.class); /** * 上报信息的设备编号 */ private String deviceNum; - /** * 上报信息的设备所属产品ID */ private Long productId; - /** * 上报信息的设备信息类型 1=属性, 2=功能,3=事件,4=设备升级,5=设备上线,6=设备下线 */ private int type; - /** * 上报的物模型集合 */ private List thingsModelSimpleItems; - /** * 触发成功的物模型集合,保留给告警记录 */ private List sceneThingsModelItems; - - private static IFunctionInvoke functionInvoke = SpringUtils.getBean(IFunctionInvoke.class); - - private static IDeviceService deviceService = SpringUtils.getBean(IDeviceService.class); - - private static IAlertService alertService = SpringUtils.getBean(IAlertService.class); - - private static NotifySendService notifySendService = SpringUtils.getBean(NotifySendService.class); - - private static RedisCache redisCache = SpringUtils.getBean(RedisCache.class); - - private static IAlertLogService alertLogService = SpringUtils.getBean(IAlertLogService.class); - - private static IDeviceUserService deviceUserService = SpringUtils.getBean(IDeviceUserService.class); - - private static ISceneService sceneService = SpringUtils.getBean(ISceneService.class); - - private static IRuleEngine ruleService = SpringUtils.getBean(IRuleEngine.class); - - private static IDeviceAlertUserService deviceAlertUserService = SpringUtils.getBean(IDeviceAlertUserService.class); - public SceneContext(String deviceNum, Long productId, int type, List thingsModelSimpleItems) { this.deviceNum = deviceNum; this.productId = productId; diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDataHandler.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDataHandler.java index d62875eb..a648e3b1 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDataHandler.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDataHandler.java @@ -5,6 +5,7 @@ import com.fastbee.common.core.mq.message.ReportDataBo; /** * 客户端上报数据处理方法集合 + * * @author bill */ public interface IDataHandler { @@ -26,12 +27,14 @@ public interface IDataHandler { /** * 上报设备信息 + * * @param bo 上报数据模型 */ public void reportDevice(ReportDataBo bo); /** * 计算场景变量的值 + * * @param id 主键id * @return java.lang.String */ @@ -39,6 +42,7 @@ public interface IDataHandler { /** * 场景变量指令下发 + * * @param reqDto 下发类 * @return void */ diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceMessageService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceMessageService.java index dc5bed95..883f74a9 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceMessageService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceMessageService.java @@ -21,6 +21,7 @@ public interface IDeviceMessageService { /** * 变量读取 + * * @param readVO */ public void readVariableValue(VariableReadVO readVO); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceReportMessageService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceReportMessageService.java index 707d233a..63029181 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceReportMessageService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IDeviceReportMessageService.java @@ -6,6 +6,7 @@ import com.fastbee.protocol.base.protocol.IProtocol; /** * 处理设备上报数据解析 + * * @author gsb * @date 2022/10/10 13:48 */ @@ -13,18 +14,21 @@ public interface IDeviceReportMessageService { /** * 处理设备主动上报数据 + * * @param bo */ public void parseReportMsg(DeviceReportBo bo); /** * 处理设备普通消息回调 + * * @param bo */ public void parseReplyMsg(DeviceReportBo bo); /** * 处理设备OTA升级 + * * @param bo */ public void parseOTAUpdateReply(DeviceReportBo bo); @@ -32,6 +36,7 @@ public interface IDeviceReportMessageService { /** * 构建消息 + * * @param bo */ public DeviceStatusVO buildReport(DeviceReportBo bo); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskDetailService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskDetailService.java index 8886dfa8..e787ab3a 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskDetailService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskDetailService.java @@ -15,8 +15,7 @@ import java.util.List; * @author kerwincui * @date 2024-08-18 */ -public interface IFirmwareTaskDetailService extends IService -{ +public interface IFirmwareTaskDetailService extends IService { /** * 查询固件升级任务详细对象列表 @@ -29,6 +28,7 @@ public interface IFirmwareTaskDetailService extends IService /** * 查询固件升级任务详细 + * * @param taskId * @param serialNumber * @return @@ -36,9 +36,9 @@ public interface IFirmwareTaskDetailService extends IService public FirmwareTaskDetail selectFirmwareTaskDetailByTaskIdAndSerialNumber(Long taskId, String serialNumber); - /** * 更新升级状态 + * * @param taskId * @param serialNumber * @param otaUpgrade diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskService.java index 0cc10d36..26faa7e5 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFirmwareTaskService.java @@ -13,8 +13,7 @@ import java.util.List; * @author kerwincui * @date 2024-08-18 */ -public interface IFirmwareTaskService extends IService -{ +public interface IFirmwareTaskService extends IService { /** * 查询固件升级任务对象列表 @@ -35,6 +34,7 @@ public interface IFirmwareTaskService extends IService /** * OTA升级 + * * @param task */ void upgrade(OtaUpgradeDelayTask task); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFunctionInvoke.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFunctionInvoke.java index 36b89ddf..e390f864 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFunctionInvoke.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IFunctionInvoke.java @@ -5,6 +5,7 @@ import com.fastbee.common.core.mq.InvokeReqDto; /** * 设备指令下发接口 + * * @author gsb * @date 2022/12/5 11:03 */ @@ -12,6 +13,7 @@ public interface IFunctionInvoke { /** * 服务调用,等待设备响应 + * * @param reqDto 服务下发对象 * @return 数据结果 */ @@ -19,6 +21,7 @@ public interface IFunctionInvoke { /** * 服务调用,设备不响应 + * * @param reqDto 服务下发对象 * @return 消息id messageId */ diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMessagePublishService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMessagePublishService.java index 0b055c7b..5f5e55b9 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMessagePublishService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMessagePublishService.java @@ -2,6 +2,7 @@ package com.fastbee.iot.data.service; /** * 设备消息推送mq + * * @author bill */ public interface IMessagePublishService { @@ -9,9 +10,10 @@ public interface IMessagePublishService { /** * 发布消息到mq + * * @param message 设备消息 * @param channel 推送channel */ - public void publish(Object message,String channel); + public void publish(Object message, String channel); } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMqttMessagePublish.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMqttMessagePublish.java index 2f29c85a..e7b3419a 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMqttMessagePublish.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IMqttMessagePublish.java @@ -66,7 +66,7 @@ public interface IMqttMessagePublish { * 推送设备状态 * * @param device 设备 - * @param status 状态 + * @param status 状态 */ public void pushDeviceStatus(Device device, DeviceStatus status); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaTaskUpgradeService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaTaskUpgradeService.java index e364baf0..b4b8e8e1 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaTaskUpgradeService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaTaskUpgradeService.java @@ -11,6 +11,7 @@ public interface IOtaTaskUpgradeService { /** * 固件升级异步方法 + * * @param taskId * @param serialNumber * @param firmware diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaUpgradeService.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaUpgradeService.java index 07fcd520..76db2a16 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaUpgradeService.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IOtaUpgradeService.java @@ -4,12 +4,14 @@ import com.fastbee.common.core.mq.ota.OtaUpgradeDelayTask; /** * OTA升级 + * * @author bill */ public interface IOtaUpgradeService { /** * OTA延迟升级任务发送 + * * @param task */ public void upgrade(OtaUpgradeDelayTask task); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IRuleEngine.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IRuleEngine.java index d9654e76..693ace72 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IRuleEngine.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/IRuleEngine.java @@ -6,6 +6,7 @@ import java.util.concurrent.ScheduledExecutorService; /** * 规则引擎处理数据方法集合 + * * @author bill */ public interface IRuleEngine { @@ -15,6 +16,8 @@ public interface IRuleEngine { * @param bo 上报数据模型 */ public void ruleMatch(ReportDataBo bo); + public void addCheckTask(String key, ScheduledExecutorService task); + public void removeCheckTask(String key); } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DataHandlerImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DataHandlerImpl.java index 023294e5..a08583cc 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DataHandlerImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DataHandlerImpl.java @@ -42,6 +42,7 @@ import java.util.*; /** * 上报数据处理方法集合 + * * @author bill */ @Service @@ -99,7 +100,7 @@ public class DataHandlerImpl implements IDataHandler { input.setSources(bo.getSources()); List result = deviceService.reportDeviceThingsModelValue(input, bo.getType(), bo.isShadow()); // 只有设备上报进入规则引擎流程 - if (bo.isRuleEngine() && !bo.getSerialNumber().startsWith("server-")){ + if (bo.isRuleEngine() && !bo.getSerialNumber().startsWith("server-")) { ruleEngine.ruleMatch(bo); } //发送至前端 @@ -107,11 +108,11 @@ public class DataHandlerImpl implements IDataHandler { messageBo.setTopic(topicsUtils.buildTopic(bo.getProductId(), bo.getSerialNumber(), TopicType.WS_SERVICE_INVOKE)); JSONObject pushObj = new JSONObject(); pushObj.put("message", result); - pushObj.put("sources",bo.getSources()); + pushObj.put("sources", bo.getSources()); messageBo.setMessage(JSON.toJSONString(pushObj)); remoteManager.pushCommon(messageBo); - if (!Objects.isNull(bo.getGwDeviceBo())){ - messageBo.setTopic(topicsUtils.buildTopic(bo.getGwDeviceBo().getProductId(),bo.getGwDeviceBo().getSerialNumber(),TopicType.WS_SERVICE_INVOKE)); + if (!Objects.isNull(bo.getGwDeviceBo())) { + messageBo.setTopic(topicsUtils.buildTopic(bo.getGwDeviceBo().getProductId(), bo.getGwDeviceBo().getSerialNumber(), TopicType.WS_SERVICE_INVOKE)); remoteManager.pushCommon(messageBo); } // 上报属性给小度音箱,接入小度音箱后可放开 @@ -122,7 +123,7 @@ public class DataHandlerImpl implements IDataHandler { // log.error("=>上报属性信息给小度音箱异常", e); // } } catch (Exception e) { - log.error("接收属性数据,解析数据时异常 message={}", e.getMessage(),e); + log.error("接收属性数据,解析数据时异常 message={}", e.getMessage(), e); } } @@ -160,7 +161,7 @@ public class DataHandlerImpl implements IDataHandler { //eventLogService.insertEventLog(event); } eventLogService.saveBatch(results); - if (bo.isRuleEngine()){ + if (bo.isRuleEngine()) { ruleEngine.ruleMatch(bo); } } catch (Exception e) { @@ -255,10 +256,11 @@ public class DataHandlerImpl implements IDataHandler { /** * 保存场景变量值 + * * @param sceneModelTag 变量类 + * @return void * @param: value 值 * @param: now 执行时间 - * @return void */ private void saveSceneModelTagValue(SceneModelTag sceneModelTag, String value, LocalDateTime now) { // 保存运算型变量值,存缓存 diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJob.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJob.java index 486d7dbd..c10a8e15 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJob.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJob.java @@ -68,9 +68,9 @@ public class DeviceJob { //更新iot设备状态 Device dev = deviceService.selectDeviceBySerialNumber(item.getDeviceSipId()); if (dev != null && dev.getStatus() == DeviceStatus.ONLINE.getType()) { - log.warn("定时任务:=>设备:{} 已经下线,设备超过{}秒没上线!",item.getDeviceSipId(),timeout); + log.warn("定时任务:=>设备:{} 已经下线,设备超过{}秒没上线!", item.getDeviceSipId(), timeout); dev.setStatus(DeviceStatus.OFFLINE.getType()); - deviceService.updateDeviceStatusAndLocation(dev,""); + deviceService.updateDeviceStatusAndLocation(dev, ""); DeviceStatusBo bo = DeviceStatusBo.builder() .serialNumber(dev.getSerialNumber()) .status(DeviceStatus.OFFLINE) diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJobServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJobServiceImpl.java index 1465aa68..08bc7e9e 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJobServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceJobServiceImpl.java @@ -29,8 +29,7 @@ import java.util.List; */ @Service @Slf4j -public class DeviceJobServiceImpl implements IDeviceJobService -{ +public class DeviceJobServiceImpl implements IDeviceJobService { @Autowired private Scheduler scheduler; @@ -45,13 +44,11 @@ public class DeviceJobServiceImpl implements IDeviceJobService * 项目启动时,初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据) */ @PostConstruct - public void init() throws SchedulerException, TaskException - { + public void init() throws SchedulerException, TaskException { scheduler.clear(); // 设备定时任务 List jobList = jobMapper.selectJobAll(); - for (DeviceJob deviceJob : jobList) - { + for (DeviceJob deviceJob : jobList) { // 跳过设备上电触发任务,它们不需要加入调度器 if (!isPowerOnTriggerTask(deviceJob) && StringUtils.isNotEmpty(deviceJob.getCronExpression())) { DeviceScheduleUtils.createScheduleJob(scheduler, deviceJob); @@ -60,8 +57,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService // 系统定时任务 List sysJobList = sysJobMapper.selectJobAll(); - for (SysJob job : sysJobList) - { + for (SysJob job : sysJobList) { com.fastbee.quartz.util.ScheduleUtils.createScheduleJob(scheduler, job); } } @@ -73,8 +69,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService * @return */ @Override - public List selectJobList(DeviceJob job) - { + public List selectJobList(DeviceJob job) { return jobMapper.selectJobList(job); } @@ -85,8 +80,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService * @return 调度任务对象信息 */ @Override - public DeviceJob selectJobById(Long jobId) - { + public DeviceJob selectJobById(Long jobId) { return jobMapper.selectJobById(jobId); } @@ -97,14 +91,12 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int pauseJob(DeviceJob job) throws SchedulerException - { + public int pauseJob(DeviceJob job) throws SchedulerException { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); int rows = jobMapper.updateJob(job); - if (rows > 0) - { + if (rows > 0) { scheduler.pauseJob(DeviceScheduleUtils.getJobKey(jobId, jobGroup)); } return rows; @@ -117,14 +109,12 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int resumeJob(DeviceJob job) throws SchedulerException - { + public int resumeJob(DeviceJob job) throws SchedulerException { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); job.setStatus(ScheduleConstants.Status.NORMAL.getValue()); int rows = jobMapper.updateJob(job); - if (rows > 0) - { + if (rows > 0) { scheduler.resumeJob(DeviceScheduleUtils.getJobKey(jobId, jobGroup)); } return rows; @@ -137,13 +127,11 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int deleteJob(DeviceJob job) throws SchedulerException - { + public int deleteJob(DeviceJob job) throws SchedulerException { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); int rows = jobMapper.deleteJobById(jobId); - if (rows > 0) - { + if (rows > 0) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(jobId, jobGroup)); } return rows; @@ -157,10 +145,8 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public void deleteJobByIds(Long[] jobIds) throws SchedulerException - { - for (Long jobId : jobIds) - { + public void deleteJobByIds(Long[] jobIds) throws SchedulerException { + for (Long jobId : jobIds) { DeviceJob job = jobMapper.selectJobById(jobId); deleteJob(job); } @@ -174,14 +160,13 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public void deleteJobByDeviceIds(Long[] deviceIds) throws SchedulerException - { + public void deleteJobByDeviceIds(Long[] deviceIds) throws SchedulerException { // 查出所有job - List deviceJobs=jobMapper.selectShortJobListByDeviceIds(deviceIds); + List deviceJobs = jobMapper.selectShortJobListByDeviceIds(deviceIds); // 批量删除job - int rows=jobMapper.deleteJobByDeviceIds(deviceIds); + int rows = jobMapper.deleteJobByDeviceIds(deviceIds); // 批量删除调度器 - for(DeviceJob job:deviceJobs){ + for (DeviceJob job : deviceJobs) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup())); } } @@ -194,14 +179,13 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public void deleteJobByAlertIds(Long[] alertIds) throws SchedulerException - { + public void deleteJobByAlertIds(Long[] alertIds) throws SchedulerException { // 查出所有job - List deviceJobs=jobMapper.selectShortJobListByAlertIds(alertIds); + List deviceJobs = jobMapper.selectShortJobListByAlertIds(alertIds); // 批量删除job - int rows=jobMapper.deleteJobByAlertIds(alertIds); + int rows = jobMapper.deleteJobByAlertIds(alertIds); // 批量删除调度器 - for(DeviceJob job:deviceJobs){ + for (DeviceJob job : deviceJobs) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup())); } } @@ -214,14 +198,13 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public void deleteJobBySceneIds(Long[] sceneIds) throws SchedulerException - { + public void deleteJobBySceneIds(Long[] sceneIds) throws SchedulerException { // 查出所有job - List deviceJobs=jobMapper.selectShortJobListBySceneIds(sceneIds); + List deviceJobs = jobMapper.selectShortJobListBySceneIds(sceneIds); // 批量删除job - int rows=jobMapper.deleteJobBySceneIds(sceneIds); + int rows = jobMapper.deleteJobBySceneIds(sceneIds); // 批量删除调度器 - for(DeviceJob job:deviceJobs){ + for (DeviceJob job : deviceJobs) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup())); } } @@ -233,16 +216,12 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int changeStatus(DeviceJob job) throws SchedulerException - { + public int changeStatus(DeviceJob job) throws SchedulerException { int rows = 0; String status = job.getStatus(); - if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) - { + if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) { rows = resumeJob(job); - } - else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) - { + } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) { rows = pauseJob(job); } return rows; @@ -255,8 +234,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public void run(DeviceJob job) throws SchedulerException - { + public void run(DeviceJob job) throws SchedulerException { Long jobId = job.getJobId(); String jobGroup = job.getJobGroup(); DeviceJob properties = selectJobById(job.getJobId()); @@ -273,8 +251,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int insertJob(DeviceJob deviceJob) throws SchedulerException, TaskException - { + public int insertJob(DeviceJob deviceJob) throws SchedulerException, TaskException { int rows = jobMapper.insertJob(deviceJob); if (rows > 0) { // 检查是否是设备上电触发任务(通过检查remark或cron表达式) @@ -289,6 +266,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService /** * 检查是否是设备上电触发任务 + * * @param deviceJob 设备任务 * @return true表示是设备上电触发任务 */ @@ -315,12 +293,10 @@ public class DeviceJobServiceImpl implements IDeviceJobService */ @Override @Transactional(rollbackFor = Exception.class) - public int updateJob(DeviceJob deviceJob) throws SchedulerException, TaskException - { + public int updateJob(DeviceJob deviceJob) throws SchedulerException, TaskException { DeviceJob properties = selectJobById(deviceJob.getJobId()); int rows = jobMapper.updateJob(deviceJob); - if (rows > 0) - { + if (rows > 0) { updateSchedulerJob(deviceJob, properties.getJobGroup()); } return rows; @@ -330,15 +306,13 @@ public class DeviceJobServiceImpl implements IDeviceJobService * 更新任务 * * @param deviceJob 任务对象 - * @param jobGroup 任务组名 + * @param jobGroup 任务组名 */ - public void updateSchedulerJob(DeviceJob deviceJob, String jobGroup) throws SchedulerException, TaskException - { + public void updateSchedulerJob(DeviceJob deviceJob, String jobGroup) throws SchedulerException, TaskException { Long jobId = deviceJob.getJobId(); // 判断是否存在 JobKey jobKey = DeviceScheduleUtils.getJobKey(jobId, jobGroup); - if (scheduler.checkExists(jobKey)) - { + if (scheduler.checkExists(jobKey)) { // 防止创建时存在数据问题 先移除,然后在执行创建操作 scheduler.deleteJob(jobKey); } @@ -356,8 +330,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService * @return 结果 */ @Override - public boolean checkCronExpressionIsValid(String cronExpression) - { + public boolean checkCronExpressionIsValid(String cronExpression) { return CronUtils.isValid(cronExpression); } @@ -374,7 +347,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService // 批量删除job int rows = jobMapper.deleteJobByJobTypeAndDatasourceIds(datasourceIds, jobType); // 批量删除调度器 - for(DeviceJob job:deviceJobs){ + for (DeviceJob job : deviceJobs) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup())); } } @@ -387,6 +360,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService /** * 根据条件批量删除定时任务 + * * @param deviceId * @param jobType */ @@ -401,7 +375,7 @@ public class DeviceJobServiceImpl implements IDeviceJobService // 批量删除job jobMapper.deleteJobByJobTypeAndDeviceId(deviceId, jobType); // 批量删除调度器 - for(DeviceJob job:deviceJobs){ + for (DeviceJob job : deviceJobs) { scheduler.deleteJob(DeviceScheduleUtils.getJobKey(job.getJobId(), job.getJobGroup())); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceMessageServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceMessageServiceImpl.java index dd54e026..7d75dd59 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceMessageServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceMessageServiceImpl.java @@ -87,12 +87,12 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService { DeviceAndProtocol deviceAndProtocol = deviceService.selectProtocolBySerialNumber(serialNumber); String transport = deviceAndProtocol.getTransport(); TopicType type = TopicType.getType(topicName); - topicName = topicsUtils.buildTopic(deviceAndProtocol.getProductId(), serialNumber,type); - switch (type){ + topicName = topicsUtils.buildTopic(deviceAndProtocol.getProductId(), serialNumber, type); + switch (type) { case FUNCTION_GET: - if (transport.equals(ServerType.MQTT.getCode())){ + if (transport.equals(ServerType.MQTT.getCode())) { mqttClient.publish(0, false, topicName, deviceMessage.getMessage().toString()); - }else if (transport.equals(ServerType.TCP.getCode())){ + } else if (transport.equals(ServerType.TCP.getCode())) { //处理TCP下发 ModbusPollMsg modbusPollMsg = new ModbusPollMsg(); modbusPollMsg.setSerialNumber(serialNumber); @@ -102,8 +102,8 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService { modbusPollMsg.setCommandList(commandList); DeviceStatusVO deviceStatusVO = deviceService.selectDeviceStatusAndTransportStatus(modbusPollMsg.getSerialNumber()); modbusPollMsg.setTransport(deviceStatusVO.getTransport()); - if (deviceStatusVO.getStatus() != DeviceStatus.ONLINE.getType()){ - log.info("设备:[{}],不在线",modbusPollMsg.getSerialNumber()); + if (deviceStatusVO.getStatus() != DeviceStatus.ONLINE.getType()) { + log.info("设备:[{}],不在线", modbusPollMsg.getSerialNumber()); return; } ModbusPollJob modbusPollJob = new ModbusPollJob(); @@ -149,13 +149,13 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService { out = modbusTcpEncoder.encode(modbusTcp); } else { //兼容15、16功能码 - if (modbusRtu.getCode() == ModbusCode.Write10.getCode()){ + if (modbusRtu.getCode() == ModbusCode.Write10.getCode()) { //计算:字节数=2*N;N为寄存器个数 modbusRtu.setBitCount(2 * modbusRtu.getCount()); - }else if (modbusRtu.getCode() == ModbusCode.Write0F.getCode()){ + } else if (modbusRtu.getCode() == ModbusCode.Write0F.getCode()) { //计算:字节数=N/8 余数为0是 N需要再+1。N是线圈个数 int i = modbusRtu.getCount() / 8; - if (modbusRtu.getCount() % 8!= 0){ + if (modbusRtu.getCount() % 8 != 0) { i++; } modbusRtu.setBitCount(i); @@ -192,31 +192,33 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService { /** * 变量读取 + * * @param readVO */ @Override - public void readVariableValue(VariableReadVO readVO){ + public void readVariableValue(VariableReadVO readVO) { String serialNumber = readVO.getSerialNumber(); assert !Objects.isNull(serialNumber) : "设备编号为空"; DeviceAndProtocol deviceAndProtocol = deviceService.selectProtocolBySerialNumber(serialNumber); if (!(deviceAndProtocol.getProtocolCode().equals(FastBeeConstant.PROTOCOL.ModbusRtu) || - deviceAndProtocol.getProtocolCode().equals(FastBeeConstant.PROTOCOL.ModbusTcp))) throw new ServiceException("非modbus协议请先配置主动采集协议"); + deviceAndProtocol.getProtocolCode().equals(FastBeeConstant.PROTOCOL.ModbusTcp))) + throw new ServiceException("非modbus协议请先配置主动采集协议"); Long productId = deviceAndProtocol.getProductId(); //如果是子设备,则获取网关子设备的产品id和设备编号 Integer deviceType = deviceAndProtocol.getDeviceType(); - if (deviceType == DeviceType.SUB_GATEWAY.getCode()){ + if (deviceType == DeviceType.SUB_GATEWAY.getCode()) { serialNumber = deviceAndProtocol.getGwSerialNumber(); productId = deviceAndProtocol.getGwProductId(); } Integer type = readVO.getType(); type = Objects.isNull(type) ? 1 : type; - if (type == 1){ + if (type == 1) { //单个变量获取 String identifier = readVO.getIdentifier(); ThingsModelValueItem thingModels = itslCache.getSingleThingModels(deviceAndProtocol.getProductId(), identifier); ModbusConfig config = thingModels.getConfig(); if (Objects.isNull(config)) throw new ServiceException("未配置modbus点位"); - thingModels.getConfig().setModbusCode(ModbusUtils.getReadModbusCode(config.getType(),config.getIsReadonly())); + thingModels.getConfig().setModbusCode(ModbusUtils.getReadModbusCode(config.getType(), config.getIsReadonly())); MQSendMessageBo messageBo = new MQSendMessageBo(); messageBo.setThingsModel(JSON.toJSONString(thingModels)); messageBo.setSerialNumber(readVO.getSerialNumber()); @@ -235,15 +237,15 @@ public class DeviceMessageServiceImpl implements IDeviceMessageService { modbusPollMsg.setCommandList(commandList); DeviceStatusVO deviceStatusVO = deviceService.selectDeviceStatusAndTransportStatus(modbusPollMsg.getSerialNumber()); modbusPollMsg.setTransport(deviceStatusVO.getTransport()); - if (deviceStatusVO.getStatus() != DeviceStatus.ONLINE.getType()){ - log.info("设备:[{}],不在线",modbusPollMsg.getSerialNumber()); + if (deviceStatusVO.getStatus() != DeviceStatus.ONLINE.getType()) { + log.info("设备:[{}],不在线", modbusPollMsg.getSerialNumber()); return; } ModbusPollJob job = new ModbusPollJob(); job.setPollMsg(modbusPollMsg); job.setType(1); MessageProducer.sendPropFetch(job); - }else { + } else { //读取当前设备的所有变量,这里读取所有的,判断传递的设备是网关设备、网关子设备、直连设备 DeviceType code = DeviceType.transfer(deviceType); List modbusJobList = modbusJobService.selectDevicesJobByDeviceType(code, readVO.getSerialNumber()); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceReportMessageServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceReportMessageServiceImpl.java index e34d38c8..d6d071bc 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceReportMessageServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceReportMessageServiceImpl.java @@ -22,14 +22,14 @@ import com.fastbee.iot.data.service.IDataHandler; import com.fastbee.iot.data.service.IDeviceReportMessageService; import com.fastbee.iot.data.service.IFirmwareTaskDetailService; import com.fastbee.iot.domain.FunctionLog; +import com.fastbee.iot.domain.Product; +import com.fastbee.iot.domain.ProductAuthorize; import com.fastbee.iot.enums.DeviceType; import com.fastbee.iot.model.DeviceStatusVO; import com.fastbee.iot.service.IDeviceService; import com.fastbee.iot.service.IFunctionLogService; -import com.fastbee.iot.service.IProductService; import com.fastbee.iot.service.IProductAuthorizeService; -import com.fastbee.iot.domain.ProductAuthorize; -import com.fastbee.iot.domain.Product; +import com.fastbee.iot.service.IProductService; import com.fastbee.mq.producer.MessageProducer; import com.fastbee.mqtt.manager.MqttRemoteManager; import com.fastbee.mqtt.model.PushMessageBo; @@ -108,7 +108,7 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi handlerDeviceReply(reportMessage); } serialNumber = reportMessage.getSerialNumber() == null ? serialNumber : reportMessage.getSerialNumber(); - productId = reportMessage.getProductId()== null ? productId : reportMessage.getProductId(); + productId = reportMessage.getProductId() == null ? productId : reportMessage.getProductId(); reportMessage.setSerialNumber(serialNumber); reportMessage.setProductId(productId); reportMessage.setPlatformDate(bo.getPlatformDate()); @@ -122,7 +122,7 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi log.debug("*MQ收到TCP推送消息[{}]", JSON.toJSON(bo.getThingsModelSimpleItem())); DeviceStatusVO deviceStatusVO1 = deviceService.selectDeviceStatusAndTransportStatus(serialNumber); Optional.ofNullable(deviceStatusVO1).orElseThrow(() -> new ServiceException("设备不存在")); - + // TCP协议授权码校验 productId = deviceStatusVO1.getProductId(); Product product = productService.selectProductByProductId(productId); @@ -138,7 +138,7 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi } log.debug("TCP数据上报-授权码校验通过: 设备[{}]已绑定授权码", serialNumber); } - + //同步设备状态 this.synchDeviceStatus(serialNumber); DeviceReport deviceReport = new DeviceReport(); @@ -157,7 +157,6 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi } - /** * 处理设备回调数据 */ @@ -199,9 +198,9 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi return; } int size = 256; - if ((int)data[0] == 1) { + if ((int) data[0] == 1) { size = 512; - } else if ((int)data[0] == 2) { + } else if ((int) data[0] == 2) { size = 1024; } otaTaskCache.setOtaCacheValue(bo.getSerialNumber(), "packageSize", String.valueOf(size), 5); @@ -299,6 +298,7 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi /** * 处理设备回调信息,此处按照topic区分 prop上报和设备回调reply, * 如果模组可订阅的topic有限,不能区分prop上报和reply,自行根据上报数据来区分 + * * @param message */ public void handlerDeviceReply(DeviceReport message) { @@ -310,13 +310,13 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi //从redis中获取messageId 流水号,获取下发记录 for (String fun : functionList) { String[] split = fun.split(":"); - if (split[0].equals(sources)){ + if (split[0].equals(sources)) { messageId = split[1]; } - redisCache.zRem(cacheKey,fun); + redisCache.zRem(cacheKey, fun); } FunctionLog functionLog = new FunctionLog(); - switch (message.getProtocolCode()){ + switch (message.getProtocolCode()) { case FastBeeConstant.PROTOCOL.ModbusRtu: case FastBeeConstant.PROTOCOL.ModbusToJsonHP: case FastBeeConstant.PROTOCOL.ModbusRtuPak: @@ -340,13 +340,14 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi /** * 同步设备状态 + * * @param */ - private void synchDeviceStatus(String serialNumber){ + private void synchDeviceStatus(String serialNumber) { //如果有数据上报,但是数据库设备状态为离线,则进行同步 DeviceStatusVO deviceStatusVO = deviceService.selectDeviceStatusAndTransportStatus(serialNumber); if (deviceStatusVO.getStatus() == DeviceStatus.OFFLINE.getType() - || deviceStatusVO.getStatus() == DeviceStatus.UNACTIVATED.getType()){ + || deviceStatusVO.getStatus() == DeviceStatus.UNACTIVATED.getType()) { DeviceStatusBo statusBo = new DeviceStatusBo(); statusBo.setStatus(DeviceStatus.ONLINE); statusBo.setSerialNumber(deviceStatusVO.getSerialNumber()); @@ -362,11 +363,11 @@ public class DeviceReportMessageServiceImpl implements IDeviceReportMessageServi session.setConnected(true); sessionStore.storeSession(deviceStatusVO.getSerialNumber(), session); } - }else if (deviceStatusVO.getStatus() == DeviceStatus.ONLINE.getType() ){ - if (deviceStatusVO.getDeviceType() == DeviceType.SUB_GATEWAY.getCode()){ + } else if (deviceStatusVO.getStatus() == DeviceStatus.ONLINE.getType()) { + if (deviceStatusVO.getDeviceType() == DeviceType.SUB_GATEWAY.getCode()) { //如果是在线,则更新session在线时间 Session session = sessionStore.getSession(deviceStatusVO.getSerialNumber()); - if (session!= null) { + if (session != null) { session.setLastAccessTime(DateUtils.getTimestamp()); sessionStore.storeSession(deviceStatusVO.getSerialNumber(), session); } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceTestHandler.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceTestHandler.java index cc85bcc0..7f0038fd 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceTestHandler.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/DeviceTestHandler.java @@ -34,10 +34,11 @@ public class DeviceTestHandler implements IDeviceTestService { /** * 处理数据调试信息 + * * @param testReportBo */ @Override - public void messageHandler(DeviceTestReportBo testReportBo){ + public void messageHandler(DeviceTestReportBo testReportBo) { boolean isReply = testReportBo.getIsReply(); Long productId = testReportBo.getProductId(); String serialNumber = testReportBo.getSerialNumber(); @@ -49,7 +50,7 @@ public class DeviceTestHandler implements IDeviceTestService { } else { deviceMessage.setTopicName(TopicType.PROPERTY_POST.getTopicSuffix()); } - if (Objects.isNull(productId)){ + if (Objects.isNull(productId)) { DeviceAndProtocol protocol = deviceService.selectProtocolBySerialNumber(serialNumber); productId = protocol.getProductId(); } @@ -58,7 +59,7 @@ public class DeviceTestHandler implements IDeviceTestService { messageBo.setTopic(topicsUtils.buildTopic(productId, serialNumber.toUpperCase(), TopicType.WS_SERVICE_INVOKE)); JSONObject pushObj = new JSONObject(); pushObj.put("message", testReportBo.getThingsModelSimpleItem()); - pushObj.put("sources",testReportBo.getSources()); + pushObj.put("sources", testReportBo.getSources()); messageBo.setMessage(JSON.toJSONString(pushObj)); mqttRemoteManager.pushCommon(messageBo); } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/FirmwareTaskDetailServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/FirmwareTaskDetailServiceImpl.java index c62b5453..0c991f7c 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/FirmwareTaskDetailServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/FirmwareTaskDetailServiceImpl.java @@ -28,7 +28,7 @@ import java.util.Objects; * @date 2024-08-18 */ @Service -public class FirmwareTaskDetailServiceImpl extends ServiceImpl implements IFirmwareTaskDetailService { +public class FirmwareTaskDetailServiceImpl extends ServiceImpl implements IFirmwareTaskDetailService { @Resource private FirmwareTaskDetailMapper firmwareTaskDetailMapper; @@ -66,19 +66,21 @@ public class FirmwareTaskDetailServiceImpl extends ServiceImpl wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(FirmwareTaskDetail::getId,taskId); - wrapper.eq(FirmwareTaskDetail::getSerialNumber,serialNumber); + wrapper.eq(FirmwareTaskDetail::getId, taskId); + wrapper.eq(FirmwareTaskDetail::getSerialNumber, serialNumber); return baseMapper.selectOne(wrapper); } /** * 更新升级状态 + * * @param taskId * @param serialNumber * @param otaUpgrade @@ -97,6 +99,7 @@ public class FirmwareTaskDetailServiceImpl extends ServiceImpl implements IFirmwareTaskService { +public class FirmwareTaskServiceImpl extends ServiceImpl implements IFirmwareTaskService { @Resource private FirmwareTaskMapper firmwareTaskMapper; @@ -47,7 +47,6 @@ public class FirmwareTaskServiceImpl extends ServiceImpl0){ - throw new ServiceException("任务:" + firmwareTaskInput.getTaskName() +"已存在"); + if (count > 0) { + throw new ServiceException("任务:" + firmwareTaskInput.getTaskName() + "已存在"); } List deviceList; if (1 == firmwareTaskInput.getUpgradeType()) { @@ -101,7 +99,7 @@ public class FirmwareTaskServiceImpl extends ServiceImpl 0){ + if (taskId > 0) { OtaUpgradeDelayTask otaTask = new OtaUpgradeDelayTask(); otaTask.setTaskId(taskId); otaTask.setFirmwareId(firmwareTaskInput.getFirmwareId()); @@ -132,13 +130,14 @@ public class FirmwareTaskServiceImpl extends ServiceImpl下发指令请求:[{}]",reqDto); + public AjaxResult invokeNoReply(InvokeReqDto reqDto) { + log.debug("=>下发指令请求:[{}]", reqDto); if (null != reqDto.getSceneModelId() && null != reqDto.getVariableType() && !SceneModelVariableTypeEnum.THINGS_MODEL.getType().equals(reqDto.getVariableType())) { String messageId = snowflakeIdWorker.nextId() + ""; dataHandler.invokeSceneModelTagValue(reqDto, messageId); @@ -70,10 +72,10 @@ public class FunctionInvokeImpl implements IFunctionInvoke { return AjaxResult.error("设备编号不能为空"); } MQSendMessageBo bo = new MQSendMessageBo(); - BeanUtils.copyBeanProp(bo,reqDto); + BeanUtils.copyBeanProp(bo, reqDto); long id = snowflakeIdWorker.nextId(); - String messageId = id+""; - bo.setMessageId(messageId+""); + String messageId = id + ""; + bo.setMessageId(messageId + ""); bo.setUserId(reqDto.getUserId()); bo.setIsShadow("true".equals(reqDto.getIsShadow())); MessageProducer.sendFunctionInvoke(bo); @@ -82,6 +84,7 @@ public class FunctionInvokeImpl implements IFunctionInvoke { /** * 轮询5S拿返回值 + * * @param messageId 消息id * @return 回调对象 */ @@ -107,9 +110,10 @@ public class FunctionInvokeImpl implements IFunctionInvoke { /** * 更新设备下发指令,当设备超时未回复情况 + * * @param messageId */ - private void updateFunctionLog(String messageId){ + private void updateFunctionLog(String messageId) { FunctionLog functionLog = new FunctionLog(); functionLog.setResultCode(FunctionReplyStatus.UNKNOWN.getCode()); functionLog.setResultMsg(FunctionReplyStatus.UNKNOWN.getMessage()); diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MessageManager.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MessageManager.java index 315397f7..cc183518 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MessageManager.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MessageManager.java @@ -21,57 +21,59 @@ import java.time.Duration; public class MessageManager { private static final Mono NEVER = Mono.never(); - private static final Mono OFFLINE_EXCEPTION = Mono.error( new ServiceException("离线的客户端",4000)); + private static final Mono OFFLINE_EXCEPTION = Mono.error(new ServiceException("离线的客户端", 4000)); private static final Mono OFFLINE_RESULT = Mono.just(new AjaxResult(4000, "离线的客户端")); private static final Mono SEND_FAIL_RESULT = Mono.just(new AjaxResult(4001, "消息发送失败")); private SessionManager sessionManager; - public MessageManager(SessionManager sessionManager){ + public MessageManager(SessionManager sessionManager) { this.sessionManager = sessionManager; } - public Mono notifyR(String sessionId, ModbusRtu request){ + public Mono notifyR(String sessionId, ModbusRtu request) { Session session = sessionManager.getSession(sessionId); - if (session == null){ + if (session == null) { return OFFLINE_EXCEPTION; } return session.notify(request); } - public Mono requestR(String sessionId, Message request, Class responseClass){ + public Mono requestR(String sessionId, Message request, Class responseClass) { Session session = sessionManager.getSession(sessionId); - if (session == null){ + if (session == null) { return OFFLINE_RESULT; } - return session.request(request,responseClass) + return session.request(request, responseClass) .map(message -> AjaxResult.success(message)) - .onErrorResume(e ->{ - log.warn("消息发送失败:{}",e); + .onErrorResume(e -> { + log.warn("消息发送失败:{}", e); return SEND_FAIL_RESULT; }); } /** * 下发指令等待回复 + * * @param sessionId * @return */ - public Mono request(String sessionId, ModbusRtu request, Class responseClass, long timeout){ - return request(sessionId,request,responseClass).timeout(Duration.ofMillis(timeout)); + public Mono request(String sessionId, ModbusRtu request, Class responseClass, long timeout) { + return request(sessionId, request, responseClass).timeout(Duration.ofMillis(timeout)); } /** * 下发指令,不等待回复 + * * @param sessionId * @return */ - public Mono request(String sessionId, ModbusRtu request, Class responseClass){ + public Mono request(String sessionId, ModbusRtu request, Class responseClass) { Session session = sessionManager.getSession(sessionId); - if (session == null){ + if (session == null) { return OFFLINE_EXCEPTION; } - return session.request(request,responseClass); + return session.request(request, responseClass); } } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MqttMessagePublishImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MqttMessagePublishImpl.java index 6b3d67fc..9f9c6ab2 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MqttMessagePublishImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/MqttMessagePublishImpl.java @@ -62,6 +62,7 @@ import static com.fastbee.common.constant.FastBeeConstant.PROTOCOL.ModbusRtu; @Service public class MqttMessagePublishImpl implements IMqttMessagePublish { + private final SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(3); @Resource private IProtocolManagerService protocolManagerService; @Resource @@ -92,8 +93,6 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { private PubMqttClient pubMqttClient; @Resource private IOrderControlService orderControlService; - private final SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(3); - /** * 服务(指令)下发 @@ -143,7 +142,7 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { backBo.setMessage(context.getPayload().getBytes()); } - publishWithLog(backBo.getTopicName(), backBo.getMessage(), funcLog,bo.getDelay()); + publishWithLog(backBo.getTopicName(), backBo.getMessage(), funcLog, bo.getDelay()); log.debug("=>服务下发,topic=[{}],指令=[{}]", backBo.getTopicName(), new String(backBo.getMessage())); break; case TCP: @@ -172,7 +171,7 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { deviceMessage.setTime(new Date()); deviceMessage.setTopicName(TopicType.FUNCTION_GET.getTopicSuffix()); byte[] bytes = JSONObject.toJSONString(deviceMessage).getBytes(); - publishWithLog(topic, bytes, null,null); + publishWithLog(topic, bytes, null, null); if (deviceAndProtocol.getProtocolCode().equals(ModbusRtu)) { //这里做一个消息id标记消息下发顺序,如果设备指令带流水号,则不需要使用 @@ -246,9 +245,8 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { log.setFunType(3); log.setIdentify("OTA"); log.setShowValue(ByteBufUtil.hexDump(bo.getMsg())); - mqttClient.publish(0,false,topicName, ByteBufUtil.hexDump(bo.getMsg())); - } - else if (TopicType.HTTP_FIRMWARE_SET.getTopicSuffix().equals(bo.getTopicName())) { + mqttClient.publish(0, false, topicName, ByteBufUtil.hexDump(bo.getMsg())); + } else if (TopicType.HTTP_FIRMWARE_SET.getTopicSuffix().equals(bo.getTopicName())) { String topicName = topicsUtils.buildTopic(bo.getSerialNumber(), TopicType.HTTP_FIRMWARE_SET); JSONObject message = new JSONObject(); message.put("taskId", bo.getTaskId()); @@ -348,9 +346,9 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { } - public void publishWithLog(String topic, byte[] pushMessage, FunctionLog log ,Long delay) { + public void publishWithLog(String topic, byte[] pushMessage, FunctionLog log, Long delay) { try { - if (!Objects.isNull(delay) && delay >0){ + if (!Objects.isNull(delay) && delay > 0) { Thread.sleep(delay); } mqttClient.publish(pushMessage, topic, false, 0); @@ -374,7 +372,7 @@ public class MqttMessagePublishImpl implements IMqttMessagePublish { * 推送设备状态 * * @param device 设备 - * @param status 状态 + * @param status 状态 */ public void pushDeviceStatus(Device device, DeviceStatus status) { String message = "{\"status\":" + status.getType() + ",\"isShadow\":" + device.getIsShadow() + ",\"rssi\":" + device.getRssi() + "}"; diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaTaskUpgradeServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaTaskUpgradeServiceImpl.java index 1090b3a4..202ea567 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaTaskUpgradeServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaTaskUpgradeServiceImpl.java @@ -58,6 +58,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * 固件升级异步方法 + * * @param taskId * @param serialNumber * @param firmware @@ -99,6 +100,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * 分包拉取方式固件升级 + * * @param taskId * @param serialNumber * @param firmware @@ -209,6 +211,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * HTTP方式固件升级 + * * @param taskId * @param serialNumber * @param firmware @@ -246,6 +249,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * 升级失败或结束返回 + * * @param taskId * @param serialNumber * @param appMessageBo @@ -260,6 +264,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * 生成WS消息体 + * * @param serialNumber * @param otaUpgrade * @param progress @@ -282,6 +287,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { /** * 获取拆包升级分包大小 + * * @param serialNumber * @param msg * @return @@ -305,13 +311,14 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { return Integer.parseInt(packageSize); } } - count ++; + count++; } return 0; } /** * 发送分包升级消息到队列中 + * * @param msg */ private boolean sendPackageUpgradeMsg(String serialNumber, byte[] msg) throws InterruptedException { @@ -334,7 +341,7 @@ public class OtaTaskUpgradeServiceImpl implements IOtaTaskUpgradeService { return true; } } - count ++; + count++; } return false; } diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaUpgradeServiceImpl.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaUpgradeServiceImpl.java index dd387801..4e957a48 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaUpgradeServiceImpl.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/OtaUpgradeServiceImpl.java @@ -33,7 +33,6 @@ public class OtaUpgradeServiceImpl implements IOtaUpgradeService { private IOtaTaskUpgradeService otaTaskUpgradeService; - @Override public void upgrade(OtaUpgradeDelayTask task) { //查询固件版本信息 diff --git a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/RuleEngineHandler.java b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/RuleEngineHandler.java index fb36cced..9bbeedc5 100644 --- a/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/RuleEngineHandler.java +++ b/fastbee-iot-data/src/main/java/com/fastbee/iot/data/service/impl/RuleEngineHandler.java @@ -30,14 +30,12 @@ import java.util.concurrent.ScheduledExecutorService; @Slf4j public class RuleEngineHandler implements IRuleEngine { + private static final Map CEHCK_CACHE = new ConcurrentHashMap<>(); @Resource private ISceneDeviceService sceneDeviceService; - @Autowired private FlowLogExecutor flowExecutor; - private static final Map CEHCK_CACHE = new ConcurrentHashMap<>(); - /** * 规则匹配(告警和场景联动) * diff --git a/fastbee-mq/pom.xml b/fastbee-mq/pom.xml index f2465c74..864f7bed 100644 --- a/fastbee-mq/pom.xml +++ b/fastbee-mq/pom.xml @@ -1,61 +1,61 @@ - - 4.0.0 - - fastbee - com.fastbee - 3.8.5 - + + 4.0.0 + + fastbee + com.fastbee + 3.8.5 + - fastbee-mq + fastbee-mq - + - - org.apache.rocketmq - rocketmq-spring-boot-starter - 2.2.0 - + + org.apache.rocketmq + rocketmq-spring-boot-starter + 2.2.0 + - - com.fastbee - fastbee-protocol-base - + + com.fastbee + fastbee-protocol-base + - - com.fastbee - fastbee-protocol-collect - + + com.fastbee + fastbee-protocol-collect + - - com.fastbee - sip-server - + + com.fastbee + sip-server + - - cn.hutool - hutool-all - + + cn.hutool + hutool-all + - - com.yomahub - liteflow-core - ${liteflow.version} - + + com.yomahub + liteflow-core + ${liteflow.version} + - - com.yomahub - liteflow-spring - ${liteflow.version} - + + com.yomahub + liteflow-spring + ${liteflow.version} + - - com.fastbee - fastbee-notify-core - + + com.fastbee + fastbee-notify-core + - + diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/producer/EmqxMessageProducer.java b/fastbee-mq/src/main/java/com/fastbee/mq/producer/EmqxMessageProducer.java index 7c4e3fdc..b077f41b 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/producer/EmqxMessageProducer.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/producer/EmqxMessageProducer.java @@ -13,7 +13,7 @@ public class EmqxMessageProducer implements IEmqxMessageProducer { @Override public void sendEmqxMessage(String topicName, DeviceReportBo deviceReportBo) { - if (topicName.contains("property/post")){ + if (topicName.contains("property/post")) { MessageProducer.sendPublishMsg(deviceReportBo); } else { MessageProducer.sendOtherMsg(deviceReportBo); diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/producer/MessageProducer.java b/fastbee-mq/src/main/java/com/fastbee/mq/producer/MessageProducer.java index f477c067..84efde23 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/producer/MessageProducer.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/producer/MessageProducer.java @@ -9,35 +9,41 @@ import com.fastbee.iot.model.modbus.ModbusPollJob; import com.fastbee.mq.queue.*; /** - *设备消息生产者 ,设备的消息发送通道 + * 设备消息生产者 ,设备的消息发送通道 + * * @author bill */ public class MessageProducer { /*发送设备获取属性消息到队列*/ - public static void sendPropFetch(ModbusPollJob deviceJob){ + public static void sendPropFetch(ModbusPollJob deviceJob) { DevicePropFetchQueue.offer(deviceJob); } + /*发送设备服务下发消息到队列*/ - public static void sendFunctionInvoke(MQSendMessageBo bo){ + public static void sendFunctionInvoke(MQSendMessageBo bo) { FunctionInvokeQueue.offer(bo); } + /*发送设备上报消息到队列*/ - public static void sendPublishMsg(DeviceReportBo bo){ + public static void sendPublishMsg(DeviceReportBo bo) { DeviceReportQueue.offer(bo); } - public static void sendOtherMsg(DeviceReportBo bo){ + + public static void sendOtherMsg(DeviceReportBo bo) { DeviceOtherQueue.offer(bo); } - public static void sendStatusMsg(DeviceStatusBo bo){ + public static void sendStatusMsg(DeviceStatusBo bo) { DeviceStatusQueue.offer(bo); } + /** * 设备调试通道 + * * @param bo */ - public static void sendDeviceTestMsg(DeviceTestReportBo bo){ + public static void sendDeviceTestMsg(DeviceTestReportBo bo) { DeviceTestQueue.offer(bo); } @@ -45,6 +51,7 @@ public class MessageProducer { public static void sendOtaUpgradeMsg(OtaUpgradeBo bo) { OtaUpgradeQueue.offer(bo); } + /*发送设备回复消息到队列*/ public static void sendDeviceReplyMsg(DeviceReportBo bo) { DeviceReplyQueue.offer(bo); diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceOtherQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceOtherQueue.java index d1611677..d551b461 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceOtherQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceOtherQueue.java @@ -14,12 +14,13 @@ public class DeviceOtherQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(DeviceReportBo dto){ + public static void offer(DeviceReportBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static DeviceReportBo take(){ + public static DeviceReportBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DevicePropFetchQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DevicePropFetchQueue.java index f35cc4ae..f4976682 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DevicePropFetchQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DevicePropFetchQueue.java @@ -7,6 +7,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * 设备属性获取存储列队 + * * @author gsb * @date 2022/10/11 8:29 */ @@ -14,12 +15,13 @@ public class DevicePropFetchQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(ModbusPollJob deviceJob){ + public static void offer(ModbusPollJob deviceJob) { queue.offer(deviceJob); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static ModbusPollJob take(){ + public static ModbusPollJob take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReplyQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReplyQueue.java index 4d7bea4d..e379d8b8 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReplyQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReplyQueue.java @@ -7,6 +7,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * 设备消息回调队列 {@link DeviceReportBo} + * * @author gsb * @date 2022/10/10 10:15 */ @@ -14,12 +15,13 @@ public class DeviceReplyQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(DeviceReportBo dto){ + public static void offer(DeviceReportBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static DeviceReportBo take(){ + public static DeviceReportBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReportQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReportQueue.java index 6d1dfc92..c2803d85 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReportQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceReportQueue.java @@ -14,12 +14,13 @@ public class DeviceReportQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(DeviceReportBo dto){ + public static void offer(DeviceReportBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static DeviceReportBo take(){ + public static DeviceReportBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceStatusQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceStatusQueue.java index 62bf4ece..06ace021 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceStatusQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceStatusQueue.java @@ -7,6 +7,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * 设备消息缓存队列 添加{@link DeviceStatusBo} 消息 + * * @author gsb * @date 2022/10/10 9:59 */ @@ -14,12 +15,13 @@ public class DeviceStatusQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(DeviceStatusBo dto){ + public static void offer(DeviceStatusBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static DeviceStatusBo take(){ + public static DeviceStatusBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceTestQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceTestQueue.java index bb35a1f7..573f7dbb 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceTestQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/DeviceTestQueue.java @@ -14,12 +14,13 @@ public class DeviceTestQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(DeviceTestReportBo dto){ + public static void offer(DeviceTestReportBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static DeviceTestReportBo take(){ + public static DeviceTestReportBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/FunctionInvokeQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/FunctionInvokeQueue.java index bc54d7e6..ec5fb173 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/FunctionInvokeQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/FunctionInvokeQueue.java @@ -7,6 +7,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * 服务下发队列 处理{@link MQSendMessageBo} + * * @author gsb * @date 2022/10/10 10:11 */ @@ -14,12 +15,13 @@ public class FunctionInvokeQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(MQSendMessageBo dto){ + public static void offer(MQSendMessageBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static MQSendMessageBo take(){ + public static MQSendMessageBo take() { return queue.take(); } } diff --git a/fastbee-mq/src/main/java/com/fastbee/mq/queue/OtaUpgradeQueue.java b/fastbee-mq/src/main/java/com/fastbee/mq/queue/OtaUpgradeQueue.java index ff754f9f..d2002814 100644 --- a/fastbee-mq/src/main/java/com/fastbee/mq/queue/OtaUpgradeQueue.java +++ b/fastbee-mq/src/main/java/com/fastbee/mq/queue/OtaUpgradeQueue.java @@ -7,6 +7,7 @@ import java.util.concurrent.LinkedBlockingQueue; /** * OTA升级列队 {@link OtaUpgradeBo} + * * @author gsb * @date 2022/10/10 10:30 */ @@ -14,12 +15,13 @@ public class OtaUpgradeQueue { private static final LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); /*元素加入队列,最后*/ - public static void offer(OtaUpgradeBo dto){ + public static void offer(OtaUpgradeBo dto) { queue.offer(dto); } + /*取出队列元素 先进先出*/ @SneakyThrows - public static OtaUpgradeBo take(){ + public static OtaUpgradeBo take() { return queue.take(); } } diff --git a/fastbee-notify/fastbee-notify-core/pom.xml b/fastbee-notify/fastbee-notify-core/pom.xml index 12c77f6a..91dcdf1d 100644 --- a/fastbee-notify/fastbee-notify-core/pom.xml +++ b/fastbee-notify/fastbee-notify-core/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/controller/NotifyController.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/controller/NotifyController.java index 755324ed..543e2c54 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/controller/NotifyController.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/controller/NotifyController.java @@ -34,7 +34,7 @@ public class NotifyController { @PreAuthorize("@ss.hasPermi('notify:template:send')") @PostMapping("/send") @ApiOperation("通知模版测试发送接口") - public AjaxResult send(@RequestBody SendParams sendParams){ + public AjaxResult send(@RequestBody SendParams sendParams) { return notifySendService.send(sendParams); } @@ -45,26 +45,27 @@ public class NotifyController { */ @GetMapping("/smsLoginCaptcha") @ApiOperation("短信登录获取验证码") - public AjaxResult smsLoginCaptcha(String phoneNumber){ + public AjaxResult smsLoginCaptcha(String phoneNumber) { return notifySendService.smsLoginCaptcha(phoneNumber); } /** * 企业微信验证url有效性 + * * @param msgSignature + * @return void * @param: timestamp * @param: nonce * @param: echostr * @param: response - * @return void */ @ApiOperation("企业微信验证url有效性") @GetMapping("/weComVerifyUrl") public void weComVerifyUrl(@RequestParam(value = "msg_signature") String msgSignature, - @RequestParam(value = "timestamp") String timestamp, - @RequestParam(value = "nonce") String nonce, - @RequestParam(value = "echostr") String echostr, - HttpServletResponse response) { + @RequestParam(value = "timestamp") String timestamp, + @RequestParam(value = "nonce") String nonce, + @RequestParam(value = "echostr") String echostr, + HttpServletResponse response) { String msg = notifySendService.weComVerifyUrl(msgSignature, timestamp, nonce, echostr); try { response.getWriter().print(msg); @@ -80,7 +81,7 @@ public class NotifyController { */ @GetMapping("/smsRegisterCaptcha") @ApiOperation("短信登录获取验证码") - public AjaxResult smsRegisterCaptcha(String phoneNumber){ + public AjaxResult smsRegisterCaptcha(String phoneNumber) { return notifySendService.smsRegisterCaptcha(phoneNumber); } diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/DingTalkService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/DingTalkService.java index 1b1c22d7..d39b3b79 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/DingTalkService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/DingTalkService.java @@ -5,17 +5,19 @@ import com.fastbee.notify.vo.NotifyVO; /** * 钉钉通知服务类 + * * @author fastb - * @date 2024-01-12 17:57 * @version 1.0 + * @date 2024-01-12 17:57 */ public interface DingTalkService { - /** + /** * 钉钉统一发送方法 + * * @param notifyVO 通知参数 * @return com.fastbee.common.core.notify.NotifySendResponse - */ + */ NotifySendResponse send(NotifyVO notifyVO); } diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/impl/DingTalkServiceImpl.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/impl/DingTalkServiceImpl.java index 60ac927c..23dc3e33 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/impl/DingTalkServiceImpl.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/dingtalk/service/impl/DingTalkServiceImpl.java @@ -56,10 +56,11 @@ public class DingTalkServiceImpl implements DingTalkService { /** * 自定义机器人发送 + * * @param dingTalkConfigParams 渠道配置参数 + * @return com.fastbee.common.core.notify.NotifySendResponse * @param: dingTalkMsgParams 模版配置参数 * @param: sendContent 发送内容 - * @return com.fastbee.common.core.notify.NotifySendResponse */ private NotifySendResponse customizeRobotSend(DingTalkConfigParams dingTalkConfigParams, DingTalkMsgParams dingTalkMsgParams, String sendContent) { NotifySendResponse notifySendResponse = new NotifySendResponse(); @@ -78,11 +79,12 @@ public class DingTalkServiceImpl implements DingTalkService { /** * 工作通知发送 + * * @param dingTalkConfigParams 渠道配置参数 + * @return com.fastbee.common.core.notify.NotifySendResponse * @param: dingTalkMsgParams 模版配置参数 * @param: sendAccount 发送账号,多个以,隔开 * @param: sendContent 发送内容 - * @return com.fastbee.common.core.notify.NotifySendResponse */ private NotifySendResponse workSend(DingTalkConfigParams dingTalkConfigParams, DingTalkMsgParams dingTalkMsgParams, String sendAccount, String sendContent) { NotifySendResponse notifySendResponse = new NotifySendResponse(); @@ -162,6 +164,7 @@ public class DingTalkServiceImpl implements DingTalkService { /** * 构建钉钉发送消息 + * * @param msgParams 消息参数 * @return */ @@ -193,9 +196,10 @@ public class DingTalkServiceImpl implements DingTalkService { /** * 获取AccessToken + * * @param appKey - * @param: appSecret * @return java.lang.String + * @param: appSecret */ private String getAccessToken(String appKey, String appSecret) { try { diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/email/service/EmailService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/email/service/EmailService.java index b53fc0d1..53a7d4dd 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/email/service/EmailService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/email/service/EmailService.java @@ -4,15 +4,15 @@ import com.fastbee.common.core.notify.NotifySendResponse; import com.fastbee.notify.vo.NotifyVO; /** - * @description: 邮箱发送业务类 * @author fastb - * @date 2023-12-29 16:20 * @version 1.0 + * @description: 邮箱发送业务类 + * @date 2023-12-29 16:20 */ public interface EmailService { /** - * @description: 邮件简要内容发送 + * @description: 邮件简要内容发送 * @param: notifyVO 发送VO类 * @return: void */ diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/NotifySendService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/NotifySendService.java index 0464d4a8..922f4329 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/NotifySendService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/NotifySendService.java @@ -6,11 +6,11 @@ import com.fastbee.notify.core.vo.SendParams; import com.fastbee.notify.vo.NotifyVO; /** + * @author fastb + * @version 1.0 * @description: 所有通知发送入口 * 以后有通知业务可写在这里 - * @author fastb * @date 2023-12-26 15:47 - * @version 1.0 */ public interface NotifySendService { @@ -30,6 +30,7 @@ public interface NotifySendService { /** * 告警通知统一推送 + * * @param alertPushParams 告警推送参数 * @return void */ @@ -44,17 +45,17 @@ public interface NotifySendService { AjaxResult sendCaptchaSms(String phone, String captcha); /** - * @description: 根据业务编码、渠道、服务商获取唯一启用通知配置信息 * @param serviceCode 业务编码,一定传 * @param channelType 渠道类型 一定传 - * @param provider 钉钉和微信渠道 一定传 + * @param provider 钉钉和微信渠道 一定传 + * @description: 根据业务编码、渠道、服务商获取唯一启用通知配置信息 * @author fastb * @date 2024-01-02 11:13 */ NotifyVO selectOnlyEnable(String serviceCode, String channelType, String provider, Long tenantId); /** - * @description: 短信登录获取验证码 + * @description: 短信登录获取验证码 * @param: phoneNumber * @return: com.fastbee.common.core.domain.AjaxResult */ @@ -62,12 +63,13 @@ public interface NotifySendService { /** * 企业微信验证url有效性 + * * @param msgSignature + * @return void * @param: timestamp * @param: nonce * @param: echostr * @param: response - * @return void */ String weComVerifyUrl(String msgSignature, String timestamp, String nonce, String echostr); diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/impl/NotifySendServiceImpl.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/impl/NotifySendServiceImpl.java index 93ffb69a..8fefebc5 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/impl/NotifySendServiceImpl.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/service/impl/NotifySendServiceImpl.java @@ -73,7 +73,7 @@ public class NotifySendServiceImpl implements NotifySendService { // 获取配置参数 NotifyTemplate notifyTemplate = notifyTemplateService.selectNotifyTemplateById(sendParams.getId()); NotifyChannel notifyChannel = notifyChannelService.selectNotifyChannelById(notifyTemplate.getChannelId()); - LinkedHashMap map = new LinkedHashMap<>(); + LinkedHashMap map = new LinkedHashMap<>(); if (StringUtils.isNotEmpty(sendParams.getVariables())) { map = JSONObject.parseObject(sendParams.getVariables(), LinkedHashMap.class); } @@ -120,7 +120,7 @@ public class NotifySendServiceImpl implements NotifySendService { // 保存日志 NotifyLog notifyLog = new NotifyLog(); notifyLog.setChannelId(notifyChannel.getId()).setNotifyTemplateId(notifyTemplate.getId()) - .setSendAccount(StringUtils.isNotEmpty(notifySendResponse.getOtherSendAccount()) ? notifySendResponse.getOtherSendAccount() : sendAccount) + .setSendAccount(StringUtils.isNotEmpty(notifySendResponse.getOtherSendAccount()) ? notifySendResponse.getOtherSendAccount() : sendAccount) .setServiceCode(notifyTemplate.getServiceCode()) .setMsgContent(notifySendResponse.getSendContent()) .setSendStatus(notifySendResponse.getStatus()).setResultContent(notifySendResponse.getResultContent()) @@ -298,9 +298,10 @@ public class NotifySendServiceImpl implements NotifySendService { /** * 校验发送账号格式 + * * @param sendAccount 发送账号 - * @param: notifyChannelEnum 通知枚举 * @return java.lang.String + * @param: notifyChannelEnum 通知枚举 */ private String checkSendAccountMsg(String sendAccount, NotifyChannelProviderEnum notifyChannelProviderEnum) { boolean matches; @@ -310,7 +311,7 @@ public class NotifySendServiceImpl implements NotifySendService { case VOICE_ALIBABA: case DING_TALK_WORK: case WECHAT_WECOM_APPLY: - matches = ValidationUtils.isMobile(sendAccount); + matches = ValidationUtils.isMobile(sendAccount); if (!matches) { return "请输入正确的电话号码!"; } diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/ISmsService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/ISmsService.java index 13e18f5a..8b843ba3 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/ISmsService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/ISmsService.java @@ -10,6 +10,7 @@ import java.util.List; /** * 短信发送接口 + * * @author gsb * @date 2023/12/15 11:01 */ @@ -17,6 +18,7 @@ public interface ISmsService { /** * 根据模版统一发送短信 + * * @param notifyVO 发送类 * @return com.fastbee.common.core.notify.NotifySendResponse */ @@ -25,7 +27,8 @@ public interface ISmsService { /** * 单个电话发送短信 - * @param phone 电话 + * + * @param phone 电话 * @param message 模板内容 * @return 结果 */ @@ -33,36 +36,40 @@ public interface ISmsService { /** * 根据模板id发送 --多参数 - * @param phone 电话 + * + * @param phone 电话 * @param templateId 模板id * @param messages 内容集合 * @return 结果 */ - SmsResponse sendMessage(SmsBlend smsBlend, String phone, String templateId, LinkedHashMap messages); + SmsResponse sendMessage(SmsBlend smsBlend, String phone, String templateId, LinkedHashMap messages); /** * 群发短信 - * @param phones 电话集合 + * + * @param phones 电话集合 * @param templateId 模板id * @param messages 内容集合 * @return 结果 */ - SmsResponse massTexting(SmsBlend smsBlend, List phones, String templateId, LinkedHashMap messages); + SmsResponse massTexting(SmsBlend smsBlend, List phones, String templateId, LinkedHashMap messages); /** * 延迟发送 - * @param phone 电话 - * @param message 模板内容 + * + * @param phone 电话 + * @param message 模板内容 * @param delayedTime 延迟时间 */ - void delayedMessage(SmsBlend smsBlend,String phone ,String message,Long delayedTime); + void delayedMessage(SmsBlend smsBlend, String phone, String message, Long delayedTime); /** * 根据模板延迟发送 - * @param phone 电话 - * @param messages 模板内容集合 + * + * @param phone 电话 + * @param messages 模板内容集合 * @param delayedTime 延迟时间 */ - void delayedMessage(SmsBlend smsBlend, String phone ,String templateId, LinkedHashMap messages,Long delayedTime); + void delayedMessage(SmsBlend smsBlend, String phone, String templateId, LinkedHashMap messages, Long delayedTime); } diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/Impl/SmsServiceImpl.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/Impl/SmsServiceImpl.java index e41a1321..32f1838d 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/Impl/SmsServiceImpl.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/sms/service/Impl/SmsServiceImpl.java @@ -62,11 +62,12 @@ public class SmsServiceImpl implements ISmsService { /** * 获取短信实例 + * * @return */ - private SmsBlend getSmsInstance(String configId){ + private SmsBlend getSmsInstance(String configId) { SmsBlend smsBlend = SmsFactory.getSmsBlend(configId); - if (Objects.isNull(smsBlend)){ + if (Objects.isNull(smsBlend)) { //如果没有初始化,则先进行初始化 SmsFactory.createSmsBlend(config, configId); return SmsFactory.getSmsBlend(configId); @@ -102,13 +103,13 @@ public class SmsServiceImpl implements ISmsService { /** * 群发短信 * - * @param phones 电话集合 + * @param phones 电话集合 * @param templateId 模板id * @param messages 内容集合 * @return 结果 */ @Override - public SmsResponse massTexting(SmsBlend smsBlend, List phones, String templateId, LinkedHashMap messages) { + public SmsResponse massTexting(SmsBlend smsBlend, List phones, String templateId, LinkedHashMap messages) { return smsBlend.massTexting(phones, templateId, messages); } diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/config/VoiceConfig.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/config/VoiceConfig.java index eeb6687e..08ddaa36 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/config/VoiceConfig.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/config/VoiceConfig.java @@ -13,6 +13,7 @@ public class VoiceConfig { /** * 使用AK&SK初始化账号Client + * * @param accessKeyId * @param accessKeySecret * @return Client diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/VoiceService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/VoiceService.java index 0ad08547..110c00fd 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/VoiceService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/VoiceService.java @@ -4,15 +4,16 @@ import com.fastbee.common.core.notify.NotifySendResponse; import com.fastbee.notify.vo.NotifyVO; /** - * @description: 语音通知服务类 * @author fastb - * @date 2023-12-15 11:05 * @version 1.0 + * @description: 语音通知服务类 + * @date 2023-12-15 11:05 */ public interface VoiceService { /** * 语音发送 + * * @param notifyVO 发送参数 * @return */ diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/impl/VoiceServiceImpl.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/impl/VoiceServiceImpl.java index c0fe1d84..727f6713 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/impl/VoiceServiceImpl.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/voice/service/impl/VoiceServiceImpl.java @@ -71,7 +71,7 @@ public class VoiceServiceImpl implements VoiceService { default: break; } - resultList.add("phone:[" + phone + "],status:[" + notifySendResponse.getStatus() + "],resultContent:[" + notifySendResponse.getResultContent() + "]"); + resultList.add("phone:[" + phone + "],status:[" + notifySendResponse.getStatus() + "],resultContent:[" + notifySendResponse.getResultContent() + "]"); } notifySendResponse.setSendContent(sendContent); notifySendResponse.setResultContent(StringUtils.join(resultList, "; ")); @@ -79,7 +79,6 @@ public class VoiceServiceImpl implements VoiceService { } - /** * @description: 阿里云文本转语音通知 * @param: configParams 渠道服务商配置参数 @@ -169,7 +168,8 @@ public class VoiceServiceImpl implements VoiceService { // 模板参数,若模板没有参数,请提供为空数组 - String[] templateParamSet = map.values().toArray(new String[0]);; + String[] templateParamSet = map.values().toArray(new String[0]); + ; req.setTemplateParamSet(templateParamSet); diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/WeChatPushService.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/WeChatPushService.java index 0d6c7446..c4fc03e3 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/WeChatPushService.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/WeChatPushService.java @@ -7,15 +7,16 @@ import com.fastbee.notify.domain.NotifyTemplate; import com.fastbee.notify.vo.NotifyVO; /** - * @description: 微信通知推送业务类 * @author fastb - * @date 2023-12-29 16:39 * @version 1.0 + * @description: 微信通知推送业务类 + * @date 2023-12-29 16:39 */ public interface WeChatPushService { /** * 统一发送接口 + * * @param notifyVO 发送参数 * @return */ diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/impl/WeChatPushServiceImpl.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/impl/WeChatPushServiceImpl.java index e50f0802..18748205 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/impl/WeChatPushServiceImpl.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/service/impl/WeChatPushServiceImpl.java @@ -48,9 +48,9 @@ import java.util.stream.Collectors; @Service public class WeChatPushServiceImpl implements WeChatPushService { + private static RestTemplate restTemplate; @Resource private ISocialUserService socialUserService; - private static RestTemplate restTemplate; @Resource private RedisCache redisCache; @@ -79,6 +79,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 微信公众号发送 + * * @param notifyVO 通知参数 * @return com.fastbee.common.core.notify.NotifySendResponse */ @@ -90,7 +91,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { return notifySendResponse; } LinkedHashMap map = notifyVO.getMap(); - LinkedHashMap mapVariable = new LinkedHashMap<>(); + LinkedHashMap mapVariable = new LinkedHashMap<>(); Map sendMap = new HashMap<>(5); for (Map.Entry m : map.entrySet()) { sendMap.put(m.getKey(), new TemplateDataVo(m.getValue())); @@ -142,7 +143,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { } weChatPublicAccountPushVO.setTouser(openId); notifySendResponse = this.weChatPostPush(JSON.toJSONString(weChatPublicAccountPushVO), pushUrl); - resultContentList.add("userId:[" + userId + "],status:[" + notifySendResponse.getStatus() +"],resultContent:[" + notifySendResponse.getResultContent() + "]"); + resultContentList.add("userId:[" + userId + "],status:[" + notifySendResponse.getStatus() + "],resultContent:[" + notifySendResponse.getResultContent() + "]"); } String content = JSONObject.parseObject(notifyVO.getNotifyTemplate().getMsgParams()).get("content").toString(); String sendContent = StringUtils.strReplaceVariable("{{", "}}", content, mapVariable); @@ -153,6 +154,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 企业微信应用消息发送 + * * @param notifyVO 发送vo类 * @return com.fastbee.common.core.notify.NotifySendResponse */ @@ -216,6 +218,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 企业微信群机器人发送 + * * @param notifyVO 发送配置类 * @return com.fastbee.common.core.notify.NotifySendResponse */ @@ -241,9 +244,10 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 构建企业微信发送参数 + * * @param weComMsgParams 消息配置参数 - * @param: sendContent * @return java.lang.String + * @param: sendContent */ private JSONObject createWeComMsg(WeComMsgParams weComMsgParams, String sendContent) { JSONObject req = new JSONObject(); @@ -278,6 +282,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 小程序发送 + * * @param notifyVO 发送vo类 * @return com.fastbee.common.core.notify.NotifySendResponse */ @@ -290,7 +295,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { return notifySendResponse; } LinkedHashMap map = notifyVO.getMap(); - LinkedHashMap mapVariable = new LinkedHashMap<>(); + LinkedHashMap mapVariable = new LinkedHashMap<>(); Map sendMap = new HashMap<>(5); for (Map.Entry m : map.entrySet()) { sendMap.put(m.getKey(), new TemplateDataVo(m.getValue())); @@ -306,14 +311,14 @@ public class WeChatPushServiceImpl implements WeChatPushService { continue; } if (StringUtils.isNotEmpty(weChatMiniPushVO.getErrorMsg())) { - resultContentList.add("userId:[" + userId + "],status:[0],resultContent:[" + weChatMiniPushVO.getErrorMsg() + "]"); + resultContentList.add("userId:[" + userId + "],status:[0],resultContent:[" + weChatMiniPushVO.getErrorMsg() + "]"); notifySendResponse.setStatus(0); continue; } WxMssVo wxMssVo = weChatMiniPushVO.getWxMssVo(); wxMssVo.setData(sendMap); notifySendResponse = this.weChatPostPush(JSON.toJSONString(wxMssVo), weChatMiniPushVO.getUrl()); - resultContentList.add("userId:[" + userId + "],status:[" + notifySendResponse.getStatus() +"],resultContent:[" + notifySendResponse.getResultContent() + "]"); + resultContentList.add("userId:[" + userId + "],status:[" + notifySendResponse.getStatus() + "],resultContent:[" + notifySendResponse.getResultContent() + "]"); } String content = JSONObject.parseObject(notifyVO.getNotifyTemplate().getMsgParams()).get("content").toString(); String sendContent = StringUtils.strReplaceVariable("{{", "}}", content, mapVariable); @@ -324,13 +329,14 @@ public class WeChatPushServiceImpl implements WeChatPushService { /** * 推送消息给指定的用户 --微信小程序服务号推送 + * * @param json 推送参数 * @return 推送结果 */ @Override public NotifySendResponse weChatPostPush(String json, String url) { NotifySendResponse notifySendResponse = new NotifySendResponse(); - if(restTemplate==null){ + if (restTemplate == null) { restTemplate = new RestTemplate(); } HttpHeaders headers = new HttpHeaders(); @@ -388,7 +394,7 @@ public class WeChatPushServiceImpl implements WeChatPushService { //模版id wxMssVo.setTemplateId(msgParams.getTemplateId()); //推送路径 - if (StringUtils.isNotEmpty(msgParams.getRedirectUrl())){ + if (StringUtils.isNotEmpty(msgParams.getRedirectUrl())) { wxMssVo.setPage(msgParams.getRedirectUrl()); } weChatMiniPushVO.setWxMssVo(wxMssVo); diff --git a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/vo/WxMssVo.java b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/vo/WxMssVo.java index bff65a44..50c14be3 100644 --- a/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/vo/WxMssVo.java +++ b/fastbee-notify/fastbee-notify-core/src/main/java/com/fastbee/notify/core/wechat/vo/WxMssVo.java @@ -40,6 +40,7 @@ public class WxMssVo { */ @JSONField(name = "lang") private String lang; + /** * 默认正式版 和 简体中文 */ diff --git a/fastbee-notify/fastbee-notify-web/pom.xml b/fastbee-notify/fastbee-notify-web/pom.xml index c19e1f19..cab71389 100644 --- a/fastbee-notify/fastbee-notify-web/pom.xml +++ b/fastbee-notify/fastbee-notify-web/pom.xml @@ -1,6 +1,6 @@ - 4.0.0 diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyChannelController.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyChannelController.java index da497d5d..0a9e1f32 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyChannelController.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyChannelController.java @@ -26,8 +26,7 @@ import java.util.List; @RestController @RequestMapping("/notify/channel") @Api(tags = "通知渠道") -public class NotifyChannelController extends BaseController -{ +public class NotifyChannelController extends BaseController { @Resource private INotifyChannelService notifyChannelService; @@ -37,8 +36,7 @@ public class NotifyChannelController extends BaseController @PreAuthorize("@ss.hasPermi('notify:channel:list')") @GetMapping("/list") @ApiOperation(value = "查询通知渠道列表") - public TableDataInfo list(NotifyChannel notifyChannel) - { + public TableDataInfo list(NotifyChannel notifyChannel) { startPage(); List list = notifyChannelService.selectNotifyChannelList(notifyChannel); return getDataTable(list); @@ -51,8 +49,7 @@ public class NotifyChannelController extends BaseController @PreAuthorize("@ss.hasPermi('notify:channel:export')") @Log(title = "通知渠道", businessType = BusinessType.EXPORT) @PostMapping("/export") - public void export(HttpServletResponse response, NotifyChannel notifyChannel) - { + public void export(HttpServletResponse response, NotifyChannel notifyChannel) { List list = notifyChannelService.selectNotifyChannelList(notifyChannel); ExcelUtil util = new ExcelUtil(NotifyChannel.class); util.exportExcel(response, list, "通知渠道数据"); @@ -64,8 +61,7 @@ public class NotifyChannelController extends BaseController @PreAuthorize("@ss.hasPermi('notify:channel:query')") @GetMapping(value = "/{id}") @ApiOperation(value = "获取通知渠道详细信息") - public AjaxResult getInfo(@PathVariable("id") Long id) - { + public AjaxResult getInfo(@PathVariable("id") Long id) { return success(notifyChannelService.selectNotifyChannelById(id)); } @@ -76,8 +72,7 @@ public class NotifyChannelController extends BaseController @Log(title = "通知渠道", businessType = BusinessType.INSERT) @PostMapping @ApiOperation(value = "新增通知渠道") - public AjaxResult add(@RequestBody NotifyChannel notifyChannel) - { + public AjaxResult add(@RequestBody NotifyChannel notifyChannel) { return toAjax(notifyChannelService.insertNotifyChannel(notifyChannel)); } @@ -88,8 +83,7 @@ public class NotifyChannelController extends BaseController @Log(title = "通知渠道", businessType = BusinessType.UPDATE) @PutMapping @ApiOperation(value = "修改通知渠道") - public AjaxResult edit(@RequestBody NotifyChannel notifyChannel) - { + public AjaxResult edit(@RequestBody NotifyChannel notifyChannel) { return toAjax(notifyChannelService.updateNotifyChannel(notifyChannel)); } @@ -98,15 +92,15 @@ public class NotifyChannelController extends BaseController */ @PreAuthorize("@ss.hasPermi('notify:channel:remove')") @Log(title = "通知渠道", businessType = BusinessType.DELETE) - @DeleteMapping("/{ids}") + @DeleteMapping("/{ids}") @ApiOperation(value = "删除通知渠道") - public AjaxResult remove(@PathVariable Long[] ids) - { + public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(notifyChannelService.deleteNotifyChannelByIds(ids)); } /** * 查询通知渠道和服务商 + * * @return 结果 */ @GetMapping("/listChannel") @@ -117,9 +111,10 @@ public class NotifyChannelController extends BaseController /** * 获取消息通知渠道参数信息 + * * @param channelType 渠道类型 - * @param: provider 服务商 * @return com.fastbee.common.core.domain.AjaxResult + * @param: provider 服务商 */ @GetMapping(value = "/getConfigContent") @ApiOperation("获取渠道参数配置") diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyLogController.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyLogController.java index 2b6963fe..26dccbfe 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyLogController.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/controller/NotifyLogController.java @@ -19,15 +19,14 @@ import java.util.List; /** * 通知日志Controller - * + * * @author fastbee * @date 2023-12-16 */ @Api(tags = "通知日志") @RestController @RequestMapping("/notify/log") -public class NotifyLogController extends BaseController -{ +public class NotifyLogController extends BaseController { @Resource private INotifyLogService notifyLogService; @@ -37,8 +36,7 @@ public class NotifyLogController extends BaseController @PreAuthorize("@ss.hasPermi('notify:log:list')") @ApiOperation(value = "查询通知日志列表") @GetMapping("/list") - public TableDataInfo list(NotifyLog notifyLog) - { + public TableDataInfo list(NotifyLog notifyLog) { startPage(); List list = notifyLogService.selectNotifyLogList(notifyLog); return getDataTable(list); @@ -51,8 +49,7 @@ public class NotifyLogController extends BaseController @Log(title = "通知日志", businessType = BusinessType.EXPORT) @ApiOperation(value = "导出通知日志列表") @PostMapping("/export") - public void export(HttpServletResponse response, NotifyLog notifyLog) - { + public void export(HttpServletResponse response, NotifyLog notifyLog) { List list = notifyLogService.selectNotifyLogList(notifyLog); ExcelUtil util = new ExcelUtil(NotifyLog.class); util.exportExcel(response, list, "通知日志数据"); @@ -64,8 +61,7 @@ public class NotifyLogController extends BaseController @PreAuthorize("@ss.hasPermi('notify:log:query')") @ApiOperation(value = "获取通知日志详细信息") @GetMapping(value = "/{id}") - public AjaxResult getInfo(@PathVariable("id") Long id) - { + public AjaxResult getInfo(@PathVariable("id") Long id) { return success(notifyLogService.selectNotifyLogById(id)); } @@ -75,8 +71,7 @@ public class NotifyLogController extends BaseController @PreAuthorize("@ss.hasPermi('notify:log:add')") @Log(title = "通知日志", businessType = BusinessType.INSERT) @PostMapping - public AjaxResult add(@RequestBody NotifyLog notifyLog) - { + public AjaxResult add(@RequestBody NotifyLog notifyLog) { return toAjax(notifyLogService.insertNotifyLog(notifyLog)); } @@ -86,8 +81,7 @@ public class NotifyLogController extends BaseController @PreAuthorize("@ss.hasPermi('notify:log:edit')") @Log(title = "通知日志", businessType = BusinessType.UPDATE) @PutMapping - public AjaxResult edit(@RequestBody NotifyLog notifyLog) - { + public AjaxResult edit(@RequestBody NotifyLog notifyLog) { return toAjax(notifyLogService.updateNotifyLog(notifyLog)); } @@ -97,9 +91,8 @@ public class NotifyLogController extends BaseController @PreAuthorize("@ss.hasPermi('notify:log:remove')") @Log(title = "通知日志", businessType = BusinessType.DELETE) @ApiOperation(value = "批量删除通知日志") - @DeleteMapping("/{ids}") - public AjaxResult remove(@PathVariable Long[] ids) - { + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(notifyLogService.deleteNotifyLogByIds(ids)); } } diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyChannel.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyChannel.java index d61ad093..349dbca1 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyChannel.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyChannel.java @@ -15,36 +15,51 @@ import lombok.experimental.Accessors; @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) -public class NotifyChannel extends BaseEntity -{ +public class NotifyChannel extends BaseEntity { private static final long serialVersionUID = 1L; - /** 编号 */ + /** + * 编号 + */ private Long id; - /** 通知名称 */ + /** + * 通知名称 + */ @Excel(name = "通知名称") private String name; - /** 发送渠道类型 */ + /** + * 发送渠道类型 + */ @Excel(name = "发送渠道类型") private String channelType; - /** 服务商 */ + /** + * 服务商 + */ @Excel(name = "服务商") private String provider; - /** 配置内容 */ + /** + * 配置内容 + */ @Excel(name = "配置内容") private String configContent; - /** 租户id */ + /** + * 租户id + */ private Long tenantId; - /** 租户名称 */ + /** + * 租户名称 + */ private String tenantName; - /** 逻辑删除标识 */ + /** + * 逻辑删除标识 + */ private Integer delFlag; } diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyLog.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyLog.java index 0968df69..ffe2bd04 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyLog.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyLog.java @@ -8,59 +8,84 @@ import lombok.experimental.Accessors; /** * 通知日志对象 notify_log - * + * * @author fastbee * @date 2023-12-16 */ @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) -public class NotifyLog extends BaseEntity -{ +public class NotifyLog extends BaseEntity { private static final long serialVersionUID = 1L; - /** 编号 */ + /** + * 编号 + */ private Long id; - /** 通知模版编号 */ + /** + * 通知模版编号 + */ @Excel(name = "通知模版编号") private Long notifyTemplateId; - /** 渠道编号 */ + /** + * 渠道编号 + */ @Excel(name = "渠道编号") private Long channelId; - /** 消息内容 */ + /** + * 消息内容 + */ @Excel(name = "消息内容") private String msgContent; - /** 发送账号 */ + /** + * 发送账号 + */ @Excel(name = "发送账号") private String sendAccount; - /** 发送状态 */ + /** + * 发送状态 + */ @Excel(name = "发送状态") private Integer sendStatus; - /** 返回内容 */ + /** + * 返回内容 + */ @Excel(name = "返回内容") private String resultContent; - /** 逻辑删除标识 */ + /** + * 逻辑删除标识 + */ private Integer delFlag; - /** 渠道名称 */ + /** + * 渠道名称 + */ private String channelName; - /** 模板名称 */ + /** + * 模板名称 + */ private String templateName; - /** 租户id */ + /** + * 租户id + */ private Long tenantId; - /** 租户名称 */ + /** + * 租户名称 + */ private String tenantName; - /** 业务编码 */ + /** + * 业务编码 + */ @Excel(name = "业务编码") private String serviceCode; diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyTemplate.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyTemplate.java index cfc2e2ae..ec8083e9 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyTemplate.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/domain/NotifyTemplate.java @@ -16,49 +16,68 @@ import lombok.experimental.Accessors; @EqualsAndHashCode(callSuper = true) @Data @Accessors(chain = true) -public class NotifyTemplate extends BaseEntity -{ +public class NotifyTemplate extends BaseEntity { private static final long serialVersionUID = 1L; - /** 编号 */ + /** + * 编号 + */ private Long id; - /** 模版名称 */ + /** + * 模版名称 + */ @Excel(name = "模版名称") private String name; - /** 通知渠道 */ + /** + * 通知渠道 + */ @Excel(name = "通知渠道") private Long channelId; - /** 业务编码 */ + /** + * 业务编码 + */ @Excel(name = "业务编码") private String serviceCode; @ApiModelProperty("模版配置参数") private String msgParams; - /** 发送账号 */ + /** + * 发送账号 + */ @Excel(name = "是否启用,0-否 1-是") private Integer status; - /** 逻辑删除标识 */ + /** + * 逻辑删除标识 + */ private Integer delFlag; private String channelName; - /** 发送渠道类型 */ + /** + * 发送渠道类型 + */ @Excel(name = "发送渠道类型") private String channelType; - /** 服务商 */ + /** + * 服务商 + */ @Excel(name = "服务商") private String provider; - /** 租户id */ + /** + * 租户id + */ private Long tenantId; - /** 租户名称 */ + /** + * 租户名称 + */ private String tenantName; diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyChannelMapper.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyChannelMapper.java index 9f6d06a5..46400fdc 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyChannelMapper.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyChannelMapper.java @@ -11,8 +11,7 @@ import java.util.List; * @author kerwincui * @date 2023-12-01 */ -public interface NotifyChannelMapper -{ +public interface NotifyChannelMapper { /** * 查询通知渠道 * @@ -63,7 +62,8 @@ public interface NotifyChannelMapper /** * 批量查询通知渠道 - * @param idList 主键id集合 + * + * @param idList 主键id集合 * @return java.util.List */ List selectNotifyChannelByIds(@Param("idList") List idList); diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyLogMapper.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyLogMapper.java index d514f8ff..ec16e235 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyLogMapper.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyLogMapper.java @@ -10,8 +10,7 @@ import java.util.List; * @author fastbee * @date 2023-12-16 */ -public interface NotifyLogMapper -{ +public interface NotifyLogMapper { /** * 查询通知日志 * diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyTemplateMapper.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyTemplateMapper.java index 5827b489..c5e9c1a2 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyTemplateMapper.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/mapper/NotifyTemplateMapper.java @@ -11,8 +11,7 @@ import java.util.List; * @author kerwincui * @date 2023-12-01 */ -public interface NotifyTemplateMapper -{ +public interface NotifyTemplateMapper { /** * 查询通知模版 * @@ -31,6 +30,7 @@ public interface NotifyTemplateMapper /** * 查询同一业务已启用的模板 + * * @param notifyTemplate * @return */ @@ -54,6 +54,7 @@ public interface NotifyTemplateMapper /** * 批量更新渠道状态 + * * @param ids ids * @return */ @@ -77,6 +78,7 @@ public interface NotifyTemplateMapper /** * 根据业务编码查询启用模板 + * * @param notifyTemplate 通知模板 * @return com.fastbee.notify.domain.NotifyTemplate */ @@ -98,6 +100,7 @@ public interface NotifyTemplateMapper /** * 根据渠道id查询模板 + * * @param channelId 渠道id * @return java.util.List */ @@ -105,6 +108,7 @@ public interface NotifyTemplateMapper /** * 根据场景ID批量删除告警场景 + * * @param notifyTemplateIds * @return */ diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyChannelService.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyChannelService.java index d5a14c6b..c77a4b87 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyChannelService.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyChannelService.java @@ -12,8 +12,7 @@ import java.util.List; * @author kerwincui * @date 2023-12-01 */ -public interface INotifyChannelService -{ +public interface INotifyChannelService { /** * 查询通知渠道 * @@ -64,15 +63,17 @@ public interface INotifyChannelService /** * 查询通知渠道和服务商 + * * @return */ List listChannel(); /** * 获取消息通知渠道参数信息 + * * @param channelType 渠道类型 - * @param: provider 服务商 * @return 结果集 + * @param: provider 服务商 */ List getConfigContent(String channelType, String provider); } diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyLogService.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyLogService.java index 773598f0..192d6300 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyLogService.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyLogService.java @@ -6,15 +6,14 @@ import java.util.List; /** * 通知日志Service接口 - * + * * @author kerwincui * @date 2023-12-16 */ -public interface INotifyLogService -{ +public interface INotifyLogService { /** * 查询通知日志 - * + * * @param id 通知日志主键 * @return 通知日志 */ @@ -22,7 +21,7 @@ public interface INotifyLogService /** * 查询通知日志列表 - * + * * @param notifyLog 通知日志 * @return 通知日志集合 */ @@ -30,7 +29,7 @@ public interface INotifyLogService /** * 新增通知日志 - * + * * @param notifyLog 通知日志 * @return 结果 */ @@ -38,7 +37,7 @@ public interface INotifyLogService /** * 修改通知日志 - * + * * @param notifyLog 通知日志 * @return 结果 */ @@ -46,7 +45,7 @@ public interface INotifyLogService /** * 批量删除通知日志 - * + * * @param ids 需要删除的通知日志主键集合 * @return 结果 */ @@ -54,7 +53,7 @@ public interface INotifyLogService /** * 删除通知日志信息 - * + * * @param id 通知日志主键 * @return 结果 */ diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyTemplateService.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyTemplateService.java index 60fc769b..34321b92 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyTemplateService.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/INotifyTemplateService.java @@ -13,8 +13,7 @@ import java.util.List; * @author kerwincui * @date 2023-12-01 */ -public interface INotifyTemplateService -{ +public interface INotifyTemplateService { /** * 查询通知模版 * @@ -65,12 +64,14 @@ public interface INotifyTemplateService /** * 查询某一业务通知通道是否有启动的(业务编码唯一启用一个模板) + * * @param notifyTemplate 通知模板 */ public Integer countNormalTemplate(NotifyTemplate notifyTemplate); /** * 更新某一类型为不可用状态,选中的为可用状态 + * * @param notifyTemplate 通知模板 */ public void updateTemplateStatus(NotifyTemplate notifyTemplate); @@ -107,10 +108,11 @@ public interface INotifyTemplateService /** * 获取唯一启用模版查询条件 * 短信、语音、邮箱以业务编码+渠道保证唯一启用,微信、钉钉以业务编码+渠道+服务商保证唯一启用 + * + * @return com.fastbee.notify.domain.NotifyTemplate * @param: serviceCode * @param: channelType * @param: provider - * @return com.fastbee.notify.domain.NotifyTemplate */ NotifyTemplate getEnableQueryCondition(String serviceCode, String channelType, String provider, Long tenantId); diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyChannelServiceImpl.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyChannelServiceImpl.java index 2e37ffd0..d844056a 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyChannelServiceImpl.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyChannelServiceImpl.java @@ -33,8 +33,7 @@ import static com.fastbee.common.utils.SecurityUtils.getLoginUser; * @date 2023-12-01 */ @Service -public class NotifyChannelServiceImpl implements INotifyChannelService -{ +public class NotifyChannelServiceImpl implements INotifyChannelService { @Resource private NotifyChannelMapper notifyChannelMapper; @Resource @@ -49,8 +48,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 通知渠道 */ @Override - public NotifyChannel selectNotifyChannelById(Long id) - { + public NotifyChannel selectNotifyChannelById(Long id) { return notifyChannelMapper.selectNotifyChannelById(id); } @@ -61,8 +59,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 通知渠道 */ @Override - public List selectNotifyChannelList(NotifyChannel notifyChannel) - { + public List selectNotifyChannelList(NotifyChannel notifyChannel) { SysUser user = getLoginUser().getUser(); // List roles=user.getRoles(); // // 租户 @@ -85,8 +82,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 结果 */ @Override - public int insertNotifyChannel(NotifyChannel notifyChannel) - { + public int insertNotifyChannel(NotifyChannel notifyChannel) { SysUser user = getLoginUser().getUser(); if (null == user.getDeptId()) { throw new ServiceException("只允许租户配置"); @@ -103,8 +99,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 结果 */ @Override - public int updateNotifyChannel(NotifyChannel notifyChannel) - { + public int updateNotifyChannel(NotifyChannel notifyChannel) { notifyChannel.setUpdateTime(DateUtils.getNowDate()); List notifyTemplateList = notifyTemplateMapper.selectNotifyTemplateByChannelId(notifyChannel.getId()); for (NotifyTemplate notifyTemplate : notifyTemplateList) { @@ -120,8 +115,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 结果 */ @Override - public int deleteNotifyChannelByIds(Long[] ids) - { + public int deleteNotifyChannelByIds(Long[] ids) { int result = notifyChannelMapper.deleteNotifyChannelByIds(ids); // 删除渠道下的模板 if (result > 0) { @@ -137,8 +131,7 @@ public class NotifyChannelServiceImpl implements INotifyChannelService * @return 结果 */ @Override - public int deleteNotifyChannelById(Long id) - { + public int deleteNotifyChannelById(Long id) { int result = notifyChannelMapper.deleteNotifyChannelById(id); // 删除渠道下的模板 if (result > 0) { diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyLogServiceImpl.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyLogServiceImpl.java index 609b93f3..0f7be738 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyLogServiceImpl.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyLogServiceImpl.java @@ -27,8 +27,7 @@ import static com.fastbee.common.utils.SecurityUtils.getLoginUser; * @date 2023-12-16 */ @Service -public class NotifyLogServiceImpl implements INotifyLogService -{ +public class NotifyLogServiceImpl implements INotifyLogService { @Resource private NotifyLogMapper notifyLogMapper; @Resource @@ -43,8 +42,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 通知日志 */ @Override - public NotifyLog selectNotifyLogById(Long id) - { + public NotifyLog selectNotifyLogById(Long id) { return notifyLogMapper.selectNotifyLogById(id); } @@ -55,8 +53,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 通知日志 */ @Override - public List selectNotifyLogList(NotifyLog notifyLog) - { + public List selectNotifyLogList(NotifyLog notifyLog) { SysUser user = getLoginUser().getUser(); // List roles=user.getRoles(); // // 租户 @@ -97,8 +94,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 结果 */ @Override - public int insertNotifyLog(NotifyLog notifyLog) - { + public int insertNotifyLog(NotifyLog notifyLog) { notifyLog.setCreateTime(DateUtils.getNowDate()); return notifyLogMapper.insertNotifyLog(notifyLog); } @@ -110,8 +106,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 结果 */ @Override - public int updateNotifyLog(NotifyLog notifyLog) - { + public int updateNotifyLog(NotifyLog notifyLog) { notifyLog.setUpdateTime(DateUtils.getNowDate()); return notifyLogMapper.updateNotifyLog(notifyLog); } @@ -123,8 +118,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 结果 */ @Override - public int deleteNotifyLogByIds(Long[] ids) - { + public int deleteNotifyLogByIds(Long[] ids) { return notifyLogMapper.deleteNotifyLogByIds(ids); } @@ -135,8 +129,7 @@ public class NotifyLogServiceImpl implements INotifyLogService * @return 结果 */ @Override - public int deleteNotifyLogById(Long id) - { + public int deleteNotifyLogById(Long id) { return notifyLogMapper.deleteNotifyLogById(id); } } diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyTemplateServiceImpl.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyTemplateServiceImpl.java index ac251113..32bdb385 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyTemplateServiceImpl.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/service/impl/NotifyTemplateServiceImpl.java @@ -159,10 +159,11 @@ public class NotifyTemplateServiceImpl implements INotifyTemplateService { /** * 查询某一业务通知通道是否有启动的(业务编码唯一启用一个模板) + * * @param notifyTemplate 通知模板 */ @Override - public Integer countNormalTemplate(NotifyTemplate notifyTemplate){ + public Integer countNormalTemplate(NotifyTemplate notifyTemplate) { LoginUser loginUser = getLoginUser(); assert !Objects.isNull(notifyTemplate.getServiceCode()) : "业务编码不能为空"; NotifyTemplate selectOne = this.getEnableQueryCondition(notifyTemplate.getServiceCode(), notifyTemplate.getChannelType(), notifyTemplate.getProvider(), loginUser.getUser().getDept().getDeptUserId()); @@ -173,10 +174,11 @@ public class NotifyTemplateServiceImpl implements INotifyTemplateService { /** * 获取唯一启用模版查询条件 * 唯一启用条件:同一业务编码的模板短信、语音、邮箱渠道分别可以启用一个,微信、钉钉渠道下不同服务商分别可以启用一个 + * + * @return com.fastbee.notify.domain.NotifyTemplate * @param: serviceCode * @param: channelType * @param: provider - * @return com.fastbee.notify.domain.NotifyTemplate */ @Override public NotifyTemplate getEnableQueryCondition(String serviceCode, String channelType, String provider, Long tenantId) { @@ -204,17 +206,18 @@ public class NotifyTemplateServiceImpl implements INotifyTemplateService { /** * 更新某一类型为不可用状态,选中的为可用状态 + * * @param notifyTemplate 通知模板 */ @Override @Transactional(rollbackFor = Exception.class) - public void updateTemplateStatus(NotifyTemplate notifyTemplate){ + public void updateTemplateStatus(NotifyTemplate notifyTemplate) { LoginUser loginUser = getLoginUser(); // 查询所有统一类型可用的渠道 NotifyTemplate selectEnable = this.getEnableQueryCondition(notifyTemplate.getServiceCode(), notifyTemplate.getChannelType(), notifyTemplate.getProvider(), loginUser.getUser().getDept().getDeptUserId()); selectEnable.setId(notifyTemplate.getId()); List notifyTemplateList = this.selectNotifyTemplateList(selectEnable); - if (!CollectionUtils.isEmpty(notifyTemplateList)){ + if (!CollectionUtils.isEmpty(notifyTemplateList)) { //如果有同一类型的渠道为可用,要先将更新为不可用 List ids = notifyTemplateList.stream().map(NotifyTemplate::getId).filter(id -> !Objects.equals(id, notifyTemplate.getId())).collect(Collectors.toList()); if (!CollectionUtils.isEmpty(ids)) { diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/ChannelProviderVO.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/ChannelProviderVO.java index 64b0d633..302b2d61 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/ChannelProviderVO.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/ChannelProviderVO.java @@ -6,6 +6,7 @@ import java.util.List; /** * 渠道服务商VO类 + * * @author fastb * @date 2023-12-01 14:06 */ @@ -31,7 +32,7 @@ public class ChannelProviderVO { * 服务商 */ @Data - public static class Provider{ + public static class Provider { /** * 服务商英文标识 diff --git a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/NotifyVO.java b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/NotifyVO.java index ef88bdc8..c83598ff 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/NotifyVO.java +++ b/fastbee-notify/fastbee-notify-web/src/main/java/com/fastbee/notify/vo/NotifyVO.java @@ -27,7 +27,7 @@ public class NotifyVO { */ private String sendAccount; - private LinkedHashMap map; + private LinkedHashMap map; private NotifyChannelProviderEnum notifyChannelProviderEnum; } diff --git a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyChannelMapper.xml b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyChannelMapper.xml index e85f6494..41e9a94a 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyChannelMapper.xml +++ b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyChannelMapper.xml @@ -1,36 +1,48 @@ + PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - - - - - - - - - - - - + + + + + + + + + + + + - select id, name, channel_type, provider, config_content, tenant_id, tenant_name, create_by, create_time, update_by, update_time, del_flag from notify_channel + select id, + name, + channel_type, + provider, + config_content, + tenant_id, + tenant_name, + create_by, + create_time, + update_by, + update_time, + del_flag + from notify_channel @@ -62,7 +74,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" update_by, update_time, del_flag, - + #{name}, #{channelType}, @@ -75,7 +87,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{updateBy}, #{updateTime}, #{delFlag}, - + @@ -97,7 +109,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - delete from notify_channel where id = #{id} + delete + from notify_channel + where id = #{id} diff --git a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyLogMapper.xml b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyLogMapper.xml index 571c38f8..24ca6bc4 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyLogMapper.xml +++ b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyLogMapper.xml @@ -1,48 +1,65 @@ + PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - select id, notify_template_id, channel_id, msg_content, send_account, send_status, result_content,service_code, create_by, create_time, update_by, update_time, del_flag, tenant_id, tenant_name from notify_log + select id, + notify_template_id, + channel_id, + msg_content, + send_account, + send_status, + result_content, + service_code, + create_by, + create_time, + update_by, + update_time, + del_flag, + tenant_id, + tenant_name + from notify_log @@ -69,7 +86,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" tenant_id, tenant_name, service_code, - + #{notifyTemplateId}, #{channelId}, @@ -85,7 +102,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" #{tenantId}, #{tenantName}, #{serviceCode}, - + @@ -110,7 +127,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - delete from notify_log where id = #{id} + delete + from notify_log + where id = #{id} diff --git a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyTemplateMapper.xml b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyTemplateMapper.xml index c1c4a4e8..6a5c72db 100644 --- a/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyTemplateMapper.xml +++ b/fastbee-notify/fastbee-notify-web/src/main/resources/mapper/NotifyTemplateMapper.xml @@ -1,41 +1,56 @@ + PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - - + + - - - - - - - - - - - - + + + + + + + + + + + + - select id, service_code,msg_params,status, name, channel_id, channel_type, provider, create_by, create_time, update_by, update_time, del_flag, tenant_id, tenant_name from notify_template + select id, + service_code, + msg_params, + status, + name, + channel_id, + channel_type, + provider, + create_by, + create_time, + update_by, + update_time, + del_flag, + tenant_id, + tenant_name + from notify_template @@ -43,12 +58,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where table_id = #{tableId} order by sort - + - + select column_name, + (case when (is_nullable = 'no' column_key != 'PRI') then '1' else null end) as is_required, + (case when column_key = 'PRI' then '1' else '0' end) as is_pk, + ordinal_position as sort, + column_comment, + (case when extra = 'auto_increment' then '1' else '0' end) as is_increment, + column_type + from information_schema.columns + where table_schema = (select database()) + and table_name = (#{tableName}) + order by ordinal_position + + insert into gen_table_column ( - table_id, - column_name, - column_comment, - column_type, - java_type, - java_field, - is_pk, - is_increment, - is_required, - is_insert, - is_edit, - is_list, - is_query, - query_type, - html_type, - dict_type, - sort, - create_by, - create_time - )values( - #{tableId}, - #{columnName}, - #{columnComment}, - #{columnType}, - #{javaType}, - #{javaField}, - #{isPk}, - #{isIncrement}, - #{isRequired}, - #{isInsert}, - #{isEdit}, - #{isList}, - #{isQuery}, - #{queryType}, - #{htmlType}, - #{dictType}, - #{sort}, - #{createBy}, - sysdate() - ) + table_id, + column_name, + column_comment, + column_type, + java_type, + java_field, + is_pk, + is_increment, + is_required, + is_insert, + is_edit, + is_list, + is_query, + query_type, + html_type, + dict_type, + sort, + create_by, + create_time + )values( + #{tableId}, + #{columnName}, + #{columnComment}, + #{columnType}, + #{javaType}, + #{javaField}, + #{isPk}, + #{isIncrement}, + #{isRequired}, + #{isInsert}, + #{isEdit}, + #{isList}, + #{isQuery}, + #{queryType}, + #{htmlType}, + #{dictType}, + #{sort}, + #{createBy}, + sysdate() + ) - + update gen_table_column @@ -111,14 +141,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - delete from gen_table_column where table_id in + delete from gen_table_column where table_id in #{tableId} - + - delete from gen_table_column where column_id in + delete from gen_table_column where column_id in #{item.columnId} diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/mapper/generator/GenTableMapper.xml b/fastbee-plugs/fastbee-generator/src/main/resources/mapper/generator/GenTableMapper.xml index 14d523d5..895a12f8 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/mapper/generator/GenTableMapper.xml +++ b/fastbee-plugs/fastbee-generator/src/main/resources/mapper/generator/GenTableMapper.xml @@ -1,173 +1,288 @@ + PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + - - - select table_id, table_name, table_comment, sub_table_name, sub_table_fk_name, class_name, tpl_category, package_name, module_name, business_name, function_name, function_author, gen_type, gen_path, options, create_by, create_time, update_by, update_time, remark from gen_table - - - - + + + + AND lower(table_name) like lower(concat('%', #{tableName}, '%')) + + + AND lower(table_comment) like lower(concat('%', #{tableComment}, '%')) + + + AND date_format(create_time,'%y%m%d') >= date_format(#{params.beginTime},'%y%m%d') + + + AND date_format(create_time,'%y%m%d') <= date_format(#{params.endTime},'%y%m%d') + + + + + - - - - - - - - - - - - + + + + + + + + + + + + + insert into gen_table ( - table_name, - table_comment, - class_name, - tpl_category, - package_name, - module_name, - business_name, - function_name, - function_author, - gen_type, - gen_path, - remark, - create_by, - create_time - )values( - #{tableName}, - #{tableComment}, - #{className}, - #{tplCategory}, - #{packageName}, - #{moduleName}, - #{businessName}, - #{functionName}, - #{functionAuthor}, - #{genType}, - #{genPath}, - #{remark}, - #{createBy}, - sysdate() - ) + table_name, + table_comment, + class_name, + tpl_category, + package_name, + module_name, + business_name, + function_name, + function_author, + gen_type, + gen_path, + remark, + create_by, + create_time + )values( + #{tableName}, + #{tableComment}, + #{className}, + #{tplCategory}, + #{packageName}, + #{moduleName}, + #{businessName}, + #{functionName}, + #{functionAuthor}, + #{genType}, + #{genPath}, + #{remark}, + #{createBy}, + sysdate() + ) - + update gen_table @@ -191,9 +306,9 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where table_id = #{tableId} - + - delete from gen_table where table_id in + delete from gen_table where table_id in #{tableId} diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/controller.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/controller.java.vm index 6a40e4ca..b3d3ddb9 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/controller.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/controller.java.vm @@ -39,12 +39,12 @@ public class ${ClassName}Controller extends BaseController { @Autowired private I${ClassName}Service ${className}Service; - /** - * 查询${functionName}列表 - */ - @PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')") - @GetMapping("/list") - @ApiOperation("查询${functionName}列表") +/** + * 查询${functionName}列表 + */ +@PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')") +@GetMapping("/list") +@ApiOperation("查询${functionName}列表") #if($table.crud || $table.sub) public TableDataInfo list(${ClassName} ${className}) { startPage(); diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/convert.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/convert.java.vm index 1af38312..a2d0941a 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/convert.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/convert.java.vm @@ -14,10 +14,9 @@ import java.util.List; * @date ${datetime} */ @Mapper -public interface ${ClassName}Convert -{ +public interface ${ClassName}Convert { - ${ClassName}Convert INSTANCE = Mappers.getMapper(${ClassName}Convert.class); + ${ClassName}Convert INSTANCE = Mappers.getMapper(${ClassName}Convert.class); /** * 实体类转换为VO类 @@ -25,7 +24,7 @@ public interface ${ClassName}Convert * @param ${className} * @return ${functionName}集合 */ - ${ClassName}VO convert${ClassName}VO(${ClassName} ${className}); + ${ClassName}VO convert${ClassName}VO(${ClassName} ${className}); /** * VO类转换为实体类集合 @@ -33,7 +32,7 @@ public interface ${ClassName}Convert * @param ${className}VO * @return ${functionName}集合 */ - ${ClassName} convert${ClassName}(${ClassName}VO ${className}VO); + ${ClassName} convert${ClassName}(${ClassName}VO ${className}VO); /** * 实体类转换为VO类集合 diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/domain.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/domain.java.vm index 8184d3e3..541dabac 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/domain.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/domain.java.vm @@ -1,8 +1,8 @@ package ${packageName}.domain; -#foreach ($import in $importList) -import ${import}; -#end + #foreach ($import in $importList) + import ${import}; + #end import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; @@ -29,47 +29,49 @@ import java.util.Map; @ApiModel(value = "${ClassName}", description = "${functionName} ${tableName}") @Data -@TableName("${tableName}" ) -public class ${ClassName} implements Serializable{ - private static final long serialVersionUID=1L; +@TableName("${tableName}") +public class ${ClassName} implements -#foreach ($column in $columns) - /** $column.columnComment */ - #if($foreach.index == 0) - @TableId(value = "${column.columnName}", type = IdType.AUTO) - #end - #set($parentheseIndex=$column.columnComment.indexOf("(")) - #if($parentheseIndex != -1) - #set($comment=$column.columnComment.substring(0, $parentheseIndex)) - #else - #set($comment=$column.columnComment) - #end - #if($parentheseIndex != -1) - @ApiModelProperty("${comment}") - #elseif($column.javaType == 'Date') - @JsonFormat(pattern = "yyyy-MM-dd") - @ApiModelProperty("${comment}") - #else - @ApiModelProperty("${comment}") - #end - private $column.javaType $column.javaField; + Serializable { + private static final long serialVersionUID = 1L; -#end - @Setter - @TableField(exist = false) - @ApiModelProperty("请求参数") - @JsonInclude(JsonInclude.Include.NON_EMPTY) - private Map params; + #foreach ($column in $columns) + /** $column.columnComment */ + #if($foreach.index == 0) + @TableId(value = "${column.columnName}", type = IdType.AUTO) + #end + #set($parentheseIndex=$column.columnComment.indexOf("(")) + #if($parentheseIndex != -1) + #set($comment=$column.columnComment.substring(0, $parentheseIndex)) + #else + #set($comment=$column.columnComment) + #end + #if($parentheseIndex != -1) + @ApiModelProperty("${comment}") + #elseif($column.javaType == 'Date') + @JsonFormat(pattern = "yyyy-MM-dd") + @ApiModelProperty("${comment}") + #else + @ApiModelProperty("${comment}") + #end + private $column.javaType $column.javaField; - public Map getParams(){ - if (params == null){ - params = new HashMap<>(); + #end + @Setter + @TableField(exist = false) + @ApiModelProperty("请求参数") + @JsonInclude(JsonInclude.Include.NON_EMPTY) + private Map params; + + public Map getParams () { + if (params == null) { + params = new HashMap<>(); + } + return params; + } + + #if($table.sub) + /** $table.subTable.functionName信息 */ + private List<${subClassName}> ${subclassName}List; + #end } - return params; - } - -#if($table.sub) -/** $table.subTable.functionName信息 */ -private List<${subClassName}> ${subclassName}List; -#end -} diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/mapper.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/mapper.java.vm index a2f880e4..e32ac524 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/mapper.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/mapper.java.vm @@ -3,7 +3,7 @@ package ${packageName}.mapper; import ${packageName}.domain.${ClassName}; import com.fastbee.framework.mybatis.mapper.BaseMapperX; #if($table.sub) -import ${packageName}.domain.${subClassName}; +import ${packageName}.domain .${subClassName}; #end /** @@ -12,7 +12,6 @@ import ${packageName}.domain.${subClassName}; * @author ${author} * @date ${datetime} */ -public interface ${ClassName}Mapper extends BaseMapperX<${ClassName}> -{ +public interface ${ClassName}Mapper extends BaseMapperX<${ClassName}> { } diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/service.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/service.java.vm index 167c9674..7ba31bbe 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/service.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/service.java.vm @@ -1,17 +1,18 @@ package ${packageName}.service; import java.util.List; + import ${packageName}.domain.${ClassName}; import ${packageName}.model.${ClassName}VO; import com.baomidou.mybatisplus.extension.service.IService; + /** * ${functionName}Service接口 * * @author ${author} * @date ${datetime} */ -public interface I${ClassName}Service extends IService<${ClassName}> -{ +public interface I${ClassName}Service extends IService<${ClassName}> { /** * 查询${functionName}列表 @@ -19,7 +20,7 @@ public interface I${ClassName}Service extends IService<${ClassName}> * @param ${className} ${functionName} * @return ${functionName}集合 */ - List<${ClassName}VO> select${ClassName}VOList(${ClassName} ${className}); + List<${ClassName}VO> select${ClassName}VOList(${ClassName} ${className}); /** * 查询${functionName} @@ -27,7 +28,7 @@ public interface I${ClassName}Service extends IService<${ClassName}> * @param ${pkColumn.javaField} 主键 * @return ${functionName} */ - ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}); + ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}); /** * 查询${functionName} @@ -35,7 +36,7 @@ public interface I${ClassName}Service extends IService<${ClassName}> * @param ${pkColumn.javaField} 主键 * @return ${functionName} */ - ${ClassName} queryByIdWithCache(${pkColumn.javaType} ${pkColumn.javaField}); + ${ClassName} queryByIdWithCache(${pkColumn.javaType} ${pkColumn.javaField}); /** * 新增${functionName} @@ -60,6 +61,6 @@ public interface I${ClassName}Service extends IService<${ClassName}> * @param isValid 是否进行有效性校验 * @return 是否删除成功 */ - Boolean deleteWithCacheByIds(${pkColumn.javaType}[] ids, Boolean isValid); + Boolean deleteWithCacheByIds(${pkColumn.javaType}[]ids, Boolean isValid); } diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/serviceImpl.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/serviceImpl.java.vm index 149af3cd..3a0f572b 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/serviceImpl.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/serviceImpl.java.vm @@ -3,24 +3,27 @@ package ${packageName}.service.impl; import java.util.List; import java.util.Map; import java.util.Arrays; + import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.core.toolkit.Wrappers; -#foreach ($column in $columns) -#if($column.javaField == 'createTime' || $column.javaField == 'updateTime') -import com.fastbee.common.utils.DateUtils; -#break -#end -#end + #foreach ($column in $columns) + #if($column.javaField == 'createTime' || $column.javaField == 'updateTime') + import com.fastbee.common.utils.DateUtils; + #break + #end + #end import org.springframework.stereotype.Service; + import java.util.Objects; -#if($table.sub) -import java.util.ArrayList; -import org.springframework.transaction.annotation.Transactional; -import ${packageName}.domain.${subClassName}; -import ${packageName}.model.${ClassName}VO; -import ${packageName}.convert.${ClassName}Convert; -#end + #if($table.sub) + import java.util.ArrayList; + + import org.springframework.transaction.annotation.Transactional; + import ${packageName}.domain.${subClassName}; + import ${packageName}.model.${ClassName}VO; + import ${packageName}.convert.${ClassName}Convert; + #end import com.fastbee.common.utils.StringUtils; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; @@ -48,7 +51,7 @@ public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper,${Cl @Override @Cacheable(cacheNames = "${ClassName}", key = "#${pkColumn.javaField}") // 查询时更新key缓存,更新和删除时删除缓存,新增时不更新,下一次查询会更新缓存 - public ${ClassName} queryByIdWithCache(${pkColumn.javaType} ${pkColumn.javaField}){ + public ${ClassName} queryByIdWithCache(${pkColumn.javaType} ${pkColumn.javaField}) { return this.getById(${pkColumn.javaField}); } @@ -61,7 +64,7 @@ public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper,${Cl @Override @Cacheable(cacheNames = "${ClassName}", key = "#${pkColumn.javaField}") // 查询时更新key缓存,更新和删除时删除缓存,新增时不更新,下一次查询会更新缓存 - public ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}){ + public ${ClassName} select${ClassName}ById(${pkColumn.javaType} ${pkColumn.javaField}) { return this.getById(${pkColumn.javaField}); } @@ -98,13 +101,13 @@ public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper,${Cl lqw.$mpMethod($condition, ${ClassName}::get$AttrName, query.get$AttrName()); #else lqw.between(params.get("begin$AttrName") != null && params.get("end$AttrName") != null, - ${ClassName}::get$AttrName ,params.get("begin$AttrName"), params.get("end$AttrName")); + ${ClassName}::get$AttrName , params.get("begin$AttrName"), params.get("end$AttrName")); #end #end #end if (!Objects.isNull(params.get("beginTime")) && - !Objects.isNull(params.get("endTime"))) { + !Objects.isNull(params.get("endTime"))) { lqw.between(${ClassName}::getCreateTime, params.get("beginTime"), params.get("endTime")); } return lqw; @@ -138,7 +141,7 @@ public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper,${Cl /** * 保存前的数据校验 */ - private void validEntityBeforeSave(${ClassName} entity){ + private void validEntityBeforeSave(${ClassName} entity) { //TODO 做一些数据校验,如唯一约束 } @@ -150,9 +153,9 @@ public class ${ClassName}ServiceImpl extends ServiceImpl<${ClassName}Mapper,${Cl * @return 是否删除成功 */ @Override - @CacheEvict(cacheNames = "${ClassName}", keyGenerator = "deleteKeyGenerator" ) - public Boolean deleteWithCacheByIds(${pkColumn.javaType}[] ids, Boolean isValid) { - if(isValid){ + @CacheEvict(cacheNames = "${ClassName}", keyGenerator = "deleteKeyGenerator") + public Boolean deleteWithCacheByIds(${pkColumn.javaType}[]ids, Boolean isValid) { + if (isValid) { //TODO 做一些业务上的校验,判断是否需要校验 } return this.removeByIds(Arrays.asList(ids)); diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/sub-domain.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/sub-domain.java.vm index 5fe04c47..20df536b 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/sub-domain.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/sub-domain.java.vm @@ -1,8 +1,8 @@ package ${packageName}.domain; -#foreach ($import in $subImportList) -import ${import}; -#end + #foreach ($import in $subImportList) + import ${import}; + #end import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.fastbee.common.annotation.Excel; @@ -10,67 +10,68 @@ import com.fastbee.common.core.domain.BaseEntity; /** * ${subTable.functionName}对象 ${subTableName} - * + * * @author ${author} * @date ${datetime} */ -public class ${subClassName} extends BaseEntity -{ - private static final long serialVersionUID = 1L; +public class ${subClassName} extends -#foreach ($column in $subTable.columns) -#if(!$table.isSuperColumn($column.javaField)) - /** $column.columnComment */ -#if($column.list) -#set($parentheseIndex=$column.columnComment.indexOf("(")) -#if($parentheseIndex != -1) -#set($comment=$column.columnComment.substring(0, $parentheseIndex)) -#else -#set($comment=$column.columnComment) -#end -#if($parentheseIndex != -1) - @Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()") -#elseif($column.javaType == 'Date') - @JsonFormat(pattern = "yyyy-MM-dd") - @Excel(name = "${comment}", width = 30, dateFormat = "yyyy-MM-dd") -#else - @Excel(name = "${comment}") -#end -#end - private $column.javaType $column.javaField; + BaseEntity { + private static final long serialVersionUID = 1L; -#end -#end -#foreach ($column in $subTable.columns) -#if(!$table.isSuperColumn($column.javaField)) -#if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]")) -#set($AttrName=$column.javaField) -#else -#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) -#end - public void set${AttrName}($column.javaType $column.javaField) - { - this.$column.javaField = $column.javaField; - } + #foreach ($column in $subTable.columns) + #if(!$table.isSuperColumn($column.javaField)) + /** $column.columnComment */ + #if($column.list) + #set($parentheseIndex=$column.columnComment.indexOf("(")) + #if($parentheseIndex != -1) + #set($comment=$column.columnComment.substring(0, $parentheseIndex)) + #else + #set($comment=$column.columnComment) + #end + #if($parentheseIndex != -1) + @Excel(name = "${comment}", readConverterExp = "$column.readConverterExp()") + #elseif($column.javaType == 'Date') + @JsonFormat(pattern = "yyyy-MM-dd") + @Excel(name = "${comment}", width = 30, dateFormat = "yyyy-MM-dd") + #else + @Excel(name = "${comment}") + #end + #end + private $column.javaType $column.javaField; - public $column.javaType get${AttrName}() - { - return $column.javaField; - } -#end -#end + #end + #end + #foreach ($column in $subTable.columns) + #if(!$table.isSuperColumn($column.javaField)) + #if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]")) + #set($AttrName=$column.javaField) + #else + #set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + #end + public void set${AttrName}($column.javaType $column.javaField) + { + this.$column.javaField = $column.javaField; + } - @Override - public String toString() { - return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) -#foreach ($column in $subTable.columns) -#if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]")) -#set($AttrName=$column.javaField) -#else -#set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) -#end - .append("${column.javaField}", get${AttrName}()) -#end - .toString(); - } -} + public $column.javaType get${AttrName}() + { + return $column.javaField; + } + #end + #end + + @Override + public String toString () { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + #foreach ($column in $subTable.columns) + #if($column.javaField.length() > 2 && $column.javaField.substring(1,2).matches("[A-Z]")) + #set($AttrName=$column.javaField) + #else + #set($AttrName=$column.javaField.substring(0,1).toUpperCase() + ${column.javaField.substring(1)}) + #end + .append("${column.javaField}", get${AttrName}()) + #end + .toString(); + } + } diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/vo.java.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/vo.java.vm index 60e0e52c..2866515e 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/vo.java.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/java/vo.java.vm @@ -1,8 +1,8 @@ package ${packageName}.vo; -#foreach ($import in $importList) -import ${import}; -#end + #foreach ($import in $importList) + import ${import}; + #end import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.fastbee.common.annotation.Excel; @@ -28,35 +28,35 @@ import java.util.Map; @ApiModel(value = "${ClassName}VO", description = "${functionName} ${tableName}") @Data -public class ${ClassName}VO{ +public class ${ClassName}VO { -#foreach ($column in $columns) - /** $column.columnComment */ - #if($foreach.index == 0) - #end - #set($parentheseIndex=$column.columnComment.indexOf("(")) - #if($parentheseIndex != -1) - #set($comment=$column.columnComment.substring(0, $parentheseIndex)) - #else - #set($comment=$column.columnComment) - #end - #if($parentheseIndex != -1) - @ApiModelProperty("${comment}") - @Excel(name = "${comment}") - #elseif($column.javaType == 'Date') - @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") - @ApiModelProperty("${comment}") - @Excel(name = "${comment}") - #else - @Excel(name = "${comment}") - @ApiModelProperty("${comment}") - #end + #foreach ($column in $columns) + /** $column.columnComment */ + #if($foreach.index == 0) + #end + #set($parentheseIndex=$column.columnComment.indexOf("(")) + #if($parentheseIndex != -1) + #set($comment=$column.columnComment.substring(0, $parentheseIndex)) + #else + #set($comment=$column.columnComment) + #end + #if($parentheseIndex != -1) + @ApiModelProperty("${comment}") + @Excel(name = "${comment}") + #elseif($column.javaType == 'Date') + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @ApiModelProperty("${comment}") + @Excel(name = "${comment}") + #else + @Excel(name = "${comment}") + @ApiModelProperty("${comment}") + #end private $column.javaType $column.javaField; -#end + #end -#if($table.sub) -/** $table.subTable.functionName信息 */ -private List<${subClassName}> ${subclassName}List; -#end + #if($table.sub) + /** $table.subTable.functionName信息 */ + private List<${subClassName}> ${subclassName}List; + #end } diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/js/api.js.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/js/api.js.vm index 9295524a..346c95ec 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/js/api.js.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/js/api.js.vm @@ -2,43 +2,43 @@ import request from '@/utils/request' // 查询${functionName}列表 export function list${BusinessName}(query) { - return request({ - url: '/${moduleName}/${businessName}/list', - method: 'get', - params: query - }) + return request({ + url: '/${moduleName}/${businessName}/list', + method: 'get', + params: query + }) } // 查询${functionName}详细 export function get${BusinessName}(${pkColumn.javaField}) { - return request({ - url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, - method: 'get' - }) + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'get' + }) } // 新增${functionName} export function add${BusinessName}(data) { - return request({ - url: '/${moduleName}/${businessName}', - method: 'post', - data: data - }) + return request({ + url: '/${moduleName}/${businessName}', + method: 'post', + data: data + }) } // 修改${functionName} export function update${BusinessName}(data) { - return request({ - url: '/${moduleName}/${businessName}', - method: 'put', - data: data - }) + return request({ + url: '/${moduleName}/${businessName}', + method: 'put', + data: data + }) } // 删除${functionName} export function del${BusinessName}(${pkColumn.javaField}) { - return request({ - url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, - method: 'delete' - }) + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'delete' + }) } diff --git a/fastbee-plugs/fastbee-generator/src/main/resources/vm/vue/index-tree.vue.vm b/fastbee-plugs/fastbee-generator/src/main/resources/vm/vue/index-tree.vue.vm index 07104a7b..afe39d0a 100644 --- a/fastbee-plugs/fastbee-generator/src/main/resources/vm/vue/index-tree.vue.vm +++ b/fastbee-plugs/fastbee-generator/src/main/resources/vm/vue/index-tree.vue.vm @@ -1,68 +1,68 @@