From 798878a541757cacff4d958195fc4ae911e45874 Mon Sep 17 00:00:00 2001 From: dannyxu Date: Fri, 16 Oct 2026 10:12:06 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ai-bird-admin/pom.xml | 107 ++ .../hzvtc/AiResearchServletInitializer.java | 14 + .../net/hzvtc/AiResearchSeverApplication.java | 23 + .../controller/SpeciesInfoApiController.java | 89 + .../controller/common/CaptchaController.java | 86 + .../controller/common/CommonController.java | 110 ++ .../controller/monitor/CacheController.java | 54 + .../controller/monitor/ServerController.java | 27 + .../monitor/SysLogininforController.java | 60 + .../monitor/SysOperlogController.java | 60 + .../monitor/SysUserOnlineController.java | 75 + .../system/NoticeFileInfoController.java | 29 + .../system/SysConfigController.java | 117 ++ .../controller/system/SysDeptController.java | 190 ++ .../system/SysDictDataController.java | 106 ++ .../system/SysDictTypeController.java | 115 ++ .../controller/system/SysIndexController.java | 29 + .../controller/system/SysLoginController.java | 90 + .../controller/system/SysMenuController.java | 118 ++ .../system/SysNoticeController.java | 119 ++ .../controller/system/SysPostController.java | 110 ++ .../system/SysProfileController.java | 128 ++ .../system/SysRegisterController.java | 35 + .../controller/system/SysRoleController.java | 225 +++ .../controller/system/SysUserController.java | 235 +++ .../controller/tool/SwaggerController.java | 24 + .../web/controller/tool/TestController.java | 87 + .../hzvtc/web/controller/tool/UserEntity.java | 60 + .../hzvtc/web/core/config/SwaggerConfig.java | 121 ++ .../src/main/resources/application-d2030.yml | 135 ++ .../src/main/resources/application-dev.yml | 148 ++ .../resources/application-druid-product.yml | 61 + .../src/main/resources/application-druid.yml | 62 + .../src/main/resources/application-jxsdb.yml | 119 ++ .../src/main/resources/application-n2030.yml | 135 ++ .../src/main/resources/application-p2030.yml | 135 ++ .../src/main/resources/application-prod.yml | 136 ++ .../src/main/resources/application-pyh.yml | 134 ++ .../src/main/resources/application-pyh1.yml | 140 ++ .../src/main/resources/application-qzly.yml | 135 ++ .../src/main/resources/application-shunyi.yml | 130 ++ .../src/main/resources/application-xuebao.yml | 119 ++ .../src/main/resources/application-yndc.yml | 136 ++ .../src/main/resources/application.bak.yml | 147 ++ .../src/main/resources/application.yml | 94 + ai-bird-admin/src/main/resources/banner.txt | 2 + ai-bird-admin/src/main/resources/es_ca.crt | 31 + .../src/main/resources/es_ca_server.crt | 31 + .../main/resources/i18n/messages.properties | 35 + .../src/main/resources/logback-product.xml | 93 + .../src/main/resources/logback-pyh.xml | 93 + ai-bird-admin/src/main/resources/logback.xml | 93 + .../main/resources/mybatis/mybatis-config.xml | 20 + ai-bird-common/pom.xml | 151 ++ .../hzvtc/common/annotation/DataScope.java | 28 + .../hzvtc/common/annotation/DataSource.java | 28 + .../net/hzvtc/common/annotation/Excel.java | 106 ++ .../net/hzvtc/common/annotation/Excels.java | 18 + .../java/net/hzvtc/common/annotation/Log.java | 46 + .../hzvtc/common/annotation/RateLimiter.java | 40 + .../hzvtc/common/annotation/RepeatSubmit.java | 31 + .../hzvtc/common/config/AiBirdSysConfig.java | 158 ++ .../net/hzvtc/common/constant/Constants.java | 183 ++ .../hzvtc/common/constant/GenConstants.java | 114 ++ .../net/hzvtc/common/constant/HttpStatus.java | 89 + .../common/constant/ScheduleConstants.java | 50 + .../hzvtc/common/constant/UserConstants.java | 78 + .../core/controller/BaseController.java | 163 ++ .../hzvtc/common/core/domain/AjaxResult.java | 162 ++ .../hzvtc/common/core/domain/BaseEntity.java | 23 + .../hzvtc/common/core/domain/TreeEntity.java | 79 + .../hzvtc/common/core/domain/TreeSelect.java | 19 + .../common/core/domain/entity/SysDept.java | 32 + .../core/domain/entity/SysDictData.java | 119 ++ .../core/domain/entity/SysDictType.java | 64 + .../common/core/domain/entity/SysMenu.java | 31 + .../common/core/domain/entity/SysRole.java | 183 ++ .../common/core/domain/entity/SysUser.java | 265 +++ .../common/core/domain/model/LoginBody.java | 13 + .../common/core/domain/model/LoginUser.java | 348 ++++ .../core/domain/model/RegisterBody.java | 11 + .../hzvtc/common/core/page/PageDomain.java | 101 ++ .../hzvtc/common/core/page/TableDataInfo.java | 85 + .../hzvtc/common/core/page/TableSupport.java | 55 + .../hzvtc/common/core/redis/RedisCache.java | 246 +++ .../hzvtc/common/core/text/CharsetKit.java | 86 + .../net/hzvtc/common/core/text/Convert.java | 1005 +++++++++++ .../hzvtc/common/core/text/StrFormatter.java | 92 + .../hzvtc/common/enums/BusinessStatus.java | 20 + .../net/hzvtc/common/enums/BusinessType.java | 59 + .../hzvtc/common/enums/DataSourceType.java | 19 + .../net/hzvtc/common/enums/HttpMethod.java | 36 + .../net/hzvtc/common/enums/LimitType.java | 20 + .../net/hzvtc/common/enums/OperatorType.java | 24 + .../net/hzvtc/common/enums/UserStatus.java | 30 + .../common/exception/DemoModeException.java | 15 + .../common/exception/GlobalException.java | 58 + .../common/exception/ServiceException.java | 73 + .../hzvtc/common/exception/UtilException.java | 26 + .../common/exception/base/BaseException.java | 97 + .../common/exception/file/FileException.java | 19 + .../FileNameLengthLimitExceededException.java | 16 + .../file/FileSizeLimitExceededException.java | 16 + .../file/InvalidExtensionException.java | 81 + .../common/exception/job/TaskException.java | 34 + .../exception/user/CaptchaException.java | 16 + .../user/CaptchaExpireException.java | 16 + .../common/exception/user/UserException.java | 18 + .../user/UserNoLoginPermissionException.java | 10 + .../user/UserPasswordNotMatchException.java | 16 + .../hzvtc/common/filter/RepeatableFilter.java | 52 + .../filter/RepeatedlyRequestWrapper.java | 75 + .../net/hzvtc/common/filter/XssFilter.java | 74 + .../filter/XssHttpServletRequestWrapper.java | 111 ++ .../java/net/hzvtc/common/utils/Arith.java | 114 ++ .../hzvtc/common/utils/Chinese2pinyin.java | 54 + .../net/hzvtc/common/utils/CommonUtils.java | 34 + .../net/hzvtc/common/utils/DateUtils.java | 156 ++ .../net/hzvtc/common/utils/DictUtils.java | 183 ++ .../net/hzvtc/common/utils/ExceptionUtil.java | 40 + .../java/net/hzvtc/common/utils/LogUtils.java | 18 + .../net/hzvtc/common/utils/MessageUtils.java | 26 + .../net/hzvtc/common/utils/PageUtils.java | 38 + .../net/hzvtc/common/utils/SecurityUtils.java | 99 ++ .../net/hzvtc/common/utils/ServletUtils.java | 152 ++ .../net/hzvtc/common/utils/StringUtils.java | 535 ++++++ .../java/net/hzvtc/common/utils/Threads.java | 99 ++ .../hzvtc/common/utils/VerifyCodeUtils.java | 228 +++ .../hzvtc/common/utils/bean/BeanUtils.java | 110 ++ .../common/utils/bean/BeanValidators.java | 20 + .../common/utils/file/FileTypeUtils.java | 76 + .../common/utils/file/FileUploadUtils.java | 239 +++ .../hzvtc/common/utils/file/FileUtils.java | 216 +++ .../hzvtc/common/utils/file/ImageUtils.java | 82 + .../common/utils/file/MimeTypeUtils.java | 51 + .../hzvtc/common/utils/html/EscapeUtil.java | 167 ++ .../hzvtc/common/utils/html/HTMLFilter.java | 570 ++++++ .../hzvtc/common/utils/http/HttpHelper.java | 55 + .../hzvtc/common/utils/http/HttpUtils.java | 212 +++ .../hzvtc/common/utils/ip/AddressUtils.java | 46 + .../net/hzvtc/common/utils/ip/IpUtils.java | 195 +++ .../common/utils/poi/ExcelHandlerAdapter.java | 7 + .../net/hzvtc/common/utils/poi/ExcelUtil.java | 785 +++++++++ .../common/utils/reflect/ReflectUtils.java | 410 +++++ .../net/hzvtc/common/utils/sign/Base64.java | 214 +++ .../net/hzvtc/common/utils/sign/Md5Utils.java | 66 + .../common/utils/spring/SpringUtils.java | 146 ++ .../net/hzvtc/common/utils/sql/SqlUtil.java | 61 + .../net/hzvtc/common/utils/uuid/IdUtils.java | 49 + .../net/hzvtc/common/utils/uuid/UUID.java | 484 +++++ .../main/java/net/hzvtc/common/xss/Xss.java | 22 + .../net/hzvtc/common/xss/XssValidator.java | 29 + ai-bird-es/pom.xml | 76 + .../config/CustomDateTimeDeserializer.java | 22 + .../config/CustomDateTimeSerializer.java | 21 + .../java/net/hzvtc/config/ESClientConfig.java | 143 ++ .../hzvtc/config/JacksonConfiguration.java | 19 + .../controller/EsRecordReportController.java | 134 ++ .../EsResultRecordDetailsController.java | 134 ++ .../EsSpeciesInfoApiController.java | 24 + .../net/hzvtc/es/domain/EsResultData.java | 32 + .../es/domain/EsResultRecordDetails.java | 34 + .../es/domain/EsResultRecordDetailsVo.java | 34 + .../mapper/EsResultRecordDetailsMapper.java | 20 + .../es/service/EsRecordReportService.java | 35 + .../service/EsResultRecordDetailsService.java | 53 + .../hzvtc/es/service/impl/CommonEsUtils.java | 191 ++ .../impl/EsRecordReportServiceImpl.java | 1111 ++++++++++++ .../EsResultRecordDetailsServiceImpl.java | 885 ++++++++++ .../mapper/EsResultRecordDetailsMapper.xml | 107 ++ ai-bird-framework/pom.xml | 64 + .../framework/aspectj/DataScopeAspect.java | 149 ++ .../framework/aspectj/DataSourceAspect.java | 73 + .../hzvtc/framework/aspectj/LogAspect.java | 219 +++ .../framework/aspectj/RateLimiterAspect.java | 92 + .../framework/config/ApplicationConfig.java | 30 + .../hzvtc/framework/config/CaptchaConfig.java | 83 + .../hzvtc/framework/config/DruidConfig.java | 127 ++ .../config/FastJson2JsonRedisSerializer.java | 62 + .../hzvtc/framework/config/FilterConfig.java | 59 + .../framework/config/KaptchaTextCreator.java | 75 + .../hzvtc/framework/config/MyBatisConfig.java | 133 ++ .../hzvtc/framework/config/RedisConfig.java | 79 + .../framework/config/ResourcesConfig.java | 66 + .../framework/config/SecurityConfig.java | 149 ++ .../hzvtc/framework/config/ServerConfig.java | 33 + .../framework/config/ThreadPoolConfig.java | 63 + .../config/properties/DruidProperties.java | 77 + .../datasource/DynamicDataSource.java | 26 + .../DynamicDataSourceContextHolder.java | 45 + .../datasource/MySqlDialectCustom.java | 24 + .../interceptor/RepeatSubmitInterceptor.java | 56 + .../impl/SameUrlDataInterceptor.java | 111 ++ .../hzvtc/framework/manager/AsyncManager.java | 55 + .../framework/manager/ShutdownManager.java | 39 + .../manager/factory/AsyncFactory.java | 103 ++ .../filter/JwtAuthenticationTokenFilter.java | 45 + .../handle/AuthenticationEntryPointImpl.java | 35 + .../handle/LogoutSuccessHandlerImpl.java | 54 + .../hzvtc/framework/web/domain/Server.java | 240 +++ .../framework/web/domain/server/Cpu.java | 101 ++ .../framework/web/domain/server/Jvm.java | 122 ++ .../framework/web/domain/server/Mem.java | 61 + .../framework/web/domain/server/Sys.java | 84 + .../framework/web/domain/server/SysFile.java | 114 ++ .../web/exception/GlobalExceptionHandler.java | 106 ++ .../web/service/PermissionService.java | 166 ++ .../web/service/SysLoginService.java | 101 ++ .../web/service/SysPermissionService.java | 62 + .../web/service/SysRegisterService.java | 97 + .../framework/web/service/TokenService.java | 132 ++ .../web/service/UserDetailsServiceImpl.java | 70 + ai-bird-generator/pom.xml | 40 + .../net/hzvtc/generator/config/GenConfig.java | 73 + .../generator/controller/GenController.java | 194 ++ .../net/hzvtc/generator/domain/GenTable.java | 365 ++++ .../generator/domain/GenTableColumn.java | 350 ++++ .../mapper/GenTableColumnMapper.java | 60 + .../generator/mapper/GenTableMapper.java | 83 + .../service/GenTableColumnService.java | 44 + .../service/GenTableColumnServiceImpl.java | 64 + .../generator/service/GenTableService.java | 121 ++ .../service/GenTableServiceImpl.java | 447 +++++ .../net/hzvtc/generator/util/GenUtils.java | 259 +++ .../generator/util/VelocityInitializer.java | 35 + .../hzvtc/generator/util/VelocityUtils.java | 334 ++++ .../src/main/resources/generator.yml | 10 + .../mapper/generator/GenTableColumnMapper.xml | 136 ++ .../mapper/generator/GenTableMapper.xml | 318 ++++ .../main/resources/vm/java/controller.java.vm | 108 ++ .../src/main/resources/vm/java/domain.java.vm | 89 + .../src/main/resources/vm/java/mapper.java.vm | 91 + .../main/resources/vm/java/service.java.vm | 61 + .../resources/vm/java/serviceImpl.java.vm | 162 ++ .../main/resources/vm/java/sub-domain.java.vm | 73 + .../src/main/resources/vm/js/api.js.vm | 44 + .../src/main/resources/vm/sql/sql.vm | 22 + .../main/resources/vm/vue/index-tree.vue.vm | 482 +++++ .../src/main/resources/vm/vue/index.vue.vm | 573 ++++++ .../resources/vm/vue/v3/index-tree.vue.vm | 464 +++++ .../src/main/resources/vm/vue/v3/index.vue.vm | 670 +++++++ .../src/main/resources/vm/vue/v3/readme.txt | 1 + .../main/resources/vm/xml/mapper.xml.old.vm | 136 ++ .../src/main/resources/vm/xml/mapper.xml.vm | 159 ++ ai-bird-quartz/pom.xml | 48 + .../hzvtc/quartz/config/ScheduleConfig.java | 57 + .../quartz/controller/QuartzController.java | 24 + .../quartz/controller/SysJobController.java | 158 ++ .../controller/SysJobLogController.java | 82 + .../java/net/hzvtc/quartz/domain/SysJob.java | 117 ++ .../net/hzvtc/quartz/domain/SysJobLog.java | 156 ++ .../hzvtc/quartz/mapper/SysJobLogMapper.java | 64 + .../net/hzvtc/quartz/mapper/SysJobMapper.java | 67 + .../quartz/service/SysJobLogService.java | 56 + .../hzvtc/quartz/service/SysJobService.java | 102 ++ .../quartz/service/impl/QuartzJobUtils.java | 44 + .../service/impl/SysJobLogServiceImpl.java | 81 + .../service/impl/SysJobServiceImpl.java | 230 +++ .../task/BirdLeaveArriveCalcYearTask.java | 16 + .../java/net/hzvtc/quartz/task/DemoTask.java | 24 + .../quartz/task/DeviceConnectionTask.java | 15 + .../quartz/task/DeviceOfflineCheckTask.java | 15 + .../java/net/hzvtc/quartz/task/EmailTask.java | 20 + .../hzvtc/quartz/task/ExtraAudioListTask.java | 16 + .../task/ExtractResultDataListTask.java | 20 + .../quartz/task/LevelOneSpeciesDailyTask.java | 21 + .../quartz/task/ResultMediaDataPostTask.java | 27 + .../task/ResultRecordDailyStatTask.java | 19 + .../quartz/task/ResultRecordToEsTask.java | 15 + .../task/SpeciesWinterPeriodStatTask.java | 15 + .../hzvtc/quartz/util/AbstractQuartzJob.java | 97 + .../java/net/hzvtc/quartz/util/CronUtils.java | 63 + .../net/hzvtc/quartz/util/JobInvokeUtil.java | 182 ++ .../QuartzDisallowConcurrentExecution.java | 21 + .../hzvtc/quartz/util/QuartzJobExecution.java | 19 + .../net/hzvtc/quartz/util/ScheduleUtils.java | 134 ++ .../mapper/quartz/SysJobLogMapper.xml | 102 ++ .../resources/mapper/quartz/SysJobMapper.xml | 111 ++ ai-bird-system/pom.xml | 73 + .../java/net/hzvtc/app/domain/AppUpgrade.java | 25 + .../hzvtc/app/mapper/AppUpgradeMapper.java | 9 + .../hzvtc/app/service/AppUpgradeService.java | 9 + .../service/impl/AppUpgradeServiceImpl.java | 32 + .../controller/ProtectedAreaController.java | 151 ++ .../ProtectedAreaSpeciesController.java | 137 ++ .../ProtectedCareSpeciesController.java | 58 + .../SpeciesAbnormalInfoController.java | 80 + .../controller/WinteringPeriodController.java | 97 + .../net/hzvtc/area/domain/ProtectedArea.java | 39 + .../area/domain/ProtectedAreaSpecies.java | 24 + .../area/domain/ProtectedCareSpecies.java | 17 + .../area/domain/SpeciesAbnormalInfo.java | 29 + .../hzvtc/area/domain/WinteringPeriod.java | 20 + .../area/mapper/ProtectedAreaMapper.java | 41 + .../mapper/ProtectedAreaSpeciesMapper.java | 40 + .../mapper/ProtectedCareSpeciesMapper.java | 19 + .../mapper/SpeciesAbnormalInfoMapper.java | 30 + .../area/mapper/WinteringPeriodMapper.java | 22 + .../area/service/ProtectedAreaService.java | 41 + .../service/ProtectedAreaSpeciesService.java | 38 + .../service/ProtectedCareSpeciesService.java | 20 + .../service/SpeciesAbnormalInfoService.java | 34 + .../area/service/WinteringPeriodService.java | 24 + .../impl/ProtectedAreaServiceImpl.java | 191 ++ .../impl/ProtectedAreaSpeciesServiceImpl.java | 330 ++++ .../impl/ProtectedCareSpeciesServiceImpl.java | 73 + .../impl/SpeciesAbnormalInfoServiceImpl.java | 214 +++ .../impl/WinteringPeriodServiceImpl.java | 120 ++ .../controller/BirdCatalogueController.java | 112 ++ .../bird/controller/BirdFamilyController.java | 111 ++ .../controller/BirdFlyingInfoController.java | 96 + .../bird/controller/BirdGenusController.java | 113 ++ .../BirdLeaveArriveInfoController.java | 98 ++ .../bird/controller/BirdMediaController.java | 103 ++ .../controller/BirdSpeciesController.java | 183 ++ .../net/hzvtc/bird/domain/BirdCatalogue.java | 18 + .../net/hzvtc/bird/domain/BirdFamily.java | 20 + .../net/hzvtc/bird/domain/BirdFlyingInfo.java | 21 + .../java/net/hzvtc/bird/domain/BirdGenus.java | 21 + .../bird/domain/BirdLeaveArriveInfo.java | 23 + .../java/net/hzvtc/bird/domain/BirdMedia.java | 20 + .../net/hzvtc/bird/domain/BirdSpecies.java | 39 + .../net/hzvtc/bird/domain/SpeciesAnswer.java | 18 + .../hzvtc/bird/domain/SpeciesAnswerItem.java | 16 + .../net/hzvtc/bird/domain/SpeciesIntro.java | 25 + .../net/hzvtc/bird/domain/SpeciesList.java | 21 + .../bird/mapper/BirdCatalogueMapper.java | 24 + .../hzvtc/bird/mapper/BirdFamilyMapper.java | 24 + .../bird/mapper/BirdFlyingInfoMapper.java | 63 + .../hzvtc/bird/mapper/BirdGenusMapper.java | 24 + .../mapper/BirdLeaveArriveInfoMapper.java | 27 + .../hzvtc/bird/mapper/BirdMediaMapper.java | 22 + .../hzvtc/bird/mapper/BirdSpeciesMapper.java | 42 + .../bird/mapper/SpeciesAnswerMapper.java | 15 + .../hzvtc/bird/mapper/SpeciesIntroMapper.java | 18 + .../bird/service/BirdCatalogueService.java | 26 + .../hzvtc/bird/service/BirdFamilyService.java | 26 + .../bird/service/BirdFlyingInfoService.java | 63 + .../hzvtc/bird/service/BirdGenusService.java | 26 + .../service/BirdLeaveArriveInfoService.java | 22 + .../hzvtc/bird/service/BirdMediaService.java | 26 + .../bird/service/BirdSpeciesService.java | 56 + .../bird/service/SpeciesAnswerService.java | 15 + .../bird/service/SpeciesIntroService.java | 18 + .../impl/BirdCatalogueServiceImpl.java | 153 ++ .../service/impl/BirdFamilyServiceImpl.java | 165 ++ .../impl/BirdFlyingInfoServiceImpl.java | 92 + .../service/impl/BirdGenusServiceImpl.java | 170 ++ .../impl/BirdLeaveArriveInfoServiceImpl.java | 107 ++ .../service/impl/BirdMediaServiceImpl.java | 117 ++ .../service/impl/BirdSpeciesServiceImpl.java | 263 +++ .../impl/SpeciesAnswerServiceImpl.java | 33 + .../service/impl/SpeciesIntroServiceImpl.java | 42 + .../controller/FavoriteMediaController.java | 101 ++ .../check/controller/MediaItemController.java | 23 + .../controller/ResultMediaController.java | 77 + .../controller/ResultRecordController.java | 180 ++ .../ResultRecordDetailsController.java | 185 ++ .../data/check/domain/FavoriteMedia.java | 17 + .../hzvtc/data/check/domain/MediaItem.java | 22 + .../hzvtc/data/check/domain/ResultMedia.java | 467 +++++ .../hzvtc/data/check/domain/ResultRecord.java | 209 +++ .../check/domain/ResultRecordDetails.java | 345 ++++ .../check/mapper/FavoriteMediaMapper.java | 24 + .../data/check/mapper/MediaItemMapper.java | 61 + .../data/check/mapper/ResultMediaMapper.java | 69 + .../mapper/ResultRecordDetailsMapper.java | 71 + .../data/check/mapper/ResultRecordMapper.java | 37 + .../check/service/FavoriteMediaService.java | 24 + .../data/check/service/MediaItemService.java | 61 + .../check/service/ResultMediaService.java | 68 + .../service/ResultRecordDetailsService.java | 73 + .../service/ResultRecordExtractService.java | 18 + .../check/service/ResultRecordService.java | 52 + .../impl/FavoriteMediaServiceImpl.java | 108 ++ .../service/impl/MediaItemServiceImpl.java | 87 + .../service/impl/ResultMediaServiceImpl.java | 388 ++++ .../impl/ResultRecordDetailsServiceImpl.java | 686 ++++++++ .../impl/ResultRecordExtractServiceImpl.java | 304 ++++ .../service/impl/ResultRecordServiceImpl.java | 689 ++++++++ .../controller/TableStatInfoController.java | 81 + .../hzvtc/data/job/domain/TableStatInfo.java | 14 + .../data/job/mapper/TableStatInfoMapper.java | 20 + .../job/service/TableStatInfoService.java | 20 + .../impl/TableStatInfoServiceImpl.java | 81 + .../controller/DeviceInfoController.java | 159 ++ .../controller/HeatmapInfoController.java | 97 + .../net/hzvtc/device/domain/DeviceInfo.java | 40 + .../net/hzvtc/device/domain/HeatmapInfo.java | 24 + .../hzvtc/device/mapper/DeviceInfoMapper.java | 51 + .../device/mapper/HeatmapInfoMapper.java | 61 + .../device/service/DeviceInfoService.java | 52 + .../device/service/HeatmapInfoService.java | 23 + .../service/impl/DeviceInfoServiceImpl.java | 303 ++++ .../service/impl/HeatmapInfoServiceImpl.java | 128 ++ .../controller/BirdRealTimeController.java | 110 ++ .../echart/domain/vo/BirdStatDataVo.java | 54 + .../echart/mapper/BirdDataStatMapper.java | 55 + .../echart/service/BirdDataStatService.java | 61 + .../service/impl/BirdDataStatServiceImpl.java | 530 ++++++ .../net/hzvtc/email/service/EmailService.java | 9 + .../email/service/impl/EmailServiceImpl.java | 62 + .../controller/MediaFileInfoController.java | 262 +++ .../controller/MediaFileItemController.java | 98 ++ .../net/hzvtc/file/domain/MediaFileInfo.java | 24 + .../net/hzvtc/file/domain/MediaFileItem.java | 22 + .../file/mapper/MediaFileInfoMapper.java | 20 + .../file/mapper/MediaFileItemMapper.java | 22 + .../file/service/MediaFileInfoService.java | 57 + .../file/service/MediaFileItemService.java | 22 + .../impl/MediaFileInfoServiceImpl.java | 1559 +++++++++++++++++ .../impl/MediaFileItemServiceImpl.java | 92 + .../ObservationFilesController.java | 98 ++ .../controller/ObservationsController.java | 102 ++ .../naturalist/domain/ObservationFiles.java | 22 + .../hzvtc/naturalist/domain/Observations.java | 29 + .../mapper/ObservationFilesMapper.java | 61 + .../naturalist/mapper/ObservationsMapper.java | 61 + .../service/ObservationFilesService.java | 61 + .../service/ObservationsService.java | 28 + .../impl/ObservationFilesServiceImpl.java | 87 + .../service/impl/ObservationsServiceImpl.java | 198 +++ .../controller/CameraOnvifController.java | 46 + .../onvif/service/CameraOnvifService.java | 15 + .../service/impl/CameraOnvifServiceImpl.java | 198 +++ .../controller/MessageReadInfoController.java | 86 + .../net/hzvtc/system/domain/MenuInSys.java | 17 + .../hzvtc/system/domain/MessageReadInfo.java | 20 + .../hzvtc/system/domain/NoticeFileInfo.java | 18 + .../hzvtc/system/domain/NoticeReadDept.java | 19 + .../net/hzvtc/system/domain/NoticeReader.java | 20 + .../net/hzvtc/system/domain/RoleInArea.java | 12 + .../net/hzvtc/system/domain/SysConfig.java | 77 + .../hzvtc/system/domain/SysLogininfor.java | 144 ++ .../net/hzvtc/system/domain/SysNotice.java | 25 + .../net/hzvtc/system/domain/SysOperLog.java | 255 +++ .../java/net/hzvtc/system/domain/SysPost.java | 83 + .../net/hzvtc/system/domain/SysRoleDept.java | 46 + .../net/hzvtc/system/domain/SysRoleMenu.java | 47 + .../hzvtc/system/domain/SysUserOnline.java | 113 ++ .../net/hzvtc/system/domain/SysUserPost.java | 46 + .../net/hzvtc/system/domain/SysUserRole.java | 47 + .../system/domain/vo/DocStateCountVO.java | 11 + .../net/hzvtc/system/domain/vo/MessageVo.java | 17 + .../net/hzvtc/system/domain/vo/MetaVo.java | 106 ++ .../net/hzvtc/system/domain/vo/RouterVo.java | 19 + .../hzvtc/system/mapper/MenuInSysMapper.java | 61 + .../system/mapper/MessageReadInfoMapper.java | 22 + .../system/mapper/NoticeFileInfoMapper.java | 23 + .../system/mapper/NoticeReadDeptMapper.java | 20 + .../system/mapper/NoticeReaderMapper.java | 40 + .../hzvtc/system/mapper/SysConfigMapper.java | 68 + .../hzvtc/system/mapper/SysDeptMapper.java | 49 + .../system/mapper/SysDictDataMapper.java | 96 + .../system/mapper/SysDictTypeMapper.java | 86 + .../system/mapper/SysLogininforMapper.java | 42 + .../hzvtc/system/mapper/SysMenuMapper.java | 118 ++ .../hzvtc/system/mapper/SysNoticeMapper.java | 32 + .../hzvtc/system/mapper/SysOperLogMapper.java | 48 + .../hzvtc/system/mapper/SysPostMapper.java | 99 ++ .../system/mapper/SysRoleDeptMapper.java | 44 + .../hzvtc/system/mapper/SysRoleMapper.java | 107 ++ .../system/mapper/SysRoleMenuMapper.java | 25 + .../hzvtc/system/mapper/SysUserMapper.java | 45 + .../system/mapper/SysUserPostMapper.java | 44 + .../system/mapper/SysUserRoleMapper.java | 63 + .../system/service/MenuInSysService.java | 61 + .../service/MessageReadInfoService.java | 61 + .../system/service/NoticeFileInfoService.java | 21 + .../system/service/NoticeReadDeptService.java | 18 + .../system/service/NoticeReaderService.java | 39 + .../system/service/SysConfigService.java | 90 + .../hzvtc/system/service/SysDeptService.java | 47 + .../system/service/SysDictDataService.java | 61 + .../system/service/SysDictTypeService.java | 99 ++ .../system/service/SysLogininforService.java | 40 + .../hzvtc/system/service/SysMenuService.java | 136 ++ .../system/service/SysNoticeService.java | 33 + .../system/service/SysOperLogService.java | 48 + .../hzvtc/system/service/SysPostService.java | 100 ++ .../hzvtc/system/service/SysRoleService.java | 53 + .../system/service/SysUserOnlineService.java | 47 + .../hzvtc/system/service/SysUserService.java | 60 + .../service/impl/MenuInSysServiceImpl.java | 87 + .../impl/MessageReadInfoServiceImpl.java | 94 + .../impl/NoticeFileInfoServiceImpl.java | 83 + .../impl/NoticeReadDeptServiceImpl.java | 70 + .../service/impl/NoticeReaderServiceImpl.java | 55 + .../service/impl/SysConfigServiceImpl.java | 205 +++ .../service/impl/SysDeptServiceImpl.java | 279 +++ .../service/impl/SysDictDataServiceImpl.java | 103 ++ .../service/impl/SysDictTypeServiceImpl.java | 203 +++ .../impl/SysLogininforServiceImpl.java | 61 + .../service/impl/SysMenuServiceImpl.java | 306 ++++ .../service/impl/SysNoticeServiceImpl.java | 213 +++ .../service/impl/SysOperLogServiceImpl.java | 71 + .../service/impl/SysPostServiceImpl.java | 164 ++ .../service/impl/SysRoleServiceImpl.java | 403 +++++ .../impl/SysUserOnlineServiceImpl.java | 86 + .../service/impl/SysUserServiceImpl.java | 509 ++++++ .../api/service/SpeciesInfoApiService.java | 28 + .../impl/SpeciesInfoApiServiceImpl.java | 371 ++++ .../controller/BirdWebPageStatController.java | 87 + .../SpeciesDailyInhabitController.java | 70 + .../SpeciesDailyStatController.java | 206 +++ .../SpeciesInhabitStatController.java | 97 + .../SpeciesLocationInfoController.java | 96 + .../SpeciesWinterPeriodController.java | 96 + .../web/stat/domain/SpeciesDailyInhabit.java | 19 + .../web/stat/domain/SpeciesDailyStat.java | 21 + .../web/stat/domain/SpeciesInhabitStat.java | 22 + .../web/stat/domain/SpeciesLocationInfo.java | 19 + .../web/stat/domain/SpeciesWinterPeriod.java | 23 + .../stat/mapper/BirdWebPageStatMapper.java | 42 + .../mapper/SpeciesDailyInhabitMapper.java | 29 + .../stat/mapper/SpeciesDailyStatMapper.java | 72 + .../stat/mapper/SpeciesInhabitStatMapper.java | 61 + .../mapper/SpeciesLocationInfoMapper.java | 61 + .../mapper/SpeciesWinterPeriodMapper.java | 22 + .../stat/service/BirdWebPageStatService.java | 35 + .../service/SpeciesDailyInhabitService.java | 33 + .../stat/service/SpeciesDailyStatService.java | 91 + .../service/SpeciesInhabitStatService.java | 61 + .../service/SpeciesLocationInfoService.java | 61 + .../service/SpeciesWinterPeriodService.java | 22 + .../impl/BirdWebPageStatServiceImpl.java | 432 +++++ .../impl/SpeciesDailyInhabitServiceImpl.java | 141 ++ .../impl/SpeciesDailyStatServiceImpl.java | 1382 +++++++++++++++ .../impl/SpeciesInhabitStatServiceImpl.java | 87 + .../impl/SpeciesLocationInfoServiceImpl.java | 87 + .../impl/SpeciesWinterPeriodServiceImpl.java | 149 ++ .../resources/mapper/app/AppUpgradeMapper.xml | 27 + .../mapper/area/ProtectedAreaMapper.xml | 299 ++++ .../area/ProtectedAreaSpeciesMapper.xml | 233 +++ .../area/ProtectedCareSpeciesMapper.xml | 60 + .../mapper/area/SpeciesAbnormalInfoMapper.xml | 159 ++ .../mapper/area/WinteringPeriodMapper.xml | 90 + .../mapper/birdInfo/BirdCatalogueMapper.xml | 90 + .../mapper/birdInfo/BirdFamilyMapper.xml | 96 + .../mapper/birdInfo/BirdFlyingInfoMapper.xml | 91 + .../mapper/birdInfo/BirdGenusMapper.xml | 96 + .../birdInfo/BirdLeaveArriveInfoMapper.xml | 127 ++ .../mapper/birdInfo/BirdMediaMapper.xml | 128 ++ .../mapper/birdInfo/BirdSpeciesMapper.xml | 306 ++++ .../mapper/birdInfo/SpeciesAnswerMapper.xml | 37 + .../mapper/birdInfo/SpeciesIntroMapper.xml | 81 + .../mapper/dataCheck/FavoriteMediaMapper.xml | 75 + .../mapper/dataCheck/MediaItemMapper.xml | 90 + .../mapper/dataCheck/ResultMediaMapper.xml | 628 +++++++ .../dataCheck/ResultRecordDetailsMapper.xml | 675 +++++++ .../mapper/dataCheck/ResultRecordMapper.xml | 193 ++ .../mapper/device/DeviceInfoMapper.xml | 323 ++++ .../mapper/device/HeatmapInfoMapper.xml | 93 + .../mapper/echart/BirdDataStatMapper.xml | 616 +++++++ .../mapper/file/MediaFileInfoMapper.xml | 78 + .../mapper/file/MediaFileItemMapper.xml | 102 ++ .../mapper/job/TableStatInfoMapper.xml | 52 + .../naturalist/ObservationFilesMapper.xml | 87 + .../mapper/naturalist/ObservationsMapper.xml | 94 + .../mapper/stat/BirdWebPageStatMapper.xml | 514 ++++++ .../mapper/stat/SpeciesDailyInhabitMapper.xml | 198 +++ .../mapper/stat/SpeciesDailyStatMapper.xml | 610 +++++++ .../mapper/stat/SpeciesInhabitStatMapper.xml | 101 ++ .../mapper/stat/SpeciesLocationInfoMapper.xml | 78 + .../mapper/stat/SpeciesWinterPeriodMapper.xml | 125 ++ .../mapper/system/MenuInSysMapper.xml | 69 + .../mapper/system/MessageReadInfoMapper.xml | 73 + .../mapper/system/NoticeFileInfoMapper.xml | 78 + .../mapper/system/NoticeReadDeptMapper.xml | 69 + .../mapper/system/NoticeReaderMapper.xml | 40 + .../mapper/system/SysConfigMapper.xml | 123 ++ .../resources/mapper/system/SysDeptMapper.xml | 281 +++ .../mapper/system/SysDictDataMapper.xml | 124 ++ .../mapper/system/SysDictTypeMapper.xml | 107 ++ .../mapper/system/SysLogininforMapper.xml | 57 + .../resources/mapper/system/SysMenuMapper.xml | 272 +++ .../mapper/system/SysNoticeMapper.xml | 165 ++ .../mapper/system/SysOperLogMapper.xml | 98 ++ .../resources/mapper/system/SysPostMapper.xml | 122 ++ .../mapper/system/SysRoleDeptMapper.xml | 34 + .../resources/mapper/system/SysRoleMapper.xml | 174 ++ .../mapper/system/SysRoleMenuMapper.xml | 73 + .../resources/mapper/system/SysUserMapper.xml | 332 ++++ .../mapper/system/SysUserPostMapper.xml | 34 + .../mapper/system/SysUserRoleMapper.xml | 52 + pom.xml | 297 ++++ 586 files changed, 65645 insertions(+) create mode 100644 ai-bird-admin/pom.xml create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/AiResearchServletInitializer.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/AiResearchSeverApplication.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/api/controller/SpeciesInfoApiController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CaptchaController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CommonController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/CacheController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/ServerController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysLogininforController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysOperlogController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysUserOnlineController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/NoticeFileInfoController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysConfigController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDeptController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictDataController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictTypeController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysIndexController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysLoginController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysMenuController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysNoticeController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysPostController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysProfileController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRegisterController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRoleController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysUserController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/SwaggerController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/TestController.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/UserEntity.java create mode 100644 ai-bird-admin/src/main/java/net/hzvtc/web/core/config/SwaggerConfig.java create mode 100644 ai-bird-admin/src/main/resources/application-d2030.yml create mode 100644 ai-bird-admin/src/main/resources/application-dev.yml create mode 100644 ai-bird-admin/src/main/resources/application-druid-product.yml create mode 100644 ai-bird-admin/src/main/resources/application-druid.yml create mode 100644 ai-bird-admin/src/main/resources/application-jxsdb.yml create mode 100644 ai-bird-admin/src/main/resources/application-n2030.yml create mode 100644 ai-bird-admin/src/main/resources/application-p2030.yml create mode 100644 ai-bird-admin/src/main/resources/application-prod.yml create mode 100644 ai-bird-admin/src/main/resources/application-pyh.yml create mode 100644 ai-bird-admin/src/main/resources/application-pyh1.yml create mode 100644 ai-bird-admin/src/main/resources/application-qzly.yml create mode 100644 ai-bird-admin/src/main/resources/application-shunyi.yml create mode 100644 ai-bird-admin/src/main/resources/application-xuebao.yml create mode 100644 ai-bird-admin/src/main/resources/application-yndc.yml create mode 100644 ai-bird-admin/src/main/resources/application.bak.yml create mode 100644 ai-bird-admin/src/main/resources/application.yml create mode 100644 ai-bird-admin/src/main/resources/banner.txt create mode 100644 ai-bird-admin/src/main/resources/es_ca.crt create mode 100644 ai-bird-admin/src/main/resources/es_ca_server.crt create mode 100644 ai-bird-admin/src/main/resources/i18n/messages.properties create mode 100644 ai-bird-admin/src/main/resources/logback-product.xml create mode 100644 ai-bird-admin/src/main/resources/logback-pyh.xml create mode 100644 ai-bird-admin/src/main/resources/logback.xml create mode 100644 ai-bird-admin/src/main/resources/mybatis/mybatis-config.xml create mode 100644 ai-bird-common/pom.xml create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataScope.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataSource.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excel.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excels.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/Log.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/RateLimiter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/annotation/RepeatSubmit.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/config/AiBirdSysConfig.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/constant/Constants.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/constant/GenConstants.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/constant/HttpStatus.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/constant/ScheduleConstants.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/constant/UserConstants.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/controller/BaseController.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/AjaxResult.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/BaseEntity.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeEntity.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeSelect.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDept.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictData.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictType.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysMenu.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysRole.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysUser.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginBody.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginUser.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/RegisterBody.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/page/PageDomain.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableDataInfo.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableSupport.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/redis/RedisCache.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/text/CharsetKit.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/text/Convert.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/core/text/StrFormatter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessStatus.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessType.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/DataSourceType.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/HttpMethod.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/LimitType.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/OperatorType.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/enums/UserStatus.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/DemoModeException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/GlobalException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/ServiceException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/UtilException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/base/BaseException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileNameLengthLimitExceededException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileSizeLimitExceededException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/file/InvalidExtensionException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/job/TaskException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaExpireException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserNoLoginPermissionException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserPasswordNotMatchException.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatableFilter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatedlyRequestWrapper.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/filter/XssFilter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/filter/XssHttpServletRequestWrapper.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/Arith.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/Chinese2pinyin.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/CommonUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/DateUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/DictUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/ExceptionUtil.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/LogUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/MessageUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/PageUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/SecurityUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/ServletUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/StringUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/Threads.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/VerifyCodeUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanValidators.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileTypeUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUploadUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/file/ImageUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/file/MimeTypeUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/html/EscapeUtil.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/html/HTMLFilter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpHelper.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/AddressUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/IpUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelHandlerAdapter.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelUtil.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/reflect/ReflectUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Base64.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Md5Utils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/spring/SpringUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/sql/SqlUtil.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/IdUtils.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/UUID.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/xss/Xss.java create mode 100644 ai-bird-common/src/main/java/net/hzvtc/common/xss/XssValidator.java create mode 100644 ai-bird-es/pom.xml create mode 100644 ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeDeserializer.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeSerializer.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/config/ESClientConfig.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/config/JacksonConfiguration.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/controller/EsRecordReportController.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/controller/EsResultRecordDetailsController.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/controller/EsSpeciesInfoApiController.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultData.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetails.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetailsVo.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/mapper/EsResultRecordDetailsMapper.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/service/EsRecordReportService.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/service/EsResultRecordDetailsService.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/service/impl/CommonEsUtils.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsRecordReportServiceImpl.java create mode 100644 ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsResultRecordDetailsServiceImpl.java create mode 100644 ai-bird-es/src/main/resources/mapper/EsResultRecordDetailsMapper.xml create mode 100644 ai-bird-framework/pom.xml create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataScopeAspect.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataSourceAspect.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/LogAspect.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/RateLimiterAspect.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/ApplicationConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/CaptchaConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/DruidConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/FastJson2JsonRedisSerializer.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/FilterConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/KaptchaTextCreator.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/MyBatisConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/RedisConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/ResourcesConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/SecurityConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/ServerConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/ThreadPoolConfig.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/config/properties/DruidProperties.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSource.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSourceContextHolder.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/MySqlDialectCustom.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/RepeatSubmitInterceptor.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/impl/SameUrlDataInterceptor.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/manager/AsyncManager.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/manager/ShutdownManager.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/manager/factory/AsyncFactory.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/security/filter/JwtAuthenticationTokenFilter.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/AuthenticationEntryPointImpl.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/LogoutSuccessHandlerImpl.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/Server.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Cpu.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Jvm.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Mem.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Sys.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/SysFile.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/exception/GlobalExceptionHandler.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/PermissionService.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysLoginService.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysPermissionService.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysRegisterService.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/TokenService.java create mode 100644 ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/UserDetailsServiceImpl.java create mode 100644 ai-bird-generator/pom.xml create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/config/GenConfig.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/controller/GenController.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTable.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTableColumn.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableColumnMapper.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableMapper.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnService.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnServiceImpl.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableService.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableServiceImpl.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/util/GenUtils.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityInitializer.java create mode 100644 ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityUtils.java create mode 100644 ai-bird-generator/src/main/resources/generator.yml create mode 100644 ai-bird-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml create mode 100644 ai-bird-generator/src/main/resources/mapper/generator/GenTableMapper.xml create mode 100644 ai-bird-generator/src/main/resources/vm/java/controller.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/java/domain.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/java/mapper.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/java/service.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/java/serviceImpl.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/java/sub-domain.java.vm create mode 100644 ai-bird-generator/src/main/resources/vm/js/api.js.vm create mode 100644 ai-bird-generator/src/main/resources/vm/sql/sql.vm create mode 100644 ai-bird-generator/src/main/resources/vm/vue/index-tree.vue.vm create mode 100644 ai-bird-generator/src/main/resources/vm/vue/index.vue.vm create mode 100644 ai-bird-generator/src/main/resources/vm/vue/v3/index-tree.vue.vm create mode 100644 ai-bird-generator/src/main/resources/vm/vue/v3/index.vue.vm create mode 100644 ai-bird-generator/src/main/resources/vm/vue/v3/readme.txt create mode 100644 ai-bird-generator/src/main/resources/vm/xml/mapper.xml.old.vm create mode 100644 ai-bird-generator/src/main/resources/vm/xml/mapper.xml.vm create mode 100644 ai-bird-quartz/pom.xml create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/config/ScheduleConfig.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/QuartzController.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobController.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobLogController.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJob.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJobLog.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobLogMapper.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobMapper.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobLogService.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobService.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/QuartzJobUtils.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobLogServiceImpl.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobServiceImpl.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/BirdLeaveArriveCalcYearTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DemoTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceConnectionTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceOfflineCheckTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/EmailTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtraAudioListTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtractResultDataListTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/LevelOneSpeciesDailyTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultMediaDataPostTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordDailyStatTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordToEsTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/SpeciesWinterPeriodStatTask.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/AbstractQuartzJob.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/CronUtils.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/JobInvokeUtil.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzDisallowConcurrentExecution.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzJobExecution.java create mode 100644 ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/ScheduleUtils.java create mode 100644 ai-bird-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml create mode 100644 ai-bird-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml create mode 100644 ai-bird-system/pom.xml create mode 100644 ai-bird-system/src/main/java/net/hzvtc/app/domain/AppUpgrade.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/app/mapper/AppUpgradeMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/app/service/AppUpgradeService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/app/service/impl/AppUpgradeServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaSpeciesController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedCareSpeciesController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/controller/SpeciesAbnormalInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/controller/WinteringPeriodController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedArea.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedAreaSpecies.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedCareSpecies.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/domain/SpeciesAbnormalInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/domain/WinteringPeriod.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaSpeciesMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedCareSpeciesMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/mapper/SpeciesAbnormalInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/mapper/WinteringPeriodMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaSpeciesService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedCareSpeciesService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/SpeciesAbnormalInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/WinteringPeriodService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaSpeciesServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedCareSpeciesServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/impl/SpeciesAbnormalInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/area/service/impl/WinteringPeriodServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdCatalogueController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFamilyController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFlyingInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdGenusController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdLeaveArriveInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdMediaController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdSpeciesController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdCatalogue.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFamily.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFlyingInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdGenus.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdLeaveArriveInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdMedia.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdSpecies.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswer.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswerItem.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesIntro.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesList.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdCatalogueMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFamilyMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFlyingInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdGenusMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdLeaveArriveInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdMediaMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdSpeciesMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesAnswerMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesIntroMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdCatalogueService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFamilyService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFlyingInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdGenusService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdLeaveArriveInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdMediaService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdSpeciesService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesAnswerService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesIntroService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdCatalogueServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFamilyServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFlyingInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdGenusServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdLeaveArriveInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdMediaServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdSpeciesServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesAnswerServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesIntroServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/controller/FavoriteMediaController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/controller/MediaItemController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultMediaController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordDetailsController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/domain/FavoriteMedia.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/domain/MediaItem.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultMedia.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecord.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecordDetails.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/FavoriteMediaMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/MediaItemMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultMediaMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordDetailsMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/FavoriteMediaService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/MediaItemService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultMediaService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordDetailsService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordExtractService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/FavoriteMediaServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/MediaItemServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultMediaServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordDetailsServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordExtractServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/job/controller/TableStatInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/job/domain/TableStatInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/job/mapper/TableStatInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/job/service/TableStatInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/data/job/service/impl/TableStatInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/controller/DeviceInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/controller/HeatmapInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/domain/DeviceInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/domain/HeatmapInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/mapper/DeviceInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/mapper/HeatmapInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/service/DeviceInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/service/HeatmapInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/service/impl/DeviceInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/device/service/impl/HeatmapInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/echart/controller/BirdRealTimeController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/echart/domain/vo/BirdStatDataVo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/echart/mapper/BirdDataStatMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/echart/service/BirdDataStatService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/echart/service/impl/BirdDataStatServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/email/service/EmailService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/email/service/impl/EmailServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileItemController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileItem.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileItemMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileItemService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileItemServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationFilesController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationsController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/ObservationFiles.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/Observations.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationFilesMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationsMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationFilesService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationsService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationFilesServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationsServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/onvif/controller/CameraOnvifController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/onvif/service/CameraOnvifService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/onvif/service/impl/CameraOnvifServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/controller/MessageReadInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/MenuInSys.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/MessageReadInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeFileInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReadDept.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReader.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/RoleInArea.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysConfig.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysLogininfor.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysNotice.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysOperLog.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysPost.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleDept.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleMenu.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserOnline.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserPost.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserRole.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/DocStateCountVO.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MessageVo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MetaVo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/RouterVo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/MenuInSysMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/MessageReadInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeFileInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReadDeptMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReaderMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysConfigMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDeptMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictDataMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictTypeMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysLogininforMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysMenuMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysNoticeMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysOperLogMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysPostMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleDeptMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMenuMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserPostMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserRoleMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/MenuInSysService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/MessageReadInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeFileInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReadDeptService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReaderService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysConfigService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysDeptService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictDataService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictTypeService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysLogininforService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysMenuService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysNoticeService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysOperLogService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysPostService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysRoleService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserOnlineService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MenuInSysServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MessageReadInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeFileInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReadDeptServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReaderServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysConfigServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDeptServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictDataServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictTypeServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysLogininforServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysMenuServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysNoticeServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysOperLogServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysPostServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysRoleServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserOnlineServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/api/service/SpeciesInfoApiService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/api/service/impl/SpeciesInfoApiServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/BirdWebPageStatController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyInhabitController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyStatController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesInhabitStatController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesLocationInfoController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesWinterPeriodController.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyInhabit.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyStat.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesInhabitStat.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesLocationInfo.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesWinterPeriod.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/BirdWebPageStatMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyInhabitMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyStatMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesInhabitStatMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesLocationInfoMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesWinterPeriodMapper.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/BirdWebPageStatService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyInhabitService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyStatService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesInhabitStatService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesLocationInfoService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesWinterPeriodService.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/BirdWebPageStatServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyInhabitServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyStatServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesInhabitStatServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesLocationInfoServiceImpl.java create mode 100644 ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesWinterPeriodServiceImpl.java create mode 100644 ai-bird-system/src/main/resources/mapper/app/AppUpgradeMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/area/ProtectedAreaMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/area/ProtectedAreaSpeciesMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/area/ProtectedCareSpeciesMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/area/SpeciesAbnormalInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/area/WinteringPeriodMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdCatalogueMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdFamilyMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdFlyingInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdGenusMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdLeaveArriveInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdMediaMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/BirdSpeciesMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesAnswerMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesIntroMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/dataCheck/FavoriteMediaMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/dataCheck/MediaItemMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/dataCheck/ResultMediaMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordDetailsMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/device/DeviceInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/device/HeatmapInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/echart/BirdDataStatMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/file/MediaFileInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/file/MediaFileItemMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/job/TableStatInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/naturalist/ObservationFilesMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/naturalist/ObservationsMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/BirdWebPageStatMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyInhabitMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyStatMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/SpeciesInhabitStatMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/SpeciesLocationInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/stat/SpeciesWinterPeriodMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/MenuInSysMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/MessageReadInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/NoticeFileInfoMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/NoticeReadDeptMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/NoticeReaderMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysConfigMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysDeptMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysDictDataMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysDictTypeMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysLogininforMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysMenuMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysNoticeMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysOperLogMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysPostMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysRoleMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysUserMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysUserPostMapper.xml create mode 100644 ai-bird-system/src/main/resources/mapper/system/SysUserRoleMapper.xml create mode 100644 pom.xml diff --git a/ai-bird-admin/pom.xml b/ai-bird-admin/pom.xml new file mode 100644 index 0000000..c82b5c5 --- /dev/null +++ b/ai-bird-admin/pom.xml @@ -0,0 +1,107 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + jar + ai-bird-admin + + + web服务入口 + + + + + + + org.springframework.boot + spring-boot-devtools + true + + + + + io.springfox + springfox-boot-starter + + + + + io.swagger + swagger-models + 1.6.2 + + + + + mysql + mysql-connector-java + 8.0.33 + + + + net.hzvtc + ai-bird-framework + + + + + net.hzvtc + ai-bird-quartz + + + + net.hzvtc + ai-bird-es + + + + + + + + + + com.github.whvcse + easy-captcha + 1.6.2 + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.1.1.RELEASE + + true + + + + + repackage + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.1.0 + + false + ${project.artifactId} + + + + ${project.artifactId} + + + \ No newline at end of file diff --git a/ai-bird-admin/src/main/java/net/hzvtc/AiResearchServletInitializer.java b/ai-bird-admin/src/main/java/net/hzvtc/AiResearchServletInitializer.java new file mode 100644 index 0000000..b27c6db --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/AiResearchServletInitializer.java @@ -0,0 +1,14 @@ +package net.hzvtc; + +import net.hzvtc.AiResearchSeverApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +public class AiResearchServletInitializer +extends SpringBootServletInitializer { + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(new Class[]{AiResearchSeverApplication.class}); + } +} + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/AiResearchSeverApplication.java b/ai-bird-admin/src/main/java/net/hzvtc/AiResearchSeverApplication.java new file mode 100644 index 0000000..1b03a7e --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/AiResearchSeverApplication.java @@ -0,0 +1,23 @@ +package net.hzvtc; + +import java.util.TimeZone; +import javax.annotation.PostConstruct; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; + +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) +public class AiResearchSeverApplication { + public static void main(String[] args) { + SpringApplication.run(AiResearchSeverApplication.class, args); + System.out.println("Ai Research Server鍚姩鎴愬姛"); + } + + @PostConstruct + void setDefaultTimezone() { + TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); + } +} + + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/api/controller/SpeciesInfoApiController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/api/controller/SpeciesInfoApiController.java new file mode 100644 index 0000000..fb39f73 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/api/controller/SpeciesInfoApiController.java @@ -0,0 +1,89 @@ +package net.hzvtc.web.api.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.web.api.service.SpeciesInfoApiService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/web/species/api"}) +public class SpeciesInfoApiController +extends BaseController { + @Autowired + private SpeciesInfoApiService speciesInfoApiService; + @Autowired + private ResultRecordService resultRecordService; + @Autowired + private ResultMediaService resultMediaService; + + @GetMapping(value={"/currentDateSpeciesStat"}) + public AjaxResult getCurrentDateBirdStat() { + return AjaxResult.success((Object)this.speciesInfoApiService.getSpeciesCurrentDateStatList(null)); + } + + @PostMapping(value={"/speciesDailyStat"}) + public AjaxResult getBirdDailyStatList(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesInfoApiService.getSpeciesStatListByParam(obj)); + } + + @PostMapping(value={"/speciesPeriodStat"}) + public AjaxResult getBirdPeriodStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesInfoApiService.getBirdPeriodStatByParam(obj)); + } + + @PostMapping(value={"/speciesMonthStat"}) + public AjaxResult getBirdMonthStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesInfoApiService.getBirdMonthStatByParam(obj)); + } + + @PostMapping(value={"/speciesYearStat"}) + public AjaxResult getBirdYearStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesInfoApiService.getBirdYearStatByParam(obj)); + } + + @PostMapping(value={"/videoList"}) + public AjaxResult getBirdVideoListByParam(@RequestBody(required=false) JSONObject obj) { + if (obj == null) { + obj = new JSONObject(); + } + return AjaxResult.success((Object)this.speciesInfoApiService.getVideoMediaListByParam(obj)); + } + + @GetMapping(value={"/deviceList"}) + public AjaxResult getDeviceList() { + return AjaxResult.success((Object)this.speciesInfoApiService.getDeviceInfoListByParam()); + } + + @GetMapping(value={"/audioDeviceList"}) + public AjaxResult getAudioDeviceList() { + return AjaxResult.success((Object)this.speciesInfoApiService.getAudioDeviceInfoListByParam()); + } + + @GetMapping(value={"/todayRecords"}) + public AjaxResult getTodayRecords() { + return AjaxResult.success((Object)this.speciesInfoApiService.getTodayRecordList()); + } + + @PostMapping(value={"/recordAudioList"}) + public JSONObject getRecordDataList(@RequestBody JSONObject param) { + return this.resultRecordService.getAudioResultRecordDataListForApi(param); + } + + @PostMapping(value={"/mediaAudioList"}) + public ResponseEntity> getMediaDataList(@RequestBody JSONObject param) { + return ResponseEntity.ok((Object)this.resultMediaService.getRecordMediaDataList(param)); + } +} + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CaptchaController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CaptchaController.java new file mode 100644 index 0000000..260ca48 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CaptchaController.java @@ -0,0 +1,86 @@ +package net.hzvtc.web.controller.common; + +import com.wf.captcha.ArithmeticCaptcha; +import com.wf.captcha.SpecCaptcha; +import com.wf.captcha.base.Captcha; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.utils.uuid.IdUtils; +import net.hzvtc.system.service.SysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * 验证码操作处理 + * + * @author admin + */ +@RestController +public class CaptchaController { +// @Resource(name = "captchaProducer") +// private Producer captchaProducer; +// +// @Resource(name = "captchaProducerMath") +// private Producer captchaProducerMath; + + @Autowired + private RedisCache redisCache; + + @Autowired + private SysConfigService configService; + + /** + * 生成验证码 + */ + @GetMapping("/captchaImage") + public AjaxResult getCode(HttpServletResponse response) throws IOException { + return getImageCode(0); + } + + + @GetMapping("/appCaptchaImage") + public AjaxResult getCodeForApp(HttpServletResponse response) throws IOException { + return getImageCode(1); + } + + private AjaxResult getImageCode(int type) { + AjaxResult ajax = AjaxResult.success(); + boolean captchaOnOff = configService.selectCaptchaOnOff(); + ajax.put("captchaOnOff", captchaOnOff); + if (!captchaOnOff) { + return ajax; + } + + // 保存验证码信息 + String uuid = IdUtils.simpleUUID(); + String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; + Captcha captcha = null; + String captchaType = AiBirdSysConfig.getCaptchaType(); + if ("math".equals(captchaType)) { + captcha = new ArithmeticCaptcha(115, 42); + } else { + captcha = new SpecCaptcha(115, 42); + } + + //创建算术验证码 + + //得到算术验证码的计算值 + String code = captcha.text(); + redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);//存入redis +// log.info("验证码:{}",code); + ajax.put("uuid", uuid); + if (type == 0) { + ajax.put("img", captcha.toBase64()); + } else { + ajax.put("img", captcha.toBase64("")); + } + return ajax; + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CommonController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CommonController.java new file mode 100644 index 0000000..3c99320 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/common/CommonController.java @@ -0,0 +1,110 @@ +package net.hzvtc.web.controller.common; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.framework.config.ServerConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * 通用请求处理 + * + * @author admin + */ +@RestController +public class CommonController { + private static final Logger log = LoggerFactory.getLogger(CommonController.class); + + @Autowired + private ServerConfig serverConfig; + + /** + * 通用下载请求 + * + * @param fileName 文件名称 + * @param delete 是否删除 + */ + @GetMapping("common/download") + public void fileDownload(String fileName, Boolean delete, String downLoadFileName, HttpServletResponse response, HttpServletRequest request) { + try { + if (!FileUtils.checkAllowDownload(fileName)) { + throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName)); + } + String realFileName = ""; + if (downLoadFileName != null && !downLoadFileName.isEmpty()) { + realFileName = downLoadFileName + fileName.substring(fileName.indexOf(".")); + } else { + realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf(".")); + } + + String filePath = AiBirdSysConfig.getDownloadPath() + fileName; + + response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); + FileUtils.setAttachmentResponseHeader(response, realFileName); +// FileUtils.setAttachmentResponseHeader(response, "test.xlsx"); + FileUtils.writeBytes(filePath, response.getOutputStream()); + if (delete) { + FileUtils.deleteFile(filePath); + } + } catch (Exception e) { + log.error("下载文件失败", e); + } + } + + /** + * 通用上传请求 + */ + @PostMapping("/common/upload") + public AjaxResult uploadFile(MultipartFile file) throws Exception { + try { + // 上传文件路径 + String filePath = AiBirdSysConfig.getUploadPath(); + // 上传并返回新文件名称 + String fileName = FileUploadUtils.upload(filePath, file); + String url = serverConfig.getUrl() + fileName; + AjaxResult ajax = AjaxResult.success(); + ajax.put("fileName", fileName); + ajax.put("url", url); + return ajax; + } catch (Exception e) { + return AjaxResult.error(e.getMessage()); + } + } + + /** + * 本地资源通用下载 + */ + @GetMapping("/common/download/resource") + public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) + throws Exception { + try { + if (!FileUtils.checkAllowDownload(resource)) { + throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource)); + } + // 本地资源路径 + String localPath = AiBirdSysConfig.getProfile(); + // 数据库资源地址 + String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX); + // 下载名称 + String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); + response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); + FileUtils.setAttachmentResponseHeader(response, downloadName); + FileUtils.writeBytes(downloadPath, response.getOutputStream()); + } catch (Exception e) { + log.error("下载文件失败", e); + } + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/CacheController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/CacheController.java new file mode 100644 index 0000000..d505766 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/CacheController.java @@ -0,0 +1,54 @@ +package net.hzvtc.web.controller.monitor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 缓存监控 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/cache") +public class CacheController +{ + @Autowired + private RedisTemplate redisTemplate; + + @PreAuthorize("@ss.hasPermi('monitor:cache:list')") + @GetMapping() + public AjaxResult getInfo() throws Exception + { + Properties info = (Properties) redisTemplate.execute((RedisCallback) connection -> connection.info()); + Properties commandStats = (Properties) redisTemplate.execute((RedisCallback) connection -> connection.info("commandstats")); + Object dbSize = redisTemplate.execute((RedisCallback) connection -> connection.dbSize()); + + Map result = new HashMap<>(3); + result.put("info", info); + result.put("dbSize", dbSize); + + List> pieList = new ArrayList<>(); + commandStats.stringPropertyNames().forEach(key -> { + Map data = new HashMap<>(2); + String property = commandStats.getProperty(key); + data.put("name", StringUtils.removeStart(key, "cmdstat_")); + data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); + pieList.add(data); + }); + result.put("commandStats", pieList); + return AjaxResult.success(result); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/ServerController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/ServerController.java new file mode 100644 index 0000000..46da68d --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/ServerController.java @@ -0,0 +1,27 @@ +package net.hzvtc.web.controller.monitor; + +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.framework.web.domain.Server; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 服务器监控 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/server") +public class ServerController +{ + @PreAuthorize("@ss.hasPermi('monitor:server:list')") + @GetMapping() + public AjaxResult getInfo() throws Exception + { + Server server = new Server(); + server.copyTo(); + return AjaxResult.success(server); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysLogininforController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysLogininforController.java new file mode 100644 index 0000000..e388b3f --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysLogininforController.java @@ -0,0 +1,60 @@ +package net.hzvtc.web.controller.monitor; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.domain.SysLogininfor; +import net.hzvtc.system.service.SysLogininforService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 系统访问记录 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/logininfor") +public class SysLogininforController extends BaseController { + @Autowired + private SysLogininforService logininforService; + + @PreAuthorize("@ss.hasPermi('monitor:logininfor:list')") + @GetMapping("/list") + public TableDataInfo list(SysLogininfor logininfor) { + startPage(); + List list = logininforService.selectLogininforList(logininfor); + return getDataTable(list); + } + + @Log(title = "登录日志", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('monitor:logininfor:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysLogininfor logininfor) { + List list = logininforService.selectLogininforList(logininfor); + ExcelUtil util = new ExcelUtil(SysLogininfor.class); + util.exportExcel(response, list, "登录日志"); + } + + @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')") + @Log(title = "登录日志", businessType = BusinessType.DELETE) + @DeleteMapping("/{infoIds}") + public AjaxResult remove(@PathVariable Long[] infoIds) { + return toAjax(logininforService.deleteLogininforByIds(infoIds)); + } + + @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')") + @Log(title = "登录日志", businessType = BusinessType.CLEAN) + @DeleteMapping("/clean") + public AjaxResult clean() { + logininforService.cleanLogininfor(); + return AjaxResult.success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysOperlogController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysOperlogController.java new file mode 100644 index 0000000..accff94 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysOperlogController.java @@ -0,0 +1,60 @@ +package net.hzvtc.web.controller.monitor; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.domain.SysOperLog; +import net.hzvtc.system.service.SysOperLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 操作日志记录 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/operlog") +public class SysOperlogController extends BaseController { + @Autowired + private SysOperLogService operLogService; + + @PreAuthorize("@ss.hasPermi('monitor:operlog:list')") + @GetMapping("/list") + public TableDataInfo list(SysOperLog operLog) { + startPage(); + List list = operLogService.selectOperLogList(operLog); + return getDataTable(list); + } + + @Log(title = "操作日志", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('monitor:operlog:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysOperLog operLog) { + List list = operLogService.selectOperLogList(operLog); + ExcelUtil util = new ExcelUtil(SysOperLog.class); + util.exportExcel(response, list, "操作日志"); + } + + @Log(title = "操作日志", businessType = BusinessType.DELETE) + @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')") + @DeleteMapping("/{operIds}") + public AjaxResult remove(@PathVariable Long[] operIds) { + return toAjax(operLogService.deleteOperLogByIds(operIds)); + } + + @Log(title = "操作日志", businessType = BusinessType.CLEAN) + @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')") + @DeleteMapping("/clean") + public AjaxResult clean() { + operLogService.cleanOperLog(); + return AjaxResult.success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysUserOnlineController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysUserOnlineController.java new file mode 100644 index 0000000..b466c57 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/monitor/SysUserOnlineController.java @@ -0,0 +1,75 @@ +package net.hzvtc.web.controller.monitor; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.domain.SysUserOnline; +import net.hzvtc.system.service.SysUserOnlineService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * 在线用户监控 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/online") +public class SysUserOnlineController extends BaseController { + @Autowired + private SysUserOnlineService userOnlineService; + + @Autowired + private RedisCache redisCache; + + @PreAuthorize("@ss.hasPermi('monitor:online:list')") + @GetMapping("/list") + public TableDataInfo list(String ipaddr, String userName) { + Collection keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*"); + List userOnlineList = new ArrayList(); + for (String key : keys) { + LoginUser user = redisCache.getCacheObject(key); + if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) { + if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) { + userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); + } + } else if (StringUtils.isNotEmpty(ipaddr)) { + if (StringUtils.equals(ipaddr, user.getIpaddr())) { + userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user)); + } + } else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) { + if (StringUtils.equals(userName, user.getUsername())) { + userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user)); + } + } else { + userOnlineList.add(userOnlineService.loginUserToUserOnline(user)); + } + } + Collections.reverse(userOnlineList); + userOnlineList.removeAll(Collections.singleton(null)); + return getDataTable(userOnlineList); + } + + /** + * 强退用户 + */ + @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')") + @Log(title = "在线用户", businessType = BusinessType.FORCE) + @DeleteMapping("/{tokenId}") + public AjaxResult forceLogout(@PathVariable String tokenId) { + redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId); + return AjaxResult.success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/NoticeFileInfoController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/NoticeFileInfoController.java new file mode 100644 index 0000000..c59a8c2 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/NoticeFileInfoController.java @@ -0,0 +1,29 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import net.hzvtc.system.domain.NoticeFileInfo; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping("/system/notice/file") +public class NoticeFileInfoController extends BaseController { + @PostMapping("/upload") + public AjaxResult uploadTaskFile(MultipartFile file) { + String baseDir = FileUploadUtils.getDefaultBaseDir() + "/" + "notice" + "/" + SecurityUtils.getDeptId(); + try { + NoticeFileInfo data = new NoticeFileInfo(); + data.setFilePath(FileUploadUtils.upload(baseDir, file)); + data.setFileType(FileUploadUtils.getExtension(file)); + data.setName(FileUploadUtils.getOriginalFileName(file)); + return AjaxResult.success(data); + } catch (Exception ex) { + return AjaxResult.error(ex.getMessage()); + } + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysConfigController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysConfigController.java new file mode 100644 index 0000000..a970f83 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysConfigController.java @@ -0,0 +1,117 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.domain.SysConfig; +import net.hzvtc.system.service.SysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 参数配置 信息操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/system/config") +public class SysConfigController extends BaseController { + @Autowired + private SysConfigService configService; + + /** + * 获取参数配置列表 + */ + @PreAuthorize("@ss.hasPermi('system:config:list')") + @GetMapping("/list") + public TableDataInfo list(SysConfig config) { + startPage(); + List list = configService.selectConfigList(config); + return getDataTable(list); + } + + @Log(title = "参数管理", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:config:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysConfig config) { + List list = configService.selectConfigList(config); + ExcelUtil util = new ExcelUtil(SysConfig.class); + util.exportExcel(response, list, "参数数据"); + } + + /** + * 根据参数编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:config:query')") + @GetMapping(value = "/{configId}") + public AjaxResult getInfo(@PathVariable Long configId) { + return AjaxResult.success(configService.selectConfigById(configId)); + } + + /** + * 根据参数键名查询参数值 + */ + @GetMapping(value = "/configKey/{configKey}") + public AjaxResult getConfigKey(@PathVariable String configKey) { + return AjaxResult.success(configService.selectConfigByKey(configKey)); + } + + /** + * 新增参数配置 + */ + @PreAuthorize("@ss.hasPermi('system:config:add')") + @Log(title = "参数管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysConfig config) { + if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) { + return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); + } + config.setCreateBy(getUsername()); + return toAjax(configService.insertConfig(config)); + } + + /** + * 修改参数配置 + */ + @PreAuthorize("@ss.hasPermi('system:config:edit')") + @Log(title = "参数管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysConfig config) { + if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) { + return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); + } + config.setUpdateBy(getUsername()); + return toAjax(configService.updateConfig(config)); + } + + /** + * 删除参数配置 + */ + @PreAuthorize("@ss.hasPermi('system:config:remove')") + @Log(title = "参数管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{configIds}") + public AjaxResult remove(@PathVariable Long[] configIds) { + configService.deleteConfigByIds(configIds); + return success(); + } + + /** + * 刷新参数缓存 + */ + @PreAuthorize("@ss.hasPermi('system:config:remove')") + @Log(title = "参数管理", businessType = BusinessType.CLEAN) + @DeleteMapping("/refreshCache") + public AjaxResult refreshCache() { + configService.resetConfigCache(); + return AjaxResult.success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDeptController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDeptController.java new file mode 100644 index 0000000..eb413f3 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDeptController.java @@ -0,0 +1,190 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysDept; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.service.SysDeptService; +import org.apache.commons.lang3.ArrayUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.Iterator; +import java.util.List; + +/** + * 部门信息 + * + * @author admin + */ + +@RestController +@RequestMapping("/system/dept") +public class SysDeptController extends BaseController { + @Autowired + private SysDeptService deptService; + + /** + * 获取部门列表 + */ + @PreAuthorize("@ss.hasPermi('system:dept:list')") + @GetMapping("/list") + public AjaxResult list(SysDept dept) { + List depts = deptService.selectDeptList(dept); + return AjaxResult.success(depts); + } + + /** + * 查询部门列表(排除节点) + */ + @PreAuthorize("@ss.hasPermi('system:dept:list')") + @GetMapping("/list/exclude/{deptId}") + public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) { + List depts = deptService.selectDeptList(new SysDept()); + Iterator it = depts.iterator(); + while (it.hasNext()) { + SysDept d = (SysDept) it.next(); + if (d.getDeptId().intValue() == deptId + || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) { + it.remove(); + } + } + return AjaxResult.success(depts); + } + + /** + * 根据部门编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:dept:query')") + @GetMapping(value = "/{deptId}") + public AjaxResult getInfo(@PathVariable Long deptId) { + deptService.checkDeptDataScope(deptId); + return AjaxResult.success(deptService.selectDeptById(deptId)); + } + + /** + * 获取部门下拉树列表 + */ + @GetMapping("/treeselect/{type}") + public AjaxResult treeselect(@PathVariable Integer type) { + SysDept dept = null; + dept = new SysDept(); + SysDept data = deptService.selectDeptById(SecurityUtils.getLoginUser().getDeptId()); + if (type.intValue() == 1) { + dept.setAncestors(data.getAncestors() + ',' + data.getDeptId()); + //dept.setParentId(SecurityUtils.getLoginUser().getDeptId()); + } else if (type.intValue() == 2) { + dept.setAncestors(data.getAncestors()); +// if (data.getParentId() != 0) { +// dept.setParentId(data.getParentId()); +// } else { +// dept.setParentId(data.getDeptId()); +// } + } + + List depts = deptService.selectDeptList(dept); + return AjaxResult.success(deptService.buildDeptTreeSelect(depts)); + } + + @GetMapping("/lazyTreeselect") + public AjaxResult lazyTreeselect(@RequestParam(name = "deptId", required = false) Long deptId) { + return AjaxResult.success(deptService.buildLazyDeptTreeSelect(deptId)); + } + + @GetMapping("/compareTreeselect") + public AjaxResult compareTreeselect(Long deptId) { + if (deptId == null) { + SysDept sysDept = deptService.selectDeptById(SecurityUtils.getLoginUser().getDeptId()); + String ancestor = sysDept.getAncestors(); + if (ancestor == null) { + deptId = 0L; + } else { + String arr[] = ancestor.split(","); + if (arr.length > 1) { + deptId = Long.parseLong(arr[arr.length - 2]); + } else { + deptId = 0L; + } + } + } + return AjaxResult.success(deptService.buildLazyDeptTreeSelect(deptId)); + } + + + @PostMapping("/updateDeptAncestorPath") + public AjaxResult updateDeptFullPath(Long deptId) { + SysDept sysDept = new SysDept(); + sysDept.setDeptId(deptId); + deptService.updateDeptAncestorPath(sysDept); + return AjaxResult.success(true); + } + + /** + * 加载对应角色部门列表树 + */ + @GetMapping(value = "/roleDeptTreeselect/{roleId}") + public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) { + List depts = deptService.selectDeptList(new SysDept()); + AjaxResult ajax = AjaxResult.success(); + ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId)); + ajax.put("depts", deptService.buildDeptTreeSelect(depts)); + return ajax; + } + + /** + * 新增部门 + */ + @PreAuthorize("@ss.hasPermi('system:dept:add')") + @Log(title = "部门管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysDept dept) { + if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) { + return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); + } + dept.setCreateBy(getUsername()); + return toAjax(deptService.insertDept(dept)); + } + + /** + * 修改部门 + */ + @PreAuthorize("@ss.hasPermi('system:dept:edit')") + @Log(title = "部门管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysDept dept) { + Long deptId = dept.getDeptId(); + deptService.checkDeptDataScope(deptId); + if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) { + return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); + } else if (dept.getParentId().equals(deptId)) { + return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); + } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) { + return AjaxResult.error("该部门包含未停用的子部门!"); + } + dept.setUpdateBy(getUsername()); + return toAjax(deptService.updateDept(dept)); + } + + /** + * 删除部门 + */ + @PreAuthorize("@ss.hasPermi('system:dept:remove')") + @Log(title = "部门管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{deptId}") + public AjaxResult remove(@PathVariable Long deptId) { + if (deptService.hasChildByDeptId(deptId)) { + return AjaxResult.error("存在下级部门,不允许删除"); + } + if (deptService.checkDeptExistUser(deptId)) { + return AjaxResult.error("部门存在用户,不允许删除"); + } + deptService.checkDeptDataScope(deptId); + return toAjax(deptService.deleteDeptById(deptId)); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictDataController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictDataController.java new file mode 100644 index 0000000..fb1872b --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictDataController.java @@ -0,0 +1,106 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysDictData; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.service.SysDictDataService; +import net.hzvtc.system.service.SysDictTypeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; + +/** + * 数据字典信息 + * + * @author admin + */ +@RestController +@RequestMapping("/system/dict/data") +public class SysDictDataController extends BaseController { + @Autowired + private SysDictDataService dictDataService; + + @Autowired + private SysDictTypeService dictTypeService; + + @PreAuthorize("@ss.hasPermi('system:dict:list')") + @GetMapping("/list") + public TableDataInfo list(SysDictData dictData) { + startPage(); + List list = dictDataService.selectDictDataList(dictData); + return getDataTable(list); + } + + @Log(title = "字典数据", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:dict:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysDictData dictData) { + List list = dictDataService.selectDictDataList(dictData); + ExcelUtil util = new ExcelUtil(SysDictData.class); + util.exportExcel(response, list, "字典数据"); + } + + /** + * 查询字典数据详细 + */ + @PreAuthorize("@ss.hasPermi('system:dict:query')") + @GetMapping(value = "/{dictCode}") + public AjaxResult getInfo(@PathVariable Long dictCode) { + return AjaxResult.success(dictDataService.selectDictDataById(dictCode)); + } + + /** + * 根据字典类型查询字典数据信息 + */ + @GetMapping(value = "/type/{dictType}") + public AjaxResult dictType(@PathVariable String dictType) { + List data = dictTypeService.selectDictDataByType(dictType); + if (StringUtils.isNull(data)) { + data = new ArrayList(); + } + return AjaxResult.success(data); + } + + /** + * 新增字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:add')") + @Log(title = "字典数据", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysDictData dict) { + dict.setCreateBy(getUsername()); + return toAjax(dictDataService.insertDictData(dict)); + } + + /** + * 修改保存字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:edit')") + @Log(title = "字典数据", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysDictData dict) { + dict.setUpdateBy(getUsername()); + return toAjax(dictDataService.updateDictData(dict)); + } + + /** + * 删除字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:remove')") + @Log(title = "字典类型", businessType = BusinessType.DELETE) + @DeleteMapping("/{dictCodes}") + public AjaxResult remove(@PathVariable Long[] dictCodes) { + dictDataService.deleteDictDataByIds(dictCodes); + return success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictTypeController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictTypeController.java new file mode 100644 index 0000000..c630b46 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysDictTypeController.java @@ -0,0 +1,115 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysDictType; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.service.SysDictTypeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 数据字典信息 + * + * @author admin + */ +@RestController +@RequestMapping("/system/dict/type") +public class SysDictTypeController extends BaseController { + @Autowired + private SysDictTypeService dictTypeService; + + @PreAuthorize("@ss.hasPermi('system:dict:list')") + @GetMapping("/list") + public TableDataInfo list(SysDictType dictType) { + startPage(); + List list = dictTypeService.selectDictTypeList(dictType); + return getDataTable(list); + } + + @Log(title = "字典类型", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:dict:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysDictType dictType) { + List list = dictTypeService.selectDictTypeList(dictType); + ExcelUtil util = new ExcelUtil(SysDictType.class); + util.exportExcel(response, list, "字典类型"); + } + + /** + * 查询字典类型详细 + */ + @PreAuthorize("@ss.hasPermi('system:dict:query')") + @GetMapping(value = "/{dictId}") + public AjaxResult getInfo(@PathVariable Long dictId) { + return AjaxResult.success(dictTypeService.selectDictTypeById(dictId)); + } + + /** + * 新增字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:add')") + @Log(title = "字典类型", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysDictType dict) { + if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) { + return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); + } + dict.setCreateBy(getUsername()); + return toAjax(dictTypeService.insertDictType(dict)); + } + + /** + * 修改字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:edit')") + @Log(title = "字典类型", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysDictType dict) { + if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) { + return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); + } + dict.setUpdateBy(getUsername()); + return toAjax(dictTypeService.updateDictType(dict)); + } + + /** + * 删除字典类型 + */ + @PreAuthorize("@ss.hasPermi('system:dict:remove')") + @Log(title = "字典类型", businessType = BusinessType.DELETE) + @DeleteMapping("/{dictIds}") + public AjaxResult remove(@PathVariable Long[] dictIds) { + dictTypeService.deleteDictTypeByIds(dictIds); + return success(); + } + + /** + * 刷新字典缓存 + */ + @PreAuthorize("@ss.hasPermi('system:dict:remove')") + @Log(title = "字典类型", businessType = BusinessType.CLEAN) + @DeleteMapping("/refreshCache") + public AjaxResult refreshCache() { + dictTypeService.resetDictCache(); + return AjaxResult.success(); + } + + /** + * 获取字典选择框列表 + */ + @GetMapping("/optionselect") + public AjaxResult optionselect() { + List dictTypes = dictTypeService.selectDictTypeAll(); + return AjaxResult.success(dictTypes); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysIndexController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysIndexController.java new file mode 100644 index 0000000..a26ac24 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysIndexController.java @@ -0,0 +1,29 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 首页 + * + * @author admin + */ +@RestController +public class SysIndexController { + /** + * 系统基础配置 + */ + @Autowired + private AiBirdSysConfig adminConfig; + + /** + * 访问首页,提示语 + */ + @RequestMapping("/") + public String index() { + return StringUtils.format("欢迎使用{}后台管理框架,当前版本:v{},请通过前端地址访问。", adminConfig.getName(), adminConfig.getVersion()); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysLoginController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysLoginController.java new file mode 100644 index 0000000..0b54cd5 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysLoginController.java @@ -0,0 +1,90 @@ +package net.hzvtc.web.controller.system; + +import java.util.List; +import java.util.Set; +import net.hzvtc.app.domain.AppUpgrade; +import net.hzvtc.app.service.AppUpgradeService; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginBody; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.framework.web.service.SysLoginService; +import net.hzvtc.framework.web.service.SysPermissionService; +import net.hzvtc.system.service.SysMenuService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class SysLoginController { + @Autowired + private SysLoginService loginService; + @Autowired + private SysMenuService menuService; + @Autowired + private SysPermissionService permissionService; + @Autowired + private AppUpgradeService appUpgradeService; + + @PostMapping(value={"/login"}) + public AjaxResult login(@RequestBody LoginBody loginBody) { + AjaxResult ajax = AjaxResult.success(); + String token = this.loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(), loginBody.getLoginType()); + ajax.put("token", (Object)token); + return ajax; + } + + @PostMapping(value={"/web/api/getToken"}) + public AjaxResult getToken(@RequestBody LoginBody loginBody) { + loginBody.setLoginType(3); + return this.login(loginBody); + } + + @PostMapping(value={"/web/ssoLogin"}) + public AjaxResult ssoLogin(@RequestParam String token) { + AjaxResult ajax = AjaxResult.success(); + String str = this.loginService.ssoLogin(token); + ajax.put("token", (Object)str); + return ajax; + } + + @GetMapping(value={"getInfo"}) + public AjaxResult getInfo() { + SysUser user = SecurityUtils.getLoginUser().getUser(); + Set roles = this.permissionService.getRolePermission(user); + Set permissions = this.permissionService.getMenuPermission(user); + AjaxResult ajax = AjaxResult.success(); + ajax.put("user", (Object)user); + ajax.put("roles", (Object)roles); + ajax.put("permissions", (Object)permissions); + ajax.put("areaIds", (Object)SecurityUtils.getLoginUser().getAreaIds()); + ajax.put("areaList", (Object)SecurityUtils.getLoginUser().getAreaList()); + ajax.put("deviceList", (Object)SecurityUtils.getLoginUser().getDeviceList()); + return ajax; + } + + @GetMapping(value={"getRouters"}) + public AjaxResult getRouters(Integer sysId) { + Long userId = SecurityUtils.getUserId(); + if (sysId == null) { + sysId = 1; + } + List menus = this.menuService.selectMenuTreeByUserId(userId, sysId); + return AjaxResult.success((Object)this.menuService.buildMenus(menus)); + } + + @GetMapping(value={"/appUpdate", "/appUpdateInfo"}) + public AppUpgrade appUpgrade() { + return this.appUpgradeService.getLastAppUpgradeInfo(); + } + + @GetMapping(value={"/checkUpdate"}) + public AjaxResult checkUpdate() { + return AjaxResult.success((Object)this.appUpgradeService.getLastAppUpgradeInfo()); + } +} + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysMenuController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysMenuController.java new file mode 100644 index 0000000..b2f043f --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysMenuController.java @@ -0,0 +1,118 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysMenu; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.service.SysMenuService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 菜单信息 + * + * @author admin + */ +@RestController +@RequestMapping("/system/menu") +public class SysMenuController extends BaseController { + @Autowired + private SysMenuService menuService; + + /** + * 获取菜单列表 + */ + @PreAuthorize("@ss.hasPermi('system:menu:list')") + @GetMapping("/list") + public AjaxResult list(SysMenu menu) { + List menus = menuService.selectMenuList(menu, getUserId()); + return AjaxResult.success(menus); + } + + /** + * 根据菜单编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:menu:query')") + @GetMapping(value = "/{menuId}") + public AjaxResult getInfo(@PathVariable Long menuId) { + return AjaxResult.success(menuService.selectMenuById(menuId)); + } + + /** + * 获取菜单下拉树列表 + */ + @GetMapping("/treeselect") + public AjaxResult treeselect(SysMenu menu) { + List menus = menuService.selectMenuList(menu, getUserId()); + return AjaxResult.success(menuService.buildMenuTreeSelect(menus)); + } + + /** + * 加载对应角色菜单列表树 + */ + @GetMapping(value = "/roleMenuTreeselect/{roleId}/{sysId}") + public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId, @PathVariable("sysId") Integer sysId) { + List menus = menuService.selectMenuList(getUserId(), sysId); + AjaxResult ajax = AjaxResult.success(); + ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId)); + ajax.put("menus", menuService.buildMenuTreeSelect(menus)); + return ajax; + } + + /** + * 新增菜单 + */ + @PreAuthorize("@ss.hasPermi('system:menu:add')") + @Log(title = "菜单管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysMenu menu) { + if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { + return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); + } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { + return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); + } + menu.setCreateBy(getUsername()); + return toAjax(menuService.insertMenu(menu)); + } + + /** + * 修改菜单 + */ + @PreAuthorize("@ss.hasPermi('system:menu:edit')") + @Log(title = "菜单管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysMenu menu) { + if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) { + return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); + } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { + return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); + } else if (menu.getMenuId().equals(menu.getParentId())) { + return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己"); + } + menu.setUpdateBy(getUsername()); + return toAjax(menuService.updateMenu(menu)); + } + + /** + * 删除菜单 + */ + @PreAuthorize("@ss.hasPermi('system:menu:remove')") + @Log(title = "菜单管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{menuId}") + public AjaxResult remove(@PathVariable("menuId") Long menuId) { + if (menuService.hasChildByMenuId(menuId)) { + return AjaxResult.error("存在子菜单,不允许删除"); + } + if (menuService.checkMenuExistRole(menuId)) { + return AjaxResult.error("菜单已分配,不允许删除"); + } + return toAjax(menuService.deleteMenuById(menuId)); + } +} \ No newline at end of file diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysNoticeController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysNoticeController.java new file mode 100644 index 0000000..12237bc --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysNoticeController.java @@ -0,0 +1,119 @@ +package net.hzvtc.web.controller.system; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.area.service.SpeciesAbnormalInfoService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.system.domain.SysNotice; +import net.hzvtc.system.domain.vo.DocStateCountVO; +import net.hzvtc.system.domain.vo.MessageVo; +import net.hzvtc.system.service.SysNoticeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 公告 信息操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/system/notice") +public class SysNoticeController extends BaseController { + @Autowired + private SysNoticeService noticeService; + @Autowired + private SpeciesAbnormalInfoService abnormalInfoService; + + /** + * 获取通知公告列表 + */ + @PreAuthorize("@ss.hasPermi('system:notice:list')") + @GetMapping("/list") + public TableDataInfo list(SysNotice notice) { + startPage(); + List list = noticeService.selectNoticeList(notice); + return getDataTable(list); + } + + /** + * 根据通知公告编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:notice:query')") + @GetMapping(value = "/{noticeId}") + public AjaxResult getInfo(@PathVariable(name = "noticeId") Long noticeId) { + return AjaxResult.success(noticeService.selectNoticeById(noticeId)); + } + + @GetMapping(value = "/mobile/{noticeId}") + public AjaxResult getInfoForMobile(@PathVariable(name = "noticeId") Long noticeId) { + return AjaxResult.success(noticeService.getNoticeForMobileById(noticeId)); + } + + /** + * 新增通知公告 + */ + @PreAuthorize("@ss.hasPermi('system:notice:add')") + @Log(title = "通知公告", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysNotice notice) { + notice.setCreateBy(getUsername()); + return toAjax(noticeService.insertNotice(notice)); + } + + @GetMapping("/getDocCountByState") + public AjaxResult getDocCountByState() { + Long deptId = SecurityUtils.getLoginUser().getDeptId(); + List list = noticeService.getSysNoticeCountGroupByState(deptId); + return AjaxResult.success(list); + } + + /** + * 修改通知公告 + */ + @PreAuthorize("@ss.hasPermi('system:notice:edit')") + @Log(title = "通知公告", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysNotice notice) { + notice.setUpdateBy(getUsername()); + return toAjax(noticeService.updateNotice(notice)); + } + + /** + * 删除通知公告 + */ + @PreAuthorize("@ss.hasPermi('system:notice:remove')") + @Log(title = "通知公告", businessType = BusinessType.DELETE) + @DeleteMapping("/{noticeIds}") + public AjaxResult remove(@PathVariable Long[] noticeIds) { + return toAjax(noticeService.deleteNoticeByIds(noticeIds)); + } + + @GetMapping("/msgCatalogueList") + public AjaxResult getMessageForMobile() { + return AjaxResult.success(noticeService.getUnreadMessageCatalogueList()); + } + + @PostMapping("/messageList") + public TableDataInfo getMessageListForMobile(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + startPage(pageNum, pageSize); + int msgType = params.getInteger("msgType"); + if (msgType == 1) { + String title = params.getString("title"); + List list = noticeService.getMessageInfoList(title); + return getDataTable(list); + } else { + List list = abnormalInfoService.getSpeciesAbnormalInfoListByParam(); + return getDataTable(list); + } + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysPostController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysPostController.java new file mode 100644 index 0000000..290151d --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysPostController.java @@ -0,0 +1,110 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.domain.SysPost; +import net.hzvtc.system.service.SysPostService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 岗位信息操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/system/post") +public class SysPostController extends BaseController { + @Autowired + private SysPostService postService; + + /** + * 获取岗位列表 + */ + @PreAuthorize("@ss.hasPermi('system:post:list')") + @GetMapping("/list") + public TableDataInfo list(SysPost post) { + startPage(); + List list = postService.selectPostList(post); + return getDataTable(list); + } + + @Log(title = "岗位管理", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:post:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysPost post) { + List list = postService.selectPostList(post); + ExcelUtil util = new ExcelUtil(SysPost.class); + util.exportExcel(response, list, "岗位数据"); + } + + /** + * 根据岗位编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:post:query')") + @GetMapping(value = "/{postId}") + public AjaxResult getInfo(@PathVariable Long postId) { + return AjaxResult.success(postService.selectPostById(postId)); + } + + /** + * 新增岗位 + */ + @PreAuthorize("@ss.hasPermi('system:post:add')") + @Log(title = "岗位管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysPost post) { + if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) { + return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在"); + } else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) { + return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); + } + post.setCreateBy(getUsername()); + return toAjax(postService.insertPost(post)); + } + + /** + * 修改岗位 + */ + @PreAuthorize("@ss.hasPermi('system:post:edit')") + @Log(title = "岗位管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysPost post) { + if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) { + return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在"); + } else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) { + return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); + } + post.setUpdateBy(getUsername()); + return toAjax(postService.updatePost(post)); + } + + /** + * 删除岗位 + */ + @PreAuthorize("@ss.hasPermi('system:post:remove')") + @Log(title = "岗位管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{postIds}") + public AjaxResult remove(@PathVariable Long[] postIds) { + return toAjax(postService.deletePostByIds(postIds)); + } + + /** + * 获取岗位选择框列表 + */ + @GetMapping("/optionselect") + public AjaxResult optionselect() { + List posts = postService.selectPostAll(); + return AjaxResult.success(posts); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysProfileController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysProfileController.java new file mode 100644 index 0000000..e5acffa --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysProfileController.java @@ -0,0 +1,128 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import net.hzvtc.framework.web.service.TokenService; +import net.hzvtc.system.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +/** + * 个人信息 业务处理 + * + * @author admin + */ +@RestController +@RequestMapping("/system/user/profile") +public class SysProfileController extends BaseController { + @Autowired + private SysUserService userService; + + @Autowired + private TokenService tokenService; + + /** + * 个人信息 + */ + @GetMapping + public AjaxResult profile() { + LoginUser loginUser = getLoginUser(); + SysUser user = loginUser.getUser(); + AjaxResult ajax = AjaxResult.success(user); + ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername())); + ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername())); + return ajax; + } + + /** + * 修改用户 + */ + @Log(title = "个人信息", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult updateProfile(@RequestBody SysUser user) { + LoginUser loginUser = getLoginUser(); + SysUser sysUser = loginUser.getUser(); + user.setUserName(sysUser.getUserName()); + if (StringUtils.isNotEmpty(user.getPhonenumber()) + && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { + return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); + } + if (StringUtils.isNotEmpty(user.getEmail()) + && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { + return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); + } + user.setUserId(sysUser.getUserId()); + user.setPassword(null); + if (userService.updateUserProfile(user) > 0) { + // 更新缓存用户信息 + sysUser.setNickName(user.getNickName()); + sysUser.setPhonenumber(user.getPhonenumber()); + sysUser.setEmail(user.getEmail()); + sysUser.setSex(user.getSex()); + tokenService.setLoginUser(loginUser); + return AjaxResult.success(); + } + return AjaxResult.error("修改个人信息异常,请联系管理员"); + } + + /** + * 重置密码 + */ + @Log(title = "个人信息", businessType = BusinessType.UPDATE) + @PutMapping("/updatePwd") + public AjaxResult updatePwd(String oldPassword, String newPassword) { + LoginUser loginUser = getLoginUser(); + String userName = loginUser.getUsername(); + String password = loginUser.getPassword(); + if (!SecurityUtils.matchesPassword(oldPassword, password)) { + return AjaxResult.error("修改密码失败,旧密码错误"); + } + if (SecurityUtils.matchesPassword(newPassword, password)) { + return AjaxResult.error("新密码不能与旧密码相同"); + } + if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) { + // 更新缓存用户密码 + loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword)); + tokenService.setLoginUser(loginUser); + return AjaxResult.success(); + } + return AjaxResult.error("修改密码异常,请联系管理员"); + } + + /** + * 头像上传 + */ + @Log(title = "用户头像", businessType = BusinessType.UPDATE) + @PostMapping("/avatar") + public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException { + if (!file.isEmpty()) { + LoginUser loginUser = getLoginUser(); + String avatar = FileUploadUtils.upload(AiBirdSysConfig.getAvatarPath(), file); + + System.out.println("=====================name====" + loginUser.getUsername()); + System.out.println("=====================avatar====" + avatar); + + if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) { + AjaxResult ajax = AjaxResult.success(); + ajax.put("imgUrl", avatar); + // 更新缓存用户头像 + loginUser.getUser().setAvatar(avatar); + tokenService.setLoginUser(loginUser); + return ajax; + } + } + return AjaxResult.error("上传图片异常,请联系管理员"); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRegisterController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRegisterController.java new file mode 100644 index 0000000..0bd14a5 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRegisterController.java @@ -0,0 +1,35 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.model.RegisterBody; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.framework.web.service.SysRegisterService; +import net.hzvtc.system.service.SysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +/** + * 注册验证 + * + * @author admin + */ +@RestController +public class SysRegisterController extends BaseController { + @Autowired + private SysRegisterService registerService; + + @Autowired + private SysConfigService configService; + + @PostMapping("/register") + public AjaxResult register(@RequestBody RegisterBody user) { + if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) { + return error("当前系统没有开启注册功能!"); + } + String msg = registerService.register(user); + return StringUtils.isEmpty(msg) ? success() : error(msg); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRoleController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRoleController.java new file mode 100644 index 0000000..03e9e12 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysRoleController.java @@ -0,0 +1,225 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.framework.web.service.SysPermissionService; +import net.hzvtc.framework.web.service.TokenService; +import net.hzvtc.system.domain.SysUserRole; +import net.hzvtc.system.service.SysRoleService; +import net.hzvtc.system.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 角色信息 + * + * @author admin + */ +@RestController +@RequestMapping("/system/role") +public class SysRoleController extends BaseController { + @Autowired + private SysRoleService roleService; + + @Autowired + private TokenService tokenService; + + @Autowired + private SysPermissionService permissionService; + + @Autowired + private SysUserService userService; + + @PreAuthorize("@ss.hasPermi('system:role:list')") + @GetMapping("/list") + public TableDataInfo list(SysRole role) { + startPage(); + List list = roleService.selectRoleList(role); + return getDataTable(list); + } + + @Log(title = "角色管理", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:role:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysRole role) { + List list = roleService.selectRoleList(role); + ExcelUtil util = new ExcelUtil(SysRole.class); + util.exportExcel(response, list, "角色数据"); + } + + /** + * 根据角色编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:role:query')") + @GetMapping(value = "/{roleId}") + public AjaxResult getInfo(@PathVariable Long roleId) { + roleService.checkRoleDataScope(roleId); + return AjaxResult.success(roleService.selectRoleById(roleId)); + } + + /** + * 新增角色 + */ + @PreAuthorize("@ss.hasPermi('system:role:add')") + @Log(title = "角色管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysRole role) { + if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) { + return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在"); + } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) { + return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在"); + } + role.setCreateBy(getUsername()); + return toAjax(roleService.insertRole(role)); + + } + + /** + * 修改保存角色 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysRole role) { + roleService.checkRoleAllowed(role); + roleService.checkRoleDataScope(role.getRoleId()); + if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) { + return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在"); + } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) { + return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在"); + } + role.setUpdateBy(getUsername()); + + if (roleService.updateRole(role) > 0) { + // 更新缓存用户权限 + LoginUser loginUser = getLoginUser(); + if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) { + loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser())); + loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName())); + if (role.getAreaIds() != null) { + loginUser.setAreaIds(Arrays.stream(role.getAreaIds()).collect(Collectors.toSet())); + } else { + loginUser.setAreaIds(null); + } + tokenService.setLoginUser(loginUser); + } + return AjaxResult.success(); + } + return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员"); + } + + /** + * 修改保存数据权限 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @PutMapping("/dataScope") + public AjaxResult dataScope(@RequestBody SysRole role) { + roleService.checkRoleAllowed(role); + roleService.checkRoleDataScope(role.getRoleId()); + return toAjax(roleService.authDataScope(role)); + } + + /** + * 状态修改 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.UPDATE) + @PutMapping("/changeStatus") + public AjaxResult changeStatus(@RequestBody SysRole role) { + roleService.checkRoleAllowed(role); + roleService.checkRoleDataScope(role.getRoleId()); + role.setUpdateBy(getUsername()); + return toAjax(roleService.updateRoleStatus(role)); + } + + /** + * 删除角色 + */ + @PreAuthorize("@ss.hasPermi('system:role:remove')") + @Log(title = "角色管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{roleIds}") + public AjaxResult remove(@PathVariable Long[] roleIds) { + return toAjax(roleService.deleteRoleByIds(roleIds)); + } + + /** + * 获取角色选择框列表 + */ + @PreAuthorize("@ss.hasPermi('system:role:query')") + @GetMapping("/optionselect/{sysId}") + public AjaxResult optionselect(@PathVariable(value = "sysId") Integer sysId) { + SysRole sysRole = new SysRole(); + sysRole.setSysId(sysId); + return AjaxResult.success(roleService.selectRoleAll(sysRole)); + } + + /** + * 查询已分配用户角色列表 + */ + @PreAuthorize("@ss.hasPermi('system:role:list')") + @GetMapping("/authUser/allocatedList") + public TableDataInfo allocatedList(SysUser user) { + startPage(); + List list = userService.selectAllocatedList(user); + return getDataTable(list); + } + + /** + * 查询未分配用户角色列表 + */ + @PreAuthorize("@ss.hasPermi('system:role:list')") + @GetMapping("/authUser/unallocatedList") + public TableDataInfo unallocatedList(SysUser user) { + startPage(); + List list = userService.selectUnallocatedList(user); + return getDataTable(list); + } + + /** + * 取消授权用户 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/cancel") + public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole) { + return toAjax(roleService.deleteAuthUser(userRole)); + } + + /** + * 批量取消授权用户 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/cancelAll") + public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) { + return toAjax(roleService.deleteAuthUsers(roleId, userIds)); + } + + /** + * 批量选择用户授权 + */ + @PreAuthorize("@ss.hasPermi('system:role:edit')") + @Log(title = "角色管理", businessType = BusinessType.GRANT) + @PutMapping("/authUser/selectAll") + public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) { + roleService.checkRoleDataScope(roleId); + return toAjax(roleService.insertAuthUsers(roleId, userIds)); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysUserController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysUserController.java new file mode 100644 index 0000000..dadd3b3 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/system/SysUserController.java @@ -0,0 +1,235 @@ +package net.hzvtc.web.controller.system; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.service.SysPostService; +import net.hzvtc.system.service.SysRoleService; +import net.hzvtc.system.service.SysUserService; +import org.apache.commons.lang3.ArrayUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户信息 + * + * @author admin + */ +@RestController +@RequestMapping("/system/user") +public class SysUserController extends BaseController { + @Autowired + private SysUserService userService; + + @Autowired + private SysRoleService roleService; + + @Autowired + private SysPostService postService; + + /** + * 获取用户列表 + */ + @PreAuthorize("@ss.hasPermi('system:user:list')") + @GetMapping("/list") + public TableDataInfo list(SysUser user) { + startPage(); + if (user == null) { + user = new SysUser(); + } + if (SecurityUtils.getUserId() != 1L) { + if (user.getDeptId() == null) { + user.setDeptId(SecurityUtils.getLoginUser().getDeptId()); + } + } + List list = userService.selectUserList(user); + return getDataTable(list); + } + + @Log(title = "用户管理", businessType = BusinessType.EXPORT) + @PreAuthorize("@ss.hasPermi('system:user:export')") + @PostMapping("/export") + public void export(HttpServletResponse response, SysUser user) { + List list = userService.selectUserList(user); + ExcelUtil util = new ExcelUtil(SysUser.class); + util.exportExcel(response, list, "用户数据"); + } + + @Log(title = "用户管理", businessType = BusinessType.IMPORT) + @PreAuthorize("@ss.hasPermi('system:user:import')") + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(SysUser.class); + List userList = util.importExcel(file.getInputStream()); + String operName = getUsername(); + String message = userService.importUser(userList, updateSupport, operName); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil(SysUser.class); + util.importTemplateExcel(response, "用户数据"); + } + + /** + * 根据用户编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('system:user:query')") + @GetMapping(value = {"/{sysId}", "/{sysId}/{userId}"}) + public AjaxResult getInfo(@PathVariable(value = "sysId", required = false) Integer sysId, @PathVariable(value = "userId", required = false) Long userId) { +// userService.checkUserDataScope(userId); + AjaxResult ajax = AjaxResult.success(); + SysRole sysRole = new SysRole(); + sysRole.setSysId(sysId); + sysRole.setUserId(userId); + List roles = roleService.selectRoleAll(sysRole); + ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); + ajax.put("posts", postService.selectPostAll()); + if (StringUtils.isNotNull(userId)) { + SysUser param = new SysUser(); + param.setUserId(userId); + param.setSysId(sysId); + SysUser sysUser = userService.selectUserById(param); + ajax.put(AjaxResult.DATA_TAG, sysUser); + ajax.put("postIds", postService.selectPostListByUserId(userId)); + if (sysUser.getRoles() != null) { + ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList())); + } else { + ajax.put("roleIds", new ArrayList()); + } + } + return ajax; + } + + /** + * 新增用户 + */ + @PreAuthorize("@ss.hasPermi('system:user:add')") + @Log(title = "用户管理", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@Validated @RequestBody SysUser user) { + if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) { + return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在"); + } +// else if (StringUtils.isNotEmpty(user.getPhonenumber()) +// && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { +// return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在"); +// } else if (StringUtils.isNotEmpty(user.getEmail()) +// && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { +// return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在"); +// } + user.setCreateBy(getUsername()); + user.setPassword(SecurityUtils.encryptPassword(user.getPassword())); + return toAjax(userService.insertUser(user)); + } + + /** + * 修改用户 + */ + @PreAuthorize("@ss.hasPermi('system:user:edit')") + @Log(title = "用户管理", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@Validated @RequestBody SysUser user) { + userService.checkUserAllowed(user); + userService.checkUserDataScope(user.getUserId()); + if (StringUtils.isNotEmpty(user.getPhonenumber()) + && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) { + return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); + } else if (StringUtils.isNotEmpty(user.getEmail()) + && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) { + return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); + } + user.setUpdateBy(getUsername()); + return toAjax(userService.updateUser(user)); + } + + /** + * 删除用户 + */ + @PreAuthorize("@ss.hasPermi('system:user:remove')") + @Log(title = "用户管理", businessType = BusinessType.DELETE) + @DeleteMapping("/{userIds}") + public AjaxResult remove(@PathVariable Long[] userIds) { + if (ArrayUtils.contains(userIds, getUserId())) { + return error("当前用户不能删除"); + } + return toAjax(userService.deleteUserByIds(userIds)); + } + + /** + * 重置密码 + */ + @PreAuthorize("@ss.hasPermi('system:user:resetPwd')") + @Log(title = "用户管理", businessType = BusinessType.UPDATE) + @PutMapping("/resetPwd") + public AjaxResult resetPwd(@RequestBody SysUser user) { + userService.checkUserAllowed(user); + userService.checkUserDataScope(user.getUserId()); + user.setPassword(SecurityUtils.encryptPassword(user.getPassword())); + user.setUpdateBy(getUsername()); + return toAjax(userService.resetPwd(user)); + } + + /** + * 状态修改 + */ + @PreAuthorize("@ss.hasPermi('system:user:edit')") + @Log(title = "用户管理", businessType = BusinessType.UPDATE) + @PutMapping("/changeStatus") + public AjaxResult changeStatus(@RequestBody SysUser user) { + userService.checkUserAllowed(user); + //userService.checkUserDataScope(user.getUserId()); + user.setUpdateBy(getUsername()); + return toAjax(userService.updateUserStatus(user)); + } + + /** + * 根据用户编号获取授权角色 + */ + @PreAuthorize("@ss.hasPermi('system:user:query')") + @GetMapping("/authRole/{userId}/{sysId}") + public AjaxResult authRole(@PathVariable("userId") Long userId, @PathVariable("sysId") Integer sysId) { + AjaxResult ajax = AjaxResult.success(); + SysUser param = new SysUser(); + param.setUserId(userId); + param.setSysId(sysId); + SysUser user = userService.selectUserById(param); + SysRole sysRole = new SysRole(); + + sysRole.setSysId(sysId); + sysRole.setUserId(userId); + List roles = roleService.selectRolesByUserId(sysRole); + ajax.put("user", user); + ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); + return ajax; + } + + /** + * 用户授权角色 + */ + @PreAuthorize("@ss.hasPermi('system:user:edit')") + @Log(title = "用户管理", businessType = BusinessType.GRANT) + @PutMapping("/authRole") + public AjaxResult insertAuthRole(Long userId, Integer sysId, Long[] roleIds) { +// userService.checkUserDataScope(userId); + userService.insertUserAuth(userId, sysId, roleIds); + return success(); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/SwaggerController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/SwaggerController.java new file mode 100644 index 0000000..899e3a8 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/SwaggerController.java @@ -0,0 +1,24 @@ +package net.hzvtc.web.controller.tool; + +import net.hzvtc.common.core.controller.BaseController; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * swagger 接口 + * + * @author admin + */ +@Controller +@RequestMapping("/tool/swagger") +public class SwaggerController extends BaseController +{ + @PreAuthorize("@ss.hasPermi('tool:swagger:view')") + @GetMapping() + public String index() + { + return redirect("/swagger-ui.html"); + } +} diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/TestController.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/TestController.java new file mode 100644 index 0000000..4c07950 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/TestController.java @@ -0,0 +1,87 @@ +package net.hzvtc.web.controller.tool; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.web.controller.tool.UserEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(value="\u7528\u6237\u4fe1\u606f\u7ba1\u7406") +@RestController +@RequestMapping(value={"/test/user"}) +public class TestController +extends BaseController { + private static final Map users = new LinkedHashMap(); + + public TestController() { + users.put(1, new UserEntity(1, "admin", "admin123", "15888888888")); + users.put(2, new UserEntity(2, "ry", "admin123", "15666666666")); + } + + @ApiOperation(value="\u83b7\u53d6\u7528\u6237\u5217\u8868") + @GetMapping(value={"/list"}) + public AjaxResult userList() { + ArrayList userList = new ArrayList(users.values()); + return AjaxResult.success(userList); + } + + @ApiOperation(value="\u83b7\u53d6\u7528\u6237\u8be6\u7ec6") + @ApiImplicitParam(name="userId", value="\u7528\u6237ID", required=true, dataType="int", paramType="path", dataTypeClass=Integer.class) + @GetMapping(value={"/{userId}"}) + public AjaxResult getUser(@PathVariable Integer userId) { + if (!users.isEmpty() && users.containsKey(userId)) { + return AjaxResult.success((Object)users.get(userId)); + } + return this.error("\u7528\u6237\u4e0d\u5b58\u5728"); + } + + @ApiOperation(value="\u65b0\u589e\u7528\u6237") + @ApiImplicitParams(value={@ApiImplicitParam(name="userId", value="\u7528\u6237id", dataType="Integer", dataTypeClass=Integer.class), @ApiImplicitParam(name="username", value="\u7528\u6237\u540d\u79f0", dataType="String", dataTypeClass=String.class), @ApiImplicitParam(name="password", value="\u7528\u6237\u5bc6\u7801", dataType="String", dataTypeClass=String.class), @ApiImplicitParam(name="mobile", value="\u7528\u6237\u624b\u673a", dataType="String", dataTypeClass=String.class)}) + @PostMapping(value={"/save"}) + public AjaxResult save(UserEntity user) { + if (StringUtils.isNull((Object)user) || StringUtils.isNull((Object)user.getUserId())) { + return this.error("\u7528\u6237ID\u4e0d\u80fd\u4e3a\u7a7a"); + } + return AjaxResult.success((Object)users.put(user.getUserId(), user)); + } + + @ApiOperation(value="\u66f4\u65b0\u7528\u6237") + @PutMapping(value={"/update"}) + public AjaxResult update(@RequestBody UserEntity user) { + if (StringUtils.isNull((Object)user) || StringUtils.isNull((Object)user.getUserId())) { + return this.error("\u7528\u6237ID\u4e0d\u80fd\u4e3a\u7a7a"); + } + if (users.isEmpty() || !users.containsKey(user.getUserId())) { + return this.error("\u7528\u6237\u4e0d\u5b58\u5728"); + } + users.remove(user.getUserId()); + return AjaxResult.success((Object)users.put(user.getUserId(), user)); + } + + @ApiOperation(value="\u5220\u9664\u7528\u6237\u4fe1\u606f") + @ApiImplicitParam(name="userId", value="\u7528\u6237ID", required=true, dataType="int", paramType="path", dataTypeClass=Integer.class) + @DeleteMapping(value={"/{userId}"}) + public AjaxResult delete(@PathVariable Integer userId) { + if (!users.isEmpty() && users.containsKey(userId)) { + users.remove(userId); + return this.success(); + } + return this.error("\u7528\u6237\u4e0d\u5b58\u5728"); + } +} + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/UserEntity.java b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/UserEntity.java new file mode 100644 index 0000000..a4d7972 --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/controller/tool/UserEntity.java @@ -0,0 +1,60 @@ +package net.hzvtc.web.controller.tool; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value="UserEntity", description="\u7528\u6237\u5b9e\u4f53") +class UserEntity { + @ApiModelProperty(value="\u7528\u6237ID") + private Integer userId; + @ApiModelProperty(value="\u7528\u6237\u540d\u79f0") + private String username; + @ApiModelProperty(value="\u7528\u6237\u5bc6\u7801") + private String password; + @ApiModelProperty(value="\u7528\u6237\u624b\u673a") + private String mobile; + + public UserEntity() { + } + + public UserEntity(Integer userId, String username, String password, String mobile) { + this.userId = userId; + this.username = username; + this.password = password; + this.mobile = mobile; + } + + public Integer getUserId() { + return this.userId; + } + + public void setUserId(Integer userId) { + this.userId = userId; + } + + public String getUsername() { + return this.username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return this.password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getMobile() { + return this.mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } +} + + diff --git a/ai-bird-admin/src/main/java/net/hzvtc/web/core/config/SwaggerConfig.java b/ai-bird-admin/src/main/java/net/hzvtc/web/core/config/SwaggerConfig.java new file mode 100644 index 0000000..884f69d --- /dev/null +++ b/ai-bird-admin/src/main/java/net/hzvtc/web/core/config/SwaggerConfig.java @@ -0,0 +1,121 @@ +package net.hzvtc.web.core.config; + +import io.swagger.annotations.ApiOperation; +import io.swagger.models.auth.In; +import net.hzvtc.common.config.AiBirdSysConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.*; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spi.service.contexts.SecurityContext; +import springfox.documentation.spring.web.plugins.Docket; + +import java.util.ArrayList; +import java.util.List; + +/** + * Swagger2的接口配置 + * + * @author admin + */ +@Configuration +public class SwaggerConfig { + /** + * 系统基础配置 + */ + @Autowired + private AiBirdSysConfig adminConfig; + + /** + * 是否开启swagger + */ + @Value("${swagger.enabled}") + private boolean enabled; + + /** + * 设置请求的统一前缀 + */ + @Value("${swagger.pathMapping}") + private String pathMapping; + + /** + * 创建API + */ + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.OAS_30) + // 是否启用Swagger + .enable(enabled) + // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) + .apiInfo(apiInfo()) + // 设置哪些接口暴露给Swagger展示 + .select() + // 扫描所有有注解的api,用这种方式更灵活 + .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) + // 扫描指定包中的swagger注解 + // .apis(RequestHandlerSelectors.basePackage("net.hzvtc.project.tool.swagger")) + // 扫描所有 .apis(RequestHandlerSelectors.any()) + .paths(PathSelectors.any()) + .build() + /* 设置安全模式,swagger可以设置访问token */ + .securitySchemes(securitySchemes()) + .securityContexts(securityContexts()) + .pathMapping(pathMapping); + } + + /** + * 安全模式,这里指定token通过Authorization头请求头传递 + */ + private List securitySchemes() { + List apiKeyList = new ArrayList(); + apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue())); + return apiKeyList; + } + + /** + * 安全上下文 + */ + private List securityContexts() { + List securityContexts = new ArrayList<>(); + securityContexts.add( + SecurityContext.builder() + .securityReferences(defaultAuth()) + .operationSelector(o -> o.requestMappingPattern().matches("/.*")) + .build()); + return securityContexts; + } + + /** + * 默认的安全上引用 + */ + private List defaultAuth() { + AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); + AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; + authorizationScopes[0] = authorizationScope; + List securityReferences = new ArrayList<>(); + securityReferences.add(new SecurityReference("Authorization", authorizationScopes)); + return securityReferences; + } + + /** + * 添加摘要信息 + */ + private ApiInfo apiInfo() { + // 用ApiInfoBuilder进行定制 + return new ApiInfoBuilder() + // 设置标题 + .title("标题:AiBirdSys管理系统_接口文档") + // 描述 + .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...") + // 作者信息 + .contact(new Contact(adminConfig.getName(), null, null)) + // 版本 + .version("版本号:" + adminConfig.getVersion()) + .build(); + } +} diff --git a/ai-bird-admin/src/main/resources/application-d2030.yml b/ai-bird-admin/src/main/resources/application-d2030.yml new file mode 100644 index 0000000..5321d50 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-d2030.yml @@ -0,0 +1,135 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-dianchi-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 172.16.8.253:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-dev.yml b/ai-bird-admin/src/main/resources/application-dev.yml new file mode 100644 index 0000000..e549e75 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-dev.yml @@ -0,0 +1,148 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2022 + # 实例演示开关 + demoEnabled: true + # 文件路径 + profile: D:/message/bird + birdMediaPath: E:/data5/file + birdImagePath: D:/message/bird + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: D:\project\aibird\project\template\ + dailyReportFileOutPath: D:\project\aibird\project\report\ + cameraSnapshopFilePath: D:\message\bird\images\snapshop\ + observationFilePath: D:\message\bird\observation\ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + dianChiServerUrl: http://127.0.0.1:8080 + extractFileServerUrl: http://semi-ai.tech:9099 +# 数据源配置 +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + # url: jdbc:mysql://localhost:3306/ai-bird-db-server?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + # url: jdbc:mysql://localhost:3306/ai-data-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + # url: jdbc:mysql://localhost:33366/ai-dianchi-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + url: jdbc:mysql://localhost:33366/ai-datan-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: semiAiBird123 + # password: dKhqXaMKzKKTbY2/vHq8WxfD/5T8DnZnEwBsSl1rmCGGtRrPuuu51PBHRG0JywJRhSyHI50haZUdZwPVIycG2g== + # filters: config + # connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + # username: elastic + # password: wofQfEhTZWhq-+CqEbL3 + username: aibird + # password: aibird123 + password: Semi_Aibird*123$ + # hosts: 127.0.0.1:9200 + # hosts: 192.168.60.234:9200 + hosts: sys.ykz-ai.com:30052 + # port: 9200 + http: https + apiKey: OU83aHVwQUJiZ3BELUFiOFdaamU6T214YnhJY1dRcWFKMktmcDhKc0I5UQ== + # certName: es_ca.crt + # apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ8oUYRIPIZi4FNM6OZjV9eNC3jPngmr6T+vOawnvLNwtim3lujZGmlenAd6HnNWzbZN+BOkOep1Wxmu+yVo0q8CAwEAAQ== +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn + + diff --git a/ai-bird-admin/src/main/resources/application-druid-product.yml b/ai-bird-admin/src/main/resources/application-druid-product.yml new file mode 100644 index 0000000..e356cea --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-druid-product.yml @@ -0,0 +1,61 @@ +# 数据源配置 +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-druid.yml b/ai-bird-admin/src/main/resources/application-druid.yml new file mode 100644 index 0000000..699ea56 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-druid.yml @@ -0,0 +1,62 @@ +# 数据源配置 +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + # url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + url: jdbc:mysql://localhost:3306/ai-bird-db-server?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: dKhqXaMKzKKTbY2/vHq8WxfD/5T8DnZnEwBsSl1rmCGGtRrPuuu51PBHRG0JywJRhSyHI50haZUdZwPVIycG2g== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJ8oUYRIPIZi4FNM6OZjV9eNC3jPngmr6T+vOawnvLNwtim3lujZGmlenAd6HnNWzbZN+BOkOep1Wxmu+yVo0q8CAwEAAQ== diff --git a/ai-bird-admin/src/main/resources/application-jxsdb.yml b/ai-bird-admin/src/main/resources/application-jxsdb.yml new file mode 100644 index 0000000..38d29c7 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-jxsdb.yml @@ -0,0 +1,119 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: aibird123 + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-n2030.yml b/ai-bird-admin/src/main/resources/application-n2030.yml new file mode 100644 index 0000000..93ad4ce --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-n2030.yml @@ -0,0 +1,135 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-datan-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 172.16.8.253:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-p2030.yml b/ai-bird-admin/src/main/resources/application-p2030.yml new file mode 100644 index 0000000..85babea --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-p2030.yml @@ -0,0 +1,135 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-data-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 172.16.8.253:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-prod.yml b/ai-bird-admin/src/main/resources/application-prod.yml new file mode 100644 index 0000000..3725ebc --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-prod.yml @@ -0,0 +1,136 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + dianChiServerUrl: http://39.129.29.230:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-data-2030?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 127.0.0.1:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-pyh.yml b/ai-bird-admin/src/main/resources/application-pyh.yml new file mode 100644 index 0000000..21d9431 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-pyh.yml @@ -0,0 +1,134 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data/file + birdMediaPath: /data/file/ + birdImagePath: /data/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data/file/template/ + dailyReportFileOutPath: /data/file/excel/ + cameraSnapshopFilePath: /data/file/images/snapshot/ + observationFilePath: /data/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://223.83.100.204:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 127.0.0.1:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: Aibird123654 + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: error + org.springframework: error \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-pyh1.yml b/ai-bird-admin/src/main/resources/application-pyh1.yml new file mode 100644 index 0000000..261dd98 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-pyh1.yml @@ -0,0 +1,140 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data/file + birdMediaPath: /data/file/ + birdImagePath: /data/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data/file/template/ + dailyReportFileOutPath: /data/file/excel/ + cameraSnapshopFilePath: /data/file/images/snapshot/ + observationFilePath: /data/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://223.83.100.204:9099 + +# 开发环境配置 +server: + # 服务器的HTTP端口,默认为8080 + port: 8080 + servlet: + # 应用的访问路径 + context-path: / + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + # 连接数满后的排队数,默认为100 + accept-count: 1000 + threads: + # tomcat最大线程数,默认为200 + max: 800 + # Tomcat启动初始化的线程数,默认值10 + min-spare: 100 + +# 日 +logging: + level: + net.hzvtc: debug + org.springframework: warn + +# Spring配置 +spring: + # 资源信息 + mvc: + pathmatch: + matching-strategy: ant_path_matcher + messages: + # 国际化资源文件路径 + basename: i18n/messages + profiles: + active: druid + # 文件上传 + servlet: + multipart: + # 单个文件大小 + max-file-size: 10MB + # 设置总上传的文件大小 + max-request-size: 20MB + jackson: + default-property-inclusion: non_null + # 服务模块 + devtools: + restart: + # 热部署开关 + enabled: true + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: Aibird123654 + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +# token配置 +token: + # 令牌自定义标识 + header: Authorization + # 令牌密钥 + secret: abcdefghijklmnopqrstuvwxyz + # 令牌有效期(默认30分钟) + expireTime: 300 + +# MyBatis配置 +mybatis: + # 搜索指定包别名 + typeAliasesPackage: net.hzvtc.**.domain + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapperLocations: classpath*:mapper/**/*Mapper.xml + # 加载全局的配置文件 + configLocation: classpath:mybatis/mybatis-config.xml + +# PageHelper分页插件 +pagehelper: + helperDialect: mysql + supportMethodsArguments: true + params: count=countSql + +# Swagger配置 +swagger: + # 是否开启swagger + enabled: true + # 请求前缀 + pathMapping: /dev-api + +# 防止XSS攻击 +xss: + # 过滤开关 + enabled: true + # 排除链接(多个用逗号分隔) + excludes: /system/notice + # 匹配链接 + urlPatterns: /system/*,/monitor/*,/tool/* diff --git a/ai-bird-admin/src/main/resources/application-qzly.yml b/ai-bird-admin/src/main/resources/application-qzly.yml new file mode 100644 index 0000000..854ccac --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-qzly.yml @@ -0,0 +1,135 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data/file + birdMediaPath: /data/file/ + birdImagePath: /data/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data/file/template/ + dailyReportFileOutPath: /data/file/excel/ + cameraSnapshopFilePath: /data/file/images/snapshot/ + observationFilePath: /data/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + #fileServerUrl: http://223.83.100.204:9099 + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 127.0.0.1:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: Aibird123654 + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: error + org.springframework: error \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-shunyi.yml b/ai-bird-admin/src/main/resources/application-shunyi.yml new file mode 100644 index 0000000..678d634 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-shunyi.yml @@ -0,0 +1,130 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + extractFileServerUrl: http://semi-ai.tech:9099 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 127.0.0.1:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-xuebao.yml b/ai-bird-admin/src/main/resources/application-xuebao.yml new file mode 100644 index 0000000..9e1a1df --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-xuebao.yml @@ -0,0 +1,119 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data5/file + birdMediaPath: /data5/file/ + birdImagePath: /data5/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data5/file/template/ + dailyReportFileOutPath: /data5/file/excel/ + cameraSnapshopFilePath: /data5/file/images/snapshot/ + observationFilePath: /data5/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db-new?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application-yndc.yml b/ai-bird-admin/src/main/resources/application-yndc.yml new file mode 100644 index 0000000..ac24e07 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application-yndc.yml @@ -0,0 +1,136 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2023 + # 实例演示开关 + demoEnabled: false + profile: /data/file + birdMediaPath: /data/file/ + birdImagePath: /data/file/ + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: /data/file/template/ + dailyReportFileOutPath: /data/file/excel/ + cameraSnapshopFilePath: /data/file/images/snapshot/ + observationFilePath: /data/file/images/observation/ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + #fileServerUrl: http://223.83.100.204:9099 + fileServerUrl: http://semi-ai.tech:9099 + extractServerUrl: http://semi-ai.tech:19090 + dianChiServerUrl: http://39.129.29.230:19090 + +spring: + datasource: + type: com.alibaba.druid.pool.DruidDataSource + driverClassName: com.mysql.cj.jdbc.Driver + druid: + # 主库数据源 + master: + url: jdbc:mysql://localhost:3306/ai-bird-db?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 + username: root + password: l/e9anIszcsjpFyUvBjbX6t5tOT2lNGm5dXNrfHVAL+2P1F3dZYTcFihaJBXMnplAJ8dhp94K94RUXMpD2i4dw== + filters: config + connection-properties: 'config.decrypt=true;config.decrypt.key=${publickey}' + + # 从库数据源 + slave: + # 从数据源开关/默认关闭 + enabled: false + url: + username: + password: + # 初始连接数 + initialSize: 5 + # 最小连接池数量 + minIdle: 10 + # 最大连接池数量 + maxActive: 20 + # 配置获取连接等待超时的时间 + maxWait: 60000 + # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + timeBetweenEvictionRunsMillis: 60000 + # 配置一个连接在池中最小生存的时间,单位是毫秒 + minEvictableIdleTimeMillis: 300000 + # 配置一个连接在池中最大生存的时间,单位是毫秒 + maxEvictableIdleTimeMillis: 900000 + # 配置检测连接是否有效 + validationQuery: SELECT 1 FROM DUAL + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + webStatFilter: + enabled: true + statViewServlet: + enabled: true + # 设置白名单,不填则允许所有访问 + allow: + url-pattern: /druid/* + # 控制台管理用户名和密码 + login-username: root + login-password: root123 + filter: + stat: + enabled: true + # 慢SQL记录 + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: true + wall: + config: + multi-statement-allow: true + elastic: + #username: elastic + #password: OjNq8y*ck337qcWXmrg2 + username: aibird + password: Semi_Aibird*123$ + hosts: 127.0.0.1:9200 + # port: 9200 + http: https + apiKey: R3RkY0I1RUJaYTMtRWdUdEJZM1A6OFg4M1FlMFdRdHFsdjZkQXlMalJJdw== + certName: es_ca_server.crt + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: Aibird123654 + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData + +publicKey: MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKOmv7xNg5aqMTeQAW48cLTv0B9/IGAGkfMG/cZU27rW9SMNGmDgllAWB50xAaYlkSYJXq1LqWBSWpScpoiHoDkCAwEAAQ== + +# 日志配置 +logging: + level: + net.hzvtc: error + org.springframework: error \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/application.bak.yml b/ai-bird-admin/src/main/resources/application.bak.yml new file mode 100644 index 0000000..7b86d63 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application.bak.yml @@ -0,0 +1,147 @@ +# 项目相关配置 +hzvtc: + # 名称 + name: AiBird + # 版本 + version: 1.0.0 + # 版权年份 + copyrightYear: 2022 + # 实例演示开关 + demoEnabled: true + # 文件路径 示例( Windows配置D:/hzvtc/uploadPath,Linux配置 /home/hzvtc/uploadPath) + profile: D:/message/bird + birdMediaPath: D:/message/bird + birdImagePath: D:/message/bird + # 获取ip地址开关 + addressEnabled: false + # 验证码类型 math 数组计算 char 字符验证 + captchaType: math + dailyReportFilePath: D:\project\aibird\project\template\ + dailyReportFileOutPath: D:\project\aibird\project\report\ + cameraSnapshopFilePath: D:\message\bird\images\snapshop\ + observationFilePath: D:\message\bird\observation\ + observationTokenUrl: http://semi-ai.tech:19101/v1/getAccessToken + observationImgCheckUrl: http://semi-ai.tech:19101/v2/detImg + fileServerUrl: http://semi-ai.tech:9099 +# 开发环境配置 +server: + # 服务器的HTTP端口,默认为8080 + port: 8080 + servlet: + # 应用的访问路径 + context-path: / + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + # 连接数满后的排队数,默认为100 + accept-count: 1000 + threads: + # tomcat最大线程数,默认为200 + max: 800 + # Tomcat启动初始化的线程数,默认值10 + min-spare: 100 + +# 日志配置 +logging: + level: + net.hzvtc: debug + org.springframework: warn + +# Spring配置 +spring: + # 资源信息 + # main: + # allow-circular-references: true + mvc: + pathmatch: + matching-strategy: ant_path_matcher + messages: + # 国际化资源文件路径 + basename: i18n/messages + profiles: + active: druid + # 文件上传 + servlet: + multipart: + # 单个文件大小 + max-file-size: 10MB + # 设置总上传的文件大小 + max-request-size: 20MB + jackson: + default-property-inclusion: non_null + # 服务模块 + devtools: + restart: + # 热部署开关 + enabled: true + # redis 配置 + redis: + # 地址 + host: localhost + # 端口,默认为6379 + port: 6379 + # 数据库索引 + database: 0 + # 密码 + password: + # 连接超时时间 + timeout: 10s + lettuce: + pool: + # 连接池中的最小空闲连接 + min-idle: 0 + # 连接池中的最大空闲连接 + max-idle: 8 + # 连接池的最大数据库连接数 + max-active: 8 + # #连接池最大阻塞等待时间(使用负值表示没有限制) + max-wait: -1ms + mail: + #host: smtp.yeah.net + #username: dannyxu@yeah.net + #password: TSSTWAQFNYLGPMTT + host: smtp.163.com + username: aisemibird@163.com + password: VDRSLZUDDXGQMGVJ + +# token配置 +token: + # 令牌自定义标识 + header: Authorization + # 令牌密钥 + #secret: abcdefghijklmnopqrstuvwxyz + secret: SemiksFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJBIRD + # 令牌有效期(默认30分钟) + expireTime: 300 + +# MyBatis配置 +mybatis: + # 搜索指定包别名 + typeAliasesPackage: net.hzvtc.**.domain + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapperLocations: classpath*:mapper/**/*Mapper.xml + # 加载全局的配置文件 + configLocation: classpath:mybatis/mybatis-config.xml + +# PageHelper分页插件 +pagehelper: + # helperDialect: mysql + helperDialect: net.hzvtc.framework.datasource.MySqlDialectCustom + supportMethodsArguments: true + params: count=countSql + +# Swagger配置 +swagger: + # 是否开启swagger + enabled: true + # 请求前缀 + pathMapping: /dev-api + +# 防止XSS攻击 +xss: + # 过滤开关 + enabled: true + # 排除链接(多个用逗号分隔) + excludes: /system/notice + # 匹配链接 + urlPatterns: /system/*,/monitor/*,/tool/* diff --git a/ai-bird-admin/src/main/resources/application.yml b/ai-bird-admin/src/main/resources/application.yml new file mode 100644 index 0000000..a9fcb19 --- /dev/null +++ b/ai-bird-admin/src/main/resources/application.yml @@ -0,0 +1,94 @@ +server: + # 服务器的HTTP端口,默认为8080 + port: 8080 + servlet: + # 应用的访问路径 + context-path: / + tomcat: + # tomcat的URI编码 + uri-encoding: UTF-8 + # 连接数满后的排队数,默认为100 + accept-count: 1000 + threads: + # tomcat最大线程数,默认为200 + max: 800 + # Tomcat启动初始化的线程数,默认值10 + min-spare: 100 +hzvtc: + dianChiServerUrl: http://127.0.0.1:19090 + extractFileServerUrl: http://127.0.0.1:19090 + +VideoPostUrl: + yuyuantanUrl: http://www.byskxx.com:8066/admin/anfang/api/auto + yuyuantanDataUrl: http://www.byskxx.com:8066/admin/anfang/api/receiveData + huiXianPostUrl: http://117.140.176.248:9201/gw/api-third/birdMonitoring/receiveData +# Spring配置 +spring: + # 资源信息 + # main: + # allow-circular-references: true + mvc: + pathmatch: + matching-strategy: ant_path_matcher + messages: + # 国际化资源文件路径 + basename: i18n/messages + profiles: + active: dev + # 文件上传 + servlet: + multipart: + # 单个文件大小 + max-file-size: 10MB + # 设置总上传的文件大小 + max-request-size: 20MB + jackson: + default-property-inclusion: non_null + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + # 服务模块 + devtools: + restart: + # 热部署开关 + enabled: true +# token配置 +token: + # 令牌自定义标识 + header: Authorization + # 令牌密钥 + #secret: abcdefghijklmnopqrstuvwxyz + secret: SemiksFKLJISJFKLFKWJFQFIQWIOFJQOFFQGGSDGFFJIQOEUFIEJFIOQWEFHFQOK5FKOIQWUFFEFE423FIQEOFJHUEWHFKASKDLQWJIFSJDJKFHJBIRD + # 令牌有效期(默认30分钟) + expireTime: 300 + +# MyBatis配置 +mybatis: + # 搜索指定包别名 + typeAliasesPackage: net.hzvtc.**.domain + # 配置mapper的扫描,找到所有的mapper.xml映射文件 + mapperLocations: classpath*:mapper/**/*Mapper.xml + # 加载全局的配置文件 + configLocation: classpath:mybatis/mybatis-config.xml + +# PageHelper分页插件 +pagehelper: + # helperDialect: mysql + helperDialect: net.hzvtc.framework.datasource.MySqlDialectCustom + supportMethodsArguments: true + params: count=countSql + +# Swagger配置 +swagger: + # 是否开启swagger + enabled: false + # 请求前缀 + pathMapping: /dev-api + +# 防止XSS攻击 +xss: + # 过滤开关 + enabled: true + # 排除链接(多个用逗号分隔) + excludes: /system/notice + # 匹配链接 + urlPatterns: /system/*,/monitor/*,/tool/* diff --git a/ai-bird-admin/src/main/resources/banner.txt b/ai-bird-admin/src/main/resources/banner.txt new file mode 100644 index 0000000..7a04880 --- /dev/null +++ b/ai-bird-admin/src/main/resources/banner.txt @@ -0,0 +1,2 @@ +Application Version: ${hzvtc.version} +Spring Boot Version: ${spring-boot.version} \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/es_ca.crt b/ai-bird-admin/src/main/resources/es_ca.crt new file mode 100644 index 0000000..3babcdb --- /dev/null +++ b/ai-bird-admin/src/main/resources/es_ca.crt @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIVANil77ICYF+kh70i31uPtcjlduyiMA0GCSqGSIb3DQEB +CwUAMDwxOjA4BgNVBAMTMUVsYXN0aWNzZWFyY2ggc2VjdXJpdHkgYXV0by1jb25m +aWd1cmF0aW9uIEhUVFAgQ0EwHhcNMjQwMjE0MDI0NjAwWhcNMjcwMjEzMDI0NjAw +WjA8MTowOAYDVQQDEzFFbGFzdGljc2VhcmNoIHNlY3VyaXR5IGF1dG8tY29uZmln +dXJhdGlvbiBIVFRQIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA +r9cEwOK5db8CL+X1Bx/6kffmQGvZu7UKuVPcrch2PoxoPOBUsw0VDa+islZAA1YJ +3k8yy9vimI89eJzk4jAzKHSJ6NAgtOU1YAZ/lLRodrSWumJ8YNmocjEYTNBMF8iK +/Xz5q5mQxQs/TuqeEtgJaij1TJPQQD7Tc4UN3W6M5yL8/z6sclO55wqCatORvQur +Nn9/DZijfHEtbgIeu96LbusEfZ0HSyghY7SmisKX/iMLmtUQgTm3XBOmBQau+t8U +rqtQhZl4iGyQNXS60f0g6+Sgo2e6N4lL8j2EKUao41n9v/9f6yXDX716hILcYcck +v0bAi7ukltkgBdcmSbm9SP5HXIWJ/AcS2R9W3laLqiCHf4U1eQfpI8UmyXQKd1bV +5GneyH6NKKNE4CWQr9g2AxGmYVxVp0I5Ln37G9zW4D4heYLqxJSuVvrwbRHzpfkP +OoUaWaEG+ryOkTfw3RhywM7l2QbI31Ktl2sw5Nqv+tFlVEuoVePgOXI6YpUHgPhf +Q8aKYNUpKkurfKMMGv51G7fBkbHjTEKxFnznYpE5lDTVYarcOw5+DJzNTUOHC0D+ +7WF/7biJfyQ7H0OoVIHPlK/3U506/LHthig2yynkcyyH2xIbQIrdvWVH3t9L6Oyx +QU/TUT2qnJCghUUL+p2s56DTuDKENIbKdfp6NMi1tjkCAwEAAaNTMFEwHQYDVR0O +BBYEFIr3iIiDGACxDCsOUH08UoDsfFEBMB8GA1UdIwQYMBaAFIr3iIiDGACxDCsO +UH08UoDsfFEBMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggIBAFiM +uXyJUWEr0npmgD3Sz7gzRRgTfmYla83f/V2mCdhigIgeJJwrta7q5Qe9Ufa1ccJQ +4kmqM+rEHUAGG+90oZ10HPYI8VB1K6MW7brL1FU4FLb4eaC6Uyv6rzch9grpgM6y +T73O39qW5yuP5CuYWrPv92T7wdy2S7f7s1OCDvCaGh58NuhYx7Ww112YEGaO8hD3 +1dZijxsMfR5L1H84BVANbpTpxg0wsIRYmIeO2PJxlGTNVxoRgR2ucyHQXtZmMmhR +n5qCoa0a8CiCX5kE/z5kAA4RqxHTxhZQ9XQd+WpyaRqp26fp1RftEKw90b5yygDa +00vC6kV4dpYAA1DO08rUNGQijAQrTJO4cdZH3BbMmRQTKDx3Wt7zUfaFganFGVn+ +ExELV4CBwNIyazS+D4VSmeZ0JBf5bG++QMDkMxzPYdY5XtlPt7N41Ta/T7mDeYg+ +BIxF8OpJrlNPbxffp4bSqu4jObqS+u0oAEMGaxjZT3IlW34JCMpOE8dBAaod4mP3 +7r0KCpSC0BLuOPydkxUsRZSe6DX67jkZqiajogxBlDhi1DRBUl/55+T3SQDcsy3t +qK+7iwRV3ODbZaeE68ujHo4OErZs+shKvliO231KgWByIB/llZ4k+yZ3EXtws3JG +ogXh9v+MWIE5ZKiAhMuaqKSlJTlkgfN0MBiNn3dD +-----END CERTIFICATE----- diff --git a/ai-bird-admin/src/main/resources/es_ca_server.crt b/ai-bird-admin/src/main/resources/es_ca_server.crt new file mode 100644 index 0000000..627524a --- /dev/null +++ b/ai-bird-admin/src/main/resources/es_ca_server.crt @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIUSIljr8sHsOSVpGEnulyHwIU1au0wDQYJKoZIhvcNAQEL +BQAwPDE6MDgGA1UEAxMxRWxhc3RpY3NlYXJjaCBzZWN1cml0eSBhdXRvLWNvbmZp +Z3VyYXRpb24gSFRUUCBDQTAeFw0yNDA3MzEwMjQ4MjZaFw0yNzA3MzEwMjQ4MjZa +MDwxOjA4BgNVBAMTMUVsYXN0aWNzZWFyY2ggc2VjdXJpdHkgYXV0by1jb25maWd1 +cmF0aW9uIEhUVFAgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCN +/nnBG0Ljres5Y9b6gjNKauEYZWTAzJCGG7E7no7siwjYnwlnNqiD0kwAcdtICkjv +9uOHXGdfeExh1BQFtaWqbvCA3k8h/lilmXa+fF3xYxvetBUC1clwQl/YtGO02pPg +9vKHIq5q24xzVrMfHyY2xdITvv7fbSXUvQKFJmaGN3+5V8vKQK6KT+YY9ic9LJi1 +MD8e4CPG654XJEDMysogU2MXoW9NFTqCS7K2u49P0VfBnfqeJRQGpKMZrLRGo1zu +bZgOZdWsY1TQ/IOwbsmH2GXw995/u0R+kKpcl3ViWm+2ErUckktVUzh2f4LCPhwZ +C5ds8yhMP/WfDnrWSDwPTTptLLczgxsuYk36M6RFBF+jUd23yZJvJxGXde6zzplc +OQLNtHByUKMCq8EoS691ufJqWMMCHb1H2OQHEPRGxcgtQ1hpjz13GEelnUF3MGlD +DPiNfmRvD4IBojmh21SfuDGPZxIoIrhMt2XaC0eaq+soKJGReer5l6Q9Wh+b5s4U +HJ2yEg57VjW5Dwshad1RnD8WhV4UD1fEthGNGfMQZvNZyezA4dwHp5SthbOYgbHF +QU8ByTRcxNPsx64IIXYa0RqjyBVaD2OL7YJEYsO+PbAsCyVXtr/4h/q7fmkKNX4N +ArAtyvrDVqtYjwmGFix7l8G1GXbJAf9abci4aPGiOQIDAQABo1MwUTAdBgNVHQ4E +FgQUnqBxAJLZymZOICjUmjWXcKfk+v0wHwYDVR0jBBgwFoAUnqBxAJLZymZOICjU +mjWXcKfk+v0wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEATy/M +7kgdZrg61PgeUrzsqTLwFRV559j7deZ8K+bRofwL5vQJ14w6fuoqipLXxTq3obS3 +dQvO1xx1p2AHn8nu4d29CW8PUzZFD52ZHdU8gxVF5dUCnbF3b15d2CKoivSVSHpl +0R6SwuyhnWeaV2ue0/0H+KBlbB1pl94wNw+eSLCL/m8k68DnI+qY5skLZpfxjcoc +mEG8EckHoO3+JKshj6darBS+I5QmmbBrFzB/AJN9YbrM0OjqEC3u1SYWEPwinv4G +H9rSZC0wP8xjKVGjVub8C4Fkz+StWucotBrD3aadao09Sovrs7GmLFgmObrzuP/N +HPD+tq6sFXfDV0tnKu4EMM+GNsp9wHyASBpasbbYWSy9gjK080kzq7WjfmcBYPU0 +8/nsGH7vBrQvh5XU2zRiuRmHZnpaXpjbmD9LG69yoYI1vNlK6/qrBXVFm2zZ2bRa +UW4B1kY3avj0DvsA2ggYZDeln9pIvt6364tbqZZa9w0KRXzRcKW3zUjmjqTQgtuy +C2KvRF+vQk6BzHG8Szxi8sRLzoNaUsketbB526mjyq0I9+Q/Yjp07iobfZBCcydw +KLfmTthicyQAruDdUXltXSnuEXP8fJXHm1qSERRfOnKWy3tDJCF1u6C/di5HeOKq +dILlQH26K7yRlUcDpQZelnaHdruDmXBREClOMns= +-----END CERTIFICATE----- diff --git a/ai-bird-admin/src/main/resources/i18n/messages.properties b/ai-bird-admin/src/main/resources/i18n/messages.properties new file mode 100644 index 0000000..2d4d629 --- /dev/null +++ b/ai-bird-admin/src/main/resources/i18n/messages.properties @@ -0,0 +1,35 @@ +#错误消息 +not.null=* 必须填写 +user.jcaptcha.error=验证码错误 +user.jcaptcha.expire=验证码已失效 +user.not.exists=用户不存在/密码错误 +user.password.not.match=用户不存在/密码错误 +user.password.retry.limit.count=密码输入错误{0}次 +user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定10分钟 +user.password.delete=对不起,您的账号已被删除 +user.blocked=用户已封禁,请联系管理员 +role.blocked=角色已封禁,请联系管理员 +user.logout.success=退出成功 +length.not.valid=长度必须在{min}到{max}个字符之间 +user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成,且必须以非数字开头 +user.password.not.valid=* 5-50个字符 +user.email.not.valid=邮箱格式错误 +user.mobile.phone.number.not.valid=手机号格式错误 +user.login.success=登录成功 +user.register.success=注册成功 +user.notfound=请重新登录 +user.forcelogout=管理员强制退出,请重新登录 +user.unknown.error=未知错误,请重新登录 +##文件上传消息 +upload.exceed.maxSize=上传的文件大小超出限制的文件大小!
允许的文件最大大小是:{0}MB! +upload.filename.exceed.length=上传的文件名最长{0}个字符 +##权限 +no.permission=您没有数据的权限,请联系管理员添加权限 [{0}] +no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}] +no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}] +no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}] +no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}] +no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}] +no.portal.login=无大屏系统使用权限,请联系管理员添加权限 +no.web.login=无web系统使用权限,请联系管理员添加权限 +no.login.permission=无系统使用权限,请联系管理员添加权限 diff --git a/ai-bird-admin/src/main/resources/logback-product.xml b/ai-bird-admin/src/main/resources/logback-product.xml new file mode 100644 index 0000000..d0fe7b1 --- /dev/null +++ b/ai-bird-admin/src/main/resources/logback-product.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + ${log.pattern} + + + + + + ${log.path}/sys-info.log + + + + ${log.path}/sys-info.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + INFO + + ACCEPT + + DENY + + + + + ${log.path}/sys-error.log + + + + ${log.path}/sys-error.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + ERROR + + ACCEPT + + DENY + + + + + + ${log.path}/sys-user.log + + + ${log.path}/sys-user.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/logback-pyh.xml b/ai-bird-admin/src/main/resources/logback-pyh.xml new file mode 100644 index 0000000..a362522 --- /dev/null +++ b/ai-bird-admin/src/main/resources/logback-pyh.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + ${log.pattern} + + + + + + ${log.path}/sys-info.log + + + + ${log.path}/sys-info.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + INFO + + ACCEPT + + DENY + + + + + ${log.path}/sys-error.log + + + + ${log.path}/sys-error.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + ERROR + + ACCEPT + + DENY + + + + + + ${log.path}/sys-user.log + + + ${log.path}/sys-user.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/logback.xml b/ai-bird-admin/src/main/resources/logback.xml new file mode 100644 index 0000000..a185242 --- /dev/null +++ b/ai-bird-admin/src/main/resources/logback.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + ${log.pattern} + + + + + + ${log.path}/sys-info.log + + + + ${log.path}/sys-info.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + INFO + + ACCEPT + + DENY + + + + + ${log.path}/sys-error.log + + + + ${log.path}/sys-error.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + ERROR + + ACCEPT + + DENY + + + + + + ${log.path}/sys-user.log + + + ${log.path}/sys-user.%d{yyyy-MM-dd}.log + + 60 + + + ${log.pattern} + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-admin/src/main/resources/mybatis/mybatis-config.xml b/ai-bird-admin/src/main/resources/mybatis/mybatis-config.xml new file mode 100644 index 0000000..ac47c03 --- /dev/null +++ b/ai-bird-admin/src/main/resources/mybatis/mybatis-config.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + diff --git a/ai-bird-common/pom.xml b/ai-bird-common/pom.xml new file mode 100644 index 0000000..dc11f40 --- /dev/null +++ b/ai-bird-common/pom.xml @@ -0,0 +1,151 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + + ai-bird-common + + + common通用工具 + + + + + + + org.springframework + spring-context-support + + + + + org.springframework + spring-web + + + + + org.springframework.boot + spring-boot-starter-security + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + + + + + org.springframework.boot + spring-boot-starter-validation + + + + + org.apache.commons + commons-lang3 + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + com.alibaba + fastjson + + + + + commons-io + commons-io + + + + + commons-fileupload + commons-fileupload + + + + + org.apache.poi + poi-ooxml + 5.2.3 + + + + + org.yaml + snakeyaml + + + + + io.jsonwebtoken + jjwt + + + + + javax.xml.bind + jaxb-api + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.apache.commons + commons-pool2 + + + + + eu.bitwalker + UserAgentUtils + + + + + javax.servlet + javax.servlet-api + + + + org.projectlombok + lombok + 1.18.20 + provided + + + + com.belerweb + pinyin4j + 2.5.1 + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + + + \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataScope.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataScope.java new file mode 100644 index 0000000..3c14188 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataScope.java @@ -0,0 +1,28 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 数据权限过滤注解 + * + * @author admin + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DataScope +{ + /** + * 部门表的别名 + */ + public String deptAlias() default ""; + + /** + * 用户表的别名 + */ + public String userAlias() default ""; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataSource.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataSource.java new file mode 100644 index 0000000..6deee9a --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/DataSource.java @@ -0,0 +1,28 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import net.hzvtc.common.enums.DataSourceType; + +/** + * 自定义多数据源切换注解 + * + * 优先级:先方法,后类,如果方法覆盖了类上的数据源类型,以方法的为准,否则以类上的为准 + * + * @author admin + */ +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface DataSource +{ + /** + * 切换数据源名称 + */ + public DataSourceType value() default DataSourceType.MASTER; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excel.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excel.java new file mode 100644 index 0000000..22930c0 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excel.java @@ -0,0 +1,106 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import net.hzvtc.common.utils.poi.ExcelHandlerAdapter; + +@Retention(value=RetentionPolicy.RUNTIME) +@Target(value={ElementType.FIELD}) +public @interface Excel { + public int sort() default 0x7FFFFFFF; + + public String name() default ""; + + public String dateFormat() default ""; + + public String dictType() default ""; + + public String readConverterExp() default ""; + + public String separator() default ","; + + public int scale() default -1; + + public int roundingMode() default 6; + + public ColumnType cellType() default ColumnType.STRING; + + public double height() default 14.0; + + public double width() default 16.0; + + public String suffix() default ""; + + public String defaultValue() default ""; + + public String prompt() default ""; + + public String[] combo() default {}; + + public boolean isExport() default true; + + public String targetAttr() default ""; + + public boolean isStatistics() default false; + + public Align align() default Align.AUTO; + + public Class handler() default ExcelHandlerAdapter.class; + + public String[] args() default {}; + + public Type type() default Type.ALL; + + public static enum ColumnType { + NUMERIC(0), + STRING(1), + IMAGE(2); + + private final int value; + + private ColumnType(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } + + public static enum Type { + ALL(0), + EXPORT(1), + IMPORT(2); + + private final int value; + + private Type(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } + + public static enum Align { + AUTO(0), + LEFT(1), + CENTER(2), + RIGHT(3); + + private final int value; + + private Align(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excels.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excels.java new file mode 100644 index 0000000..45dae6a --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Excels.java @@ -0,0 +1,18 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Excel注解集 + * + * @author admin + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Excels +{ + public Excel[] value(); +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Log.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Log.java new file mode 100644 index 0000000..357ba72 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/Log.java @@ -0,0 +1,46 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.enums.OperatorType; + +/** + * 自定义操作日志记录注解 + * + * @author admin + * + */ +@Target({ ElementType.PARAMETER, ElementType.METHOD }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Log +{ + /** + * 模块 + */ + public String title() default ""; + + /** + * 功能 + */ + public BusinessType businessType() default BusinessType.OTHER; + + /** + * 操作人类别 + */ + public OperatorType operatorType() default OperatorType.MANAGE; + + /** + * 是否保存请求的参数 + */ + public boolean isSaveRequestData() default true; + + /** + * 是否保存响应的参数 + */ + public boolean isSaveResponseData() default true; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RateLimiter.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RateLimiter.java new file mode 100644 index 0000000..dac23a0 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RateLimiter.java @@ -0,0 +1,40 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.enums.LimitType; + +/** + * 限流注解 + * + * @author admin + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RateLimiter +{ + /** + * 限流key + */ + public String key() default Constants.RATE_LIMIT_KEY; + + /** + * 限流时间,单位秒 + */ + public int time() default 60; + + /** + * 限流次数 + */ + public int count() default 100; + + /** + * 限流类型 + */ + public LimitType limitType() default LimitType.DEFAULT; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RepeatSubmit.java b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RepeatSubmit.java new file mode 100644 index 0000000..0566ff3 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/annotation/RepeatSubmit.java @@ -0,0 +1,31 @@ +package net.hzvtc.common.annotation; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 自定义注解防止表单重复提交 + * + * @author admin + * + */ +@Inherited +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RepeatSubmit +{ + /** + * 间隔时间(ms),小于此时间视为重复提交 + */ + public int interval() default 5000; + + /** + * 提示消息 + */ + public String message() default "不允许重复提交,请稍候再试"; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/config/AiBirdSysConfig.java b/ai-bird-common/src/main/java/net/hzvtc/common/config/AiBirdSysConfig.java new file mode 100644 index 0000000..2b3cb87 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/config/AiBirdSysConfig.java @@ -0,0 +1,158 @@ +package net.hzvtc.common.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * 读取项目相关配置 + * + * @author admin + */ +@Component +@ConfigurationProperties(prefix = "hzvtc") +public class AiBirdSysConfig { + /** + * 上传路径 + */ + private static String profile; + /** + * 获取地址开关 + */ + private static boolean addressEnabled; + /** + * 验证码类型 + */ + private static String captchaType; + + private static String birdMediaPath; + + private static String birdImagePath; + + + private static String observationFilePath; + /** + * 项目名称 + */ + private String name; + /** + * 版本 + */ + private String version; + /** + * 版权年份 + */ + private String copyrightYear; + /** + * 实例演示开关 + */ + private boolean demoEnabled; + + public static String getProfile() { + return profile; + } + + public void setProfile(String profile) { + AiBirdSysConfig.profile = profile; + } + + public static boolean isAddressEnabled() { + return addressEnabled; + } + + public void setAddressEnabled(boolean addressEnabled) { + AiBirdSysConfig.addressEnabled = addressEnabled; + } + + public static String getCaptchaType() { + return captchaType; + } + + public void setCaptchaType(String captchaType) { + AiBirdSysConfig.captchaType = captchaType; + } + + public static String getObservationFilePath() { + return observationFilePath; + } + + public void setObservationFilePath(String observationFilePath) { + AiBirdSysConfig.observationFilePath = observationFilePath; + } + + /** + * 获取导入上传路径 + */ + public static String getImportPath() { + return getProfile() + "/import"; + } + + /** + * 获取头像上传路径 + */ + public static String getAvatarPath() { + return getProfile() + "/avatar"; + } + + /** + * 获取下载路径 + */ + public static String getDownloadPath() { + //return getProfile() + "/download/"; + return getProfile(); + } + + /** + * 获取上传路径 + */ + public static String getUploadPath() { + return getProfile() + "/upload"; + } + + public static String getBirdMediaPath() { + return birdMediaPath; + } + + public void setBirdMediaPath(String birdMediaPath) { + AiBirdSysConfig.birdMediaPath = birdMediaPath; + } + + public static String getBirdImagePath() { + return birdImagePath; + } + + public void setBirdImagePath(String birdImagePath) { + AiBirdSysConfig.birdImagePath = birdImagePath; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getCopyrightYear() { + return copyrightYear; + } + + public void setCopyrightYear(String copyrightYear) { + this.copyrightYear = copyrightYear; + } + + public boolean isDemoEnabled() { + return demoEnabled; + } + + public void setDemoEnabled(boolean demoEnabled) { + this.demoEnabled = demoEnabled; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/constant/Constants.java b/ai-bird-common/src/main/java/net/hzvtc/common/constant/Constants.java new file mode 100644 index 0000000..299332d --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/constant/Constants.java @@ -0,0 +1,183 @@ +package net.hzvtc.common.constant; + +import io.jsonwebtoken.Claims; + +/** + * 通用常量信息 + * + * @author admin + */ +public class Constants { + /** + * UTF-8 字符集 + */ + public static final String UTF8 = "UTF-8"; + + /** + * GBK 字符集 + */ + public static final String GBK = "GBK"; + + /** + * http请求 + */ + public static final String HTTP = "http://"; + + /** + * https请求 + */ + public static final String HTTPS = "https://"; + + /** + * 通用成功标识 + */ + public static final String SUCCESS = "0"; + + /** + * 通用失败标识 + */ + public static final String FAIL = "1"; + + /** + * 登录成功 + */ + public static final String LOGIN_SUCCESS = "Success"; + + /** + * 注销 + */ + public static final String LOGOUT = "Logout"; + + /** + * 注册 + */ + public static final String REGISTER = "Register"; + + /** + * 登录失败 + */ + public static final String LOGIN_FAIL = "Error"; + + /** + * 验证码 redis key + */ + public static final String CAPTCHA_CODE_KEY = "captcha_codes:"; + + /** + * 登录用户 redis key + */ + public static final String LOGIN_TOKEN_KEY = "login_tokens:"; + + /** + * 防重提交 redis key + */ + public static final String REPEAT_SUBMIT_KEY = "repeat_submit:"; + + /** + * 限流 redis key + */ + public static final String RATE_LIMIT_KEY = "rate_limit:"; + + /** + * 密码错误次数 redis key + */ + public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:"; + + /** + * 密码错误次数限制 + */ +// public static final int PASSWORD_ERROR_LIMIT = 5; + + /** + * 密码错误锁定时间(分钟) + */ +// public static final int PASSWORD_LOCK_TIME = 30; + + /** + * 验证码有效期(分钟) + */ + public static final Integer CAPTCHA_EXPIRATION = 2; + + /** + * 令牌 + */ + public static final String TOKEN = "token"; + + public static final String AREAIDS = "areaIds"; + + /** + * 令牌前缀 + */ + public static final String TOKEN_PREFIX = "Bearer "; + + /** + * 令牌前缀 + */ + public static final String LOGIN_USER_KEY = "login_user_key"; + + /** + * 用户ID + */ + public static final String JWT_USERID = "userid"; + + /** + * 用户名称 + */ + public static final String JWT_USERNAME = Claims.SUBJECT; + + /** + * 用户头像 + */ + public static final String JWT_AVATAR = "avatar"; + + /** + * 创建时间 + */ + public static final String JWT_CREATED = "created"; + + /** + * 用户权限 + */ + public static final String JWT_AUTHORITIES = "authorities"; + + /** + * 参数管理 cache key + */ + public static final String SYS_CONFIG_KEY = "sys_config:"; + + /** + * 字典管理 cache key + */ + public static final String SYS_DICT_KEY = "sys_dict:"; + + /** + * 资源映射路径 前缀 + */ + public static final String RESOURCE_PREFIX = ""; + + /** + * RMI 远程方法调用 + */ + public static final String LOOKUP_RMI = "rmi:"; + + /** + * LDAP 远程方法调用 + */ + public static final String LOOKUP_LDAP = "ldap:"; + + /** + * LDAPS 远程方法调用 + */ + public static final String LOOKUP_LDAPS = "ldaps:"; + + /** + * 定时任务白名单配置(仅允许访问的包名,如其他需要可以自行添加) + */ + public static final String[] JOB_WHITELIST_STR = {"net.hzvtc"}; + + /** + * 定时任务违规的字符 + */ + public static final String[] JOB_ERROR_STR = {"java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml", + "org.springframework", "org.apache", "net.hzvtc.common.utils.file"}; +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/constant/GenConstants.java b/ai-bird-common/src/main/java/net/hzvtc/common/constant/GenConstants.java new file mode 100644 index 0000000..d5cdce6 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/constant/GenConstants.java @@ -0,0 +1,114 @@ +package net.hzvtc.common.constant; + +/** + * 代码生成通用常量 + * + * @author admin + */ +public class GenConstants +{ + /** 单表(增删改查) */ + public static final String TPL_CRUD = "crud"; + + /** 树表(增删改查) */ + public static final String TPL_TREE = "tree"; + + /** 主子表(增删改查) */ + public static final String TPL_SUB = "sub"; + + /** 树编码字段 */ + public static final String TREE_CODE = "treeCode"; + + /** 树父编码字段 */ + public static final String TREE_PARENT_CODE = "treeParentCode"; + + /** 树名称字段 */ + public static final String TREE_NAME = "treeName"; + + /** 上级菜单ID字段 */ + public static final String PARENT_MENU_ID = "parentMenuId"; + + /** 上级菜单名称字段 */ + public static final String PARENT_MENU_NAME = "parentMenuName"; + + /** 数据库字符串类型 */ + public static final String[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" }; + + /** 数据库文本类型 */ + public static final String[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" }; + + /** 数据库时间类型 */ + public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" }; + + /** 数据库数字类型 */ + public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer", + "bit", "bigint", "float", "double", "decimal" }; + + /** 页面不需要编辑字段 */ + public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" }; + + /** 页面不需要显示的列表字段 */ + public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by", + "update_time" }; + + /** 页面不需要查询字段 */ + public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by", + "update_time", "remark" }; + + /** Entity基类字段 */ + public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" }; + + /** Tree基类字段 */ + public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors", "children" }; + + /** 文本框 */ + public static final String HTML_INPUT = "input"; + + /** 文本域 */ + public static final String HTML_TEXTAREA = "textarea"; + + /** 下拉框 */ + public static final String HTML_SELECT = "select"; + + /** 单选框 */ + public static final String HTML_RADIO = "radio"; + + /** 复选框 */ + public static final String HTML_CHECKBOX = "checkbox"; + + /** 日期控件 */ + public static final String HTML_DATETIME = "datetime"; + + /** 图片上传控件 */ + public static final String HTML_IMAGE_UPLOAD = "imageUpload"; + + /** 文件上传控件 */ + public static final String HTML_FILE_UPLOAD = "fileUpload"; + + /** 富文本控件 */ + public static final String HTML_EDITOR = "editor"; + + /** 字符串类型 */ + public static final String TYPE_STRING = "String"; + + /** 整型 */ + public static final String TYPE_INTEGER = "Integer"; + + /** 长整型 */ + public static final String TYPE_LONG = "Long"; + + /** 浮点型 */ + public static final String TYPE_DOUBLE = "Double"; + + /** 高精度计算类型 */ + public static final String TYPE_BIGDECIMAL = "BigDecimal"; + + /** 时间类型 */ + public static final String TYPE_DATE = "Date"; + + /** 模糊查询 */ + public static final String QUERY_LIKE = "LIKE"; + + /** 需要 */ + public static final String REQUIRE = "1"; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/constant/HttpStatus.java b/ai-bird-common/src/main/java/net/hzvtc/common/constant/HttpStatus.java new file mode 100644 index 0000000..172e105 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/constant/HttpStatus.java @@ -0,0 +1,89 @@ +package net.hzvtc.common.constant; + +/** + * 返回状态码 + * + * @author admin + */ +public class HttpStatus +{ + /** + * 操作成功 + */ + public static final int SUCCESS = 200; + + /** + * 对象创建成功 + */ + public static final int CREATED = 201; + + /** + * 请求已经被接受 + */ + public static final int ACCEPTED = 202; + + /** + * 操作已经执行成功,但是没有返回数据 + */ + public static final int NO_CONTENT = 204; + + /** + * 资源已被移除 + */ + public static final int MOVED_PERM = 301; + + /** + * 重定向 + */ + public static final int SEE_OTHER = 303; + + /** + * 资源没有被修改 + */ + public static final int NOT_MODIFIED = 304; + + /** + * 参数列表错误(缺少,格式不匹配) + */ + public static final int BAD_REQUEST = 400; + + /** + * 未授权 + */ + public static final int UNAUTHORIZED = 401; + + /** + * 访问受限,授权过期 + */ + public static final int FORBIDDEN = 403; + + /** + * 资源,服务未找到 + */ + public static final int NOT_FOUND = 404; + + /** + * 不允许的http方法 + */ + public static final int BAD_METHOD = 405; + + /** + * 资源冲突,或者资源被锁 + */ + public static final int CONFLICT = 409; + + /** + * 不支持的数据,媒体类型 + */ + public static final int UNSUPPORTED_TYPE = 415; + + /** + * 系统内部错误 + */ + public static final int ERROR = 500; + + /** + * 接口未实现 + */ + public static final int NOT_IMPLEMENTED = 501; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/constant/ScheduleConstants.java b/ai-bird-common/src/main/java/net/hzvtc/common/constant/ScheduleConstants.java new file mode 100644 index 0000000..069cc57 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/constant/ScheduleConstants.java @@ -0,0 +1,50 @@ +package net.hzvtc.common.constant; + +/** + * 任务调度通用常量 + * + * @author admin + */ +public class ScheduleConstants +{ + public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME"; + + /** 执行目标key */ + public static final String TASK_PROPERTIES = "TASK_PROPERTIES"; + + /** 默认 */ + public static final String MISFIRE_DEFAULT = "0"; + + /** 立即触发执行 */ + public static final String MISFIRE_IGNORE_MISFIRES = "1"; + + /** 触发一次执行 */ + public static final String MISFIRE_FIRE_AND_PROCEED = "2"; + + /** 不触发立即执行 */ + public static final String MISFIRE_DO_NOTHING = "3"; + + public enum Status + { + /** + * 正常 + */ + NORMAL("0"), + /** + * 暂停 + */ + PAUSE("1"); + + private String value; + + private Status(String value) + { + this.value = value; + } + + public String getValue() + { + return value; + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/constant/UserConstants.java b/ai-bird-common/src/main/java/net/hzvtc/common/constant/UserConstants.java new file mode 100644 index 0000000..994c503 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/constant/UserConstants.java @@ -0,0 +1,78 @@ +package net.hzvtc.common.constant; + +/** + * 用户常量信息 + * + * @author admin + */ +public class UserConstants +{ + /** + * 平台内系统用户的唯一标志 + */ + public static final String SYS_USER = "SYS_USER"; + + /** 正常状态 */ + public static final String NORMAL = "0"; + + /** 异常状态 */ + public static final String EXCEPTION = "1"; + + /** 用户封禁状态 */ + public static final String USER_DISABLE = "1"; + + /** 角色封禁状态 */ + public static final String ROLE_DISABLE = "1"; + + /** 部门正常状态 */ + public static final String DEPT_NORMAL = "0"; + + /** 部门停用状态 */ + public static final String DEPT_DISABLE = "1"; + + /** 字典正常状态 */ + public static final String DICT_NORMAL = "0"; + + /** 是否为系统默认(是) */ + public static final String YES = "Y"; + + /** 是否菜单外链(是) */ + public static final String YES_FRAME = "0"; + + /** 是否菜单外链(否) */ + public static final String NO_FRAME = "1"; + + /** 菜单类型(目录) */ + public static final String TYPE_DIR = "M"; + + /** 菜单类型(菜单) */ + public static final String TYPE_MENU = "C"; + + /** 菜单类型(按钮) */ + public static final String TYPE_BUTTON = "F"; + + /** Layout组件标识 */ + public final static String LAYOUT = "Layout"; + + /** ParentView组件标识 */ + public final static String PARENT_VIEW = "ParentView"; + + /** InnerLink组件标识 */ + public final static String INNER_LINK = "InnerLink"; + + /** 校验返回结果码 */ + public final static String UNIQUE = "0"; + public final static String NOT_UNIQUE = "1"; + + /** + * 用户名长度限制 + */ + public static final int USERNAME_MIN_LENGTH = 2; + public static final int USERNAME_MAX_LENGTH = 20; + + /** + * 密码长度限制 + */ + public static final int PASSWORD_MIN_LENGTH = 5; + public static final int PASSWORD_MAX_LENGTH = 20; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/controller/BaseController.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/controller/BaseController.java new file mode 100644 index 0000000..711613e --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/controller/BaseController.java @@ -0,0 +1,163 @@ +package net.hzvtc.common.core.controller; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.core.page.PageDomain; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.core.page.TableSupport; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.PageUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.sql.SqlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; + +import java.beans.PropertyEditorSupport; +import java.util.Date; +import java.util.List; + +/** + * web层通用数据处理 + * + * @author admin + */ +public class BaseController { + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + /** + * 将前台传递过来的日期格式的字符串,自动转化为Date类型 + */ + @InitBinder + public void initBinder(WebDataBinder binder) { + // Date 类型转换 + binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { + @Override + public void setAsText(String text) { + setValue(DateUtils.parseDate(text)); + } + }); + } + + /** + * 设置请求分页数据 + */ + protected void startPage() { + PageUtils.startPage(); + } + + protected void startPage(Integer pageNum, Integer pageSize) { + PageUtils.startPage(pageNum, pageSize); + } + + /** + * 设置请求排序数据 + */ + protected void startOrderBy() { + PageDomain pageDomain = TableSupport.buildPageRequest(); + if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { + String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); + PageHelper.orderBy(orderBy); + } + } + + /** + * 响应请求分页数据 + */ + protected TableDataInfo getDataTable(List list) { + TableDataInfo rspData = new TableDataInfo(); + rspData.setCode(HttpStatus.SUCCESS); + rspData.setMsg("查询成功"); + rspData.setRows(list); + rspData.setTotal(new PageInfo(list).getTotal()); + return rspData; + } + + /** + * 返回成功 + */ + public AjaxResult success() { + return AjaxResult.success(); + } + + /** + * 返回失败消息 + */ + public AjaxResult error() { + return AjaxResult.error(); + } + + /** + * 返回成功消息 + */ + public AjaxResult success(String message) { + return AjaxResult.success(message); + } + + /** + * 返回失败消息 + */ + public AjaxResult error(String message) { + return AjaxResult.error(message); + } + + /** + * 响应返回结果 + * + * @param rows 影响行数 + * @return 操作结果 + */ + protected AjaxResult toAjax(int rows) { + return rows > 0 ? AjaxResult.success() : AjaxResult.error(); + } + + /** + * 响应返回结果 + * + * @param result 结果 + * @return 操作结果 + */ + protected AjaxResult toAjax(boolean result) { + return result ? success() : error(); + } + + /** + * 页面跳转 + */ + public String redirect(String url) { + return StringUtils.format("redirect:{}", url); + } + + /** + * 获取用户缓存信息 + */ + public LoginUser getLoginUser() { + return SecurityUtils.getLoginUser(); + } + + /** + * 获取登录用户id + */ + public Long getUserId() { + return getLoginUser().getUserId(); + } + + /** + * 获取登录部门id + */ + public Long getDeptId() { + return getLoginUser().getDeptId(); + } + + /** + * 获取登录用户名 + */ + public String getUsername() { + return getLoginUser().getUsername(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/AjaxResult.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/AjaxResult.java new file mode 100644 index 0000000..4d0fcab --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/AjaxResult.java @@ -0,0 +1,162 @@ +package net.hzvtc.common.core.domain; + +import java.util.HashMap; +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.utils.StringUtils; + +/** + * 操作消息提醒 + * + * @author admin + */ +public class AjaxResult extends HashMap +{ + private static final long serialVersionUID = 1L; + + /** 状态码 */ + public static final String CODE_TAG = "code"; + + /** 返回内容 */ + public static final String MSG_TAG = "msg"; + + /** 数据对象 */ + public static final String DATA_TAG = "data"; + + /** + * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 + */ + public AjaxResult() + { + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param code 状态码 + * @param msg 返回内容 + */ + public AjaxResult(int code, String msg) + { + super.put(CODE_TAG, code); + super.put(MSG_TAG, msg); + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param code 状态码 + * @param msg 返回内容 + * @param data 数据对象 + */ + public AjaxResult(int code, String msg, Object data) + { + super.put(CODE_TAG, code); + super.put(MSG_TAG, msg); + if (StringUtils.isNotNull(data)) + { + super.put(DATA_TAG, data); + } + } + + /** + * 返回成功消息 + * + * @return 成功消息 + */ + public static AjaxResult success() + { + return AjaxResult.success("操作成功"); + } + + /** + * 返回成功数据 + * + * @return 成功消息 + */ + public static AjaxResult success(Object data) + { + return AjaxResult.success("操作成功", data); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @return 成功消息 + */ + public static AjaxResult success(String msg) + { + return AjaxResult.success(msg, null); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 成功消息 + */ + public static AjaxResult success(String msg, Object data) + { + return new AjaxResult(HttpStatus.SUCCESS, msg, data); + } + + /** + * 返回错误消息 + * + * @return + */ + public static AjaxResult error() + { + return AjaxResult.error("操作失败"); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult error(String msg) + { + return AjaxResult.error(msg, null); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 警告消息 + */ + public static AjaxResult error(String msg, Object data) + { + return new AjaxResult(HttpStatus.ERROR, msg, data); + } + + /** + * 返回错误消息 + * + * @param code 状态码 + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult error(int code, String msg) + { + return new AjaxResult(code, msg, null); + } + + /** + * 方便链式调用 + * + * @param key 键 + * @param value 值 + * @return 数据对象 + */ + @Override + public AjaxResult put(String key, Object value) + { + super.put(key, value); + return this; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/BaseEntity.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/BaseEntity.java new file mode 100644 index 0000000..f6549e3 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/BaseEntity.java @@ -0,0 +1,23 @@ +package net.hzvtc.common.core.domain; + + +import java.io.Serializable; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import java.util.Map; +import lombok.Data; + +@Data +public class BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + private String searchValue; + private String createBy; + private Long createDept; + private Date createTime; + private String updateBy; + private Date updateTime; + private String remark; + private int isDeleted = 0; + private Integer limit; + private Map params; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeEntity.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeEntity.java new file mode 100644 index 0000000..6c22bf6 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeEntity.java @@ -0,0 +1,79 @@ +package net.hzvtc.common.core.domain; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tree基类 + * + * @author admin + */ +public class TreeEntity extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 父菜单名称 */ + private String parentName; + + /** 父菜单ID */ + private Long parentId; + + /** 显示顺序 */ + private Integer orderNum; + + /** 祖级列表 */ + private String ancestors; + + /** 子部门 */ + private List children = new ArrayList<>(); + + public String getParentName() + { + return parentName; + } + + public void setParentName(String parentName) + { + this.parentName = parentName; + } + + public Long getParentId() + { + return parentId; + } + + public void setParentId(Long parentId) + { + this.parentId = parentId; + } + + public Integer getOrderNum() + { + return orderNum; + } + + public void setOrderNum(Integer orderNum) + { + this.orderNum = orderNum; + } + + public String getAncestors() + { + return ancestors; + } + + public void setAncestors(String ancestors) + { + this.ancestors = ancestors; + } + + public List getChildren() + { + return children; + } + + public void setChildren(List children) + { + this.children = children; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeSelect.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeSelect.java new file mode 100644 index 0000000..de30371 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/TreeSelect.java @@ -0,0 +1,19 @@ +package net.hzvtc.common.core.domain; + + +import java.io.Serializable; +import java.util.List; +import lombok.Data; + +@Data +public class TreeSelect implements Serializable { + private static final long serialVersionUID = 1L; + private Long id; + private String label; + private String fullName; + private String fullPathName; + private String ancestor; + private boolean leaf; + private int type; + private List children; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDept.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDept.java new file mode 100644 index 0000000..f7e73b4 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDept.java @@ -0,0 +1,32 @@ +package net.hzvtc.common.core.domain.entity; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysDept") +@Data +public class SysDept extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long deptId; + private String deptCode; + private int deptLevel; + private String fullPinyin; + private String simplePinyin; + private Long parentId; + private String ancestors; + private String ancestorPath; + private String deptName; + private String fullName; + private String fullPathName; + private String orderNum; + private String leader; + private String phone; + private String email; + private String status; + private String delFlag; + private String parentName; + private List children = new ArrayList(); +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictData.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictData.java new file mode 100644 index 0000000..fa0d4af --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictData.java @@ -0,0 +1,119 @@ +package net.hzvtc.common.core.domain.entity; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class SysDictData +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u5b57\u5178\u7f16\u7801", cellType=Excel.ColumnType.NUMERIC) + private Long dictCode; + @Excel(name="\u5b57\u5178\u6392\u5e8f", cellType=Excel.ColumnType.NUMERIC) + private Long dictSort; + @Excel(name="\u5b57\u5178\u6807\u7b7e") + private String dictLabel; + @Excel(name="\u5b57\u5178\u952e\u503c") + private String dictValue; + @Excel(name="\u5b57\u5178\u7c7b\u578b") + private String dictType; + private String cssClass; + private String listClass; + @Excel(name="\u662f\u5426\u9ed8\u8ba4", readConverterExp="Y=\u662f,N=\u5426") + private String isDefault; + @Excel(name="\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u505c\u7528") + private String status; + + public Long getDictCode() { + return this.dictCode; + } + + public void setDictCode(Long dictCode) { + this.dictCode = dictCode; + } + + public Long getDictSort() { + return this.dictSort; + } + + public void setDictSort(Long dictSort) { + this.dictSort = dictSort; + } + + @NotBlank(message="\u5b57\u5178\u6807\u7b7e\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u5b57\u5178\u6807\u7b7e\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5b57\u5178\u6807\u7b7e\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u5b57\u5178\u6807\u7b7e\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getDictLabel() { + return this.dictLabel; + } + + public void setDictLabel(String dictLabel) { + this.dictLabel = dictLabel; + } + + @NotBlank(message="\u5b57\u5178\u952e\u503c\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u5b57\u5178\u952e\u503c\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5b57\u5178\u952e\u503c\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u5b57\u5178\u952e\u503c\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getDictValue() { + return this.dictValue; + } + + public void setDictValue(String dictValue) { + this.dictValue = dictValue; + } + + @NotBlank(message="\u5b57\u5178\u7c7b\u578b\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5b57\u5178\u7c7b\u578b\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getDictType() { + return this.dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + @Size(min=0, max=100, message="\u6837\u5f0f\u5c5e\u6027\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @Size(min=0, max=100, message="\u6837\u5f0f\u5c5e\u6027\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getCssClass() { + return this.cssClass; + } + + public void setCssClass(String cssClass) { + this.cssClass = cssClass; + } + + public String getListClass() { + return this.listClass; + } + + public void setListClass(String listClass) { + this.listClass = listClass; + } + + public boolean getDefault() { + return "Y".equals(this.isDefault); + } + + public String getIsDefault() { + return this.isDefault; + } + + public void setIsDefault(String isDefault) { + this.isDefault = isDefault; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("dictCode", (Object)this.getDictCode()).append("dictSort", (Object)this.getDictSort()).append("dictLabel", (Object)this.getDictLabel()).append("dictValue", (Object)this.getDictValue()).append("dictType", (Object)this.getDictType()).append("cssClass", (Object)this.getCssClass()).append("listClass", (Object)this.getListClass()).append("isDefault", (Object)this.getIsDefault()).append("status", (Object)this.getStatus()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictType.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictType.java new file mode 100644 index 0000000..d32e4ba --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysDictType.java @@ -0,0 +1,64 @@ +package net.hzvtc.common.core.domain.entity; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class SysDictType +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u5b57\u5178\u4e3b\u952e", cellType=Excel.ColumnType.NUMERIC) + private Long dictId; + @Excel(name="\u5b57\u5178\u540d\u79f0") + private String dictName; + @Excel(name="\u5b57\u5178\u7c7b\u578b") + private String dictType; + @Excel(name="\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u505c\u7528") + private String status; + + public Long getDictId() { + return this.dictId; + } + + public void setDictId(Long dictId) { + this.dictId = dictId; + } + + @NotBlank(message="\u5b57\u5178\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5b57\u5178\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getDictName() { + return this.dictName; + } + + public void setDictName(String dictName) { + this.dictName = dictName; + } + + @NotBlank(message="\u5b57\u5178\u7c7b\u578b\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u7c7b\u578b\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5b57\u5178\u7c7b\u578b\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u5b57\u5178\u7c7b\u578b\u7c7b\u578b\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getDictType() { + return this.dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("dictId", (Object)this.getDictId()).append("dictName", (Object)this.getDictName()).append("dictType", (Object)this.getDictType()).append("status", (Object)this.getStatus()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysMenu.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysMenu.java new file mode 100644 index 0000000..f0b76dc --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysMenu.java @@ -0,0 +1,31 @@ +package net.hzvtc.common.core.domain.entity; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysMenu") +@Data +public class SysMenu extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long menuId; + private String menuName; + private String parentName; + private Long parentId; + private Integer orderNum; + private String path; + private String component; + private String query; + private String isFrame; + private String isCache; + private String menuType; + private String visible; + private String status; + private String perms; + private String icon; + private int isShow; + private Integer sysId; + private List children = new ArrayList(); +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysRole.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysRole.java new file mode 100644 index 0000000..5f623d5 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysRole.java @@ -0,0 +1,183 @@ +package net.hzvtc.common.core.domain.entity; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysRole") +public class SysRole +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u89d2\u8272\u5e8f\u53f7", cellType=Excel.ColumnType.NUMERIC) + private Long roleId; + @Excel(name="\u89d2\u8272\u540d\u79f0") + private String roleName; + @Excel(name="\u89d2\u8272\u6743\u9650") + private String roleKey; + @Excel(name="\u89d2\u8272\u6392\u5e8f") + private String roleSort; + @Excel(name="\u6570\u636e\u8303\u56f4", readConverterExp="1=\u6240\u6709\u6570\u636e\u6743\u9650,2=\u81ea\u5b9a\u4e49\u6570\u636e\u6743\u9650,3=\u672c\u90e8\u95e8\u6570\u636e\u6743\u9650,4=\u672c\u90e8\u95e8\u53ca\u4ee5\u4e0b\u6570\u636e\u6743\u9650,5=\u4ec5\u672c\u4eba\u6570\u636e\u6743\u9650") + private String dataScope; + private boolean menuCheckStrictly; + private boolean deptCheckStrictly; + @Excel(name="\u89d2\u8272\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u505c\u7528") + private String status; + private String delFlag; + private boolean flag = false; + private Integer sysId; + private Long userId; + private Long[] menuIds; + private Long[] areaIds; + private Long[] deptIds; + + public SysRole() { + } + + public SysRole(Long roleId) { + this.roleId = roleId; + } + + public static boolean isAdmin(Long roleId) { + return roleId != null && 1L == roleId; + } + + public Long[] getAreaIds() { + return this.areaIds; + } + + public void setAreaIds(Long[] areaIds) { + this.areaIds = areaIds; + } + + public Long getRoleId() { + return this.roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public boolean isAdmin() { + return SysRole.isAdmin(this.roleId); + } + + @NotBlank(message="\u89d2\u8272\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=30, message="\u89d2\u8272\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u89d2\u8272\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=30, message="\u89d2\u8272\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") String getRoleName() { + return this.roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + @NotBlank(message="\u6743\u9650\u5b57\u7b26\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u6743\u9650\u5b57\u7b26\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u6743\u9650\u5b57\u7b26\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u6743\u9650\u5b57\u7b26\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getRoleKey() { + return this.roleKey; + } + + public void setRoleKey(String roleKey) { + this.roleKey = roleKey; + } + + @NotBlank(message="\u663e\u793a\u987a\u5e8f\u4e0d\u80fd\u4e3a\u7a7a") + public @NotBlank(message="\u663e\u793a\u987a\u5e8f\u4e0d\u80fd\u4e3a\u7a7a") String getRoleSort() { + return this.roleSort; + } + + public void setRoleSort(String roleSort) { + this.roleSort = roleSort; + } + + public String getDataScope() { + return this.dataScope; + } + + public void setDataScope(String dataScope) { + this.dataScope = dataScope; + } + + public boolean isMenuCheckStrictly() { + return this.menuCheckStrictly; + } + + public void setMenuCheckStrictly(boolean menuCheckStrictly) { + this.menuCheckStrictly = menuCheckStrictly; + } + + public boolean isDeptCheckStrictly() { + return this.deptCheckStrictly; + } + + public void setDeptCheckStrictly(boolean deptCheckStrictly) { + this.deptCheckStrictly = deptCheckStrictly; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDelFlag() { + return this.delFlag; + } + + public void setDelFlag(String delFlag) { + this.delFlag = delFlag; + } + + public boolean isFlag() { + return this.flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + public Long[] getMenuIds() { + return this.menuIds; + } + + public void setMenuIds(Long[] menuIds) { + this.menuIds = menuIds; + } + + public Long[] getDeptIds() { + return this.deptIds; + } + + public void setDeptIds(Long[] deptIds) { + this.deptIds = deptIds; + } + + public Integer getSysId() { + return this.sysId; + } + + public void setSysId(Integer sysId) { + this.sysId = sysId; + } + + public Long getUserId() { + return this.userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + @Override + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("roleId", (Object)this.getRoleId()).append("roleName", (Object)this.getRoleName()).append("roleKey", (Object)this.getRoleKey()).append("roleSort", (Object)this.getRoleSort()).append("dataScope", (Object)this.getDataScope()).append("menuCheckStrictly", this.isMenuCheckStrictly()).append("deptCheckStrictly", this.isDeptCheckStrictly()).append("status", (Object)this.getStatus()).append("delFlag", (Object)this.getDelFlag()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysUser.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysUser.java new file mode 100644 index 0000000..39c1fd9 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/entity/SysUser.java @@ -0,0 +1,265 @@ +package net.hzvtc.common.core.domain.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Date; +import java.util.List; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.annotation.Excels; +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.common.core.domain.entity.SysDept; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.xss.Xss; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysUser") +public class SysUser +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u7528\u6237\u5e8f\u53f7", cellType=Excel.ColumnType.NUMERIC, prompt="\u7528\u6237\u7f16\u53f7") + private Long userId; + @Excel(name="\u90e8\u95e8ID", type=Excel.Type.IMPORT) + private Long deptId; + @Excel(name="\u767b\u5f55\u540d\u79f0") + private String userName; + @Excel(name="\u7528\u6237\u540d\u79f0") + private String nickName; + @Excel(name="\u7528\u6237\u90ae\u7bb1") + private String email; + @Excel(name="\u624b\u673a\u53f7\u7801") + private String phonenumber; + @Excel(name="\u7528\u6237\u6027\u522b", readConverterExp="0=\u7537,1=\u5973,2=\u672a\u77e5") + private String sex; + private String avatar; + private String password; + private String salt; + @Excel(name="\u5e10\u53f7\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u505c\u7528") + private String status; + private String delFlag; + @Excel(name="\u6700\u540e\u767b\u5f55IP", type=Excel.Type.EXPORT) + private String loginIp; + @Excel(name="\u6700\u540e\u767b\u5f55\u65f6\u95f4", width=30.0, dateFormat="yyyy-MM-dd HH:mm:ss", type=Excel.Type.EXPORT) + private Date loginDate; + private int webLogin = 0; + private int portalLogin = 0; + private Integer sysId; + @Excels(value={@Excel(name="\u90e8\u95e8\u540d\u79f0", targetAttr="deptName", type=Excel.Type.EXPORT), @Excel(name="\u90e8\u95e8\u8d1f\u8d23\u4eba", targetAttr="leader", type=Excel.Type.EXPORT)}) + private SysDept dept; + private List roles; + private Long[] roleIds; + private Long[] postIds; + private Long roleId; + + public SysUser() { + } + + public SysUser(Long userId) { + this.userId = userId; + } + + public static boolean isAdmin(Long userId) { + return userId != null && userId <= 1L; + } + + public Long getUserId() { + return this.userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public boolean isAdmin() { + return SysUser.isAdmin(this.userId); + } + + public Long getDeptId() { + return this.deptId; + } + + public void setDeptId(Long deptId) { + this.deptId = deptId; + } + + @Xss(message="\u7528\u6237\u6635\u79f0\u4e0d\u80fd\u5305\u542b\u811a\u672c\u5b57\u7b26") + @Size(min=0, max=30, message="\u7528\u6237\u6635\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") + public @Size(min=0, max=30, message="\u7528\u6237\u6635\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") String getNickName() { + return this.nickName; + } + + public void setNickName(String nickName) { + this.nickName = nickName; + } + + @Xss(message="\u7528\u6237\u8d26\u53f7\u4e0d\u80fd\u5305\u542b\u811a\u672c\u5b57\u7b26") + @NotBlank(message="\u7528\u6237\u8d26\u53f7\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=30, message="\u7528\u6237\u8d26\u53f7\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u7528\u6237\u8d26\u53f7\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=30, message="\u7528\u6237\u8d26\u53f7\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc730\u4e2a\u5b57\u7b26") String getUserName() { + return this.userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Email(message="\u90ae\u7bb1\u683c\u5f0f\u4e0d\u6b63\u786e") + @Size(min=0, max=50, message="\u90ae\u7bb1\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc750\u4e2a\u5b57\u7b26") + public @Email(message="\u90ae\u7bb1\u683c\u5f0f\u4e0d\u6b63\u786e") @Size(min=0, max=50, message="\u90ae\u7bb1\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc750\u4e2a\u5b57\u7b26") String getEmail() { + return this.email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Size(min=0, max=11, message="\u624b\u673a\u53f7\u7801\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc711\u4e2a\u5b57\u7b26") + public @Size(min=0, max=11, message="\u624b\u673a\u53f7\u7801\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc711\u4e2a\u5b57\u7b26") String getPhonenumber() { + return this.phonenumber; + } + + public void setPhonenumber(String phonenumber) { + this.phonenumber = phonenumber; + } + + public String getSex() { + return this.sex; + } + + public void setSex(String sex) { + this.sex = sex; + } + + public String getAvatar() { + return this.avatar; + } + + public void setAvatar(String avatar) { + this.avatar = avatar; + } + + @JsonIgnore + @JsonProperty + public String getPassword() { + return this.password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getSalt() { + return this.salt; + } + + public void setSalt(String salt) { + this.salt = salt; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getDelFlag() { + return this.delFlag; + } + + public void setDelFlag(String delFlag) { + this.delFlag = delFlag; + } + + public String getLoginIp() { + return this.loginIp; + } + + public void setLoginIp(String loginIp) { + this.loginIp = loginIp; + } + + public Date getLoginDate() { + return this.loginDate; + } + + public void setLoginDate(Date loginDate) { + this.loginDate = loginDate; + } + + public SysDept getDept() { + return this.dept; + } + + public void setDept(SysDept dept) { + this.dept = dept; + } + + public List getRoles() { + return this.roles; + } + + public void setRoles(List roles) { + this.roles = roles; + } + + public Long[] getRoleIds() { + return this.roleIds; + } + + public void setRoleIds(Long[] roleIds) { + this.roleIds = roleIds; + } + + public Long[] getPostIds() { + return this.postIds; + } + + public void setPostIds(Long[] postIds) { + this.postIds = postIds; + } + + public Long getRoleId() { + return this.roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public int getWebLogin() { + return this.webLogin; + } + + public void setWebLogin(int webLogin) { + this.webLogin = webLogin; + } + + public int getPortalLogin() { + return this.portalLogin; + } + + public void setPortalLogin(int portalLogin) { + this.portalLogin = portalLogin; + } + + public Integer getSysId() { + return this.sysId; + } + + public void setSysId(Integer sysId) { + this.sysId = sysId; + } + + @Override + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("userId", (Object)this.getUserId()).append("deptId", (Object)this.getDeptId()).append("userName", (Object)this.getUserName()).append("nickName", (Object)this.getNickName()).append("email", (Object)this.getEmail()).append("phonenumber", (Object)this.getPhonenumber()).append("sex", (Object)this.getSex()).append("avatar", (Object)this.getAvatar()).append("password", (Object)this.getPassword()).append("salt", (Object)this.getSalt()).append("status", (Object)this.getStatus()).append("delFlag", (Object)this.getDelFlag()).append("loginIp", (Object)this.getLoginIp()).append("loginDate", (Object)this.getLoginDate()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).append("dept", (Object)this.getDept()).toString(); + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginBody.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginBody.java new file mode 100644 index 0000000..3a6b9c0 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginBody.java @@ -0,0 +1,13 @@ +package net.hzvtc.common.core.domain.model; + +import lombok.Data; + +/** 用户登录对象 */ +@Data +public class LoginBody { + private String username; + private String password; + private String code; + private String uuid = ""; + private int loginType; +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginUser.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginUser.java new file mode 100644 index 0000000..5da8fc5 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/LoginUser.java @@ -0,0 +1,348 @@ +package net.hzvtc.common.core.domain.model; + +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.annotation.JSONField; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import net.hzvtc.common.core.domain.entity.SysUser; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +public class LoginUser +implements UserDetails { + private static final long serialVersionUID = 1L; + private Long userId; + private Long deptId; + private String token; + private Long loginTime; + private Long expireTime; + private String ipaddr; + private String loginLocation; + private String browser; + private String os; + private Set permissions; + private Set areaIds; + private List areaList; + private List deviceList; + private SysUser user; + private int webLogin; + private int portalLogin; + + public LoginUser() { + } + + public LoginUser(SysUser user, Set permissions) { + this.user = user; + this.permissions = permissions; + } + + public LoginUser(Long userId, Long deptId, SysUser user, Set permissions, int webLogin, int portalLogin, List areaList, List deviceList) { + this.userId = userId; + this.deptId = deptId; + this.user = user; + this.permissions = permissions; + this.areaList = areaList; + this.deviceList = deviceList; + List list = areaList.stream().map(item -> item.getLong("id")).collect(Collectors.toList()); + this.areaIds = new HashSet(); + this.areaIds.addAll(list); + this.webLogin = webLogin; + this.portalLogin = portalLogin; + } + + @JSONField(serialize=false) + public String getPassword() { + return this.user.getPassword(); + } + + public String getUsername() { + return this.user.getUserName(); + } + + @JSONField(serialize=false) + public boolean isAccountNonExpired() { + return true; + } + + @JSONField(serialize=false) + public boolean isAccountNonLocked() { + return true; + } + + @JSONField(serialize=false) + public boolean isCredentialsNonExpired() { + return true; + } + + @JSONField(serialize=false) + public boolean isEnabled() { + return true; + } + + public Collection getAuthorities() { + return null; + } + + public Long getUserId() { + return this.userId; + } + + public Long getDeptId() { + return this.deptId; + } + + public String getToken() { + return this.token; + } + + public Long getLoginTime() { + return this.loginTime; + } + + public Long getExpireTime() { + return this.expireTime; + } + + public String getIpaddr() { + return this.ipaddr; + } + + public String getLoginLocation() { + return this.loginLocation; + } + + public String getBrowser() { + return this.browser; + } + + public String getOs() { + return this.os; + } + + public Set getPermissions() { + return this.permissions; + } + + public Set getAreaIds() { + return this.areaIds; + } + + public List getAreaList() { + return this.areaList; + } + + public List getDeviceList() { + return this.deviceList; + } + + public SysUser getUser() { + return this.user; + } + + public int getWebLogin() { + return this.webLogin; + } + + public int getPortalLogin() { + return this.portalLogin; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public void setDeptId(Long deptId) { + this.deptId = deptId; + } + + public void setToken(String token) { + this.token = token; + } + + public void setLoginTime(Long loginTime) { + this.loginTime = loginTime; + } + + public void setExpireTime(Long expireTime) { + this.expireTime = expireTime; + } + + public void setIpaddr(String ipaddr) { + this.ipaddr = ipaddr; + } + + public void setLoginLocation(String loginLocation) { + this.loginLocation = loginLocation; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public void setOs(String os) { + this.os = os; + } + + public void setPermissions(Set permissions) { + this.permissions = permissions; + } + + public void setAreaIds(Set areaIds) { + this.areaIds = areaIds; + } + + public void setAreaList(List areaList) { + this.areaList = areaList; + } + + public void setDeviceList(List deviceList) { + this.deviceList = deviceList; + } + + public void setUser(SysUser user) { + this.user = user; + } + + public void setWebLogin(int webLogin) { + this.webLogin = webLogin; + } + + public void setPortalLogin(int portalLogin) { + this.portalLogin = portalLogin; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof LoginUser)) { + return false; + } + LoginUser other = (LoginUser)o; + if (!other.canEqual(this)) { + return false; + } + if (this.getWebLogin() != other.getWebLogin()) { + return false; + } + if (this.getPortalLogin() != other.getPortalLogin()) { + return false; + } + Long this$userId = this.getUserId(); + Long other$userId = other.getUserId(); + if (this$userId == null ? other$userId != null : !((Object)this$userId).equals(other$userId)) { + return false; + } + Long this$deptId = this.getDeptId(); + Long other$deptId = other.getDeptId(); + if (this$deptId == null ? other$deptId != null : !((Object)this$deptId).equals(other$deptId)) { + return false; + } + Long this$loginTime = this.getLoginTime(); + Long other$loginTime = other.getLoginTime(); + if (this$loginTime == null ? other$loginTime != null : !((Object)this$loginTime).equals(other$loginTime)) { + return false; + } + Long this$expireTime = this.getExpireTime(); + Long other$expireTime = other.getExpireTime(); + if (this$expireTime == null ? other$expireTime != null : !((Object)this$expireTime).equals(other$expireTime)) { + return false; + } + String this$token = this.getToken(); + String other$token = other.getToken(); + if (this$token == null ? other$token != null : !this$token.equals(other$token)) { + return false; + } + String this$ipaddr = this.getIpaddr(); + String other$ipaddr = other.getIpaddr(); + if (this$ipaddr == null ? other$ipaddr != null : !this$ipaddr.equals(other$ipaddr)) { + return false; + } + String this$loginLocation = this.getLoginLocation(); + String other$loginLocation = other.getLoginLocation(); + if (this$loginLocation == null ? other$loginLocation != null : !this$loginLocation.equals(other$loginLocation)) { + return false; + } + String this$browser = this.getBrowser(); + String other$browser = other.getBrowser(); + if (this$browser == null ? other$browser != null : !this$browser.equals(other$browser)) { + return false; + } + String this$os = this.getOs(); + String other$os = other.getOs(); + if (this$os == null ? other$os != null : !this$os.equals(other$os)) { + return false; + } + Set this$permissions = this.getPermissions(); + Set other$permissions = other.getPermissions(); + if (this$permissions == null ? other$permissions != null : !((Object)this$permissions).equals(other$permissions)) { + return false; + } + Set this$areaIds = this.getAreaIds(); + Set other$areaIds = other.getAreaIds(); + if (this$areaIds == null ? other$areaIds != null : !((Object)this$areaIds).equals(other$areaIds)) { + return false; + } + List this$areaList = this.getAreaList(); + List other$areaList = other.getAreaList(); + if (this$areaList == null ? other$areaList != null : !((Object)this$areaList).equals(other$areaList)) { + return false; + } + List this$deviceList = this.getDeviceList(); + List other$deviceList = other.getDeviceList(); + if (this$deviceList == null ? other$deviceList != null : !((Object)this$deviceList).equals(other$deviceList)) { + return false; + } + SysUser this$user = this.getUser(); + SysUser other$user = other.getUser(); + return !(this$user == null ? other$user != null : !((Object)this$user).equals(other$user)); + } + + protected boolean canEqual(Object other) { + return other instanceof LoginUser; + } + + public int hashCode() { + int PRIME = 59; + int result = 1; + result = result * 59 + this.getWebLogin(); + result = result * 59 + this.getPortalLogin(); + Long $userId = this.getUserId(); + result = result * 59 + ($userId == null ? 43 : ((Object)$userId).hashCode()); + Long $deptId = this.getDeptId(); + result = result * 59 + ($deptId == null ? 43 : ((Object)$deptId).hashCode()); + Long $loginTime = this.getLoginTime(); + result = result * 59 + ($loginTime == null ? 43 : ((Object)$loginTime).hashCode()); + Long $expireTime = this.getExpireTime(); + result = result * 59 + ($expireTime == null ? 43 : ((Object)$expireTime).hashCode()); + String $token = this.getToken(); + result = result * 59 + ($token == null ? 43 : $token.hashCode()); + String $ipaddr = this.getIpaddr(); + result = result * 59 + ($ipaddr == null ? 43 : $ipaddr.hashCode()); + String $loginLocation = this.getLoginLocation(); + result = result * 59 + ($loginLocation == null ? 43 : $loginLocation.hashCode()); + String $browser = this.getBrowser(); + result = result * 59 + ($browser == null ? 43 : $browser.hashCode()); + String $os = this.getOs(); + result = result * 59 + ($os == null ? 43 : $os.hashCode()); + Set $permissions = this.getPermissions(); + result = result * 59 + ($permissions == null ? 43 : ((Object)$permissions).hashCode()); + Set $areaIds = this.getAreaIds(); + result = result * 59 + ($areaIds == null ? 43 : ((Object)$areaIds).hashCode()); + List $areaList = this.getAreaList(); + result = result * 59 + ($areaList == null ? 43 : ((Object)$areaList).hashCode()); + List $deviceList = this.getDeviceList(); + result = result * 59 + ($deviceList == null ? 43 : ((Object)$deviceList).hashCode()); + SysUser $user = this.getUser(); + result = result * 59 + ($user == null ? 43 : ((Object)$user).hashCode()); + return result; + } + + public String toString() { + return "LoginUser(userId=" + this.getUserId() + ", deptId=" + this.getDeptId() + ", token=" + this.getToken() + ", loginTime=" + this.getLoginTime() + ", expireTime=" + this.getExpireTime() + ", ipaddr=" + this.getIpaddr() + ", loginLocation=" + this.getLoginLocation() + ", browser=" + this.getBrowser() + ", os=" + this.getOs() + ", permissions=" + this.getPermissions() + ", areaIds=" + this.getAreaIds() + ", areaList=" + this.getAreaList() + ", deviceList=" + this.getDeviceList() + ", user=" + this.getUser() + ", webLogin=" + this.getWebLogin() + ", portalLogin=" + this.getPortalLogin() + ")"; + } +} + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/RegisterBody.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/RegisterBody.java new file mode 100644 index 0000000..e9616d0 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/domain/model/RegisterBody.java @@ -0,0 +1,11 @@ +package net.hzvtc.common.core.domain.model; + +/** + * 用户注册对象 + * + * @author admin + */ +public class RegisterBody extends LoginBody +{ + +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/page/PageDomain.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/PageDomain.java new file mode 100644 index 0000000..477ec94 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/PageDomain.java @@ -0,0 +1,101 @@ +package net.hzvtc.common.core.page; + +import net.hzvtc.common.utils.StringUtils; + +/** + * 分页数据 + * + * @author admin + */ +public class PageDomain +{ + /** 当前记录起始索引 */ + private Integer pageNum; + + /** 每页显示记录数 */ + private Integer pageSize; + + /** 排序列 */ + private String orderByColumn; + + /** 排序的方向desc或者asc */ + private String isAsc = "asc"; + + /** 分页参数合理化 */ + private Boolean reasonable = true; + + public String getOrderBy() + { + if (StringUtils.isEmpty(orderByColumn)) + { + return ""; + } + return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; + } + + public Integer getPageNum() + { + return pageNum; + } + + public void setPageNum(Integer pageNum) + { + this.pageNum = pageNum; + } + + public Integer getPageSize() + { + return pageSize; + } + + public void setPageSize(Integer pageSize) + { + this.pageSize = pageSize; + } + + public String getOrderByColumn() + { + return orderByColumn; + } + + public void setOrderByColumn(String orderByColumn) + { + this.orderByColumn = orderByColumn; + } + + public String getIsAsc() + { + return isAsc; + } + + public void setIsAsc(String isAsc) + { + if (StringUtils.isNotEmpty(isAsc)) + { + // 兼容前端排序类型 + if ("ascending".equals(isAsc)) + { + isAsc = "asc"; + } + else if ("descending".equals(isAsc)) + { + isAsc = "desc"; + } + this.isAsc = isAsc; + } + } + + public Boolean getReasonable() + { + if (StringUtils.isNull(reasonable)) + { + return Boolean.TRUE; + } + return reasonable; + } + + public void setReasonable(Boolean reasonable) + { + this.reasonable = reasonable; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableDataInfo.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableDataInfo.java new file mode 100644 index 0000000..8b2a869 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableDataInfo.java @@ -0,0 +1,85 @@ +package net.hzvtc.common.core.page; + +import java.io.Serializable; +import java.util.List; + +/** + * 表格分页数据对象 + * + * @author admin + */ +public class TableDataInfo implements Serializable +{ + private static final long serialVersionUID = 1L; + + /** 总记录数 */ + private long total; + + /** 列表数据 */ + private List rows; + + /** 消息状态码 */ + private int code; + + /** 消息内容 */ + private String msg; + + /** + * 表格数据对象 + */ + public TableDataInfo() + { + } + + /** + * 分页 + * + * @param list 列表数据 + * @param total 总记录数 + */ + public TableDataInfo(List list, int total) + { + this.rows = list; + this.total = total; + } + + public long getTotal() + { + return total; + } + + public void setTotal(long total) + { + this.total = total; + } + + public List getRows() + { + return rows; + } + + public void setRows(List rows) + { + this.rows = rows; + } + + public int getCode() + { + return code; + } + + public void setCode(int code) + { + this.code = code; + } + + public String getMsg() + { + return msg; + } + + public void setMsg(String msg) + { + this.msg = msg; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableSupport.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableSupport.java new file mode 100644 index 0000000..5f9550a --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/page/TableSupport.java @@ -0,0 +1,55 @@ +package net.hzvtc.common.core.page; + +import net.hzvtc.common.utils.ServletUtils; + +/** + * 表格数据处理 + * + * @author admin + */ +public class TableSupport +{ + /** + * 当前记录起始索引 + */ + public static final String PAGE_NUM = "pageNum"; + + /** + * 每页显示记录数 + */ + public static final String PAGE_SIZE = "pageSize"; + + /** + * 排序列 + */ + public static final String ORDER_BY_COLUMN = "orderByColumn"; + + /** + * 排序的方向 "desc" 或者 "asc". + */ + public static final String IS_ASC = "isAsc"; + + /** + * 分页参数合理化 + */ + public static final String REASONABLE = "reasonable"; + + /** + * 封装分页对象 + */ + public static PageDomain getPageDomain() + { + PageDomain pageDomain = new PageDomain(); + pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM)); + pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE)); + pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN)); + pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC)); + pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE)); + return pageDomain; + } + + public static PageDomain buildPageRequest() + { + return getPageDomain(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/redis/RedisCache.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/redis/RedisCache.java new file mode 100644 index 0000000..d4b95f4 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/redis/RedisCache.java @@ -0,0 +1,246 @@ +package net.hzvtc.common.core.redis; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.BoundSetOperations; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; + +/** + * spring redis 工具类 + * + * @author admin + **/ +@SuppressWarnings(value = { "unchecked", "rawtypes" }) +@Component +public class RedisCache +{ + @Autowired + public RedisTemplate redisTemplate; + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + */ + public void setCacheObject(final String key, final T value) + { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + * @param timeout 时间 + * @param timeUnit 时间颗粒度 + */ + public void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) + { + redisTemplate.opsForValue().set(key, value, timeout, timeUnit); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout) + { + return expire(key, timeout, TimeUnit.SECONDS); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @param unit 时间单位 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout, final TimeUnit unit) + { + return redisTemplate.expire(key, timeout, unit); + } + + /** + * 获得缓存的基本对象。 + * + * @param key 缓存键值 + * @return 缓存键值对应的数据 + */ + public T getCacheObject(final String key) + { + ValueOperations operation = redisTemplate.opsForValue(); + return operation.get(key); + } + + /** + * 删除单个对象 + * + * @param key + */ + public boolean deleteObject(final String key) + { + return redisTemplate.delete(key); + } + + /** + * 删除集合对象 + * + * @param collection 多个对象 + * @return + */ + public long deleteObject(final Collection collection) + { + return redisTemplate.delete(collection); + } + + /** + * 缓存List数据 + * + * @param key 缓存的键值 + * @param dataList 待缓存的List数据 + * @return 缓存的对象 + */ + public long setCacheList(final String key, final List dataList) + { + Long count = redisTemplate.opsForList().rightPushAll(key, dataList); + return count == null ? 0 : count; + } + + /** + * 获得缓存的list对象 + * + * @param key 缓存的键值 + * @return 缓存键值对应的数据 + */ + public List getCacheList(final String key) + { + return redisTemplate.opsForList().range(key, 0, -1); + } + + /** + * 缓存Set + * + * @param key 缓存键值 + * @param dataSet 缓存的数据 + * @return 缓存数据的对象 + */ + public BoundSetOperations setCacheSet(final String key, final Set dataSet) + { + BoundSetOperations setOperation = redisTemplate.boundSetOps(key); + Iterator it = dataSet.iterator(); + while (it.hasNext()) + { + setOperation.add(it.next()); + } + return setOperation; + } + + /** + * 获得缓存的set + * + * @param key + * @return + */ + public Set getCacheSet(final String key) + { + return redisTemplate.opsForSet().members(key); + } + + /** + * 缓存Map + * + * @param key + * @param dataMap + */ + public void setCacheMap(final String key, final Map dataMap) + { + if (dataMap != null) { + redisTemplate.opsForHash().putAll(key, dataMap); + } + } + + /** + * 获得缓存的Map + * + * @param key + * @return + */ + public Map getCacheMap(final String key) + { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 往Hash中存入数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @param value 值 + */ + public void setCacheMapValue(final String key, final String hKey, final T value) + { + redisTemplate.opsForHash().put(key, hKey, value); + } + + /** + * 获取Hash中的数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @return Hash中的对象 + */ + public T getCacheMapValue(final String key, final String hKey) + { + HashOperations opsForHash = redisTemplate.opsForHash(); + return opsForHash.get(key, hKey); + } + + /** + * 删除Hash中的数据 + * + * @param key + * @param mapkey + */ + public void delCacheMapValue(final String key, final String hkey) + { + HashOperations hashOperations = redisTemplate.opsForHash(); + hashOperations.delete(key, hkey); + } + + /** + * 获取多个Hash中的数据 + * + * @param key Redis键 + * @param hKeys Hash键集合 + * @return Hash对象集合 + */ + public List getMultiCacheMapValue(final String key, final Collection hKeys) + { + return redisTemplate.opsForHash().multiGet(key, hKeys); + } + + /** + * 获得缓存的基本对象列表 + * + * @param pattern 字符串前缀 + * @return 对象列表 + */ + public Collection keys(final String pattern) + { + return redisTemplate.keys(pattern); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/text/CharsetKit.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/CharsetKit.java new file mode 100644 index 0000000..5292a97 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/CharsetKit.java @@ -0,0 +1,86 @@ +package net.hzvtc.common.core.text; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import net.hzvtc.common.utils.StringUtils; + +/** + * 字符集工具类 + * + * @author admin + */ +public class CharsetKit +{ + /** ISO-8859-1 */ + public static final String ISO_8859_1 = "ISO-8859-1"; + /** UTF-8 */ + public static final String UTF_8 = "UTF-8"; + /** GBK */ + public static final String GBK = "GBK"; + + /** ISO-8859-1 */ + public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); + /** UTF-8 */ + public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); + /** GBK */ + public static final Charset CHARSET_GBK = Charset.forName(GBK); + + /** + * 转换为Charset对象 + * + * @param charset 字符集,为空则返回默认字符集 + * @return Charset + */ + public static Charset charset(String charset) + { + return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, String srcCharset, String destCharset) + { + return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, Charset srcCharset, Charset destCharset) + { + if (null == srcCharset) + { + srcCharset = StandardCharsets.ISO_8859_1; + } + + if (null == destCharset) + { + destCharset = StandardCharsets.UTF_8; + } + + if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) + { + return source; + } + return new String(source.getBytes(srcCharset), destCharset); + } + + /** + * @return 系统字符集编码 + */ + public static String systemCharset() + { + return Charset.defaultCharset().name(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/text/Convert.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/Convert.java new file mode 100644 index 0000000..a4c693f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/Convert.java @@ -0,0 +1,1005 @@ +package net.hzvtc.common.core.text; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.text.NumberFormat; +import java.util.Set; +import net.hzvtc.common.utils.StringUtils; +import org.apache.commons.lang3.ArrayUtils; + +/** + * 类型转换器 + * + * @author admin + */ +public class Convert +{ + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static String toStr(Object value, String defaultValue) + { + if (null == value) + { + return defaultValue; + } + if (value instanceof String) + { + return (String) value; + } + return value.toString(); + } + + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static String toStr(Object value) + { + return toStr(value, null); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Character toChar(Object value, Character defaultValue) + { + if (null == value) + { + return defaultValue; + } + if (value instanceof Character) + { + return (Character) value; + } + + final String valueStr = toStr(value, null); + return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Character toChar(Object value) + { + return toChar(value, null); + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Byte toByte(Object value, Byte defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Byte) + { + return (Byte) value; + } + if (value instanceof Number) + { + return ((Number) value).byteValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return Byte.parseByte(valueStr); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Byte toByte(Object value) + { + return toByte(value, null); + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Short toShort(Object value, Short defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Short) + { + return (Short) value; + } + if (value instanceof Number) + { + return ((Number) value).shortValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return Short.parseShort(valueStr.trim()); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Short toShort(Object value) + { + return toShort(value, null); + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Number toNumber(Object value, Number defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Number) + { + return (Number) value; + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return NumberFormat.getInstance().parse(valueStr); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Number toNumber(Object value) + { + return toNumber(value, null); + } + + /** + * 转换为int
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Integer toInt(Object value, Integer defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Integer) + { + return (Integer) value; + } + if (value instanceof Number) + { + return ((Number) value).intValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return Integer.parseInt(valueStr.trim()); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为int
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Integer toInt(Object value) + { + return toInt(value, null); + } + + /** + * 转换为Integer数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String str) + { + return toIntArray(",", str); + } + + /** + * 转换为Long数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String str) + { + return toLongArray(",", str); + } + + /** + * 转换为Integer数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String split, String str) + { + if (StringUtils.isEmpty(str)) + { + return new Integer[] {}; + } + String[] arr = str.split(split); + final Integer[] ints = new Integer[arr.length]; + for (int i = 0; i < arr.length; i++) + { + final Integer v = toInt(arr[i], 0); + ints[i] = v; + } + return ints; + } + + /** + * 转换为Long数组
+ * + * @param split 分隔符 + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String split, String str) + { + if (StringUtils.isEmpty(str)) + { + return new Long[] {}; + } + String[] arr = str.split(split); + final Long[] longs = new Long[arr.length]; + for (int i = 0; i < arr.length; i++) + { + final Long v = toLong(arr[i], null); + longs[i] = v; + } + return longs; + } + + /** + * 转换为String数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String str) + { + return toStrArray(",", str); + } + + /** + * 转换为String数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String split, String str) + { + return str.split(split); + } + + /** + * 转换为long
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Long toLong(Object value, Long defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Long) + { + return (Long) value; + } + if (value instanceof Number) + { + return ((Number) value).longValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).longValue(); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为long
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Long toLong(Object value) + { + return toLong(value, null); + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Double toDouble(Object value, Double defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Double) + { + return (Double) value; + } + if (value instanceof Number) + { + return ((Number) value).doubleValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).doubleValue(); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Double toDouble(Object value) + { + return toDouble(value, null); + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Float toFloat(Object value, Float defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Float) + { + return (Float) value; + } + if (value instanceof Number) + { + return ((Number) value).floatValue(); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return Float.parseFloat(valueStr.trim()); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Float toFloat(Object value) + { + return toFloat(value, null); + } + + /** + * 转换为boolean
+ * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Boolean toBool(Object value, Boolean defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof Boolean) + { + return (Boolean) value; + } + String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + valueStr = valueStr.trim().toLowerCase(); + switch (valueStr) + { + case "true": + return true; + case "false": + return false; + case "yes": + return true; + case "ok": + return true; + case "no": + return false; + case "1": + return true; + case "0": + return false; + default: + return defaultValue; + } + } + + /** + * 转换为boolean
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Boolean toBool(Object value) + { + return toBool(value, null); + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * + * @param clazz Enum的Class + * @param value 值 + * @param defaultValue 默认值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value, E defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (clazz.isAssignableFrom(value.getClass())) + { + @SuppressWarnings("unchecked") + E myE = (E) value; + return myE; + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return Enum.valueOf(clazz, valueStr); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * + * @param clazz Enum的Class + * @param value 值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value) + { + return toEnum(clazz, value, null); + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value, BigInteger defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof BigInteger) + { + return (BigInteger) value; + } + if (value instanceof Long) + { + return BigInteger.valueOf((Long) value); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return new BigInteger(valueStr); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value) + { + return toBigInteger(value, null); + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) + { + if (value == null) + { + return defaultValue; + } + if (value instanceof BigDecimal) + { + return (BigDecimal) value; + } + if (value instanceof Long) + { + return new BigDecimal((Long) value); + } + if (value instanceof Double) + { + return new BigDecimal((Double) value); + } + if (value instanceof Integer) + { + return new BigDecimal((Integer) value); + } + final String valueStr = toStr(value, null); + if (StringUtils.isEmpty(valueStr)) + { + return defaultValue; + } + try + { + return new BigDecimal(valueStr); + } + catch (Exception e) + { + return defaultValue; + } + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value) + { + return toBigDecimal(value, null); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @return 字符串 + */ + public static String utf8Str(Object obj) + { + return str(obj, CharsetKit.CHARSET_UTF_8); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charsetName 字符集 + * @return 字符串 + */ + public static String str(Object obj, String charsetName) + { + return str(obj, Charset.forName(charsetName)); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(Object obj, Charset charset) + { + if (null == obj) + { + return null; + } + + if (obj instanceof String) + { + return (String) obj; + } + else if (obj instanceof byte[]) + { + return str((byte[]) obj, charset); + } + else if (obj instanceof Byte[]) + { + byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj); + return str(bytes, charset); + } + else if (obj instanceof ByteBuffer) + { + return str((ByteBuffer) obj, charset); + } + return obj.toString(); + } + + /** + * 将byte数组转为字符串 + * + * @param bytes byte数组 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(byte[] bytes, String charset) + { + return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset)); + } + + /** + * 解码字节码 + * + * @param data 字符串 + * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @return 解码后的字符串 + */ + public static String str(byte[] data, Charset charset) + { + if (data == null) + { + return null; + } + + if (null == charset) + { + return new String(data); + } + return new String(data, charset); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, String charset) + { + if (data == null) + { + return null; + } + + return str(data, Charset.forName(charset)); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, Charset charset) + { + if (null == charset) + { + charset = Charset.defaultCharset(); + } + return charset.decode(data).toString(); + } + + // ----------------------------------------------------------------------- 全角半角转换 + /** + * 半角转全角 + * + * @param input String. + * @return 全角字符串. + */ + public static String toSBC(String input) + { + return toSBC(input, null); + } + + /** + * 半角转全角 + * + * @param input String + * @param notConvertSet 不替换的字符集合 + * @return 全角字符串. + */ + public static String toSBC(String input, Set notConvertSet) + { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) + { + if (null != notConvertSet && notConvertSet.contains(c[i])) + { + // 跳过不替换的字符 + continue; + } + + if (c[i] == ' ') + { + c[i] = '\u3000'; + } + else if (c[i] < '\177') + { + c[i] = (char) (c[i] + 65248); + + } + } + return new String(c); + } + + /** + * 全角转半角 + * + * @param input String. + * @return 半角字符串 + */ + public static String toDBC(String input) + { + return toDBC(input, null); + } + + /** + * 替换全角为半角 + * + * @param text 文本 + * @param notConvertSet 不替换的字符集合 + * @return 替换后的字符 + */ + public static String toDBC(String text, Set notConvertSet) + { + char c[] = text.toCharArray(); + for (int i = 0; i < c.length; i++) + { + if (null != notConvertSet && notConvertSet.contains(c[i])) + { + // 跳过不替换的字符 + continue; + } + + if (c[i] == '\u3000') + { + c[i] = ' '; + } + else if (c[i] > '\uFF00' && c[i] < '\uFF5F') + { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + + return returnString; + } + + /** + * 数字金额大写转换 先写个完整的然后将如零拾替换成零 + * + * @param n 数字 + * @return 中文大写数字 + */ + public static String digitUppercase(double n) + { + String[] fraction = { "角", "分" }; + String[] digit = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; + String[][] unit = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } }; + + String head = n < 0 ? "负" : ""; + n = Math.abs(n); + + String s = ""; + for (int i = 0; i < fraction.length; i++) + { + s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); + } + if (s.length() < 1) + { + s = "整"; + } + int integerPart = (int) Math.floor(n); + + for (int i = 0; i < unit[0].length && integerPart > 0; i++) + { + String p = ""; + for (int j = 0; j < unit[1].length && n > 0; j++) + { + p = digit[integerPart % 10] + unit[1][j] + p; + integerPart = integerPart / 10; + } + s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; + } + return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/core/text/StrFormatter.java b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/StrFormatter.java new file mode 100644 index 0000000..f7fdcfb --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/core/text/StrFormatter.java @@ -0,0 +1,92 @@ +package net.hzvtc.common.core.text; + +import net.hzvtc.common.utils.StringUtils; + +/** + * 字符串格式化 + * + * @author admin + */ +public class StrFormatter +{ + public static final String EMPTY_JSON = "{}"; + public static final char C_BACKSLASH = '\\'; + public static final char C_DELIM_START = '{'; + public static final char C_DELIM_END = '}'; + + /** + * 格式化字符串
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param strPattern 字符串模板 + * @param argArray 参数列表 + * @return 结果 + */ + public static String format(final String strPattern, final Object... argArray) + { + if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) + { + return strPattern; + } + final int strPatternLength = strPattern.length(); + + // 初始化定义好的长度以获得更好的性能 + StringBuilder sbuf = new StringBuilder(strPatternLength + 50); + + int handledPosition = 0; + int delimIndex;// 占位符所在位置 + for (int argIndex = 0; argIndex < argArray.length; argIndex++) + { + delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); + if (delimIndex == -1) + { + if (handledPosition == 0) + { + return strPattern; + } + else + { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 + sbuf.append(strPattern, handledPosition, strPatternLength); + return sbuf.toString(); + } + } + else + { + if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) + { + if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) + { + // 转义符之前还有一个转义符,占位符依旧有效 + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } + else + { + // 占位符被转义 + argIndex--; + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(C_DELIM_START); + handledPosition = delimIndex + 1; + } + } + else + { + // 正常占位符 + sbuf.append(strPattern, handledPosition, delimIndex); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } + } + } + // 加入最后一个占位符后所有的字符 + sbuf.append(strPattern, handledPosition, strPattern.length()); + + return sbuf.toString(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessStatus.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessStatus.java new file mode 100644 index 0000000..1a0c72b --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessStatus.java @@ -0,0 +1,20 @@ +package net.hzvtc.common.enums; + +/** + * 操作状态 + * + * @author admin + * + */ +public enum BusinessStatus +{ + /** + * 成功 + */ + SUCCESS, + + /** + * 失败 + */ + FAIL, +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessType.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessType.java new file mode 100644 index 0000000..bded87f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/BusinessType.java @@ -0,0 +1,59 @@ +package net.hzvtc.common.enums; + +/** + * 业务操作类型 + * + * @author admin + */ +public enum BusinessType +{ + /** + * 其它 + */ + OTHER, + + /** + * 新增 + */ + INSERT, + + /** + * 修改 + */ + UPDATE, + + /** + * 删除 + */ + DELETE, + + /** + * 授权 + */ + GRANT, + + /** + * 导出 + */ + EXPORT, + + /** + * 导入 + */ + IMPORT, + + /** + * 强退 + */ + FORCE, + + /** + * 生成代码 + */ + GENCODE, + + /** + * 清空数据 + */ + CLEAN, +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/DataSourceType.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/DataSourceType.java new file mode 100644 index 0000000..b966ba3 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/DataSourceType.java @@ -0,0 +1,19 @@ +package net.hzvtc.common.enums; + +/** + * 数据源 + * + * @author admin + */ +public enum DataSourceType +{ + /** + * 主库 + */ + MASTER, + + /** + * 从库 + */ + SLAVE +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/HttpMethod.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/HttpMethod.java new file mode 100644 index 0000000..63e1a99 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/HttpMethod.java @@ -0,0 +1,36 @@ +package net.hzvtc.common.enums; + +import java.util.HashMap; +import java.util.Map; +import org.springframework.lang.Nullable; + +/** + * 请求方式 + * + * @author admin + */ +public enum HttpMethod +{ + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; + + private static final Map mappings = new HashMap<>(16); + + static + { + for (HttpMethod httpMethod : values()) + { + mappings.put(httpMethod.name(), httpMethod); + } + } + + @Nullable + public static HttpMethod resolve(@Nullable String method) + { + return (method != null ? mappings.get(method) : null); + } + + public boolean matches(String method) + { + return (this == resolve(method)); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/LimitType.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/LimitType.java new file mode 100644 index 0000000..8539150 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/LimitType.java @@ -0,0 +1,20 @@ +package net.hzvtc.common.enums; + +/** + * 限流类型 + * + * @author admin + */ + +public enum LimitType +{ + /** + * 默认策略全局限流 + */ + DEFAULT, + + /** + * 根据请求者IP进行限流 + */ + IP +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/OperatorType.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/OperatorType.java new file mode 100644 index 0000000..53e3e83 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/OperatorType.java @@ -0,0 +1,24 @@ +package net.hzvtc.common.enums; + +/** + * 操作人类别 + * + * @author admin + */ +public enum OperatorType +{ + /** + * 其它 + */ + OTHER, + + /** + * 后台用户 + */ + MANAGE, + + /** + * 手机端用户 + */ + MOBILE +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/enums/UserStatus.java b/ai-bird-common/src/main/java/net/hzvtc/common/enums/UserStatus.java new file mode 100644 index 0000000..0e59a02 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/enums/UserStatus.java @@ -0,0 +1,30 @@ +package net.hzvtc.common.enums; + +/** + * 用户状态 + * + * @author admin + */ +public enum UserStatus +{ + OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); + + private final String code; + private final String info; + + UserStatus(String code, String info) + { + this.code = code; + this.info = info; + } + + public String getCode() + { + return code; + } + + public String getInfo() + { + return info; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/DemoModeException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/DemoModeException.java new file mode 100644 index 0000000..f689f9a --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/DemoModeException.java @@ -0,0 +1,15 @@ +package net.hzvtc.common.exception; + +/** + * 演示模式异常 + * + * @author admin + */ +public class DemoModeException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public DemoModeException() + { + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/GlobalException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/GlobalException.java new file mode 100644 index 0000000..e335b57 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/GlobalException.java @@ -0,0 +1,58 @@ +package net.hzvtc.common.exception; + +/** + * 全局异常 + * + * @author admin + */ +public class GlobalException extends RuntimeException +{ + + private static final long serialVersionUID = 1L; + + /** + * 错误提示 + */ + private String message; + + /** + * 错误明细,内部调试错误 + * + * 和 {@link CommonResult#getDetailMessage()} 一致的设计 + */ + private String detailMessage; + + /** + * 空构造方法,避免反序列化问题 + */ + public GlobalException() + { + } + + public GlobalException(String message) + { + this.message = message; + } + + public String getDetailMessage() + { + return detailMessage; + } + + public GlobalException setDetailMessage(String detailMessage) + { + this.detailMessage = detailMessage; + return this; + } + + public String getMessage() + { + return message; + } + + public GlobalException setMessage(String message) + { + this.message = message; + return this; + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/ServiceException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/ServiceException.java new file mode 100644 index 0000000..1e758ec --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/ServiceException.java @@ -0,0 +1,73 @@ +package net.hzvtc.common.exception; + +/** + * 业务异常 + * + * @author admin + */ +public final class ServiceException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + /** + * 错误码 + */ + private Integer code; + + /** + * 错误提示 + */ + private String message; + + /** + * 错误明细,内部调试错误 + * + * 和 {@link CommonResult#getDetailMessage()} 一致的设计 + */ + private String detailMessage; + + /** + * 空构造方法,避免反序列化问题 + */ + public ServiceException() + { + } + + public ServiceException(String message) + { + this.message = message; + } + + public ServiceException(String message, Integer code) + { + this.message = message; + this.code = code; + } + + public String getDetailMessage() + { + return detailMessage; + } + + public String getMessage() + { + return message; + } + + public Integer getCode() + { + return code; + } + + public ServiceException setMessage(String message) + { + this.message = message; + return this; + } + + public ServiceException setDetailMessage(String detailMessage) + { + this.detailMessage = detailMessage; + return this; + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/UtilException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/UtilException.java new file mode 100644 index 0000000..ec146b7 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/UtilException.java @@ -0,0 +1,26 @@ +package net.hzvtc.common.exception; + +/** + * 工具类异常 + * + * @author admin + */ +public class UtilException extends RuntimeException +{ + private static final long serialVersionUID = 8247610319171014183L; + + public UtilException(Throwable e) + { + super(e.getMessage(), e); + } + + public UtilException(String message) + { + super(message); + } + + public UtilException(String message, Throwable throwable) + { + super(message, throwable); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/base/BaseException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/base/BaseException.java new file mode 100644 index 0000000..bbf0c20 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/base/BaseException.java @@ -0,0 +1,97 @@ +package net.hzvtc.common.exception.base; + +import net.hzvtc.common.utils.MessageUtils; +import net.hzvtc.common.utils.StringUtils; + +/** + * 基础异常 + * + * @author admin + */ +public class BaseException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + /** + * 所属模块 + */ + private String module; + + /** + * 错误码 + */ + private String code; + + /** + * 错误码对应的参数 + */ + private Object[] args; + + /** + * 错误消息 + */ + private String defaultMessage; + + public BaseException(String module, String code, Object[] args, String defaultMessage) + { + this.module = module; + this.code = code; + this.args = args; + this.defaultMessage = defaultMessage; + } + + public BaseException(String module, String code, Object[] args) + { + this(module, code, args, null); + } + + public BaseException(String module, String defaultMessage) + { + this(module, null, null, defaultMessage); + } + + public BaseException(String code, Object[] args) + { + this(null, code, args, null); + } + + public BaseException(String defaultMessage) + { + this(null, null, null, defaultMessage); + } + + @Override + public String getMessage() + { + String message = null; + if (!StringUtils.isEmpty(code)) + { + message = MessageUtils.message(code, args); + } + if (message == null) + { + message = defaultMessage; + } + return message; + } + + public String getModule() + { + return module; + } + + public String getCode() + { + return code; + } + + public Object[] getArgs() + { + return args; + } + + public String getDefaultMessage() + { + return defaultMessage; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileException.java new file mode 100644 index 0000000..d55efdb --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileException.java @@ -0,0 +1,19 @@ +package net.hzvtc.common.exception.file; + +import net.hzvtc.common.exception.base.BaseException; + +/** + * 文件信息异常类 + * + * @author admin + */ +public class FileException extends BaseException +{ + private static final long serialVersionUID = 1L; + + public FileException(String code, Object[] args) + { + super("file", code, args, null); + } + +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileNameLengthLimitExceededException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileNameLengthLimitExceededException.java new file mode 100644 index 0000000..cc7764e --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileNameLengthLimitExceededException.java @@ -0,0 +1,16 @@ +package net.hzvtc.common.exception.file; + +/** + * 文件名称超长限制异常类 + * + * @author admin + */ +public class FileNameLengthLimitExceededException extends FileException +{ + private static final long serialVersionUID = 1L; + + public FileNameLengthLimitExceededException(int defaultFileNameLength) + { + super("upload.filename.exceed.length", new Object[] { defaultFileNameLength }); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileSizeLimitExceededException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileSizeLimitExceededException.java new file mode 100644 index 0000000..11ea71a --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/FileSizeLimitExceededException.java @@ -0,0 +1,16 @@ +package net.hzvtc.common.exception.file; + +/** + * 文件名大小限制异常类 + * + * @author admin + */ +public class FileSizeLimitExceededException extends FileException +{ + private static final long serialVersionUID = 1L; + + public FileSizeLimitExceededException(long defaultMaxSize) + { + super("upload.exceed.maxSize", new Object[] { defaultMaxSize }); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/InvalidExtensionException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/InvalidExtensionException.java new file mode 100644 index 0000000..9e22f6c --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/file/InvalidExtensionException.java @@ -0,0 +1,81 @@ +package net.hzvtc.common.exception.file; + +import java.util.Arrays; +import org.apache.commons.fileupload.FileUploadException; + +/** + * 文件上传 误异常类 + * + * @author admin + */ +public class InvalidExtensionException extends FileUploadException +{ + private static final long serialVersionUID = 1L; + + private String[] allowedExtension; + private String extension; + private String filename; + + public InvalidExtensionException(String[] allowedExtension, String extension, String filename) + { + super("filename : [" + filename + "], extension : [" + extension + "], allowed extension : [" + Arrays.toString(allowedExtension) + "]"); + this.allowedExtension = allowedExtension; + this.extension = extension; + this.filename = filename; + } + + public String[] getAllowedExtension() + { + return allowedExtension; + } + + public String getExtension() + { + return extension; + } + + public String getFilename() + { + return filename; + } + + public static class InvalidImageExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidFlashExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidMediaExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } + + public static class InvalidVideoExtensionException extends InvalidExtensionException + { + private static final long serialVersionUID = 1L; + + public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename) + { + super(allowedExtension, extension, filename); + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/job/TaskException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/job/TaskException.java new file mode 100644 index 0000000..cf83c0f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/job/TaskException.java @@ -0,0 +1,34 @@ +package net.hzvtc.common.exception.job; + +/** + * 计划策略异常 + * + * @author admin + */ +public class TaskException extends Exception +{ + private static final long serialVersionUID = 1L; + + private Code code; + + public TaskException(String msg, Code code) + { + this(msg, code, null); + } + + public TaskException(String msg, Code code, Exception nestedEx) + { + super(msg, nestedEx); + this.code = code; + } + + public Code getCode() + { + return code; + } + + public enum Code + { + TASK_EXISTS, NO_TASK_EXISTS, TASK_ALREADY_STARTED, UNKNOWN, CONFIG_ERROR, TASK_NODE_NOT_AVAILABLE + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaException.java new file mode 100644 index 0000000..4af51d4 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaException.java @@ -0,0 +1,16 @@ +package net.hzvtc.common.exception.user; + +/** + * 验证码错误异常类 + * + * @author admin + */ +public class CaptchaException extends UserException +{ + private static final long serialVersionUID = 1L; + + public CaptchaException() + { + super("user.jcaptcha.error", null); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaExpireException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaExpireException.java new file mode 100644 index 0000000..5a878b3 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/CaptchaExpireException.java @@ -0,0 +1,16 @@ +package net.hzvtc.common.exception.user; + +/** + * 验证码失效异常类 + * + * @author admin + */ +public class CaptchaExpireException extends UserException +{ + private static final long serialVersionUID = 1L; + + public CaptchaExpireException() + { + super("user.jcaptcha.expire", null); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserException.java new file mode 100644 index 0000000..7ba3c79 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserException.java @@ -0,0 +1,18 @@ +package net.hzvtc.common.exception.user; + +import net.hzvtc.common.exception.base.BaseException; + +/** + * 用户信息异常类 + * + * @author admin + */ +public class UserException extends BaseException +{ + private static final long serialVersionUID = 1L; + + public UserException(String code, Object[] args) + { + super("user", code, args, null); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserNoLoginPermissionException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserNoLoginPermissionException.java new file mode 100644 index 0000000..59d7666 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserNoLoginPermissionException.java @@ -0,0 +1,10 @@ +package net.hzvtc.common.exception.user; + +public class UserNoLoginPermissionException extends UserException { + + private static final long serialVersionUID = 7376693448481486168L; + + public UserNoLoginPermissionException() { + super("no.login.permission", null); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserPasswordNotMatchException.java b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserPasswordNotMatchException.java new file mode 100644 index 0000000..220b105 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/exception/user/UserPasswordNotMatchException.java @@ -0,0 +1,16 @@ +package net.hzvtc.common.exception.user; + +/** + * 用户密码不正确或不符合规范异常类 + * + * @author admin + */ +public class UserPasswordNotMatchException extends UserException +{ + private static final long serialVersionUID = 1L; + + public UserPasswordNotMatchException() + { + super("user.password.not.match", null); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatableFilter.java b/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatableFilter.java new file mode 100644 index 0000000..4317b4c --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatableFilter.java @@ -0,0 +1,52 @@ +package net.hzvtc.common.filter; + +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import org.springframework.http.MediaType; +import net.hzvtc.common.utils.StringUtils; + +/** + * Repeatable 过滤器 + * + * @author admin + */ +public class RepeatableFilter implements Filter +{ + @Override + public void init(FilterConfig filterConfig) throws ServletException + { + + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException + { + ServletRequest requestWrapper = null; + if (request instanceof HttpServletRequest + && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) + { + requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response); + } + if (null == requestWrapper) + { + chain.doFilter(request, response); + } + else + { + chain.doFilter(requestWrapper, response); + } + } + + @Override + public void destroy() + { + + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatedlyRequestWrapper.java b/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatedlyRequestWrapper.java new file mode 100644 index 0000000..2f88128 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/filter/RepeatedlyRequestWrapper.java @@ -0,0 +1,75 @@ +package net.hzvtc.common.filter; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import net.hzvtc.common.utils.http.HttpHelper; + +/** + * 构建可重复读取inputStream的request + * + * @author admin + */ +public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper +{ + private final byte[] body; + + public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException + { + super(request); + request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding("UTF-8"); + + body = HttpHelper.getBodyString(request).getBytes("UTF-8"); + } + + @Override + public BufferedReader getReader() throws IOException + { + return new BufferedReader(new InputStreamReader(getInputStream())); + } + + @Override + public ServletInputStream getInputStream() throws IOException + { + final ByteArrayInputStream bais = new ByteArrayInputStream(body); + return new ServletInputStream() + { + @Override + public int read() throws IOException + { + return bais.read(); + } + + @Override + public int available() throws IOException + { + return body.length; + } + + @Override + public boolean isFinished() + { + return false; + } + + @Override + public boolean isReady() + { + return false; + } + + @Override + public void setReadListener(ReadListener readListener) + { + + } + }; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssFilter.java b/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssFilter.java new file mode 100644 index 0000000..bd4bedc --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssFilter.java @@ -0,0 +1,74 @@ +package net.hzvtc.common.filter; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.utils.StringUtils; + +/** + * 防止XSS攻击的过滤器 + * + * @author admin + */ +public class XssFilter implements Filter +{ + /** + * 排除链接 + */ + public List excludes = new ArrayList<>(); + + @Override + public void init(FilterConfig filterConfig) throws ServletException + { + String tempExcludes = filterConfig.getInitParameter("excludes"); + if (StringUtils.isNotEmpty(tempExcludes)) + { + String[] url = tempExcludes.split(","); + for (int i = 0; url != null && i < url.length; i++) + { + excludes.add(url[i]); + } + } + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException + { + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse resp = (HttpServletResponse) response; + if (handleExcludeURL(req, resp)) + { + chain.doFilter(request, response); + return; + } + XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); + chain.doFilter(xssRequest, response); + } + + private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) + { + String url = request.getServletPath(); + String method = request.getMethod(); + // GET DELETE 不过滤 + if (method == null || method.matches("GET") || method.matches("DELETE")) + { + return true; + } + return StringUtils.matches(url, excludes); + } + + @Override + public void destroy() + { + + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssHttpServletRequestWrapper.java b/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssHttpServletRequestWrapper.java new file mode 100644 index 0000000..676351b --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/filter/XssHttpServletRequestWrapper.java @@ -0,0 +1,111 @@ +package net.hzvtc.common.filter; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import org.apache.commons.io.IOUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.html.EscapeUtil; + +/** + * XSS过滤处理 + * + * @author admin + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper +{ + /** + * @param request + */ + public XssHttpServletRequestWrapper(HttpServletRequest request) + { + super(request); + } + + @Override + public String[] getParameterValues(String name) + { + String[] values = super.getParameterValues(name); + if (values != null) + { + int length = values.length; + String[] escapseValues = new String[length]; + for (int i = 0; i < length; i++) + { + // 防xss攻击和过滤前后空格 + escapseValues[i] = EscapeUtil.clean(values[i]).trim(); + } + return escapseValues; + } + return super.getParameterValues(name); + } + + @Override + public ServletInputStream getInputStream() throws IOException + { + // 非json类型,直接返回 + if (!isJsonRequest()) + { + return super.getInputStream(); + } + + // 为空,直接返回 + String json = IOUtils.toString(super.getInputStream(), "utf-8"); + if (StringUtils.isEmpty(json)) + { + return super.getInputStream(); + } + + // xss过滤 + json = EscapeUtil.clean(json).trim(); + byte[] jsonBytes = json.getBytes("utf-8"); + final ByteArrayInputStream bis = new ByteArrayInputStream(jsonBytes); + return new ServletInputStream() + { + @Override + public boolean isFinished() + { + return true; + } + + @Override + public boolean isReady() + { + return true; + } + + @Override + public int available() throws IOException + { + return jsonBytes.length; + } + + @Override + public void setReadListener(ReadListener readListener) + { + } + + @Override + public int read() throws IOException + { + return bis.read(); + } + }; + } + + /** + * 是否是Json请求 + * + * @param request + */ + public boolean isJsonRequest() + { + String header = super.getHeader(HttpHeaders.CONTENT_TYPE); + return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE); + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/Arith.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Arith.java new file mode 100644 index 0000000..62d8e72 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Arith.java @@ -0,0 +1,114 @@ +package net.hzvtc.common.utils; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +/** + * 精确的浮点数运算 + * + * @author admin + */ +public class Arith +{ + + /** 默认除法运算精度 */ + private static final int DEF_DIV_SCALE = 10; + + /** 这个类不能实例化 */ + private Arith() + { + } + + /** + * 提供精确的加法运算。 + * @param v1 被加数 + * @param v2 加数 + * @return 两个参数的和 + */ + public static double add(double v1, double v2) + { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.add(b2).doubleValue(); + } + + /** + * 提供精确的减法运算。 + * @param v1 被减数 + * @param v2 减数 + * @return 两个参数的差 + */ + public static double sub(double v1, double v2) + { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.subtract(b2).doubleValue(); + } + + /** + * 提供精确的乘法运算。 + * @param v1 被乘数 + * @param v2 乘数 + * @return 两个参数的积 + */ + public static double mul(double v1, double v2) + { + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + return b1.multiply(b2).doubleValue(); + } + + /** + * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 + * 小数点以后10位,以后的数字四舍五入。 + * @param v1 被除数 + * @param v2 除数 + * @return 两个参数的商 + */ + public static double div(double v1, double v2) + { + return div(v1, v2, DEF_DIV_SCALE); + } + + /** + * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 + * 定精度,以后的数字四舍五入。 + * @param v1 被除数 + * @param v2 除数 + * @param scale 表示表示需要精确到小数点以后几位。 + * @return 两个参数的商 + */ + public static double div(double v1, double v2, int scale) + { + if (scale < 0) + { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b1 = new BigDecimal(Double.toString(v1)); + BigDecimal b2 = new BigDecimal(Double.toString(v2)); + if (b1.compareTo(BigDecimal.ZERO) == 0) + { + return BigDecimal.ZERO.doubleValue(); + } + return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue(); + } + + /** + * 提供精确的小数位四舍五入处理。 + * @param v 需要四舍五入的数字 + * @param scale 小数点后保留几位 + * @return 四舍五入后的结果 + */ + public static double round(double v, int scale) + { + if (scale < 0) + { + throw new IllegalArgumentException( + "The scale must be a positive integer or zero"); + } + BigDecimal b = new BigDecimal(Double.toString(v)); + BigDecimal one = BigDecimal.ONE; + return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/Chinese2pinyin.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Chinese2pinyin.java new file mode 100644 index 0000000..df1e9a9 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Chinese2pinyin.java @@ -0,0 +1,54 @@ +package net.hzvtc.common.utils; + +import net.sourceforge.pinyin4j.PinyinHelper; +import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; +import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; +import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; +import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; +import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class Chinese2pinyin { + public static Map changeChinese2Pinyin(String chinese) { + Map pinyin = new HashMap(); + + HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); + format.setCaseType(HanyuPinyinCaseType.LOWERCASE); + format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); + format.setVCharType(HanyuPinyinVCharType.WITH_V); + + String fullPinyin = ""; + String simplePinyin = ""; + char[] chineseChar = chinese.toCharArray(); + for (int i = 0; i < chineseChar.length; i++) { + String[] str = null; + try { + str = PinyinHelper.toHanyuPinyinStringArray(chineseChar[i], + format); + } catch (BadHanyuPinyinOutputFormatCombination e) { + e.printStackTrace(); + } + if (str != null && str.length > 0) { + fullPinyin = fullPinyin + str[0].toString(); + simplePinyin = simplePinyin + str[0].charAt(0); + } + if (str == null) { + String regex = "^[0-9]*[a-zA-Z]*+$"; + Pattern pattern = Pattern.compile(regex); + Matcher m = pattern.matcher(String.valueOf(chineseChar[i])); + if (m.find()) { + fullPinyin = fullPinyin + chineseChar[i]; + simplePinyin = simplePinyin + chineseChar[i]; + } + } + } + pinyin.put("fullPinyin", fullPinyin); + pinyin.put("simplePinyin", simplePinyin); + + return pinyin; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/CommonUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/CommonUtils.java new file mode 100644 index 0000000..be15381 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/CommonUtils.java @@ -0,0 +1,34 @@ +package net.hzvtc.common.utils; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.List; + +public class CommonUtils { + + public static void sortArrayByParam(JSONArray jsonArray, List list) { + jsonArray.sort((o1, o2) -> { + JSONObject j1 = (JSONObject) o1; + JSONObject j2 = (JSONObject) o2; + boolean j1InList = list.contains(j1.getLong("speciesId")); + boolean j2InList = list.contains(j2.getLong("speciesId")); + + // 如果 j1 在 frontList 中而 j2 不在,则 j1 排前面 + if (j1InList && !j2InList) { + return -1; + } + // 如果 j2 在 frontList 中而 j1 不在,则 j2 排前面 + if (!j1InList && j2InList) { + return 1; + } + // 如果两者都在 frontList 中,按照 frontList 中的顺序排序 + if (j1InList) { + return Integer.compare(list.indexOf(j1.getLong("speciesId")), + list.indexOf(j2.getLong("speciesId"))); + } + // 否则保持原顺序(或按其他标准排序,这里返回 0) + return 0; + }); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/DateUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/DateUtils.java new file mode 100644 index 0000000..8c7610b --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/DateUtils.java @@ -0,0 +1,156 @@ +package net.hzvtc.common.utils; + +import java.lang.management.ManagementFactory; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; +import java.util.Date; +import org.apache.commons.lang3.time.DateFormatUtils; + +public class DateUtils +extends org.apache.commons.lang3.time.DateUtils { + public static String YYYY = "yyyy"; + public static String YYYY_MM = "yyyy-MM"; + public static String YYYY_MM_DD = "yyyy-MM-dd"; + public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; + public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + private static String[] parsePatterns = new String[]{"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; + + public static Date getNowDate() { + return new Date(); + } + + public static String getDate() { + return DateUtils.dateTimeNow(YYYY_MM_DD); + } + + public static final String getTime() { + return DateUtils.dateTimeNow(YYYY_MM_DD_HH_MM_SS); + } + + public static final String dateTimeNow() { + return DateUtils.dateTimeNow(YYYYMMDDHHMMSS); + } + + public static final String dateTimeNow(String format) { + return DateUtils.parseDateToStr(format, new Date()); + } + + public static final String dateTime(Date date) { + return DateUtils.parseDateToStr(YYYY_MM_DD, date); + } + + public static final String parseDateToStr(String format, Date date) { + return new SimpleDateFormat(format).format(date); + } + + public static final Date dateTime(String format, String ts) { + try { + return new SimpleDateFormat(format).parse(ts); + } + catch (ParseException e) { + throw new RuntimeException(e); + } + } + + public static final String datePath() { + Date now = new Date(); + return DateFormatUtils.format((Date)now, (String)"yyyy/MM/dd"); + } + + public static final String dateTime() { + Date now = new Date(); + return DateFormatUtils.format((Date)now, (String)"yyyyMMdd"); + } + + public static Date parseDate(Object str) { + if (str == null) { + return null; + } + try { + return DateUtils.parseDate((String)str.toString(), (String[])parsePatterns); + } + catch (ParseException e) { + return null; + } + } + + public static Date getServerStartDate() { + long time = ManagementFactory.getRuntimeMXBean().getStartTime(); + return new Date(time); + } + + public static String getDatePoor(Date endDate, Date nowDate) { + long nd = 86400000L; + long nh = 3600000L; + long nm = 60000L; + long diff = endDate.getTime() - nowDate.getTime(); + long day = diff / nd; + long hour = diff % nd / nh; + long min = diff % nd % nh / nm; + return day + "\u5929" + hour + "\u5c0f\u65f6" + min + "\u5206\u949f"; + } + + public static String getFirstDayOfWeek(String date) { + try { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Calendar c = Calendar.getInstance(); + c.setTime(df.parse(date)); + if (c.get(7) == 1) { + c.add(5, -1); + } + c.add(5, c.getFirstDayOfWeek() - c.get(7) + 1); + return df.format(c.getTime()); + } + catch (Exception exception) { + return null; + } + } + + public static String getLastDayOfWeek(String date) { + try { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Calendar c = Calendar.getInstance(); + c.setTime(df.parse(date)); + if (c.get(7) == 1) { + return date; + } + c.add(5, 7 - c.get(7) + 1); + return df.format(c.getTime()); + } + catch (Exception exception) { + return null; + } + } + + public static String getFirstDayOfMonth(String strDate) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate date = LocalDate.parse(strDate, formatter); + LocalDate firstDayOfMonth = date.with(TemporalAdjusters.firstDayOfMonth()); + return formatter.format(firstDayOfMonth); + } + + public static String getLastDayOfMonth(String strDate) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate date = LocalDate.parse(strDate, formatter); + LocalDate lastDayOfMonth = date.with(TemporalAdjusters.lastDayOfMonth()); + return formatter.format(lastDayOfMonth); + } + + public static int getDaysOfMonth(String calcDate) { + try { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(df.parse(calcDate)); + return calendar.getActualMaximum(5); + } + catch (Exception ex) { + return 1; + } + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/DictUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/DictUtils.java new file mode 100644 index 0000000..d2ef57d --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/DictUtils.java @@ -0,0 +1,183 @@ +package net.hzvtc.common.utils; + +import java.util.Collection; +import java.util.List; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.domain.entity.SysDictData; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.utils.spring.SpringUtils; + +/** + * 字典工具类 + * + * @author admin + */ +public class DictUtils +{ + /** + * 分隔符 + */ + public static final String SEPARATOR = ","; + + /** + * 设置字典缓存 + * + * @param key 参数键 + * @param dictDatas 字典数据列表 + */ + public static void setDictCache(String key, List dictDatas) + { + SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas); + } + + /** + * 获取字典缓存 + * + * @param key 参数键 + * @return dictDatas 字典数据列表 + */ + public static List getDictCache(String key) + { + Object cacheObj = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key)); + if (StringUtils.isNotNull(cacheObj)) + { + List dictDatas = StringUtils.cast(cacheObj); + return dictDatas; + } + return null; + } + + /** + * 根据字典类型和字典值获取字典标签 + * + * @param dictType 字典类型 + * @param dictValue 字典值 + * @return 字典标签 + */ + public static String getDictLabel(String dictType, String dictValue) + { + return getDictLabel(dictType, dictValue, SEPARATOR); + } + + /** + * 根据字典类型和字典标签获取字典值 + * + * @param dictType 字典类型 + * @param dictLabel 字典标签 + * @return 字典值 + */ + public static String getDictValue(String dictType, String dictLabel) + { + return getDictValue(dictType, dictLabel, SEPARATOR); + } + + /** + * 根据字典类型和字典值获取字典标签 + * + * @param dictType 字典类型 + * @param dictValue 字典值 + * @param separator 分隔符 + * @return 字典标签 + */ + public static String getDictLabel(String dictType, String dictValue, String separator) + { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + + if (StringUtils.containsAny(separator, dictValue) && StringUtils.isNotEmpty(datas)) + { + for (SysDictData dict : datas) + { + for (String value : dictValue.split(separator)) + { + if (value.equals(dict.getDictValue())) + { + propertyString.append(dict.getDictLabel() + separator); + break; + } + } + } + } + else + { + for (SysDictData dict : datas) + { + if (dictValue.equals(dict.getDictValue())) + { + return dict.getDictLabel(); + } + } + } + return StringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 根据字典类型和字典标签获取字典值 + * + * @param dictType 字典类型 + * @param dictLabel 字典标签 + * @param separator 分隔符 + * @return 字典值 + */ + public static String getDictValue(String dictType, String dictLabel, String separator) + { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + + if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) + { + for (SysDictData dict : datas) + { + for (String label : dictLabel.split(separator)) + { + if (label.equals(dict.getDictLabel())) + { + propertyString.append(dict.getDictValue() + separator); + break; + } + } + } + } + else + { + for (SysDictData dict : datas) + { + if (dictLabel.equals(dict.getDictLabel())) + { + return dict.getDictValue(); + } + } + } + return StringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 删除指定字典缓存 + * + * @param key 字典键 + */ + public static void removeDictCache(String key) + { + SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key)); + } + + /** + * 清空字典缓存 + */ + public static void clearDictCache() + { + Collection keys = SpringUtils.getBean(RedisCache.class).keys(Constants.SYS_DICT_KEY + "*"); + SpringUtils.getBean(RedisCache.class).deleteObject(keys); + } + + /** + * 设置cache key + * + * @param configKey 参数键 + * @return 缓存键key + */ + public static String getCacheKey(String configKey) + { + return Constants.SYS_DICT_KEY + configKey; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/ExceptionUtil.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ExceptionUtil.java new file mode 100644 index 0000000..e50aa16 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ExceptionUtil.java @@ -0,0 +1,40 @@ +package net.hzvtc.common.utils; + +import java.io.PrintWriter; +import java.io.StringWriter; +import org.apache.commons.lang3.exception.ExceptionUtils; + +/** + * 错误信息处理类。 + * + * @author admin + */ +public class ExceptionUtil +{ + /** + * 获取exception的详细错误信息。 + */ + public static String getExceptionMessage(Throwable e) + { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw, true)); + String str = sw.toString(); + return str; + } + + public static String getRootErrorMessage(Exception e) + { + Throwable root = ExceptionUtils.getRootCause(e); + root = (root == null ? e : root); + if (root == null) + { + return ""; + } + String msg = root.getMessage(); + if (msg == null) + { + return "null"; + } + return StringUtils.defaultString(msg); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/LogUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/LogUtils.java new file mode 100644 index 0000000..f11aa4d --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/LogUtils.java @@ -0,0 +1,18 @@ +package net.hzvtc.common.utils; + +/** + * 处理并记录日志文件 + * + * @author admin + */ +public class LogUtils +{ + public static String getBlock(Object msg) + { + if (msg == null) + { + msg = ""; + } + return "[" + msg.toString() + "]"; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/MessageUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/MessageUtils.java new file mode 100644 index 0000000..4223028 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/MessageUtils.java @@ -0,0 +1,26 @@ +package net.hzvtc.common.utils; + +import net.hzvtc.common.utils.spring.SpringUtils; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +/** + * 获取i18n资源文件 + * + * @author admin + */ +public class MessageUtils +{ + /** + * 根据消息键和参数 获取消息 委托给spring messageSource + * + * @param code 消息键 + * @param args 参数 + * @return 获取国际化翻译值 + */ + public static String message(String code, Object... args) + { + MessageSource messageSource = SpringUtils.getBean(MessageSource.class); + return messageSource.getMessage(code, args, LocaleContextHolder.getLocale()); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/PageUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/PageUtils.java new file mode 100644 index 0000000..84d30be --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/PageUtils.java @@ -0,0 +1,38 @@ +package net.hzvtc.common.utils; + +import com.github.pagehelper.PageHelper; +import net.hzvtc.common.core.page.PageDomain; +import net.hzvtc.common.core.page.TableSupport; +import net.hzvtc.common.utils.sql.SqlUtil; + +/** + * 分页工具类 + * + * @author admin + */ +public class PageUtils extends PageHelper { + /** + * 设置请求分页数据 + */ + public static void startPage() { + PageDomain pageDomain = TableSupport.buildPageRequest(); + Integer pageNum = pageDomain.getPageNum(); + Integer pageSize = pageDomain.getPageSize(); + if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { + String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); + Boolean reasonable = pageDomain.getReasonable(); + PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable); + } + } + + public static void startPage(Integer pageNum, Integer pageSize) { + PageDomain pageDomain = TableSupport.buildPageRequest(); +// Integer pageNum = pageDomain.getPageNum(); +// Integer pageSize = pageDomain.getPageSize(); + if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { + String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); + Boolean reasonable = pageDomain.getReasonable(); + PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable); + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/SecurityUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/SecurityUtils.java new file mode 100644 index 0000000..1709326 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/SecurityUtils.java @@ -0,0 +1,99 @@ +package net.hzvtc.common.utils; + +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.exception.ServiceException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +/** + * 安全服务工具类 + * + * @author admin + */ +public class SecurityUtils { + /** + * 用户ID + **/ + public static Long getUserId() { + try { + return getLoginUser().getUserId(); + } catch (Exception e) { + throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED); + } + } + + /** + * 获取部门ID + **/ + public static Long getDeptId() { + try { + return getLoginUser().getDeptId(); + } catch (Exception e) { + throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED); + } + } + + /** + * 获取用户账户 + **/ + public static String getUsername() { + try { + return getLoginUser().getUsername(); + } catch (Exception e) { + throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED); + } + } + + /** + * 获取用户 + **/ + public static LoginUser getLoginUser() { + try { + return (LoginUser) getAuthentication().getPrincipal(); + } catch (Exception e) { + throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED); + } + } + + /** + * 获取Authentication + */ + public static Authentication getAuthentication() { + return SecurityContextHolder.getContext().getAuthentication(); + } + + /** + * 生成BCryptPasswordEncoder密码 + * + * @param password 密码 + * @return 加密字符串 + */ + public static String encryptPassword(String password) { + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + return passwordEncoder.encode(password); + } + + /** + * 判断密码是否相同 + * + * @param rawPassword 真实密码 + * @param encodedPassword 加密后字符 + * @return 结果 + */ + public static boolean matchesPassword(String rawPassword, String encodedPassword) { + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + return passwordEncoder.matches(rawPassword, encodedPassword); + } + + /** + * 是否为管理员 + * + * @param userId 用户ID + * @return 结果 + */ + public static boolean isAdmin(Long userId) { + return userId != null && (userId <= 1L); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/ServletUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ServletUtils.java new file mode 100644 index 0000000..ddf7696 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ServletUtils.java @@ -0,0 +1,152 @@ +package net.hzvtc.common.utils; + +import java.io.IOException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import net.hzvtc.common.core.text.Convert; + +/** + * 客户端工具类 + * + * @author admin + */ +public class ServletUtils +{ + /** + * 获取String参数 + */ + public static String getParameter(String name) + { + return getRequest().getParameter(name); + } + + /** + * 获取String参数 + */ + public static String getParameter(String name, String defaultValue) + { + return Convert.toStr(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name) + { + return Convert.toInt(getRequest().getParameter(name)); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name, Integer defaultValue) + { + return Convert.toInt(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取Boolean参数 + */ + public static Boolean getParameterToBool(String name) + { + return Convert.toBool(getRequest().getParameter(name)); + } + + /** + * 获取Boolean参数 + */ + public static Boolean getParameterToBool(String name, Boolean defaultValue) + { + return Convert.toBool(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取request + */ + public static HttpServletRequest getRequest() + { + return getRequestAttributes().getRequest(); + } + + /** + * 获取response + */ + public static HttpServletResponse getResponse() + { + return getRequestAttributes().getResponse(); + } + + /** + * 获取session + */ + public static HttpSession getSession() + { + return getRequest().getSession(); + } + + public static ServletRequestAttributes getRequestAttributes() + { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + return (ServletRequestAttributes) attributes; + } + + /** + * 将字符串渲染到客户端 + * + * @param response 渲染对象 + * @param string 待渲染的字符串 + * @return null + */ + public static String renderString(HttpServletResponse response, String string) + { + try + { + response.setStatus(200); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().print(string); + } + catch (IOException e) + { + e.printStackTrace(); + } + return null; + } + + /** + * 是否是Ajax异步请求 + * + * @param request + */ + public static boolean isAjaxRequest(HttpServletRequest request) + { + String accept = request.getHeader("accept"); + if (accept != null && accept.indexOf("application/json") != -1) + { + return true; + } + + String xRequestedWith = request.getHeader("X-Requested-With"); + if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) + { + return true; + } + + String uri = request.getRequestURI(); + if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) + { + return true; + } + + String ajax = request.getParameter("__ajax"); + if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) + { + return true; + } + return false; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/StringUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/StringUtils.java new file mode 100644 index 0000000..3808ccc --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/StringUtils.java @@ -0,0 +1,535 @@ +package net.hzvtc.common.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.hzvtc.common.constant.Constants; +import org.springframework.util.AntPathMatcher; +import net.hzvtc.common.core.text.StrFormatter; + +/** + * 字符串工具类 + * + * @author admin + */ +public class StringUtils extends org.apache.commons.lang3.StringUtils +{ + /** 空字符串 */ + private static final String NULLSTR = ""; + + /** 下划线 */ + private static final char SEPARATOR = '_'; + + /** + * 获取参数不为空值 + * + * @param value defaultValue 要判断的value + * @return value 返回值 + */ + public static T nvl(T value, T defaultValue) + { + return value != null ? value : defaultValue; + } + + /** + * * 判断一个Collection是否为空, 包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Collection coll) + { + return isNull(coll) || coll.isEmpty(); + } + + /** + * * 判断一个Collection是否非空,包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Collection coll) + { + return !isEmpty(coll); + } + + /** + * * 判断一个对象数组是否为空 + * + * @param objects 要判断的对象数组 + ** @return true:为空 false:非空 + */ + public static boolean isEmpty(Object[] objects) + { + return isNull(objects) || (objects.length == 0); + } + + /** + * * 判断一个对象数组是否非空 + * + * @param objects 要判断的对象数组 + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Object[] objects) + { + return !isEmpty(objects); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Map map) + { + return isNull(map) || map.isEmpty(); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Map map) + { + return !isEmpty(map); + } + + /** + * * 判断一个字符串是否为空串 + * + * @param str String + * @return true:为空 false:非空 + */ + public static boolean isEmpty(String str) + { + return isNull(str) || NULLSTR.equals(str.trim()); + } + + /** + * * 判断一个字符串是否为非空串 + * + * @param str String + * @return true:非空串 false:空串 + */ + public static boolean isNotEmpty(String str) + { + return !isEmpty(str); + } + + /** + * * 判断一个对象是否为空 + * + * @param object Object + * @return true:为空 false:非空 + */ + public static boolean isNull(Object object) + { + return object == null; + } + + /** + * * 判断一个对象是否非空 + * + * @param object Object + * @return true:非空 false:空 + */ + public static boolean isNotNull(Object object) + { + return !isNull(object); + } + + /** + * * 判断一个对象是否是数组类型(Java基本型别的数组) + * + * @param object 对象 + * @return true:是数组 false:不是数组 + */ + public static boolean isArray(Object object) + { + return isNotNull(object) && object.getClass().isArray(); + } + + /** + * 去空格 + */ + public static String trim(String str) + { + return (str == null ? "" : str.trim()); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @return 结果 + */ + public static String substring(final String str, int start) + { + if (str == null) + { + return NULLSTR; + } + + if (start < 0) + { + start = str.length() + start; + } + + if (start < 0) + { + start = 0; + } + if (start > str.length()) + { + return NULLSTR; + } + + return str.substring(start); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @param end 结束 + * @return 结果 + */ + public static String substring(final String str, int start, int end) + { + if (str == null) + { + return NULLSTR; + } + + if (end < 0) + { + end = str.length() + end; + } + if (start < 0) + { + start = str.length() + start; + } + + if (end > str.length()) + { + end = str.length(); + } + + if (start > end) + { + return NULLSTR; + } + + if (start < 0) + { + start = 0; + } + if (end < 0) + { + end = 0; + } + + return str.substring(start, end); + } + + /** + * 格式化文本, {} 表示占位符
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param template 文本模板,被替换的部分用 {} 表示 + * @param params 参数值 + * @return 格式化后的文本 + */ + public static String format(String template, Object... params) + { + if (isEmpty(params) || isEmpty(template)) + { + return template; + } + return StrFormatter.format(template, params); + } + + /** + * 是否为http(s)://开头 + * + * @param link 链接 + * @return 结果 + */ + public static boolean ishttp(String link) + { + return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS); + } + + /** + * 字符串转set + * + * @param str 字符串 + * @param sep 分隔符 + * @return set集合 + */ + public static final Set str2Set(String str, String sep) + { + return new HashSet(str2List(str, sep, true, false)); + } + + /** + * 字符串转list + * + * @param str 字符串 + * @param sep 分隔符 + * @param filterBlank 过滤纯空白 + * @param trim 去掉首尾空白 + * @return list集合 + */ + public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) + { + List list = new ArrayList(); + if (StringUtils.isEmpty(str)) + { + return list; + } + + // 过滤空白字符串 + if (filterBlank && StringUtils.isBlank(str)) + { + return list; + } + String[] split = str.split(sep); + for (String string : split) + { + if (filterBlank && StringUtils.isBlank(string)) + { + continue; + } + if (trim) + { + string = string.trim(); + } + list.add(string); + } + + return list; + } + + /** + * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写 + * + * @param cs 指定字符串 + * @param searchCharSequences 需要检查的字符串数组 + * @return 是否包含任意一个字符串 + */ + public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) + { + if (isEmpty(cs) || isEmpty(searchCharSequences)) + { + return false; + } + for (CharSequence testStr : searchCharSequences) + { + if (containsIgnoreCase(cs, testStr)) + { + return true; + } + } + return false; + } + + /** + * 驼峰转下划线命名 + */ + public static String toUnderScoreCase(String str) + { + if (str == null) + { + return null; + } + StringBuilder sb = new StringBuilder(); + // 前置字符是否大写 + boolean preCharIsUpperCase = true; + // 当前字符是否大写 + boolean curreCharIsUpperCase = true; + // 下一字符是否大写 + boolean nexteCharIsUpperCase = true; + for (int i = 0; i < str.length(); i++) + { + char c = str.charAt(i); + if (i > 0) + { + preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); + } + else + { + preCharIsUpperCase = false; + } + + curreCharIsUpperCase = Character.isUpperCase(c); + + if (i < (str.length() - 1)) + { + nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); + } + + if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) + { + sb.append(SEPARATOR); + } + else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) + { + sb.append(SEPARATOR); + } + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + /** + * 是否包含字符串 + * + * @param str 验证字符串 + * @param strs 字符串组 + * @return 包含返回true + */ + public static boolean inStringIgnoreCase(String str, String... strs) + { + if (str != null && strs != null) + { + for (String s : strs) + { + if (str.equalsIgnoreCase(trim(s))) + { + return true; + } + } + } + return false; + } + + /** + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld + * + * @param name 转换前的下划线大写方式命名的字符串 + * @return 转换后的驼峰式命名的字符串 + */ + public static String convertToCamelCase(String name) + { + StringBuilder result = new StringBuilder(); + // 快速检查 + if (name == null || name.isEmpty()) + { + // 没必要转换 + return ""; + } + else if (!name.contains("_")) + { + // 不含下划线,仅将首字母大写 + return name.substring(0, 1).toUpperCase() + name.substring(1); + } + // 用下划线将原始字符串分割 + String[] camels = name.split("_"); + for (String camel : camels) + { + // 跳过原始字符串中开头、结尾的下换线或双重下划线 + if (camel.isEmpty()) + { + continue; + } + // 首字母大写 + result.append(camel.substring(0, 1).toUpperCase()); + result.append(camel.substring(1).toLowerCase()); + } + return result.toString(); + } + + /** + * 驼峰式命名法 例如:user_name->userName + */ + public static String toCamelCase(String s) + { + if (s == null) + { + return null; + } + s = s.toLowerCase(); + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) + { + char c = s.charAt(i); + + if (c == SEPARATOR) + { + upperCase = true; + } + else if (upperCase) + { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } + else + { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 + * + * @param str 指定字符串 + * @param strs 需要检查的字符串数组 + * @return 是否匹配 + */ + public static boolean matches(String str, List strs) + { + if (isEmpty(str) || isEmpty(strs)) + { + return false; + } + for (String pattern : strs) + { + if (isMatch(pattern, str)) + { + return true; + } + } + return false; + } + + /** + * 判断url是否与规则配置: + * ? 表示单个字符; + * * 表示一层路径内的任意字符串,不可跨层级; + * ** 表示任意层路径; + * + * @param pattern 匹配规则 + * @param url 需要匹配的url + * @return + */ + public static boolean isMatch(String pattern, String url) + { + AntPathMatcher matcher = new AntPathMatcher(); + return matcher.match(pattern, url); + } + + @SuppressWarnings("unchecked") + public static T cast(Object obj) + { + return (T) obj; + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/Threads.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Threads.java new file mode 100644 index 0000000..cc85def --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/Threads.java @@ -0,0 +1,99 @@ +package net.hzvtc.common.utils; + +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 线程相关工具类. + * + * @author admin + */ +public class Threads +{ + private static final Logger logger = LoggerFactory.getLogger(Threads.class); + + /** + * sleep等待,单位为毫秒 + */ + public static void sleep(long milliseconds) + { + try + { + Thread.sleep(milliseconds); + } + catch (InterruptedException e) + { + return; + } + } + + /** + * 停止线程池 + * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务. + * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数. + * 如果仍然超時,則強制退出. + * 另对在shutdown时线程本身被调用中断做了处理. + */ + public static void shutdownAndAwaitTermination(ExecutorService pool) + { + if (pool != null && !pool.isShutdown()) + { + pool.shutdown(); + try + { + if (!pool.awaitTermination(120, TimeUnit.SECONDS)) + { + pool.shutdownNow(); + if (!pool.awaitTermination(120, TimeUnit.SECONDS)) + { + logger.info("Pool did not terminate"); + } + } + } + catch (InterruptedException ie) + { + pool.shutdownNow(); + Thread.currentThread().interrupt(); + } + } + } + + /** + * 打印线程异常信息 + */ + public static void printException(Runnable r, Throwable t) + { + if (t == null && r instanceof Future) + { + try + { + Future future = (Future) r; + if (future.isDone()) + { + future.get(); + } + } + catch (CancellationException ce) + { + t = ce; + } + catch (ExecutionException ee) + { + t = ee.getCause(); + } + catch (InterruptedException ie) + { + Thread.currentThread().interrupt(); + } + } + if (t != null) + { + logger.error(t.getMessage(), t); + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/VerifyCodeUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/VerifyCodeUtils.java new file mode 100644 index 0000000..39bdaf9 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/VerifyCodeUtils.java @@ -0,0 +1,228 @@ +package net.hzvtc.common.utils; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.geom.AffineTransform; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.OutputStream; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Random; +import javax.imageio.ImageIO; + +/** + * 验证码工具类 + * + * @author admin + */ +public class VerifyCodeUtils +{ + // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符 + public static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ"; + + private static Random random = new SecureRandom(); + + /** + * 使用系统默认字符源生成验证码 + * + * @param verifySize 验证码长度 + * @return + */ + public static String generateVerifyCode(int verifySize) + { + return generateVerifyCode(verifySize, VERIFY_CODES); + } + + /** + * 使用指定源生成验证码 + * + * @param verifySize 验证码长度 + * @param sources 验证码字符源 + * @return + */ + public static String generateVerifyCode(int verifySize, String sources) + { + if (sources == null || sources.length() == 0) + { + sources = VERIFY_CODES; + } + int codesLen = sources.length(); + Random rand = new Random(System.currentTimeMillis()); + StringBuilder verifyCode = new StringBuilder(verifySize); + for (int i = 0; i < verifySize; i++) + { + verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1))); + } + return verifyCode.toString(); + } + + /** + * 输出指定验证码图片流 + * + * @param w + * @param h + * @param os + * @param code + * @throws IOException + */ + public static void outputImage(int w, int h, OutputStream os, String code) throws IOException + { + int verifySize = code.length(); + BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + Random rand = new Random(); + Graphics2D g2 = image.createGraphics(); + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + Color[] colors = new Color[5]; + Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, + Color.ORANGE, Color.PINK, Color.YELLOW }; + float[] fractions = new float[colors.length]; + for (int i = 0; i < colors.length; i++) + { + colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; + fractions[i] = rand.nextFloat(); + } + Arrays.sort(fractions); + + g2.setColor(Color.GRAY);// 设置边框色 + g2.fillRect(0, 0, w, h); + + Color c = getRandColor(200, 250); + g2.setColor(c);// 设置背景色 + g2.fillRect(0, 2, w, h - 4); + + // 绘制干扰线 + Random random = new Random(); + g2.setColor(getRandColor(160, 200));// 设置线条的颜色 + for (int i = 0; i < 20; i++) + { + int x = random.nextInt(w - 1); + int y = random.nextInt(h - 1); + int xl = random.nextInt(6) + 1; + int yl = random.nextInt(12) + 1; + g2.drawLine(x, y, x + xl + 40, y + yl + 20); + } + + // 添加噪点 + float yawpRate = 0.05f;// 噪声率 + int area = (int) (yawpRate * w * h); + for (int i = 0; i < area; i++) + { + int x = random.nextInt(w); + int y = random.nextInt(h); + int rgb = getRandomIntColor(); + image.setRGB(x, y, rgb); + } + + shear(g2, w, h, c);// 使图片扭曲 + + g2.setColor(getRandColor(100, 160)); + int fontSize = h - 4; + Font font = new Font("Algerian", Font.ITALIC, fontSize); + g2.setFont(font); + char[] chars = code.toCharArray(); + for (int i = 0; i < verifySize; i++) + { + AffineTransform affine = new AffineTransform(); + affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), + (w / verifySize) * i + fontSize / 2, h / 2); + g2.setTransform(affine); + g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); + } + + g2.dispose(); + ImageIO.write(image, "jpg", os); + } + + private static Color getRandColor(int fc, int bc) + { + if (fc > 255) { + fc = 255; + } + if (bc > 255) { + bc = 255; + } + int r = fc + random.nextInt(bc - fc); + int g = fc + random.nextInt(bc - fc); + int b = fc + random.nextInt(bc - fc); + return new Color(r, g, b); + } + + private static int getRandomIntColor() + { + int[] rgb = getRandomRgb(); + int color = 0; + for (int c : rgb) + { + color = color << 8; + color = color | c; + } + return color; + } + + private static int[] getRandomRgb() + { + int[] rgb = new int[3]; + for (int i = 0; i < 3; i++) + { + rgb[i] = random.nextInt(255); + } + return rgb; + } + + private static void shear(Graphics g, int w1, int h1, Color color) + { + shearX(g, w1, h1, color); + shearY(g, w1, h1, color); + } + + private static void shearX(Graphics g, int w1, int h1, Color color) + { + + int period = random.nextInt(2); + + boolean borderGap = true; + int frames = 1; + int phase = random.nextInt(2); + + for (int i = 0; i < h1; i++) + { + double d = (double) (period >> 1) + * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); + g.copyArea(0, i, w1, 1, (int) d, 0); + if (borderGap) + { + g.setColor(color); + g.drawLine((int) d, i, 0, i); + g.drawLine((int) d + w1, i, w1, i); + } + } + + } + + private static void shearY(Graphics g, int w1, int h1, Color color) + { + + int period = random.nextInt(40) + 10; // 50; + + boolean borderGap = true; + int frames = 20; + int phase = 7; + for (int i = 0; i < w1; i++) + { + double d = (double) (period >> 1) + * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); + g.copyArea(i, 0, 1, h1, 0, (int) d); + if (borderGap) + { + g.setColor(color); + g.drawLine(i, (int) d, i, 0); + g.drawLine(i, (int) d + h1, i, h1); + } + + } + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanUtils.java new file mode 100644 index 0000000..7ca5d3b --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanUtils.java @@ -0,0 +1,110 @@ +package net.hzvtc.common.utils.bean; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Bean 工具类 + * + * @author admin + */ +public class BeanUtils extends org.springframework.beans.BeanUtils +{ + /** Bean方法名中属性名开始的下标 */ + private static final int BEAN_METHOD_PROP_INDEX = 3; + + /** * 匹配getter方法的正则表达式 */ + private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)"); + + /** * 匹配setter方法的正则表达式 */ + private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)"); + + /** + * Bean属性复制工具方法。 + * + * @param dest 目标对象 + * @param src 源对象 + */ + public static void copyBeanProp(Object dest, Object src) + { + try + { + copyProperties(src, dest); + } + catch (Exception e) + { + e.printStackTrace(); + } + } + + /** + * 获取对象的setter方法。 + * + * @param obj 对象 + * @return 对象的setter方法列表 + */ + public static List getSetterMethods(Object obj) + { + // setter方法列表 + List setterMethods = new ArrayList(); + + // 获取所有方法 + Method[] methods = obj.getClass().getMethods(); + + // 查找setter方法 + + for (Method method : methods) + { + Matcher m = SET_PATTERN.matcher(method.getName()); + if (m.matches() && (method.getParameterTypes().length == 1)) + { + setterMethods.add(method); + } + } + // 返回setter方法列表 + return setterMethods; + } + + /** + * 获取对象的getter方法。 + * + * @param obj 对象 + * @return 对象的getter方法列表 + */ + + public static List getGetterMethods(Object obj) + { + // getter方法列表 + List getterMethods = new ArrayList(); + // 获取所有方法 + Method[] methods = obj.getClass().getMethods(); + // 查找getter方法 + for (Method method : methods) + { + Matcher m = GET_PATTERN.matcher(method.getName()); + if (m.matches() && (method.getParameterTypes().length == 0)) + { + getterMethods.add(method); + } + } + // 返回getter方法列表 + return getterMethods; + } + + /** + * 检查Bean方法名中的属性名是否相等。
+ * 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。 + * + * @param m1 方法名1 + * @param m2 方法名2 + * @return 属性名一样返回true,否则返回false + */ + + public static boolean isMethodPropEquals(String m1, String m2) + { + return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX)); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanValidators.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanValidators.java new file mode 100644 index 0000000..c2f56a6 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/bean/BeanValidators.java @@ -0,0 +1,20 @@ +package net.hzvtc.common.utils.bean; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.Validator; +import java.util.Set; + +/** + * bean对象属性验证 + * + * @author admin + */ +public class BeanValidators { + public static void validateWithException(Validator validator, Object object, Class... groups) throws ConstraintViolationException { + Set> constraintViolations = validator.validate(object, groups); + if (!constraintViolations.isEmpty()) { + throw new ConstraintViolationException(constraintViolations); + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileTypeUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileTypeUtils.java new file mode 100644 index 0000000..21cb0f8 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileTypeUtils.java @@ -0,0 +1,76 @@ +package net.hzvtc.common.utils.file; + +import java.io.File; +import org.apache.commons.lang3.StringUtils; + +/** + * 文件类型工具类 + * + * @author admin + */ +public class FileTypeUtils +{ + /** + * 获取文件类型 + *

+ * 例如: .txt, 返回: txt + * + * @param file 文件名 + * @return 后缀(不含".") + */ + public static String getFileType(File file) + { + if (null == file) + { + return StringUtils.EMPTY; + } + return getFileType(file.getName()); + } + + /** + * 获取文件类型 + *

+ * 例如: .txt, 返回: txt + * + * @param fileName 文件名 + * @return 后缀(不含".") + */ + public static String getFileType(String fileName) + { + int separatorIndex = fileName.lastIndexOf("."); + if (separatorIndex < 0) + { + return ""; + } + return fileName.substring(separatorIndex + 1).toLowerCase(); + } + + /** + * 获取文件类型 + * + * @param photoByte 文件字节码 + * @return 后缀(不含".") + */ + public static String getFileExtendName(byte[] photoByte) + { + String strFileExtendName = "JPG"; + if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) + && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) + { + strFileExtendName = "GIF"; + } + else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) + { + strFileExtendName = "JPG"; + } + else if ((photoByte[0] == 66) && (photoByte[1] == 77)) + { + strFileExtendName = "BMP"; + } + else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) + { + strFileExtendName = "PNG"; + } + return strFileExtendName; + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUploadUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUploadUtils.java new file mode 100644 index 0000000..9d1eed2 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUploadUtils.java @@ -0,0 +1,239 @@ +package net.hzvtc.common.utils.file; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.exception.file.FileNameLengthLimitExceededException; +import net.hzvtc.common.exception.file.FileSizeLimitExceededException; +import net.hzvtc.common.exception.file.InvalidExtensionException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.uuid.IdUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.util.Objects; + +/** + * 文件上传工具类 + * + * @author admin + */ +public class FileUploadUtils { + /** + * 默认大小 50M + */ + public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; + + /** + * 默认的文件名最大长度 100 + */ + public static final int DEFAULT_FILE_NAME_LENGTH = 512; + + /** + * 默认上传的地址 + */ + private static String defaultBaseDir = AiBirdSysConfig.getProfile(); + + private static String birdMediaPath = AiBirdSysConfig.getBirdMediaPath(); + + public static String getBirdMediaPath() { + return birdMediaPath; + } + + + public static String getDefaultBaseDir() { + return defaultBaseDir; + } + + public static void setDefaultBaseDir(String defaultBaseDir) { + FileUploadUtils.defaultBaseDir = defaultBaseDir; + } + + /** + * 以默认配置进行文件上传 + * + * @param file 上传的文件 + * @return 文件名称 + * @throws Exception + */ + public static final String upload(MultipartFile file) throws IOException { + try { + return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } catch (Exception e) { + throw new IOException(e.getMessage(), e); + } + } + + /** + * 根据文件路径上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @return 文件名称 + * @throws IOException + */ + public static String upload(String baseDir, MultipartFile file) throws IOException { + try { + return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } catch (Exception e) { +// e.printStackTrace(); + throw new IOException(e.getMessage(), e); + } + } + + public static String uploadFromMobile(String baseDir, MultipartFile file) throws IOException { + try { + return uploadFromMobile(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); + } catch (Exception e) { +// e.printStackTrace(); + throw new IOException(e.getMessage(), e); + } + } + + public static String uploadFromMobile(String baseDir, MultipartFile file, String[] allowedExtension) + throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, + InvalidExtensionException { + assertAllowed(file, allowedExtension); + String fileName = extractFilename(file); + File desc = getAbsoluteFile(baseDir, fileName); + + FileUtils.copyInputStreamToFile(file.getInputStream(), desc); + String pathFileName = getPathFileName(baseDir, fileName); + return pathFileName; + } + + + /** + * 文件上传 + * + * @param baseDir 相对应用的基目录 + * @param file 上传的文件 + * @param allowedExtension 上传文件类型 + * @return 返回上传成功的文件名 + * @throws FileSizeLimitExceededException 如果超出最大大小 + * @throws FileNameLengthLimitExceededException 文件名太长 + * @throws IOException 比如读写文件出错时 + * @throws InvalidExtensionException 文件校验异常 + */ + public static String upload(String baseDir, MultipartFile file, String[] allowedExtension) + throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, + InvalidExtensionException { + int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length(); + if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { + throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); + } + + assertAllowed(file, allowedExtension); + String fileName = extractFilename(file); + File desc = getAbsoluteFile(baseDir, fileName); + file.transferTo(desc); + + return getPathFileName(baseDir, fileName); + } + + /** + * 编码文件名 + */ + public static final String extractFilename(MultipartFile file) { + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; + return fileName; + } + + public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { + File desc = new File(uploadDir + File.separator + fileName); + + if (!desc.exists()) { + if (!desc.getParentFile().exists()) { + desc.getParentFile().mkdirs(); + } + } + return desc; + } + + public static final String getPathFileName(String uploadDir, String fileName) throws IOException { +// System.out.println("===========uploadDir===========" + AiBirdSysConfig.getProfile()); + int dirLastIndex = AiBirdSysConfig.getProfile().length() + 1; +// System.out.println("===========uploadDir===========" + uploadDir); + String currentDir = StringUtils.substring(uploadDir, dirLastIndex); +// System.out.println("===========currentDir===========" + currentDir); + String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; + return pathFileName; + } + + /** + * 文件大小校验 + * + * @param file 上传的文件 + * @return + * @throws FileSizeLimitExceededException 如果超出最大大小 + * @throws InvalidExtensionException + */ + public static final void assertAllowed(MultipartFile file, String[] allowedExtension) + throws FileSizeLimitExceededException, InvalidExtensionException { + long size = file.getSize(); + if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) { + throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); + } + + String fileName = file.getOriginalFilename(); + String extension = getExtension(file); + if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) { + if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { + throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, + fileName); + } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { + throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, + fileName); + } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { + throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, + fileName); + } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) { + throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, + fileName); + } else { + throw new InvalidExtensionException(allowedExtension, extension, fileName); + } + } + + } + + /** + * 判断MIME类型是否是允许的MIME类型 + * + * @param extension + * @param allowedExtension + * @return + */ + public static final boolean isAllowedExtension(String extension, String[] allowedExtension) { + for (String str : allowedExtension) { + if (str.equalsIgnoreCase(extension)) { + return true; + } + } + return false; + } + + public static final String getOriginalFileName(MultipartFile file) { + String filename = FilenameUtils.getBaseName(file.getOriginalFilename()); + return filename; + } + + /** + * 获取文件名的后缀 + * + * @param file 表单文件 + * @return 后缀名 + */ + public static final String getExtension(MultipartFile file) { + String extension = FilenameUtils.getExtension(file.getOriginalFilename()); + if (StringUtils.isEmpty(extension)) { + extension = MimeTypeUtils.getExtension(file.getContentType()); + } + return extension; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUtils.java new file mode 100644 index 0000000..8a925a9 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/FileUtils.java @@ -0,0 +1,216 @@ +package net.hzvtc.common.utils.file; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.uuid.IdUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.ArrayUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * 文件处理工具类 + * + * @author admin + */ +public class FileUtils { + public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; + + /** + * 输出指定文件的byte数组 + * + * @param filePath 文件路径 + * @param os 输出流 + * @return + */ + public static void writeBytes(String filePath, OutputStream os) throws IOException { + FileInputStream fis = null; + try { + File file = new File(filePath); + if (!file.exists()) { + throw new FileNotFoundException(filePath); + } + fis = new FileInputStream(file); + byte[] b = new byte[1024]; + int length; + while ((length = fis.read(b)) > 0) { + os.write(b, 0, length); + } + } catch (IOException e) { + throw e; + } finally { + IOUtils.close(os); + IOUtils.close(fis); + } + } + + /** + * 写数据到文件中 + * + * @param data 数据 + * @return 目标文件 + * @throws IOException IO异常 + */ + public static String writeImportBytes(byte[] data) throws IOException { + return writeBytes(data, AiBirdSysConfig.getImportPath()); + } + + /** + * 写数据到文件中 + * + * @param data 数据 + * @param uploadDir 目标文件 + * @return 目标文件 + * @throws IOException IO异常 + */ + public static String writeBytes(byte[] data, String uploadDir) throws IOException { + FileOutputStream fos = null; + String pathName = ""; + try { + String extension = getFileExtendName(data); + pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; + File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); + fos = new FileOutputStream(file); + fos.write(data); + } finally { + IOUtils.close(fos); + } + return FileUploadUtils.getPathFileName(uploadDir, pathName); + } + + /** + * 删除文件 + * + * @param filePath 文件 + * @return + */ + public static boolean deleteFile(String filePath) { + boolean flag = false; + File file = new File(filePath); + // 路径为文件且不为空则进行删除 + if (file.isFile() && file.exists()) { + file.delete(); + flag = true; + } + return flag; + } + + /** + * 文件名称验证 + * + * @param filename 文件名称 + * @return true 正常 false 非法 + */ + public static boolean isValidFilename(String filename) { + return filename.matches(FILENAME_PATTERN); + } + + /** + * 检查文件是否可下载 + * + * @param resource 需要下载的文件 + * @return true 正常 false 非法 + */ + public static boolean checkAllowDownload(String resource) { + // 禁止目录上跳级别 + if (StringUtils.contains(resource, "..")) { + return false; + } + + // 检查允许下载的文件规则 + if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) { + return true; + } + + // 不在允许下载的文件规则 + return false; + } + + /** + * 下载文件名重新编码 + * + * @param request 请求对象 + * @param fileName 文件名 + * @return 编码后的文件名 + */ + public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException { + String agent = request.getHeader("USER-AGENT"); + String filename = fileName; + if (agent.contains("MSIE")) { + // IE浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + filename = filename.replace("+", " "); + } else if (agent.contains("Firefox")) { + // 火狐浏览器 + filename = new String(fileName.getBytes(), "ISO8859-1"); + } else if (agent.contains("Chrome")) { + // google浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } else { + // 其它浏览器 + filename = URLEncoder.encode(filename, "utf-8"); + } + return filename; + } + + /** + * 下载文件名重新编码 + * + * @param response 响应对象 + * @param realFileName 真实文件名 + * @return + */ + public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException { + String percentEncodedFileName = percentEncode(realFileName); + + StringBuilder contentDispositionValue = new StringBuilder(); + contentDispositionValue.append("attachment; filename=") + .append(percentEncodedFileName) + .append(";") + .append("filename*=") + .append("utf-8''") + .append(percentEncodedFileName); + + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename"); + response.setHeader("Content-disposition", contentDispositionValue.toString()); + response.setHeader("download-filename", percentEncodedFileName); + } + + /** + * 百分号编码工具方法 + * + * @param s 需要百分号编码的字符串 + * @return 百分号编码后的字符串 + */ + public static String percentEncode(String s) throws UnsupportedEncodingException { + String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString()); + return encode.replaceAll("\\+", "%20"); + } + + /** + * 获取图像后缀 + * + * @param photoByte 图像数据 + * @return 后缀名 + */ + public static String getFileExtendName(byte[] photoByte) { + String strFileExtendName = "jpg"; + if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) + && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) { + strFileExtendName = "gif"; + } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) { + strFileExtendName = "jpg"; + } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) { + strFileExtendName = "bmp"; + } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) { + strFileExtendName = "png"; + } + return strFileExtendName; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/ImageUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/ImageUtils.java new file mode 100644 index 0000000..69c60a2 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/ImageUtils.java @@ -0,0 +1,82 @@ +package net.hzvtc.common.utils.file; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.utils.StringUtils; +import org.apache.poi.util.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.util.Arrays; + +/** + * 图片处理工具类 + * + * @author admin + */ +public class ImageUtils { + private static final Logger log = LoggerFactory.getLogger(ImageUtils.class); + + public static byte[] getImage(String imagePath) { + InputStream is = getFile(imagePath); + try { + return IOUtils.toByteArray(is); + } catch (Exception e) { + log.error("图片加载异常 {}", e); + return null; + } finally { + IOUtils.closeQuietly(is); + } + } + + public static InputStream getFile(String imagePath) { + try { + byte[] result = readFile(imagePath); + result = Arrays.copyOf(result, result.length); + return new ByteArrayInputStream(result); + } catch (Exception e) { + log.error("获取图片异常 {}", e); + } + return null; + } + + /** + * 读取文件为字节数据 + * + * @param key 地址 + * @return 字节数据 + */ + public static byte[] readFile(String url) { + InputStream in = null; + ByteArrayOutputStream baos = null; + try { + if (url.startsWith("http")) { + // 网络地址 + URL urlObj = new URL(url); + URLConnection urlConnection = urlObj.openConnection(); + urlConnection.setConnectTimeout(30 * 1000); + urlConnection.setReadTimeout(60 * 1000); + urlConnection.setDoInput(true); + in = urlConnection.getInputStream(); + } else { + // 本机地址 + String localPath = AiBirdSysConfig.getProfile(); + String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX); + in = new FileInputStream(downloadPath); + } + return IOUtils.toByteArray(in); + } catch (Exception e) { + log.error("获取文件路径异常 {}", e); + return null; + } finally { + IOUtils.closeQuietly(in); + IOUtils.closeQuietly(baos); + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/MimeTypeUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/MimeTypeUtils.java new file mode 100644 index 0000000..18f4e0d --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/file/MimeTypeUtils.java @@ -0,0 +1,51 @@ +package net.hzvtc.common.utils.file; + +/** + * 媒体类型工具类 + * + * @author admin + */ +public class MimeTypeUtils { + public static final String IMAGE_PNG = "image/png"; + + public static final String IMAGE_JPG = "image/jpg"; + + public static final String IMAGE_JPEG = "image/jpeg"; + + public static final String IMAGE_BMP = "image/bmp"; + + public static final String IMAGE_GIF = "image/gif"; + + public static final String[] IMAGE_EXTENSION = {"bmp", "gif", "jpg", "jpeg", "png"}; + + public static final String[] FLASH_EXTENSION = {"swf", "flv"}; + + public static final String[] MEDIA_EXTENSION = {"swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", + "asf", "rm", "rmvb"}; + + public static final String[] VIDEO_EXTENSION = {"mp4", "avi", "rmvb"}; + + public static final String[] DEFAULT_ALLOWED_EXTENSION = { + "bmp", "gif", "jpg", "jpeg", "png", + "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt", + "rar", "zip", "7z", "gz", "bz2", + "mp4", "avi", "rmvb", "m4v", "wmv", + "mp3", "wav", "pdf"}; + + public static String getExtension(String prefix) { + switch (prefix) { + case IMAGE_PNG: + return "png"; + case IMAGE_JPG: + return "jpg"; + case IMAGE_JPEG: + return "jpeg"; + case IMAGE_BMP: + return "bmp"; + case IMAGE_GIF: + return "gif"; + default: + return ""; + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/EscapeUtil.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/EscapeUtil.java new file mode 100644 index 0000000..3082b0f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/EscapeUtil.java @@ -0,0 +1,167 @@ +package net.hzvtc.common.utils.html; + +import net.hzvtc.common.utils.StringUtils; + +/** + * 转义和反转义工具类 + * + * @author admin + */ +public class EscapeUtil +{ + public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)"; + + private static final char[][] TEXT = new char[64][]; + + static + { + for (int i = 0; i < 64; i++) + { + TEXT[i] = new char[] { (char) i }; + } + + // special HTML characters + TEXT['\''] = "'".toCharArray(); // 单引号 + TEXT['"'] = """.toCharArray(); // 双引号 + TEXT['&'] = "&".toCharArray(); // &符 + TEXT['<'] = "<".toCharArray(); // 小于号 + TEXT['>'] = ">".toCharArray(); // 大于号 + } + + /** + * 转义文本中的HTML字符为安全的字符 + * + * @param text 被转义的文本 + * @return 转义后的文本 + */ + public static String escape(String text) + { + return encode(text); + } + + /** + * 还原被转义的HTML特殊字符 + * + * @param content 包含转义符的HTML内容 + * @return 转换后的字符串 + */ + public static String unescape(String content) + { + return decode(content); + } + + /** + * 清除所有HTML标签,但是不删除标签内的内容 + * + * @param content 文本 + * @return 清除标签后的文本 + */ + public static String clean(String content) + { + return new HTMLFilter().filter(content); + } + + /** + * Escape编码 + * + * @param text 被编码的文本 + * @return 编码后的字符 + */ + private static String encode(String text) + { + if (StringUtils.isEmpty(text)) + { + return StringUtils.EMPTY; + } + + final StringBuilder tmp = new StringBuilder(text.length() * 6); + char c; + for (int i = 0; i < text.length(); i++) + { + c = text.charAt(i); + if (c < 256) + { + tmp.append("%"); + if (c < 16) + { + tmp.append("0"); + } + tmp.append(Integer.toString(c, 16)); + } + else + { + tmp.append("%u"); + if (c <= 0xfff) + { + // issue#I49JU8@Gitee + tmp.append("0"); + } + tmp.append(Integer.toString(c, 16)); + } + } + return tmp.toString(); + } + + /** + * Escape解码 + * + * @param content 被转义的内容 + * @return 解码后的字符串 + */ + public static String decode(String content) + { + if (StringUtils.isEmpty(content)) + { + return content; + } + + StringBuilder tmp = new StringBuilder(content.length()); + int lastPos = 0, pos = 0; + char ch; + while (lastPos < content.length()) + { + pos = content.indexOf("%", lastPos); + if (pos == lastPos) + { + if (content.charAt(pos + 1) == 'u') + { + ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16); + tmp.append(ch); + lastPos = pos + 6; + } + else + { + ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16); + tmp.append(ch); + lastPos = pos + 3; + } + } + else + { + if (pos == -1) + { + tmp.append(content.substring(lastPos)); + lastPos = content.length(); + } + else + { + tmp.append(content.substring(lastPos, pos)); + lastPos = pos; + } + } + } + return tmp.toString(); + } + + public static void main(String[] args) + { + String html = ""; + String escape = EscapeUtil.escape(html); + // String html = "ipt>alert(\"XSS\")ipt>"; + // String html = "<123"; + // String html = "123>"; + System.out.println("clean: " + EscapeUtil.clean(html)); + System.out.println("escape: " + escape); + System.out.println("unescape: " + EscapeUtil.unescape(escape)); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/HTMLFilter.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/HTMLFilter.java new file mode 100644 index 0000000..4b02d2d --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/html/HTMLFilter.java @@ -0,0 +1,570 @@ +package net.hzvtc.common.utils.html; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * HTML过滤器,用于去除XSS漏洞隐患。 + * + * @author admin + */ +public final class HTMLFilter +{ + /** + * regex flag union representing /si modifiers in php + **/ + private static final int REGEX_FLAGS_SI = Pattern.CASE_INSENSITIVE | Pattern.DOTALL; + private static final Pattern P_COMMENTS = Pattern.compile("", Pattern.DOTALL); + private static final Pattern P_COMMENT = Pattern.compile("^!--(.*)--$", REGEX_FLAGS_SI); + private static final Pattern P_TAGS = Pattern.compile("<(.*?)>", Pattern.DOTALL); + private static final Pattern P_END_TAG = Pattern.compile("^/([a-z0-9]+)", REGEX_FLAGS_SI); + private static final Pattern P_START_TAG = Pattern.compile("^([a-z0-9]+)(.*?)(/?)$", REGEX_FLAGS_SI); + private static final Pattern P_QUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)=([\"'])(.*?)\\2", REGEX_FLAGS_SI); + private static final Pattern P_UNQUOTED_ATTRIBUTES = Pattern.compile("([a-z0-9]+)(=)([^\"\\s']+)", REGEX_FLAGS_SI); + private static final Pattern P_PROTOCOL = Pattern.compile("^([^:]+):", REGEX_FLAGS_SI); + private static final Pattern P_ENTITY = Pattern.compile("&#(\\d+);?"); + private static final Pattern P_ENTITY_UNICODE = Pattern.compile("&#x([0-9a-f]+);?"); + private static final Pattern P_ENCODE = Pattern.compile("%([0-9a-f]{2});?"); + private static final Pattern P_VALID_ENTITIES = Pattern.compile("&([^&;]*)(?=(;|&|$))"); + private static final Pattern P_VALID_QUOTES = Pattern.compile("(>|^)([^<]+?)(<|$)", Pattern.DOTALL); + private static final Pattern P_END_ARROW = Pattern.compile("^>"); + private static final Pattern P_BODY_TO_END = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_XML_CONTENT = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_STRAY_LEFT_ARROW = Pattern.compile("<([^>]*?)(?=<|$)"); + private static final Pattern P_STRAY_RIGHT_ARROW = Pattern.compile("(^|>)([^<]*?)(?=>)"); + private static final Pattern P_AMP = Pattern.compile("&"); + private static final Pattern P_QUOTE = Pattern.compile("\""); + private static final Pattern P_LEFT_ARROW = Pattern.compile("<"); + private static final Pattern P_RIGHT_ARROW = Pattern.compile(">"); + private static final Pattern P_BOTH_ARROWS = Pattern.compile("<>"); + + // @xxx could grow large... maybe use sesat's ReferenceMap + private static final ConcurrentMap P_REMOVE_PAIR_BLANKS = new ConcurrentHashMap<>(); + private static final ConcurrentMap P_REMOVE_SELF_BLANKS = new ConcurrentHashMap<>(); + + /** + * set of allowed html elements, along with allowed attributes for each element + **/ + private final Map> vAllowed; + /** + * counts of open tags for each (allowable) html element + **/ + private final Map vTagCounts = new HashMap<>(); + + /** + * html elements which must always be self-closing (e.g. "") + **/ + private final String[] vSelfClosingTags; + /** + * html elements which must always have separate opening and closing tags (e.g. "") + **/ + private final String[] vNeedClosingTags; + /** + * set of disallowed html elements + **/ + private final String[] vDisallowed; + /** + * attributes which should be checked for valid protocols + **/ + private final String[] vProtocolAtts; + /** + * allowed protocols + **/ + private final String[] vAllowedProtocols; + /** + * tags which should be removed if they contain no content (e.g. "" or "") + **/ + private final String[] vRemoveBlanks; + /** + * entities allowed within html markup + **/ + private final String[] vAllowedEntities; + /** + * flag determining whether comments are allowed in input String. + */ + private final boolean stripComment; + private final boolean encodeQuotes; + /** + * flag determining whether to try to make tags when presented with "unbalanced" angle brackets (e.g. "" + * becomes " text "). If set to false, unbalanced angle brackets will be html escaped. + */ + private final boolean alwaysMakeTags; + + /** + * Default constructor. + */ + public HTMLFilter() + { + vAllowed = new HashMap<>(); + + final ArrayList a_atts = new ArrayList<>(); + a_atts.add("href"); + a_atts.add("target"); + vAllowed.put("a", a_atts); + + final ArrayList img_atts = new ArrayList<>(); + img_atts.add("src"); + img_atts.add("width"); + img_atts.add("height"); + img_atts.add("alt"); + vAllowed.put("img", img_atts); + + final ArrayList no_atts = new ArrayList<>(); + vAllowed.put("b", no_atts); + vAllowed.put("strong", no_atts); + vAllowed.put("i", no_atts); + vAllowed.put("em", no_atts); + + vSelfClosingTags = new String[] { "img" }; + vNeedClosingTags = new String[] { "a", "b", "strong", "i", "em" }; + vDisallowed = new String[] {}; + vAllowedProtocols = new String[] { "http", "mailto", "https" }; // no ftp. + vProtocolAtts = new String[] { "src", "href" }; + vRemoveBlanks = new String[] { "a", "b", "strong", "i", "em" }; + vAllowedEntities = new String[] { "amp", "gt", "lt", "quot" }; + stripComment = true; + encodeQuotes = true; + alwaysMakeTags = false; + } + + /** + * Map-parameter configurable constructor. + * + * @param conf map containing configuration. keys match field names. + */ + @SuppressWarnings("unchecked") + public HTMLFilter(final Map conf) + { + + assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; + assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; + assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; + assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; + assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; + assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; + assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; + assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; + + vAllowed = Collections.unmodifiableMap((HashMap>) conf.get("vAllowed")); + vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); + vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); + vDisallowed = (String[]) conf.get("vDisallowed"); + vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); + vProtocolAtts = (String[]) conf.get("vProtocolAtts"); + vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); + vAllowedEntities = (String[]) conf.get("vAllowedEntities"); + stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; + encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; + alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; + } + + private void reset() + { + vTagCounts.clear(); + } + + // --------------------------------------------------------------- + // my versions of some PHP library functions + public static String chr(final int decimal) + { + return String.valueOf((char) decimal); + } + + public static String htmlSpecialChars(final String s) + { + String result = s; + result = regexReplace(P_AMP, "&", result); + result = regexReplace(P_QUOTE, """, result); + result = regexReplace(P_LEFT_ARROW, "<", result); + result = regexReplace(P_RIGHT_ARROW, ">", result); + return result; + } + + // --------------------------------------------------------------- + + /** + * given a user submitted input String, filter out any invalid or restricted html. + * + * @param input text (i.e. submitted by a user) than may contain html + * @return "clean" version of input, with only valid, whitelisted html elements allowed + */ + public String filter(final String input) + { + reset(); + String s = input; + + s = escapeComments(s); + + s = balanceHTML(s); + + s = checkTags(s); + + s = processRemoveBlanks(s); + + // s = validateEntities(s); + + return s; + } + + public boolean isAlwaysMakeTags() + { + return alwaysMakeTags; + } + + public boolean isStripComments() + { + return stripComment; + } + + private String escapeComments(final String s) + { + final Matcher m = P_COMMENTS.matcher(s); + final StringBuffer buf = new StringBuffer(); + if (m.find()) + { + final String match = m.group(1); // (.*?) + m.appendReplacement(buf, Matcher.quoteReplacement("")); + } + m.appendTail(buf); + + return buf.toString(); + } + + private String balanceHTML(String s) + { + if (alwaysMakeTags) + { + // + // try and form html + // + s = regexReplace(P_END_ARROW, "", s); + // 不追加结束标签 + s = regexReplace(P_BODY_TO_END, "<$1>", s); + s = regexReplace(P_XML_CONTENT, "$1<$2", s); + + } + else + { + // + // escape stray brackets + // + s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); + s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); + + // + // the last regexp causes '<>' entities to appear + // (we need to do a lookahead assertion so that the last bracket can + // be used in the next pass of the regexp) + // + s = regexReplace(P_BOTH_ARROWS, "", s); + } + + return s; + } + + private String checkTags(String s) + { + Matcher m = P_TAGS.matcher(s); + + final StringBuffer buf = new StringBuffer(); + while (m.find()) + { + String replaceStr = m.group(1); + replaceStr = processTag(replaceStr); + m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); + } + m.appendTail(buf); + + // these get tallied in processTag + // (remember to reset before subsequent calls to filter method) + final StringBuilder sBuilder = new StringBuilder(buf.toString()); + for (String key : vTagCounts.keySet()) + { + for (int ii = 0; ii < vTagCounts.get(key); ii++) + { + sBuilder.append(""); + } + } + s = sBuilder.toString(); + + return s; + } + + private String processRemoveBlanks(final String s) + { + String result = s; + for (String tag : vRemoveBlanks) + { + if (!P_REMOVE_PAIR_BLANKS.containsKey(tag)) + { + P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?>")); + } + result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); + if (!P_REMOVE_SELF_BLANKS.containsKey(tag)) + { + P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); + } + result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); + } + + return result; + } + + private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) + { + Matcher m = regex_pattern.matcher(s); + return m.replaceAll(replacement); + } + + private String processTag(final String s) + { + // ending tags + Matcher m = P_END_TAG.matcher(s); + if (m.find()) + { + final String name = m.group(1).toLowerCase(); + if (allowed(name)) + { + if (!inArray(name, vSelfClosingTags)) + { + if (vTagCounts.containsKey(name)) + { + vTagCounts.put(name, vTagCounts.get(name) - 1); + return ""; + } + } + } + } + + // starting tags + m = P_START_TAG.matcher(s); + if (m.find()) + { + final String name = m.group(1).toLowerCase(); + final String body = m.group(2); + String ending = m.group(3); + + // debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); + if (allowed(name)) + { + final StringBuilder params = new StringBuilder(); + + final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); + final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); + final List paramNames = new ArrayList<>(); + final List paramValues = new ArrayList<>(); + while (m2.find()) + { + paramNames.add(m2.group(1)); // ([a-z0-9]+) + paramValues.add(m2.group(3)); // (.*?) + } + while (m3.find()) + { + paramNames.add(m3.group(1)); // ([a-z0-9]+) + paramValues.add(m3.group(3)); // ([^\"\\s']+) + } + + String paramName, paramValue; + for (int ii = 0; ii < paramNames.size(); ii++) + { + paramName = paramNames.get(ii).toLowerCase(); + paramValue = paramValues.get(ii); + + // debug( "paramName='" + paramName + "'" ); + // debug( "paramValue='" + paramValue + "'" ); + // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); + + if (allowedAttribute(name, paramName)) + { + if (inArray(paramName, vProtocolAtts)) + { + paramValue = processParamProtocol(paramValue); + } + params.append(' ').append(paramName).append("=\\\"").append(paramValue).append("\""); + } + } + + if (inArray(name, vSelfClosingTags)) + { + ending = " /"; + } + + if (inArray(name, vNeedClosingTags)) + { + ending = ""; + } + + if (ending == null || ending.length() < 1) + { + if (vTagCounts.containsKey(name)) + { + vTagCounts.put(name, vTagCounts.get(name) + 1); + } + else + { + vTagCounts.put(name, 1); + } + } + else + { + ending = " /"; + } + return "<" + name + params + ending + ">"; + } + else + { + return ""; + } + } + + // comments + m = P_COMMENT.matcher(s); + if (!stripComment && m.find()) + { + return "<" + m.group() + ">"; + } + + return ""; + } + + private String processParamProtocol(String s) + { + s = decodeEntities(s); + final Matcher m = P_PROTOCOL.matcher(s); + if (m.find()) + { + final String protocol = m.group(1); + if (!inArray(protocol, vAllowedProtocols)) + { + // bad protocol, turn into local anchor link instead + s = "#" + s.substring(protocol.length() + 1); + if (s.startsWith("#//")) + { + s = "#" + s.substring(3); + } + } + } + + return s; + } + + private String decodeEntities(String s) + { + StringBuffer buf = new StringBuffer(); + + Matcher m = P_ENTITY.matcher(s); + while (m.find()) + { + final String match = m.group(1); + final int decimal = Integer.decode(match).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + buf = new StringBuffer(); + m = P_ENTITY_UNICODE.matcher(s); + while (m.find()) + { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + buf = new StringBuffer(); + m = P_ENCODE.matcher(s); + while (m.find()) + { + final String match = m.group(1); + final int decimal = Integer.valueOf(match, 16).intValue(); + m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); + } + m.appendTail(buf); + s = buf.toString(); + + s = validateEntities(s); + return s; + } + + private String validateEntities(final String s) + { + StringBuffer buf = new StringBuffer(); + + // validate entities throughout the string + Matcher m = P_VALID_ENTITIES.matcher(s); + while (m.find()) + { + final String one = m.group(1); // ([^&;]*) + final String two = m.group(2); // (?=(;|&|$)) + m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); + } + m.appendTail(buf); + + return encodeQuotes(buf.toString()); + } + + private String encodeQuotes(final String s) + { + if (encodeQuotes) + { + StringBuffer buf = new StringBuffer(); + Matcher m = P_VALID_QUOTES.matcher(s); + while (m.find()) + { + final String one = m.group(1); // (>|^) + final String two = m.group(2); // ([^<]+?) + final String three = m.group(3); // (<|$) + // 不替换双引号为",防止json格式无效 regexReplace(P_QUOTE, """, two) + m.appendReplacement(buf, Matcher.quoteReplacement(one + two + three)); + } + m.appendTail(buf); + return buf.toString(); + } + else + { + return s; + } + } + + private String checkEntity(final String preamble, final String term) + { + + return ";".equals(term) && isValidEntity(preamble) ? '&' + preamble : "&" + preamble; + } + + private boolean isValidEntity(final String entity) + { + return inArray(entity, vAllowedEntities); + } + + private static boolean inArray(final String s, final String[] array) + { + for (String item : array) + { + if (item != null && item.equals(s)) + { + return true; + } + } + return false; + } + + private boolean allowed(final String name) + { + return (vAllowed.isEmpty() || vAllowed.containsKey(name)) && !inArray(name, vDisallowed); + } + + private boolean allowedAttribute(final String name, final String paramName) + { + return allowed(name) && (vAllowed.isEmpty() || vAllowed.get(name).contains(paramName)); + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpHelper.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpHelper.java new file mode 100644 index 0000000..8de1afe --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpHelper.java @@ -0,0 +1,55 @@ +package net.hzvtc.common.utils.http; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import javax.servlet.ServletRequest; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 通用http工具封装 + * + * @author admin + */ +public class HttpHelper +{ + private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class); + + public static String getBodyString(ServletRequest request) + { + StringBuilder sb = new StringBuilder(); + BufferedReader reader = null; + try (InputStream inputStream = request.getInputStream()) + { + reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); + String line = ""; + while ((line = reader.readLine()) != null) + { + sb.append(line); + } + } + catch (IOException e) + { + LOGGER.warn("getBodyString出现问题!"); + } + finally + { + if (reader != null) + { + try + { + reader.close(); + } + catch (IOException e) + { + LOGGER.error(ExceptionUtils.getMessage(e)); + } + } + } + return sb.toString(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpUtils.java new file mode 100644 index 0000000..71741aa --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/http/HttpUtils.java @@ -0,0 +1,212 @@ +package net.hzvtc.common.utils.http; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.utils.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.*; +import java.io.*; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLConnection; +import java.security.cert.X509Certificate; + +/** + * 通用http发送方法 + * + * @author admin + */ +public class HttpUtils { + private static final Logger log = LoggerFactory.getLogger(HttpUtils.class); + + /** + * 向指定 URL 发送GET方法的请求 + * + * @param url 发送请求的 URL + * @return 所代表远程资源的响应结果 + */ + public static String sendGet(String url) { + return sendGet(url, StringUtils.EMPTY); + } + + /** + * 向指定 URL 发送GET方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendGet(String url, String param) { + return sendGet(url, param, Constants.UTF8); + } + + /** + * 向指定 URL 发送GET方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @param contentType 编码类型 + * @return 所代表远程资源的响应结果 + */ + public static String sendGet(String url, String param, String contentType) { + StringBuilder result = new StringBuilder(); + BufferedReader in = null; + try { + String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url; + log.info("sendGet - {}", urlNameString); + URL realUrl = new URL(urlNameString); + URLConnection connection = realUrl.openConnection(); + connection.setRequestProperty("accept", "*/*"); + connection.setRequestProperty("connection", "Keep-Alive"); + connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + connection.connect(); + in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType)); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + log.info("recv - {}", result); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e); + } finally { + try { + if (in != null) { + in.close(); + } + } catch (Exception ex) { + log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); + } + } + return result.toString(); + } + + /** + * 向指定 URL 发送POST方法的请求 + * + * @param url 发送请求的 URL + * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 + * @return 所代表远程资源的响应结果 + */ + public static String sendPost(String url, String param) { + PrintWriter out = null; + BufferedReader in = null; + StringBuilder result = new StringBuilder(); + try { + String urlNameString = url; + log.info("sendPost - {}", urlNameString); + URL realUrl = new URL(urlNameString); + URLConnection conn = realUrl.openConnection(); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("Accept-Charset", "utf-8"); + conn.setRequestProperty("contentType", "utf-8"); + conn.setDoOutput(true); + conn.setDoInput(true); + out = new PrintWriter(conn.getOutputStream()); + out.print(param); + out.flush(); + in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); + String line; + while ((line = in.readLine()) != null) { + result.append(line); + } + log.info("recv - {}", result); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e); + } finally { + try { + if (out != null) { + out.close(); + } + if (in != null) { + in.close(); + } + } catch (IOException ex) { + log.error("调用in.close Exception, url=" + url + ",param=" + param, ex); + } + } + return result.toString(); + } + + public static String sendSSLPost(String url, String param) { + StringBuilder result = new StringBuilder(); + String urlNameString = url + "?" + param; + try { + log.info("sendSSLPost - {}", urlNameString); + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); + URL console = new URL(urlNameString); + HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); + conn.setRequestProperty("accept", "*/*"); + conn.setRequestProperty("connection", "Keep-Alive"); + conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); + conn.setRequestProperty("Accept-Charset", "utf-8"); + conn.setRequestProperty("contentType", "utf-8"); + conn.setDoOutput(true); + conn.setDoInput(true); + + conn.setSSLSocketFactory(sc.getSocketFactory()); + conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); + conn.connect(); + InputStream is = conn.getInputStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(is)); + String ret = ""; + while ((ret = br.readLine()) != null) { + if (ret != null && !"".equals(ret.trim())) { + result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8")); + } + } + log.info("recv - {}", result); + conn.disconnect(); + br.close(); + } catch (ConnectException e) { + log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e); + } catch (SocketTimeoutException e) { + log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e); + } catch (IOException e) { + log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e); + } catch (Exception e) { + log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e); + } + return result.toString(); + } + + private static class TrustAnyTrustManager implements X509TrustManager { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[]{}; + } + } + + private static class TrustAnyHostnameVerifier implements HostnameVerifier { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + } + + +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/AddressUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/AddressUtils.java new file mode 100644 index 0000000..4733f22 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/AddressUtils.java @@ -0,0 +1,46 @@ +package net.hzvtc.common.utils.ip; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.http.HttpUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 获取地址类 + * + * @author admin + */ +public class AddressUtils { + // IP地址查询 + public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"; + // 未知地址 + public static final String UNKNOWN = "XX XX"; + private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); + + public static String getRealAddressByIP(String ip) { + String address = UNKNOWN; + // 内网不查询 + if (IpUtils.internalIp(ip)) { + return "内网IP"; + } + if (AiBirdSysConfig.isAddressEnabled()) { + try { + String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK); + if (StringUtils.isEmpty(rspStr)) { + log.error("获取地理位置异常 {}", ip); + return UNKNOWN; + } + JSONObject obj = JSONObject.parseObject(rspStr); + String region = obj.getString("pro"); + String city = obj.getString("city"); + return String.format("%s %s", region, city); + } catch (Exception e) { + log.error("获取地理位置异常 {}", ip); + } + } + return address; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/IpUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/IpUtils.java new file mode 100644 index 0000000..a4d2e3f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/ip/IpUtils.java @@ -0,0 +1,195 @@ +package net.hzvtc.common.utils.ip; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import javax.servlet.http.HttpServletRequest; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.html.EscapeUtil; + +/** + * 获取IP方法 + * + * @author admin + */ +public class IpUtils +{ + 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)) + { + ip = request.getHeader("Proxy-Client-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)) + { + ip = request.getHeader("WL-Proxy-Client-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)) + { + ip = request.getRemoteAddr(); + } + return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : EscapeUtil.clean(ip); + } + + public static boolean internalIp(String ip) + { + byte[] addr = textToNumericFormatV4(ip); + return internalIp(addr) || "127.0.0.1".equals(ip); + } + + private static boolean internalIp(byte[] addr) + { + if (StringUtils.isNull(addr) || addr.length < 2) + { + return true; + } + final byte b0 = addr[0]; + final byte b1 = addr[1]; + // 10.x.x.x/8 + final byte SECTION_1 = 0x0A; + // 172.16.x.x/12 + final byte SECTION_2 = (byte) 0xAC; + final byte SECTION_3 = (byte) 0x10; + final byte SECTION_4 = (byte) 0x1F; + // 192.168.x.x/16 + final byte SECTION_5 = (byte) 0xC0; + final byte SECTION_6 = (byte) 0xA8; + switch (b0) + { + case SECTION_1: + return true; + case SECTION_2: + if (b1 >= SECTION_3 && b1 <= SECTION_4) + { + return true; + } + case SECTION_5: + switch (b1) + { + case SECTION_6: + return true; + } + default: + return false; + } + } + + /** + * 将IPv4地址转换成字节 + * + * @param text IPv4地址 + * @return byte 字节 + */ + public static byte[] textToNumericFormatV4(String text) + { + if (text.length() == 0) + { + return null; + } + + byte[] bytes = new byte[4]; + String[] elements = text.split("\\.", -1); + try + { + long l; + int i; + switch (elements.length) + { + case 1: + l = Long.parseLong(elements[0]); + if ((l < 0L) || (l > 4294967295L)) { + return null; + } + bytes[0] = (byte) (int) (l >> 24 & 0xFF); + bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF); + bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); + bytes[3] = (byte) (int) (l & 0xFF); + break; + case 2: + l = Integer.parseInt(elements[0]); + if ((l < 0L) || (l > 255L)) { + return null; + } + bytes[0] = (byte) (int) (l & 0xFF); + l = Integer.parseInt(elements[1]); + if ((l < 0L) || (l > 16777215L)) { + return null; + } + bytes[1] = (byte) (int) (l >> 16 & 0xFF); + bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF); + bytes[3] = (byte) (int) (l & 0xFF); + break; + case 3: + for (i = 0; i < 2; ++i) + { + l = Integer.parseInt(elements[i]); + if ((l < 0L) || (l > 255L)) { + return null; + } + bytes[i] = (byte) (int) (l & 0xFF); + } + l = Integer.parseInt(elements[2]); + 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) + { + l = Integer.parseInt(elements[i]); + if ((l < 0L) || (l > 255L)) { + return null; + } + bytes[i] = (byte) (int) (l & 0xFF); + } + break; + default: + return null; + } + } + catch (NumberFormatException e) + { + return null; + } + return bytes; + } + + public static String getHostIp() + { + try + { + return InetAddress.getLocalHost().getHostAddress(); + } + catch (UnknownHostException e) + { + } + return "127.0.0.1"; + } + + public static String getHostName() + { + try + { + return InetAddress.getLocalHost().getHostName(); + } + catch (UnknownHostException e) + { + } + return "未知"; + } +} \ No newline at end of file diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelHandlerAdapter.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelHandlerAdapter.java new file mode 100644 index 0000000..eaf875e --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelHandlerAdapter.java @@ -0,0 +1,7 @@ +package net.hzvtc.common.utils.poi; + +public interface ExcelHandlerAdapter { + public Object format(Object var1, String[] var2); +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelUtil.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelUtil.java new file mode 100644 index 0000000..9f3d60e --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/poi/ExcelUtil.java @@ -0,0 +1,785 @@ +package net.hzvtc.common.utils.poi; + +import java.io.Closeable; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.annotation.Excels; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.common.exception.UtilException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.DictUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.file.FileTypeUtils; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.common.utils.file.ImageUtils; +import net.hzvtc.common.utils.poi.ExcelHandlerAdapter; +import net.hzvtc.common.utils.reflect.ReflectUtils; +import org.apache.poi.hssf.usermodel.HSSFClientAnchor; +import org.apache.poi.hssf.usermodel.HSSFPicture; +import org.apache.poi.hssf.usermodel.HSSFPictureData; +import org.apache.poi.hssf.usermodel.HSSFShape; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ooxml.POIXMLDocumentPart; +import org.apache.poi.ss.usermodel.BorderStyle; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.DataValidation; +import org.apache.poi.ss.usermodel.DataValidationConstraint; +import org.apache.poi.ss.usermodel.DataValidationHelper; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.Drawing; +import org.apache.poi.ss.usermodel.FillPatternType; +import org.apache.poi.ss.usermodel.Font; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.PictureData; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.VerticalAlignment; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.util.IOUtils; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFClientAnchor; +import org.apache.poi.xssf.usermodel.XSSFDataValidation; +import org.apache.poi.xssf.usermodel.XSSFDrawing; +import org.apache.poi.xssf.usermodel.XSSFPicture; +import org.apache.poi.xssf.usermodel.XSSFShape; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ExcelUtil { + public static final String[] FORMULA_STR = new String[]{"=", "-", "+", "@"}; + public static final int sheetSize = 65536; + private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class); + private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); + public Class clazz; + private String sheetName; + private Excel.Type type; + private Workbook wb; + private Sheet sheet; + private Map styles; + private List list; + private List fields; + private int rownum; + private String title; + private short maxHeight; + private Map statistics = new HashMap(); + + public ExcelUtil(Class clazz) { + this.clazz = clazz; + } + + public static Drawing getDrawingPatriarch(Sheet sheet) { + if (sheet.getDrawingPatriarch() == null) { + sheet.createDrawingPatriarch(); + } + return sheet.getDrawingPatriarch(); + } + + public static String convertByExp(String propertyValue, String converterExp, String separator) { + String[] convertSource; + StringBuilder propertyString = new StringBuilder(); + block0: for (String item : convertSource = converterExp.split(",")) { + String[] itemArray = item.split("="); + if (StringUtils.containsAny((CharSequence)separator, (CharSequence)propertyValue)) { + for (String value : propertyValue.split(separator)) { + if (!itemArray[0].equals(value)) continue; + propertyString.append(itemArray[1] + separator); + continue block0; + } + continue; + } + if (!itemArray[0].equals(propertyValue)) continue; + return itemArray[1]; + } + return StringUtils.stripEnd((String)propertyString.toString(), (String)separator); + } + + public static String reverseByExp(String propertyValue, String converterExp, String separator) { + String[] convertSource; + StringBuilder propertyString = new StringBuilder(); + block0: for (String item : convertSource = converterExp.split(",")) { + String[] itemArray = item.split("="); + if (StringUtils.containsAny((CharSequence)separator, (CharSequence)propertyValue)) { + for (String value : propertyValue.split(separator)) { + if (!itemArray[1].equals(value)) continue; + propertyString.append(itemArray[0] + separator); + continue block0; + } + continue; + } + if (!itemArray[1].equals(propertyValue)) continue; + return itemArray[0]; + } + return StringUtils.stripEnd((String)propertyString.toString(), (String)separator); + } + + public static String convertDictByExp(String dictValue, String dictType, String separator) { + return DictUtils.getDictLabel(dictType, dictValue, separator); + } + + public static String reverseDictByExp(String dictLabel, String dictType, String separator) { + return DictUtils.getDictValue(dictType, dictLabel, separator); + } + + public static Map getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook) { + HashMap sheetIndexPicMap = new HashMap(); + List pictures = workbook.getAllPictures(); + if (!pictures.isEmpty()) { + for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) { + HSSFClientAnchor anchor = (HSSFClientAnchor)shape.getAnchor(); + if (!(shape instanceof HSSFPicture)) continue; + HSSFPicture pic = (HSSFPicture)shape; + int pictureIndex = pic.getPictureIndex() - 1; + HSSFPictureData picData = (HSSFPictureData)pictures.get(pictureIndex); + String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1()); + sheetIndexPicMap.put(picIndex, (PictureData)picData); + } + return sheetIndexPicMap; + } + return sheetIndexPicMap; + } + + public static Map getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook) { + HashMap sheetIndexPicMap = new HashMap(); + for (POIXMLDocumentPart dr : sheet.getRelations()) { + if (!(dr instanceof XSSFDrawing)) continue; + XSSFDrawing drawing = (XSSFDrawing)dr; + List shapes = drawing.getShapes(); + for (XSSFShape shape : shapes) { + if (!(shape instanceof XSSFPicture)) continue; + XSSFPicture pic = (XSSFPicture)shape; + XSSFClientAnchor anchor = pic.getPreferredSize(); + CTMarker ctMarker = anchor.getFrom(); + String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol(); + sheetIndexPicMap.put(picIndex, (PictureData)pic.getPictureData()); + } + } + return sheetIndexPicMap; + } + + public void init(List list, String sheetName, String title, Excel.Type type) { + if (list == null) { + list = new ArrayList(); + } + this.list = list; + this.sheetName = sheetName; + this.type = type; + this.title = title; + this.createExcelField(); + this.createWorkbook(); + this.createTitle(); + } + + public void createTitle() { + if (StringUtils.isNotEmpty(this.title)) { + int n; + if (this.rownum == 0) { + int n2 = this.rownum; + n = n2; + this.rownum = n2 + 1; + } else { + n = 0; + } + Row titleRow = this.sheet.createRow(n); + titleRow.setHeightInPoints(30.0f); + Cell titleCell = titleRow.createCell(0); + titleCell.setCellStyle(this.styles.get("title")); + titleCell.setCellValue(this.title); + this.sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), this.fields.size() - 1)); + } + } + + public List importExcel(InputStream is) throws Exception { + return this.importExcel(is, 0); + } + + public List importExcel(InputStream is, int titleNum) throws Exception { + return this.importExcel("", is, titleNum); + } + + public List importExcel(String sheetName, InputStream is, int titleNum) throws Exception { + Sheet sheet; + this.type = Excel.Type.IMPORT; + this.wb = WorkbookFactory.create((InputStream)is); + ArrayList list = new ArrayList(); + Sheet sheet2 = sheet = StringUtils.isNotEmpty(sheetName) ? this.wb.getSheet(sheetName) : this.wb.getSheetAt(0); + if (sheet == null) { + throw new IOException("\u6587\u4ef6sheet\u4e0d\u5b58\u5728"); + } + boolean isXSSFWorkbook = !(this.wb instanceof HSSFWorkbook); + Map pictures = isXSSFWorkbook ? ExcelUtil.getSheetPictures07((XSSFSheet)sheet, (XSSFWorkbook)this.wb) : ExcelUtil.getSheetPictures03((HSSFSheet)sheet, (HSSFWorkbook)this.wb); + int rows = sheet.getLastRowNum(); + if (rows > 0) { + HashMap cellMap = new HashMap(); + Row heard = sheet.getRow(titleNum); + for (int i = 0; i < heard.getPhysicalNumberOfCells(); ++i) { + Cell cell = heard.getCell(i); + if (StringUtils.isNotNull(cell)) { + String value = this.getCellValue(heard, i).toString(); + cellMap.put(value, i); + continue; + } + cellMap.put(null, i); + } + List fields = this.getFields(); + HashMap fieldsMap = new HashMap(); + for (Object[] objects : fields) { + Excel attr = (Excel)objects[1]; + Integer column = (Integer)cellMap.get(attr.name()); + if (column == null) continue; + fieldsMap.put(column, objects); + } + for (int i = titleNum + 1; i <= rows; ++i) { + Row row = sheet.getRow(i); + if (this.isRowEmpty(row)) continue; + Object entity = null; + for (Map.Entry entry : fieldsMap.entrySet()) { + Object val = this.getCellValue(row, (Integer)entry.getKey()); + entity = entity == null ? (Object)this.clazz.newInstance() : entity; + Field field = (Field)((Object[])entry.getValue())[0]; + Excel attr = (Excel)((Object[])entry.getValue())[1]; + Class fieldType = field.getType(); + if (String.class == fieldType) { + String dateFormat; + String s = Convert.toStr(val); + val = StringUtils.endsWith((CharSequence)s, (CharSequence)".0") ? StringUtils.substringBefore((String)s, (String)".0") : (StringUtils.isNotEmpty(dateFormat = field.getAnnotation(Excel.class).dateFormat()) ? DateUtils.parseDateToStr(dateFormat, (Date)val) : Convert.toStr(val)); + } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric((CharSequence)Convert.toStr(val))) { + val = Convert.toInt(val); + } else if (Long.TYPE == fieldType || Long.class == fieldType) { + val = Convert.toLong(val); + } else if (Double.TYPE == fieldType || Double.class == fieldType) { + val = Convert.toDouble(val); + } else if (Float.TYPE == fieldType || Float.class == fieldType) { + val = Convert.toFloat(val); + } else if (BigDecimal.class == fieldType) { + val = Convert.toBigDecimal(val); + } else if (Date.class == fieldType) { + if (val instanceof String) { + val = DateUtils.parseDate(val); + } else if (val instanceof Double) { + val = DateUtil.getJavaDate((double)((Double)val)); + } + } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) { + val = Convert.toBool(val, false); + } + if (!StringUtils.isNotNull(fieldType)) continue; + String propertyName = field.getName(); + if (StringUtils.isNotEmpty(attr.targetAttr())) { + propertyName = field.getName() + "." + attr.targetAttr(); + } else if (StringUtils.isNotEmpty(attr.readConverterExp())) { + val = ExcelUtil.reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); + } else if (StringUtils.isNotEmpty(attr.dictType())) { + val = ExcelUtil.reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); + } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { + val = this.dataFormatHandlerAdapter(val, attr); + } else if (Excel.ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures)) { + PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey()); + if (image == null) { + val = ""; + } else { + byte[] data = image.getData(); + val = FileUtils.writeImportBytes(data); + } + } + ReflectUtils.invokeSetter(entity, propertyName, val); + } + list.add(entity); + } + } + return list; + } + + public AjaxResult exportExcel(List list, String sheetName) { + return this.exportExcel(list, sheetName, ""); + } + + public AjaxResult exportExcel(List list, String sheetName, String title) { + this.init(list, sheetName, title, Excel.Type.EXPORT); + return this.exportExcel(); + } + + public void exportExcel(HttpServletResponse response, List list, String sheetName) { + this.exportExcel(response, list, sheetName, ""); + } + + public void exportExcel(HttpServletResponse response, List list, String sheetName, String title) { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + this.init(list, sheetName, title, Excel.Type.EXPORT); + this.exportExcel(response); + } + + public AjaxResult importTemplateExcel(String sheetName) { + return this.importTemplateExcel(sheetName, ""); + } + + public AjaxResult importTemplateExcel(String sheetName, String title) { + this.init(null, sheetName, title, Excel.Type.IMPORT); + return this.exportExcel(); + } + + public void importTemplateExcel(HttpServletResponse response, String sheetName) { + this.importTemplateExcel(response, sheetName, ""); + } + + public void importTemplateExcel(HttpServletResponse response, String sheetName, String title) { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + this.init(null, sheetName, title, Excel.Type.IMPORT); + this.exportExcel(response); + } + + public void exportExcel(HttpServletResponse response) { + try { + this.writeSheet(); + this.wb.write((OutputStream)response.getOutputStream()); + } + catch (Exception e) { + log.error("\u5bfc\u51faExcel\u5f02\u5e38{}", (Object)e.getMessage()); + } + finally { + IOUtils.closeQuietly((Closeable)this.wb); + } + } + + public AjaxResult exportExcel() { + AjaxResult ajaxResult; + FileOutputStream out = null; + try { + this.writeSheet(); + String filename = this.encodingFilename(this.sheetName); + out = new FileOutputStream(this.getAbsoluteFile(filename)); + this.wb.write((OutputStream)out); + ajaxResult = AjaxResult.success(filename); + } + catch (Exception e) { + try { + log.error("\u5bfc\u51faExcel\u5f02\u5e38{}", (Object)e.getMessage()); + throw new UtilException("\u5bfc\u51faExcel\u5931\u8d25\uff0c\u8bf7\u8054\u7cfb\u7f51\u7ad9\u7ba1\u7406\u5458\uff01"); + } + catch (Throwable throwable) { + IOUtils.closeQuietly((Closeable)this.wb); + IOUtils.closeQuietly(out); + throw throwable; + } + } + IOUtils.closeQuietly((Closeable)this.wb); + IOUtils.closeQuietly((Closeable)out); + return ajaxResult; + } + + public void writeSheet() { + int sheetNo = Math.max(1, (int)Math.ceil((double)this.list.size() * 1.0 / 65536.0)); + for (int index = 0; index < sheetNo; ++index) { + this.createSheet(sheetNo, index); + Row row = this.sheet.createRow(this.rownum); + int column = 0; + for (Object[] os : this.fields) { + Excel excel = (Excel)os[1]; + this.createCell(excel, row, column++); + } + if (!Excel.Type.EXPORT.equals((Object)this.type)) continue; + this.fillExcelData(index, row); + this.addStatisticsRow(); + } + } + + public void fillExcelData(int index, Row row) { + int startNo = index * 65536; + int endNo = Math.min(startNo + 65536, this.list.size()); + for (int i = startNo; i < endNo; ++i) { + row = this.sheet.createRow(i + 1 + this.rownum - startNo); + T vo = this.list.get(i); + int column = 0; + for (Object[] os : this.fields) { + Field field = (Field)os[0]; + Excel excel = (Excel)os[1]; + this.addCell(excel, row, vo, field, column++); + } + } + } + + private Map createStyles(Workbook wb) { + HashMap styles = new HashMap(); + CellStyle style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + Font titleFont = wb.createFont(); + titleFont.setFontName("Arial"); + titleFont.setFontHeightInPoints((short)16); + titleFont.setBold(true); + style.setFont(titleFont); + styles.put("title", style); + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderTop(BorderStyle.THIN); + style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + Font dataFont = wb.createFont(); + dataFont.setFontName("Arial"); + dataFont.setFontHeightInPoints((short)10); + style.setFont(dataFont); + styles.put("data", style); + style = wb.createCellStyle(); + style.cloneStyleFrom((CellStyle)styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + Font headerFont = wb.createFont(); + headerFont.setFontName("Arial"); + headerFont.setFontHeightInPoints((short)10); + headerFont.setBold(true); + headerFont.setColor(IndexedColors.WHITE.getIndex()); + style.setFont(headerFont); + styles.put("header", style); + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + Font totalFont = wb.createFont(); + totalFont.setFontName("Arial"); + totalFont.setFontHeightInPoints((short)10); + style.setFont(totalFont); + styles.put("total", style); + style = wb.createCellStyle(); + style.cloneStyleFrom((CellStyle)styles.get("data")); + style.setAlignment(HorizontalAlignment.LEFT); + styles.put("data1", style); + style = wb.createCellStyle(); + style.cloneStyleFrom((CellStyle)styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + styles.put("data2", style); + style = wb.createCellStyle(); + style.cloneStyleFrom((CellStyle)styles.get("data")); + style.setAlignment(HorizontalAlignment.RIGHT); + styles.put("data3", style); + return styles; + } + + public Cell createCell(Excel attr, Row row, int column) { + Cell cell = row.createCell(column); + cell.setCellValue(attr.name()); + this.setDataValidation(attr, row, column); + cell.setCellStyle(this.styles.get("header")); + return cell; + } + + public void setCellVo(Object value, Excel attr, Cell cell) { + if (Excel.ColumnType.STRING == attr.cellType()) { + String cellValue = Convert.toStr(value); + if (StringUtils.containsAny((CharSequence)cellValue, (CharSequence[])FORMULA_STR)) { + cellValue = StringUtils.replaceEach((String)cellValue, (String[])FORMULA_STR, (String[])new String[]{"\t=", "\t-", "\t+", "\t@"}); + } + cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix()); + } else if (Excel.ColumnType.NUMERIC == attr.cellType()) { + if (StringUtils.isNotNull(value)) { + cell.setCellValue(StringUtils.contains((CharSequence)Convert.toStr(value), (CharSequence)".") ? Convert.toDouble(value) : (double)Convert.toInt(value).intValue()); + } + } else if (Excel.ColumnType.IMAGE == attr.cellType()) { + XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (int)((short)cell.getColumnIndex()), cell.getRow().getRowNum(), (int)((short)(cell.getColumnIndex() + 1)), cell.getRow().getRowNum() + 1); + String imagePath = Convert.toStr(value); + if (StringUtils.isNotEmpty(imagePath)) { + byte[] data = ImageUtils.getImage(imagePath); + ExcelUtil.getDrawingPatriarch(cell.getSheet()).createPicture((ClientAnchor)anchor, cell.getSheet().getWorkbook().addPicture(data, this.getImageType(data))); + } + } + } + + public int getImageType(byte[] value) { + String type = FileTypeUtils.getFileExtendName(value); + if ("JPG".equalsIgnoreCase(type)) { + return 5; + } + if ("PNG".equalsIgnoreCase(type)) { + return 6; + } + return 5; + } + + public void setDataValidation(Excel attr, Row row, int column) { + if (attr.name().indexOf("\u6ce8\uff1a") >= 0) { + this.sheet.setColumnWidth(column, 6000); + } else { + this.sheet.setColumnWidth(column, (int)((attr.width() + 0.72) * 256.0)); + } + if (StringUtils.isNotEmpty(attr.prompt())) { + this.setXSSFPrompt(this.sheet, "", attr.prompt(), 1, 100, column, column); + } + if (attr.combo().length > 0) { + this.setXSSFValidation(this.sheet, attr.combo(), 1, 100, column, column); + } + } + + public Cell addCell(Excel attr, Row row, T vo, Field field, int column) { + Cell cell = null; + try { + row.setHeight(this.maxHeight); + if (attr.isExport()) { + cell = row.createCell(column); + int align = attr.align().value(); + cell.setCellStyle(this.styles.get("data" + (align >= 1 && align <= 3 ? Integer.valueOf(align) : ""))); + Object value = this.getTargetValue(vo, field, attr); + String dateFormat = attr.dateFormat(); + String readConverterExp = attr.readConverterExp(); + String separator = attr.separator(); + String dictType = attr.dictType(); + if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) { + cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date)value)); + } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) { + cell.setCellValue(ExcelUtil.convertByExp(Convert.toStr(value), readConverterExp, separator)); + } else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) { + cell.setCellValue(ExcelUtil.convertDictByExp(Convert.toStr(value), dictType, separator)); + } else if (value instanceof BigDecimal && -1 != attr.scale()) { + cell.setCellValue(((BigDecimal)value).setScale(attr.scale(), attr.roundingMode()).toString()); + } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { + cell.setCellValue(this.dataFormatHandlerAdapter(value, attr)); + } else { + this.setCellVo(value, attr, cell); + } + this.addStatisticsData(column, Convert.toStr(value), attr); + } + } + catch (Exception e) { + log.error("\u5bfc\u51faExcel\u5931\u8d25{}", (Throwable)e); + } + return cell; + } + + public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, int firstCol, int endCol) { + DataValidationHelper helper = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); + CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + DataValidation dataValidation = helper.createValidation(constraint, regions); + dataValidation.createPromptBox(promptTitle, promptContent); + dataValidation.setShowPromptBox(true); + sheet.addValidationData(dataValidation); + } + + public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) { + CellRangeAddressList regions; + DataValidationConstraint constraint; + DataValidationHelper helper = sheet.getDataValidationHelper(); + DataValidation dataValidation = helper.createValidation(constraint = helper.createExplicitListConstraint(textlist), regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol)); + if (dataValidation instanceof XSSFDataValidation) { + dataValidation.setSuppressDropDownArrow(true); + dataValidation.setShowErrorBox(true); + } else { + dataValidation.setSuppressDropDownArrow(false); + } + sheet.addValidationData(dataValidation); + } + + public String dataFormatHandlerAdapter(Object value, Excel excel) { + try { + Object instance = excel.handler().newInstance(); + Method formatMethod = excel.handler().getMethod("format", Object.class, String[].class); + value = formatMethod.invoke(instance, value, excel.args()); + } + catch (Exception e) { + log.error("\u4e0d\u80fd\u683c\u5f0f\u5316\u6570\u636e " + excel.handler(), (Object)e.getMessage()); + } + return Convert.toStr(value); + } + + private void addStatisticsData(Integer index, String text, Excel entity) { + if (entity != null && entity.isStatistics()) { + Double temp = 0.0; + if (!this.statistics.containsKey(index)) { + this.statistics.put(index, temp); + } + try { + temp = Double.valueOf(text); + } + catch (NumberFormatException numberFormatException) { + // empty catch block + } + this.statistics.put(index, this.statistics.get(index) + temp); + } + } + + public void addStatisticsRow() { + if (this.statistics.size() > 0) { + Row row = this.sheet.createRow(this.sheet.getLastRowNum() + 1); + Set keys = this.statistics.keySet(); + Cell cell = row.createCell(0); + cell.setCellStyle(this.styles.get("total")); + cell.setCellValue("\u5408\u8ba1"); + for (Integer key : keys) { + cell = row.createCell(key.intValue()); + cell.setCellStyle(this.styles.get("total")); + cell.setCellValue(DOUBLE_FORMAT.format(this.statistics.get(key))); + } + this.statistics.clear(); + } + } + + public String encodingFilename(String filename) { + filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; + return filename; + } + + public String getAbsoluteFile(String filename) { + String downloadPath = AiBirdSysConfig.getDownloadPath() + filename; + File desc = new File(downloadPath); + if (!desc.getParentFile().exists()) { + desc.getParentFile().mkdirs(); + } + return downloadPath; + } + + private Object getTargetValue(T vo, Field field, Excel excel) throws Exception { + Object o = field.get(vo); + if (StringUtils.isNotEmpty(excel.targetAttr())) { + String target = excel.targetAttr(); + if (target.indexOf(".") > -1) { + String[] targets; + for (String name : targets = target.split("[.]")) { + o = this.getValue(o, name); + } + } else { + o = this.getValue(o, target); + } + } + return o; + } + + private Object getValue(Object o, String name) throws Exception { + if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name)) { + Class clazz = o.getClass(); + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + o = field.get(o); + } + return o; + } + + private void createExcelField() { + this.fields = this.getFields(); + this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel)objects[1]).sort())).collect(Collectors.toList()); + this.maxHeight = this.getRowHeight(); + } + + public List getFields() { + ArrayList fields = new ArrayList(); + ArrayList tempFields = new ArrayList(); + tempFields.addAll(Arrays.asList(this.clazz.getSuperclass().getDeclaredFields())); + tempFields.addAll(Arrays.asList(this.clazz.getDeclaredFields())); + for (Field field : tempFields) { + Excel[] excels; + Excel attr; + if (field.isAnnotationPresent(Excel.class) && (attr = field.getAnnotation(Excel.class)) != null && (attr.type() == Excel.Type.ALL || attr.type() == this.type)) { + field.setAccessible(true); + fields.add(new Object[]{field, attr}); + } + if (!field.isAnnotationPresent(Excels.class)) continue; + Excels attrs = field.getAnnotation(Excels.class); + for (Excel attr2 : excels = attrs.value()) { + if (attr2 == null || attr2.type() != Excel.Type.ALL && attr2.type() != this.type) continue; + field.setAccessible(true); + fields.add(new Object[]{field, attr2}); + } + } + return fields; + } + + public short getRowHeight() { + double maxHeight = 0.0; + for (Object[] os : this.fields) { + Excel excel = (Excel)os[1]; + maxHeight = maxHeight > excel.height() ? maxHeight : excel.height(); + } + return (short)(maxHeight * 20.0); + } + + public void createWorkbook() { + this.wb = new SXSSFWorkbook(500); + this.sheet = this.wb.createSheet(); + this.wb.setSheetName(0, this.sheetName); + this.styles = this.createStyles(this.wb); + } + + public void createSheet(int sheetNo, int index) { + if (sheetNo > 1 && index > 0) { + this.sheet = this.wb.createSheet(); + this.createTitle(); + this.wb.setSheetName(index, this.sheetName + index); + } + } + + public Object getCellValue(Row row, int column) { + if (row == null) { + return row; + } + Object val = ""; + try { + Cell cell = row.getCell(column); + if (StringUtils.isNotNull(cell)) { + if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) { + val = cell.getNumericCellValue(); + val = DateUtil.isCellDateFormatted((Cell)cell) ? DateUtil.getJavaDate((double)((Double)val)) : ((Double)val % 1.0 != 0.0 ? new BigDecimal(val.toString()) : new DecimalFormat("0").format(val)); + } else if (cell.getCellType() == CellType.STRING) { + val = cell.getStringCellValue(); + } else if (cell.getCellType() == CellType.BOOLEAN) { + val = cell.getBooleanCellValue(); + } else if (cell.getCellType() == CellType.ERROR) { + val = cell.getErrorCellValue(); + } + } + } + catch (Exception e) { + return val; + } + return val; + } + + private boolean isRowEmpty(Row row) { + if (row == null) { + return true; + } + for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); ++i) { + Cell cell = row.getCell(i); + if (cell == null || cell.getCellType() == CellType.BLANK) continue; + return false; + } + return true; + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/reflect/ReflectUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/reflect/ReflectUtils.java new file mode 100644 index 0000000..5135a97 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/reflect/ReflectUtils.java @@ -0,0 +1,410 @@ +package net.hzvtc.common.utils.reflect; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Date; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; +import org.apache.poi.ss.usermodel.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.common.utils.DateUtils; + +/** + * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. + * + * @author admin + */ +@SuppressWarnings("rawtypes") +public class ReflectUtils +{ + private static final String SETTER_PREFIX = "set"; + + private static final String GETTER_PREFIX = "get"; + + private static final String CGLIB_CLASS_SEPARATOR = "$$"; + + private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class); + + /** + * 调用Getter方法. + * 支持多级,如:对象名.对象名.方法 + */ + @SuppressWarnings("unchecked") + public static E invokeGetter(Object obj, String propertyName) + { + Object object = obj; + for (String name : StringUtils.split(propertyName, ".")) + { + String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); + object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); + } + return (E) object; + } + + /** + * 调用Setter方法, 仅匹配方法名。 + * 支持多级,如:对象名.对象名.方法 + */ + public static void invokeSetter(Object obj, String propertyName, E value) + { + Object object = obj; + String[] names = StringUtils.split(propertyName, "."); + for (int i = 0; i < names.length; i++) + { + if (i < names.length - 1) + { + String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); + object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); + } + else + { + String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); + invokeMethodByName(object, setterMethodName, new Object[] { value }); + } + } + } + + /** + * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. + */ + @SuppressWarnings("unchecked") + public static E getFieldValue(final Object obj, final String fieldName) + { + Field field = getAccessibleField(obj, fieldName); + if (field == null) + { + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + return null; + } + E result = null; + try + { + result = (E) field.get(obj); + } + catch (IllegalAccessException e) + { + logger.error("不可能抛出的异常{}", e.getMessage()); + } + return result; + } + + /** + * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. + */ + public static void setFieldValue(final Object obj, final String fieldName, final E value) + { + Field field = getAccessibleField(obj, fieldName); + if (field == null) + { + // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + return; + } + try + { + field.set(obj, value); + } + catch (IllegalAccessException e) + { + logger.error("不可能抛出的异常: {}", e.getMessage()); + } + } + + /** + * 直接调用对象方法, 无视private/protected修饰符. + * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. + * 同时匹配方法名+参数类型, + */ + @SuppressWarnings("unchecked") + public static E invokeMethod(final Object obj, final String methodName, final Class[] parameterTypes, + final Object[] args) + { + if (obj == null || methodName == null) + { + return null; + } + Method method = getAccessibleMethod(obj, methodName, parameterTypes); + if (method == null) + { + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); + return null; + } + try + { + return (E) method.invoke(obj, args); + } + catch (Exception e) + { + String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; + throw convertReflectionExceptionToUnchecked(msg, e); + } + } + + /** + * 直接调用对象方法, 无视private/protected修饰符, + * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用. + * 只匹配函数名,如果有多个同名函数调用第一个。 + */ + @SuppressWarnings("unchecked") + public static E invokeMethodByName(final Object obj, final String methodName, final Object[] args) + { + Method method = getAccessibleMethodByName(obj, methodName, args.length); + if (method == null) + { + // 如果为空不报错,直接返回空。 + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); + return null; + } + try + { + // 类型转换(将参数数据类型转换为目标方法参数类型) + Class[] cs = method.getParameterTypes(); + for (int i = 0; i < cs.length; i++) + { + if (args[i] != null && !args[i].getClass().equals(cs[i])) + { + if (cs[i] == String.class) + { + args[i] = Convert.toStr(args[i]); + if (StringUtils.endsWith((String) args[i], ".0")) + { + args[i] = StringUtils.substringBefore((String) args[i], ".0"); + } + } + else if (cs[i] == Integer.class) + { + args[i] = Convert.toInt(args[i]); + } + else if (cs[i] == Long.class) + { + args[i] = Convert.toLong(args[i]); + } + else if (cs[i] == Double.class) + { + args[i] = Convert.toDouble(args[i]); + } + else if (cs[i] == Float.class) + { + args[i] = Convert.toFloat(args[i]); + } + else if (cs[i] == Date.class) + { + if (args[i] instanceof String) + { + args[i] = DateUtils.parseDate(args[i]); + } + else + { + args[i] = DateUtil.getJavaDate((Double) args[i]); + } + } + else if (cs[i] == boolean.class || cs[i] == Boolean.class) + { + args[i] = Convert.toBool(args[i]); + } + } + } + return (E) method.invoke(obj, args); + } + catch (Exception e) + { + String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; + throw convertReflectionExceptionToUnchecked(msg, e); + } + } + + /** + * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + */ + public static Field getAccessibleField(final Object obj, final String fieldName) + { + // 为空不报错。直接返回 null + if (obj == null) + { + return null; + } + Validate.notBlank(fieldName, "fieldName can't be blank"); + for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) + { + try + { + Field field = superClass.getDeclaredField(fieldName); + makeAccessible(field); + return field; + } + catch (NoSuchFieldException e) + { + continue; + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + * 匹配函数名+参数类型。 + * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) + */ + public static Method getAccessibleMethod(final Object obj, final String methodName, + final Class... parameterTypes) + { + // 为空不报错。直接返回 null + if (obj == null) + { + return null; + } + Validate.notBlank(methodName, "methodName can't be blank"); + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) + { + try + { + Method method = searchType.getDeclaredMethod(methodName, parameterTypes); + makeAccessible(method); + return method; + } + catch (NoSuchMethodException e) + { + continue; + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + * 只匹配函数名。 + * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) + */ + public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) + { + // 为空不报错。直接返回 null + if (obj == null) + { + return null; + } + Validate.notBlank(methodName, "methodName can't be blank"); + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) + { + Method[] methods = searchType.getDeclaredMethods(); + for (Method method : methods) + { + if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) + { + makeAccessible(method); + return method; + } + } + } + return null; + } + + /** + * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Method method) + { + if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) + && !method.isAccessible()) + { + method.setAccessible(true); + } + } + + /** + * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Field field) + { + if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) + || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) + { + field.setAccessible(true); + } + } + + /** + * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处 + * 如无法找到, 返回Object.class. + */ + @SuppressWarnings("unchecked") + public static Class getClassGenricType(final Class clazz) + { + return getClassGenricType(clazz, 0); + } + + /** + * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. + * 如无法找到, 返回Object.class. + */ + public static Class getClassGenricType(final Class clazz, final int index) + { + Type genType = clazz.getGenericSuperclass(); + + if (!(genType instanceof ParameterizedType)) + { + logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType"); + return Object.class; + } + + Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); + + if (index >= params.length || index < 0) + { + logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + + params.length); + return Object.class; + } + if (!(params[index] instanceof Class)) + { + logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); + return Object.class; + } + + return (Class) params[index]; + } + + public static Class getUserClass(Object instance) + { + if (instance == null) + { + throw new RuntimeException("Instance must not be null"); + } + Class clazz = instance.getClass(); + if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) + { + Class superClass = clazz.getSuperclass(); + if (superClass != null && !Object.class.equals(superClass)) + { + return superClass; + } + } + return clazz; + + } + + /** + * 将反射时的checked exception转换为unchecked exception. + */ + public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) + { + if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException + || e instanceof NoSuchMethodException) + { + return new IllegalArgumentException(msg, e); + } + else if (e instanceof InvocationTargetException) + { + return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException()); + } + return new RuntimeException(msg, e); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Base64.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Base64.java new file mode 100644 index 0000000..cf4e750 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Base64.java @@ -0,0 +1,214 @@ +package net.hzvtc.common.utils.sign; + +public final class Base64 { + private static final int BASELENGTH = 128; + private static final int LOOKUPLENGTH = 64; + private static final int TWENTYFOURBITGROUP = 24; + private static final int EIGHTBIT = 8; + private static final int SIXTEENBIT = 16; + private static final int FOURBYTE = 4; + private static final int SIGN = -128; + private static final char PAD = '='; + private static final byte[] base64Alphabet; + private static final char[] lookUpBase64Alphabet; + + private static boolean isWhiteSpace(char octect) { + return octect == ' ' || octect == '\r' || octect == '\n' || octect == '\t'; + } + + private static boolean isPad(char octect) { + return octect == '='; + } + + private static boolean isData(char octect) { + return octect < '\u0080' && base64Alphabet[octect] != -1; + } + + public static String encode(byte[] binaryData) { + byte val1; + if (binaryData == null) { + return null; + } + int lengthDataBits = binaryData.length * 8; + if (lengthDataBits == 0) { + return ""; + } + int fewerThan24bits = lengthDataBits % 24; + int numberTriplets = lengthDataBits / 24; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + char[] encodedData = null; + encodedData = new char[numberQuartet * 4]; + byte k = 0; + byte l = 0; + byte b1 = 0; + byte b2 = 0; + byte b3 = 0; + int encodedIndex = 0; + int dataIndex = 0; + for (int i = 0; i < numberTriplets; ++i) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + l = (byte)(b2 & 0xF); + k = (byte)(b1 & 3); + byte val12 = (b1 & 0xFFFFFF80) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 0xC0); + byte val2 = (b2 & 0xFFFFFF80) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 0xF0); + byte val3 = (b3 & 0xFFFFFF80) == 0 ? (byte)(b3 >> 6) : (byte)(b3 >> 6 ^ 0xFC); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val12]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2 | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3F]; + } + if (fewerThan24bits == 8) { + b1 = binaryData[dataIndex]; + k = (byte)(b1 & 3); + val1 = (b1 & 0xFFFFFF80) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 0xC0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = 61; + encodedData[encodedIndex++] = 61; + } else if (fewerThan24bits == 16) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex + 1]; + l = (byte)(b2 & 0xF); + k = (byte)(b1 & 3); + val1 = (b1 & 0xFFFFFF80) == 0 ? (byte)(b1 >> 2) : (byte)(b1 >> 2 ^ 0xC0); + byte val2 = (b2 & 0xFFFFFF80) == 0 ? (byte)(b2 >> 4) : (byte)(b2 >> 4 ^ 0xF0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | k << 4]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = 61; + } + return new String(encodedData); + } + + public static byte[] decode(String encoded) { + int i; + if (encoded == null) { + return null; + } + char[] base64Data = encoded.toCharArray(); + int len = Base64.removeWhiteSpace(base64Data); + if (len % 4 != 0) { + return null; + } + int numberQuadruple = len / 4; + if (numberQuadruple == 0) { + return new byte[0]; + } + byte[] decodedData = null; + byte b1 = 0; + byte b2 = 0; + byte b3 = 0; + byte b4 = 0; + char d1 = '\u0000'; + char d2 = '\u0000'; + char d3 = '\u0000'; + char d4 = '\u0000'; + int encodedIndex = 0; + int dataIndex = 0; + decodedData = new byte[numberQuadruple * 3]; + for (i = 0; i < numberQuadruple - 1; ++i) { + if (!(Base64.isData(d1 = base64Data[dataIndex++]) && Base64.isData(d2 = base64Data[dataIndex++]) && Base64.isData(d3 = base64Data[dataIndex++]) && Base64.isData(d4 = base64Data[dataIndex++]))) { + return null; + } + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte)((b2 & 0xF) << 4 | b3 >> 2 & 0xF); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); + } + if (!Base64.isData(d1 = base64Data[dataIndex++]) || !Base64.isData(d2 = base64Data[dataIndex++])) { + return null; + } + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + d3 = base64Data[dataIndex++]; + d4 = base64Data[dataIndex++]; + if (!Base64.isData(d3) || !Base64.isData(d4)) { + if (Base64.isPad(d3) && Base64.isPad(d4)) { + if ((b2 & 0xF) != 0) { + return null; + } + byte[] tmp = new byte[i * 3 + 1]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex] = (byte)(b1 << 2 | b2 >> 4); + return tmp; + } + if (!Base64.isPad(d3) && Base64.isPad(d4)) { + b3 = base64Alphabet[d3]; + if ((b3 & 3) != 0) { + return null; + } + byte[] tmp = new byte[i * 3 + 2]; + System.arraycopy(decodedData, 0, tmp, 0, i * 3); + tmp[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + tmp[encodedIndex] = (byte)((b2 & 0xF) << 4 | b3 >> 2 & 0xF); + return tmp; + } + return null; + } + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex++] = (byte)((b2 & 0xF) << 4 | b3 >> 2 & 0xF); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); + return decodedData; + } + + private static int removeWhiteSpace(char[] data) { + if (data == null) { + return 0; + } + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; ++i) { + if (Base64.isWhiteSpace(data[i])) continue; + data[newSize++] = data[i]; + } + return newSize; + } + + static { + int i; + base64Alphabet = new byte[128]; + lookUpBase64Alphabet = new char[64]; + for (i = 0; i < 128; ++i) { + Base64.base64Alphabet[i] = -1; + } + for (i = 90; i >= 65; --i) { + Base64.base64Alphabet[i] = (byte)(i - 65); + } + for (i = 122; i >= 97; --i) { + Base64.base64Alphabet[i] = (byte)(i - 97 + 26); + } + for (i = 57; i >= 48; --i) { + Base64.base64Alphabet[i] = (byte)(i - 48 + 52); + } + Base64.base64Alphabet[43] = 62; + Base64.base64Alphabet[47] = 63; + for (i = 0; i <= 25; ++i) { + Base64.lookUpBase64Alphabet[i] = (char)(65 + i); + } + i = 26; + int j = 0; + while (i <= 51) { + Base64.lookUpBase64Alphabet[i] = (char)(97 + j); + ++i; + ++j; + } + i = 52; + j = 0; + while (i <= 61) { + Base64.lookUpBase64Alphabet[i] = (char)(48 + j); + ++i; + ++j; + } + Base64.lookUpBase64Alphabet[62] = 43; + Base64.lookUpBase64Alphabet[63] = 47; + } +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Md5Utils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Md5Utils.java new file mode 100644 index 0000000..750acba --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sign/Md5Utils.java @@ -0,0 +1,66 @@ +package net.hzvtc.common.utils.sign; + +import java.security.MessageDigest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Md5加密方法 + * + * @author admin + */ +public class Md5Utils +{ + private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); + + private static byte[] md5(String s) + { + MessageDigest algorithm; + try + { + algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(s.getBytes("UTF-8")); + byte[] messageDigest = algorithm.digest(); + return messageDigest; + } + catch (Exception e) + { + log.error("MD5 Error...", e); + } + return null; + } + + private static final String toHex(byte hash[]) + { + if (hash == null) + { + return null; + } + StringBuffer buf = new StringBuffer(hash.length * 2); + int i; + + for (i = 0; i < hash.length; i++) + { + if ((hash[i] & 0xff) < 0x10) + { + buf.append("0"); + } + buf.append(Long.toString(hash[i] & 0xff, 16)); + } + return buf.toString(); + } + + public static String hash(String s) + { + try + { + return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8"); + } + catch (Exception e) + { + log.error("not supported charset...{}", e); + return s; + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/spring/SpringUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/spring/SpringUtils.java new file mode 100644 index 0000000..b953fc6 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/spring/SpringUtils.java @@ -0,0 +1,146 @@ +package net.hzvtc.common.utils.spring; + +import org.springframework.aop.framework.AopContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; +import net.hzvtc.common.utils.StringUtils; + +/** + * spring工具类 方便在非spring管理环境中获取bean + * + * @author admin + */ +@Component +public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware +{ + /** Spring应用上下文环境 */ + private static ConfigurableListableBeanFactory beanFactory; + + private static ApplicationContext applicationContext; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException + { + SpringUtils.beanFactory = beanFactory; + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException + { + SpringUtils.applicationContext = applicationContext; + } + + /** + * 获取对象 + * + * @param name + * @return Object 一个以所给名字注册的bean的实例 + * @throws org.springframework.beans.BeansException + * + */ + @SuppressWarnings("unchecked") + public static T getBean(String name) throws BeansException + { + return (T) beanFactory.getBean(name); + } + + /** + * 获取类型为requiredType的对象 + * + * @param clz + * @return + * @throws org.springframework.beans.BeansException + * + */ + public static T getBean(Class clz) throws BeansException + { + T result = (T) beanFactory.getBean(clz); + return result; + } + + /** + * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true + * + * @param name + * @return boolean + */ + public static boolean containsBean(String name) + { + return beanFactory.containsBean(name); + } + + /** + * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) + * + * @param name + * @return boolean + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * + */ + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException + { + return beanFactory.isSingleton(name); + } + + /** + * @param name + * @return Class 注册对象的类型 + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * + */ + public static Class getType(String name) throws NoSuchBeanDefinitionException + { + return beanFactory.getType(name); + } + + /** + * 如果给定的bean名字在bean定义中有别名,则返回这些别名 + * + * @param name + * @return + * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException + * + */ + public static String[] getAliases(String name) throws NoSuchBeanDefinitionException + { + return beanFactory.getAliases(name); + } + + /** + * 获取aop代理对象 + * + * @param invoker + * @return + */ + @SuppressWarnings("unchecked") + public static T getAopProxy(T invoker) + { + return (T) AopContext.currentProxy(); + } + + /** + * 获取当前的环境配置,无配置返回null + * + * @return 当前的环境配置 + */ + public static String[] getActiveProfiles() + { + return applicationContext.getEnvironment().getActiveProfiles(); + } + + /** + * 获取当前的环境配置,当有多个环境配置时,只获取第一个 + * + * @return 当前的环境配置 + */ + public static String getActiveProfile() + { + final String[] activeProfiles = getActiveProfiles(); + return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null; + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/sql/SqlUtil.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sql/SqlUtil.java new file mode 100644 index 0000000..1f06927 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/sql/SqlUtil.java @@ -0,0 +1,61 @@ +package net.hzvtc.common.utils.sql; + +import net.hzvtc.common.exception.UtilException; +import net.hzvtc.common.utils.StringUtils; + +/** + * sql操作工具类 + * + * @author admin + */ +public class SqlUtil +{ + /** + * 定义常用的 sql关键字 + */ + public static String SQL_REGEX = "select |insert |delete |update |drop |count |exec |chr |mid |master |truncate |char |and |declare "; + + /** + * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序) + */ + public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; + + /** + * 检查字符,防止注入绕过 + */ + public static String escapeOrderBySql(String value) + { + if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) + { + throw new UtilException("参数不符合规范,不能进行查询"); + } + return value; + } + + /** + * 验证 order by 语法是否符合规范 + */ + public static boolean isValidOrderBySql(String value) + { + return value.matches(SQL_PATTERN); + } + + /** + * SQL关键字检查 + */ + public static void filterKeyword(String value) + { + if (StringUtils.isEmpty(value)) + { + return; + } + String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|"); + for (int i = 0; i < sqlKeywords.length; i++) + { + if (StringUtils.indexOfIgnoreCase(value, sqlKeywords[i]) > -1) + { + throw new UtilException("参数存在SQL注入风险"); + } + } + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/IdUtils.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/IdUtils.java new file mode 100644 index 0000000..25bfe81 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/IdUtils.java @@ -0,0 +1,49 @@ +package net.hzvtc.common.utils.uuid; + +/** + * ID生成器工具类 + * + * @author admin + */ +public class IdUtils +{ + /** + * 获取随机UUID + * + * @return 随机UUID + */ + public static String randomUUID() + { + return UUID.randomUUID().toString(); + } + + /** + * 简化的UUID,去掉了横线 + * + * @return 简化的UUID,去掉了横线 + */ + public static String simpleUUID() + { + return UUID.randomUUID().toString(true); + } + + /** + * 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID + * + * @return 随机UUID + */ + public static String fastUUID() + { + return UUID.fastUUID().toString(); + } + + /** + * 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID + * + * @return 简化的UUID,去掉了横线 + */ + public static String fastSimpleUUID() + { + return UUID.fastUUID().toString(true); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/UUID.java b/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/UUID.java new file mode 100644 index 0000000..93cce53 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/utils/uuid/UUID.java @@ -0,0 +1,484 @@ +package net.hzvtc.common.utils.uuid; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Random; +import java.util.concurrent.ThreadLocalRandom; +import net.hzvtc.common.exception.UtilException; + +/** + * 提供通用唯一识别码(universally unique identifier)(UUID)实现 + * + * @author admin + */ +public final class UUID implements java.io.Serializable, Comparable +{ + private static final long serialVersionUID = -1185015143654744140L; + + /** + * SecureRandom 的单例 + * + */ + private static class Holder + { + static final SecureRandom numberGenerator = getSecureRandom(); + } + + /** 此UUID的最高64有效位 */ + private final long mostSigBits; + + /** 此UUID的最低64有效位 */ + private final long leastSigBits; + + /** + * 私有构造 + * + * @param data 数据 + */ + private UUID(byte[] data) + { + long msb = 0; + long lsb = 0; + assert data.length == 16 : "data must be 16 bytes in length"; + for (int i = 0; i < 8; i++) + { + msb = (msb << 8) | (data[i] & 0xff); + } + for (int i = 8; i < 16; i++) + { + lsb = (lsb << 8) | (data[i] & 0xff); + } + this.mostSigBits = msb; + this.leastSigBits = lsb; + } + + /** + * 使用指定的数据构造新的 UUID。 + * + * @param mostSigBits 用于 {@code UUID} 的最高有效 64 位 + * @param leastSigBits 用于 {@code UUID} 的最低有效 64 位 + */ + public UUID(long mostSigBits, long leastSigBits) + { + this.mostSigBits = mostSigBits; + this.leastSigBits = leastSigBits; + } + + /** + * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的本地线程伪随机数生成器生成该 UUID。 + * + * @return 随机生成的 {@code UUID} + */ + public static UUID fastUUID() + { + return randomUUID(false); + } + + /** + * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 + * + * @return 随机生成的 {@code UUID} + */ + public static UUID randomUUID() + { + return randomUUID(true); + } + + /** + * 获取类型 4(伪随机生成的)UUID 的静态工厂。 使用加密的强伪随机数生成器生成该 UUID。 + * + * @param isSecure 是否使用{@link SecureRandom}如果是可以获得更安全的随机码,否则可以得到更好的性能 + * @return 随机生成的 {@code UUID} + */ + public static UUID randomUUID(boolean isSecure) + { + final Random ng = isSecure ? Holder.numberGenerator : getRandom(); + + byte[] randomBytes = new byte[16]; + ng.nextBytes(randomBytes); + randomBytes[6] &= 0x0f; /* clear version */ + randomBytes[6] |= 0x40; /* set to version 4 */ + randomBytes[8] &= 0x3f; /* clear variant */ + randomBytes[8] |= 0x80; /* set to IETF variant */ + return new UUID(randomBytes); + } + + /** + * 根据指定的字节数组获取类型 3(基于名称的)UUID 的静态工厂。 + * + * @param name 用于构造 UUID 的字节数组。 + * + * @return 根据指定数组生成的 {@code UUID} + */ + public static UUID nameUUIDFromBytes(byte[] name) + { + MessageDigest md; + try + { + md = MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException nsae) + { + throw new InternalError("MD5 not supported"); + } + byte[] md5Bytes = md.digest(name); + md5Bytes[6] &= 0x0f; /* clear version */ + md5Bytes[6] |= 0x30; /* set to version 3 */ + md5Bytes[8] &= 0x3f; /* clear variant */ + md5Bytes[8] |= 0x80; /* set to IETF variant */ + return new UUID(md5Bytes); + } + + /** + * 根据 {@link #toString()} 方法中描述的字符串标准表示形式创建{@code UUID}。 + * + * @param name 指定 {@code UUID} 字符串 + * @return 具有指定值的 {@code UUID} + * @throws IllegalArgumentException 如果 name 与 {@link #toString} 中描述的字符串表示形式不符抛出此异常 + * + */ + public static UUID fromString(String name) + { + String[] components = name.split("-"); + if (components.length != 5) + { + throw new IllegalArgumentException("Invalid UUID string: " + name); + } + for (int i = 0; i < 5; i++) + { + components[i] = "0x" + components[i]; + } + + long mostSigBits = Long.decode(components[0]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[1]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[2]).longValue(); + + long leastSigBits = Long.decode(components[3]).longValue(); + leastSigBits <<= 48; + leastSigBits |= Long.decode(components[4]).longValue(); + + return new UUID(mostSigBits, leastSigBits); + } + + /** + * 返回此 UUID 的 128 位值中的最低有效 64 位。 + * + * @return 此 UUID 的 128 位值中的最低有效 64 位。 + */ + public long getLeastSignificantBits() + { + return leastSigBits; + } + + /** + * 返回此 UUID 的 128 位值中的最高有效 64 位。 + * + * @return 此 UUID 的 128 位值中最高有效 64 位。 + */ + public long getMostSignificantBits() + { + return mostSigBits; + } + + /** + * 与此 {@code UUID} 相关联的版本号. 版本号描述此 {@code UUID} 是如何生成的。 + *

+ * 版本号具有以下含意: + *

    + *
  • 1 基于时间的 UUID + *
  • 2 DCE 安全 UUID + *
  • 3 基于名称的 UUID + *
  • 4 随机生成的 UUID + *
+ * + * @return 此 {@code UUID} 的版本号 + */ + public int version() + { + // Version is bits masked by 0x000000000000F000 in MS long + return (int) ((mostSigBits >> 12) & 0x0f); + } + + /** + * 与此 {@code UUID} 相关联的变体号。变体号描述 {@code UUID} 的布局。 + *

+ * 变体号具有以下含意: + *

    + *
  • 0 为 NCS 向后兼容保留 + *
  • 2 IETF RFC 4122(Leach-Salz), 用于此类 + *
  • 6 保留,微软向后兼容 + *
  • 7 保留供以后定义使用 + *
+ * + * @return 此 {@code UUID} 相关联的变体号 + */ + public int variant() + { + // This field is composed of a varying number of bits. + // 0 - - Reserved for NCS backward compatibility + // 1 0 - The IETF aka Leach-Salz variant (used by this class) + // 1 1 0 Reserved, Microsoft backward compatibility + // 1 1 1 Reserved for future definition. + return (int) ((leastSigBits >>> (64 - (leastSigBits >>> 62))) & (leastSigBits >> 63)); + } + + /** + * 与此 UUID 相关联的时间戳值。 + * + *

+ * 60 位的时间戳值根据此 {@code UUID} 的 time_low、time_mid 和 time_hi 字段构造。
+ * 所得到的时间戳以 100 毫微秒为单位,从 UTC(通用协调时间) 1582 年 10 月 15 日零时开始。 + * + *

+ * 时间戳值仅在在基于时间的 UUID(其 version 类型为 1)中才有意义。
+ * 如果此 {@code UUID} 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 + * + * @throws UnsupportedOperationException 如果此 {@code UUID} 不是 version 为 1 的 UUID。 + */ + public long timestamp() throws UnsupportedOperationException + { + checkTimeBase(); + return (mostSigBits & 0x0FFFL) << 48// + | ((mostSigBits >> 16) & 0x0FFFFL) << 32// + | mostSigBits >>> 32; + } + + /** + * 与此 UUID 相关联的时钟序列值。 + * + *

+ * 14 位的时钟序列值根据此 UUID 的 clock_seq 字段构造。clock_seq 字段用于保证在基于时间的 UUID 中的时间唯一性。 + *

+ * {@code clockSequence} 值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。 如果此 UUID 不是基于时间的 UUID,则此方法抛出 + * UnsupportedOperationException。 + * + * @return 此 {@code UUID} 的时钟序列 + * + * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 + */ + public int clockSequence() throws UnsupportedOperationException + { + checkTimeBase(); + return (int) ((leastSigBits & 0x3FFF000000000000L) >>> 48); + } + + /** + * 与此 UUID 相关的节点值。 + * + *

+ * 48 位的节点值根据此 UUID 的 node 字段构造。此字段旨在用于保存机器的 IEEE 802 地址,该地址用于生成此 UUID 以保证空间唯一性。 + *

+ * 节点值仅在基于时间的 UUID(其 version 类型为 1)中才有意义。
+ * 如果此 UUID 不是基于时间的 UUID,则此方法抛出 UnsupportedOperationException。 + * + * @return 此 {@code UUID} 的节点值 + * + * @throws UnsupportedOperationException 如果此 UUID 的 version 不为 1 + */ + public long node() throws UnsupportedOperationException + { + checkTimeBase(); + return leastSigBits & 0x0000FFFFFFFFFFFFL; + } + + /** + * 返回此{@code UUID} 的字符串表现形式。 + * + *

+ * UUID 的字符串表示形式由此 BNF 描述: + * + *

+     * {@code
+     * UUID                   = ----
+     * time_low               = 4*
+     * time_mid               = 2*
+     * time_high_and_version  = 2*
+     * variant_and_sequence   = 2*
+     * node                   = 6*
+     * hexOctet               = 
+     * hexDigit               = [0-9a-fA-F]
+     * }
+     * 
+ * + * + * + * @return 此{@code UUID} 的字符串表现形式 + * @see #toString(boolean) + */ + @Override + public String toString() + { + return toString(false); + } + + /** + * 返回此{@code UUID} 的字符串表现形式。 + * + *

+ * UUID 的字符串表示形式由此 BNF 描述: + * + *

+     * {@code
+     * UUID                   = ----
+     * time_low               = 4*
+     * time_mid               = 2*
+     * time_high_and_version  = 2*
+     * variant_and_sequence   = 2*
+     * node                   = 6*
+     * hexOctet               = 
+     * hexDigit               = [0-9a-fA-F]
+     * }
+     * 
+ * + * + * + * @param isSimple 是否简单模式,简单模式为不带'-'的UUID字符串 + * @return 此{@code UUID} 的字符串表现形式 + */ + public String toString(boolean isSimple) + { + final StringBuilder builder = new StringBuilder(isSimple ? 32 : 36); + // time_low + builder.append(digits(mostSigBits >> 32, 8)); + if (!isSimple) + { + builder.append('-'); + } + // time_mid + builder.append(digits(mostSigBits >> 16, 4)); + if (!isSimple) + { + builder.append('-'); + } + // time_high_and_version + builder.append(digits(mostSigBits, 4)); + if (!isSimple) + { + builder.append('-'); + } + // variant_and_sequence + builder.append(digits(leastSigBits >> 48, 4)); + if (!isSimple) + { + builder.append('-'); + } + // node + builder.append(digits(leastSigBits, 12)); + + return builder.toString(); + } + + /** + * 返回此 UUID 的哈希码。 + * + * @return UUID 的哈希码值。 + */ + @Override + public int hashCode() + { + long hilo = mostSigBits ^ leastSigBits; + return ((int) (hilo >> 32)) ^ (int) hilo; + } + + /** + * 将此对象与指定对象比较。 + *

+ * 当且仅当参数不为 {@code null}、而是一个 UUID 对象、具有与此 UUID 相同的 varriant、包含相同的值(每一位均相同)时,结果才为 {@code true}。 + * + * @param obj 要与之比较的对象 + * + * @return 如果对象相同,则返回 {@code true};否则返回 {@code false} + */ + @Override + public boolean equals(Object obj) + { + if ((null == obj) || (obj.getClass() != UUID.class)) + { + return false; + } + UUID id = (UUID) obj; + return (mostSigBits == id.mostSigBits && leastSigBits == id.leastSigBits); + } + + // Comparison Operations + + /** + * 将此 UUID 与指定的 UUID 比较。 + * + *

+ * 如果两个 UUID 不同,且第一个 UUID 的最高有效字段大于第二个 UUID 的对应字段,则第一个 UUID 大于第二个 UUID。 + * + * @param val 与此 UUID 比较的 UUID + * + * @return 在此 UUID 小于、等于或大于 val 时,分别返回 -1、0 或 1。 + * + */ + @Override + public int compareTo(UUID val) + { + // The ordering is intentionally set up so that the UUIDs + // can simply be numerically compared as two numbers + return (this.mostSigBits < val.mostSigBits ? -1 : // + (this.mostSigBits > val.mostSigBits ? 1 : // + (this.leastSigBits < val.leastSigBits ? -1 : // + (this.leastSigBits > val.leastSigBits ? 1 : // + 0)))); + } + + // ------------------------------------------------------------------------------------------------------------------- + // Private method start + /** + * 返回指定数字对应的hex值 + * + * @param val 值 + * @param digits 位 + * @return 值 + */ + private static String digits(long val, int digits) + { + long hi = 1L << (digits * 4); + return Long.toHexString(hi | (val & (hi - 1))).substring(1); + } + + /** + * 检查是否为time-based版本UUID + */ + private void checkTimeBase() + { + if (version() != 1) + { + throw new UnsupportedOperationException("Not a time-based UUID"); + } + } + + /** + * 获取{@link SecureRandom},类提供加密的强随机数生成器 (RNG) + * + * @return {@link SecureRandom} + */ + public static SecureRandom getSecureRandom() + { + try + { + return SecureRandom.getInstance("SHA1PRNG"); + } + catch (NoSuchAlgorithmException e) + { + throw new UtilException(e); + } + } + + /** + * 获取随机数生成器对象
+ * ThreadLocalRandom是JDK 7之后提供并发产生随机数,能够解决多个线程发生的竞争争夺。 + * + * @return {@link ThreadLocalRandom} + */ + public static ThreadLocalRandom getRandom() + { + return ThreadLocalRandom.current(); + } +} diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/xss/Xss.java b/ai-bird-common/src/main/java/net/hzvtc/common/xss/Xss.java new file mode 100644 index 0000000..8211318 --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/xss/Xss.java @@ -0,0 +1,22 @@ +package net.hzvtc.common.xss; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import javax.validation.Constraint; +import javax.validation.Payload; +import net.hzvtc.common.xss.XssValidator; + +@Retention(value=RetentionPolicy.RUNTIME) +@Target(value={ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER}) +@Constraint(validatedBy={XssValidator.class}) +public @interface Xss { + public String message() default "\u4e0d\u5141\u8bb8\u4efb\u4f55\u811a\u672c\u8fd0\u884c"; + + public Class[] groups() default {}; + + public Class[] payload() default {}; +} + + diff --git a/ai-bird-common/src/main/java/net/hzvtc/common/xss/XssValidator.java b/ai-bird-common/src/main/java/net/hzvtc/common/xss/XssValidator.java new file mode 100644 index 0000000..c38f33f --- /dev/null +++ b/ai-bird-common/src/main/java/net/hzvtc/common/xss/XssValidator.java @@ -0,0 +1,29 @@ +package net.hzvtc.common.xss; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 自定义xss校验注解实现 + * + * @author admin + */ +public class XssValidator implements ConstraintValidator +{ + private final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />"; + + @Override + public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) + { + return !containsHtml(value); + } + + public boolean containsHtml(String value) + { + Pattern pattern = Pattern.compile(HTML_PATTERN); + Matcher matcher = pattern.matcher(value); + return matcher.matches(); + } +} \ No newline at end of file diff --git a/ai-bird-es/pom.xml b/ai-bird-es/pom.xml new file mode 100644 index 0000000..ba0ada8 --- /dev/null +++ b/ai-bird-es/pom.xml @@ -0,0 +1,76 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + ai-bird-es + + springboot-elasticsearch-service + + + + co.elastic.clients + elasticsearch-java + 8.14.3 + + + org.elasticsearch.client + elasticsearch-rest-client + 8.14.3 + + + + + + + + + + + + + + + + + + + org.projectlombok + lombok + 1.18.20 + provided + + + com.fasterxml.jackson.core + jackson-databind + 2.13.4 + + + org.springframework + spring-context + 5.3.29 + + + com.alibaba + fastjson + + + net.hzvtc + ai-bird-common + + + net.hzvtc + ai-bird-system + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.13.4 + + + \ No newline at end of file diff --git a/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeDeserializer.java b/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeDeserializer.java new file mode 100644 index 0000000..820ccae --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeDeserializer.java @@ -0,0 +1,22 @@ +package net.hzvtc.config; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +import java.io.IOException; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class CustomDateTimeDeserializer extends JsonDeserializer { + + private static final DateTimeFormatter INPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + + @Override + public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) + throws IOException, JsonProcessingException { + String dateStr = p.getText(); + return ZonedDateTime.parse(dateStr, INPUT_FORMATTER); + } +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeSerializer.java b/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeSerializer.java new file mode 100644 index 0000000..2409325 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/config/CustomDateTimeSerializer.java @@ -0,0 +1,21 @@ +package net.hzvtc.config; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.SerializerProvider; + +import java.io.IOException; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +public class CustomDateTimeSerializer extends JsonSerializer { + + private static final DateTimeFormatter OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + @Override + public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider serializers) + throws IOException { + String formattedDate = value.format(OUTPUT_FORMATTER); + gen.writeString(formattedDate); + } +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/config/ESClientConfig.java b/ai-bird-es/src/main/java/net/hzvtc/config/ESClientConfig.java new file mode 100644 index 0000000..3952686 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/config/ESClientConfig.java @@ -0,0 +1,143 @@ +package net.hzvtc.config; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.json.JsonpMapper; +import co.elastic.clients.json.jackson.JacksonJsonpMapper; +import co.elastic.clients.transport.ElasticsearchTransport; +import co.elastic.clients.transport.rest_client.RestClientTransport; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import net.hzvtc.config.JacksonConfiguration; +import org.apache.http.Header; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.util.StringUtils; + +@Configuration +public class ESClientConfig { + private static final Logger log = LoggerFactory.getLogger(ESClientConfig.class); + @Value(value="${spring.elastic.hosts}") + private String hosts; + @Value(value="${spring.elastic.http}") + private String http; + @Value(value="${spring.elastic.apiKey}") + private String apiKey; + @Value(value="${spring.elastic.username}") + private String username; + @Value(value="${spring.elastic.password}") + private String passwd; + private static String certName; + + @Value(value="${spring.elastic.certName}") + public void setAppKey(String certName) { + ESClientConfig.certName = certName; + } + + private HttpHost[] toHttpHost() { + if (!StringUtils.hasLength((String)this.hosts)) { + throw new RuntimeException("invalid elasticsearch configuration"); + } + String[] hostArray = this.hosts.split(","); + HttpHost[] httpHosts = new HttpHost[hostArray.length]; + for (int i = 0; i < hostArray.length; ++i) { + HttpHost httpHost; + String[] strings = hostArray[i].split(":"); + httpHosts[i] = httpHost = new HttpHost(strings[0], Integer.parseInt(strings[1]), "https"); + } + return httpHosts; + } + + @Bean(value={"clientByPasswd"}) + public ElasticsearchClient clientByPasswd() { + ElasticsearchTransport transport = ESClientConfig.getElasticsearchTransport(this.username, this.passwd, this.toHttpHost()); + return new ElasticsearchClient(transport); + } + + private static SSLContext buildSSLContext() { + ClassPathResource resource = new ClassPathResource(certName); + SSLContext sslContext = null; + try { + Certificate trustedCa; + CertificateFactory factory = CertificateFactory.getInstance("X.509"); + try (InputStream is = resource.getInputStream();){ + trustedCa = factory.generateCertificate(is); + } + KeyStore trustStore = KeyStore.getInstance("pkcs12"); + trustStore.load(null, null); + trustStore.setCertificateEntry("ca", trustedCa); + SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null); + sslContext = sslContextBuilder.build(); + } + catch (IOException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { + log.error("ES\u8fde\u63a5\u8ba4\u8bc1\u5931\u8d25", (Throwable)e); + } + return sslContext; + } + + private static ElasticsearchTransport getElasticsearchTransport(String username, String passwd, HttpHost ... hosts) { + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, (Credentials)new UsernamePasswordCredentials(username, passwd)); + RestClientBuilder.HttpClientConfigCallback callback = arg_0 -> ESClientConfig.lambda$getElasticsearchTransport$0((CredentialsProvider)credentialsProvider, arg_0); + RestClient client = RestClient.builder((HttpHost[])hosts).setHttpClientConfigCallback(callback).build(); + return new RestClientTransport(client, (JsonpMapper)new JacksonJsonpMapper(JacksonConfiguration.createObjectMapper())); + } + + private static ElasticsearchTransport getElasticsearchTransport(String apiKey, HttpHost ... hosts) { + Header[] headers = new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKey)}; + RestClientBuilder.HttpClientConfigCallback callback = httpAsyncClientBuilder -> httpAsyncClientBuilder.setSSLContext(ESClientConfig.buildSSLContext()).setSSLHostnameVerifier((HostnameVerifier)NoopHostnameVerifier.INSTANCE); + RestClient client = RestClient.builder((HttpHost[])hosts).setHttpClientConfigCallback(callback).setDefaultHeaders(headers).build(); + return new RestClientTransport(client, (JsonpMapper)new JacksonJsonpMapper()); + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + public void setHttp(String http) { + this.http = http; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public void setUsername(String username) { + this.username = username; + } + + public void setPasswd(String passwd) { + this.passwd = passwd; + } + + private static /* synthetic */ HttpAsyncClientBuilder lambda$getElasticsearchTransport$0(CredentialsProvider credentialsProvider, HttpAsyncClientBuilder httpAsyncClientBuilder) { + return httpAsyncClientBuilder.setSSLContext(ESClientConfig.buildSSLContext()).setSSLHostnameVerifier((HostnameVerifier)NoopHostnameVerifier.INSTANCE).setDefaultCredentialsProvider(credentialsProvider); + } +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/config/JacksonConfiguration.java b/ai-bird-es/src/main/java/net/hzvtc/config/JacksonConfiguration.java new file mode 100644 index 0000000..ff535f1 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/config/JacksonConfiguration.java @@ -0,0 +1,19 @@ +package net.hzvtc.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +import java.time.ZonedDateTime; + +public class JacksonConfiguration { + public static ObjectMapper createObjectMapper() { + return new ObjectMapper() + .setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .registerModule(new JavaTimeModule() + .addSerializer(ZonedDateTime.class, new CustomDateTimeSerializer()) + .addDeserializer(ZonedDateTime.class, new CustomDateTimeDeserializer())); + } +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsRecordReportController.java b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsRecordReportController.java new file mode 100644 index 0000000..c3eda3e --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsRecordReportController.java @@ -0,0 +1,134 @@ +package net.hzvtc.es.controller; + +import com.alibaba.fastjson.JSONObject; +import java.io.OutputStream; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.es.service.EsRecordReportService; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/es/result/report"}) +public class EsRecordReportController { + private final EsRecordReportService esRecordReportService; + + @PostMapping(value={"/getBirdStatData"}) + public AjaxResult getBirdStatData(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.getBirdDailyReportStatByParam(object)); + } + + @PostMapping(value={"/getBirdWeeklyStatData"}) + public AjaxResult getBirdWeeklyStatData(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.getSpeciesWeeklyReportByParam(object)); + } + + @PostMapping(value={"/getBirdMonthlyStatData"}) + public AjaxResult getBirdMonthlyStatData(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.getSpeciesMonthlyReportByParam(object)); + } + + @PostMapping(value={"/getBirdYearlyStatData"}) + public AjaxResult getBirdYearlyStatData(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.getSpeciesYearlyReportByParam(object)); + } + + @PostMapping(value={"/downloadWeeklyReport"}) + public void downloadWeeklyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + obj.put("isDeleted", (Object)0); + String filePath = this.esRecordReportService.getBirdDataStatWeeklyFileByParam(obj); + this.processPath(filePath, response); + } + + @PostMapping(value={"/downloadMonthlyReport"}) + public void downloadMonthlyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + obj.put("isDeleted", (Object)0); + String filePath = this.esRecordReportService.getBirdDataMonthlyStatFileByParam(obj); + this.processPath(filePath, response); + } + + @PostMapping(value={"/downloadYearlyReport"}) + public void downloadYearlyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + obj.put("isDeleted", (Object)0); + String filePath = this.esRecordReportService.getBirdDataYearlyStatFileByParam(obj); + this.processPath(filePath, response); + } + + private void processPath(String filePath, HttpServletResponse response) { + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception exception) { + // empty catch block + } + } + } + + @PostMapping(value={"/sendWeeklyEmail"}) + public AjaxResult sendWeeklyEmail(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.sendBirdDataStatWeeklyEmail(object)); + } + + @PostMapping(value={"/sendMonthlyEmail"}) + public AjaxResult sendMonthlyEmail(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.sendBirdDataStatMonthlyEmail(object)); + } + + @PostMapping(value={"/sendYearlyEmail"}) + public AjaxResult sendYearlyEmail(@RequestBody JSONObject object) { + object.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esRecordReportService.sendBirdDataStatYearlyEmail(object)); + } + + @PostMapping(value={"/downloadDailyReport"}) + public void downloadReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + obj.put("isDeleted", (Object)0); + String filePath = this.esRecordReportService.getBirdDataStatDailyFileByParam(obj); + this.processPath(filePath, response); + } + + @PostMapping(value={"/sendDailyEmail"}) + public AjaxResult sendEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.esRecordReportService.sendBirdDataStatEmail(object)); + } + + @PostMapping(value={"/speciesMediaStatList"}) + public JSONObject getSpeciesMediaListByParam(@RequestBody JSONObject object) { + return this.esRecordReportService.getSpeciesMediaListByParam(object); + } + + public EsRecordReportController(EsRecordReportService esRecordReportService) { + this.esRecordReportService = esRecordReportService; + } +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsResultRecordDetailsController.java b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsResultRecordDetailsController.java new file mode 100644 index 0000000..e9f4c13 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsResultRecordDetailsController.java @@ -0,0 +1,134 @@ +package net.hzvtc.es.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.es.service.EsResultRecordDetailsService; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/es/result/details"}) +public class EsResultRecordDetailsController { + private final EsResultRecordDetailsService esResultRecordDetailsService; + + @PostMapping(value={"/querySpeciesByParam"}) + public TableDataInfo querySpeciesListByParam(@RequestBody JSONObject params) { + params.put("isDeleted", (Object)0); + return this.esResultRecordDetailsService.querySpeciesRecordListByParam(params, 0); + } + + @PostMapping(value={"/queryDataByParam"}) + public TableDataInfo querySpeciesDataListByParam(@RequestBody JSONObject params) { + return this.esResultRecordDetailsService.querySpeciesDataListByParam(params); + } + + @PostMapping(value={"/getSpeciesStatInfoByParam"}) + public JSONObject getSpeciesStatInfoByParam(@RequestBody JSONObject params) { + return this.esResultRecordDetailsService.getSpeciesStatInfo(params); + } + + @PostMapping(value={"/querySpeciesByParamForApp"}) + public TableDataInfo querySpeciesListByParamForApp(@RequestBody JSONObject params) { + params.put("isDeleted", (Object)0); + return this.esResultRecordDetailsService.querySpeciesRecordListByParam(params, 1); + } + + @PostMapping(value={"/querySpeciesByQuery"}) + public TableDataInfo querySpeciesListByQuery(@RequestBody JSONObject obj) { + obj.put("isDeleted", (Object)0); + return this.esResultRecordDetailsService.getProtectedAreaSpeciesByQuery(obj); + } + + @PostMapping(value={"/birdResultMedias"}) + public TableDataInfo getBirdResultMediasByParam(@RequestBody JSONObject params) { + return this.esResultRecordDetailsService.getResultMediaListByParam(params); + } + + @DeleteMapping(value={"/delDocument/{ids}"}) + public AjaxResult deleteDocumentById(@PathVariable String ids) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.deleteDocumentById(ids)); + } + + @PostMapping(value={"/checkDocument/{ids}"}) + public AjaxResult updateDocumentCheckedById(@PathVariable String ids) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateDocumentCheckedById(ids)); + } + + @PostMapping(value={"/updateResultRecord"}) + public AjaxResult updateResultRecord(@RequestBody JSONObject data) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateResultRecordInfoById(data)); + } + + @PostMapping(value={"/updateResultRecords"}) + public AjaxResult updateResultRecords(@RequestBody JSONObject data) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateResultRecordInfoByIds(data)); + } + + @PostMapping(value={"/birdAudioDailyStat"}) + public AjaxResult getBirdAudioDailyStatList(@RequestBody JSONObject obj) { + obj.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esResultRecordDetailsService.getBirdAudioDailyStatListByParam(obj)); + } + + @PostMapping(value={"/birdDailyStat"}) + public AjaxResult getBirdDailyStatList(@RequestBody JSONObject obj) { + obj.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esResultRecordDetailsService.getBirdDailyStatListByParam(obj)); + } + + @PostMapping(value={"/birdAudioMonthStat"}) + public AjaxResult getBirdAudioMonthStatList(@RequestBody JSONObject obj) { + obj.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esResultRecordDetailsService.getBirdAudioMonthStatListByParam(obj)); + } + + @PostMapping(value={"/birdAudioYearStat"}) + public AjaxResult getBirdAudioYearStatList(@RequestBody JSONObject obj) { + obj.put("isDeleted", (Object)0); + return AjaxResult.success((Object)this.esResultRecordDetailsService.getBirdAudioYearStatListByParam(obj)); + } + + @GetMapping(value={"/listByParam"}) + public AjaxResult getListByParam(DeviceInfo deviceInfo) { + return AjaxResult.success(this.esResultRecordDetailsService.getDeviceInfoListForPage(deviceInfo)); + } + + @PostMapping(value={"/updateDocumentDeletedState"}) + public AjaxResult updateStatus(@RequestBody JSONObject param) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateResultRecordInfoById(param)); + } + + @PostMapping(value={"/updateDocumentFavorite"}) + public AjaxResult updateFavorite(@RequestBody JSONObject param) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateResultRecordInfoById(param)); + } + + @PostMapping(value={"/updateEsDocument/{recordId}"}) + public AjaxResult updateEsDocument(@PathVariable Long recordId) { + this.esResultRecordDetailsService.bulkAddResultRecordDocumentById(recordId); + return AjaxResult.success(); + } + + @PostMapping(value={"/areaSpeciesListByParam"}) + public AjaxResult getSpeciesListByParam(@RequestBody JSONObject params) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.getAreaSpeciesListByParam(params)); + } + + @PostMapping(value={"/updateMediaUrlPath"}) + public AjaxResult updateMediaUrlPath(@RequestBody JSONObject params) { + return AjaxResult.success((Object)this.esResultRecordDetailsService.updateMediaUrlPrefixPathByParam(params)); + } + + public EsResultRecordDetailsController(EsResultRecordDetailsService esResultRecordDetailsService) { + this.esResultRecordDetailsService = esResultRecordDetailsService; + } +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsSpeciesInfoApiController.java b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsSpeciesInfoApiController.java new file mode 100644 index 0000000..cebd979 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/controller/EsSpeciesInfoApiController.java @@ -0,0 +1,24 @@ +package net.hzvtc.es.controller; + +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.es.service.EsResultRecordDetailsService; +import org.springframework.context.annotation.Lazy; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/web/species/api") +@RequiredArgsConstructor(onConstructor = @__(@Lazy)) +public class EsSpeciesInfoApiController extends BaseController { + private final EsResultRecordDetailsService esResultRecordDetailsService; + + @PostMapping("/audioList") + public AjaxResult getBirdAudioListByParam(@RequestBody JSONObject obj) { + return AjaxResult.success(esResultRecordDetailsService.getAudioListByParam(obj)); + } +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultData.java b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultData.java new file mode 100644 index 0000000..8709d41 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultData.java @@ -0,0 +1,32 @@ +package net.hzvtc.es.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="EsResultData") +@Data +public class EsResultData { + private String id; + private ZonedDateTime recordTime; + private Long detailsId; + private Long deviceId; + private String deviceName; + private String serialNumber; + private Long speciesId; + private String name; + private String scientificName; + private int count; + private String habitat; + private double confidence; + private Long mediaId; + private String mediaUrl; + private String metaUrl; + private String fileUrl; + private Integer mediaType; + private Integer subType; + private String birdIcon; + private String description; + private BirdSpecies birdSpecies; +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetails.java b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetails.java new file mode 100644 index 0000000..96bd71c --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetails.java @@ -0,0 +1,34 @@ +package net.hzvtc.es.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="EsResultRecordDetails") +@Data +public class EsResultRecordDetails { + private Long id; + private ZonedDateTime recordTime; + private Long recordId; + private Long deviceId; + private String deviceName; + private String serialNumber; + private Long speciesId; + private String speciesName; + private String scientificName; + private Long areaId; + private String areaName; + private int checked; + private int count; + private String habitat; + private double confidence; + private Long mediaId; + private String mediaUrl; + private String metaUrl; + private int mediaType; + private int recordType; + private Integer favorite; + private String birdIcon; + private int isDeleted; +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetailsVo.java b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetailsVo.java new file mode 100644 index 0000000..3bc5d63 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/domain/EsResultRecordDetailsVo.java @@ -0,0 +1,34 @@ +package net.hzvtc.es.domain; + +import java.util.Date; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="EsResultRecordDetailsVo") +@JsonIgnoreProperties(ignoreUnknown=true) +@Data +public class EsResultRecordDetailsVo { + private Long id; + private LocalDateTime recordTime1; + private Long recordId; + private Long deviceId; + private String deviceName; + private String serialNumber; + private Long speciesId; + private String speciesName; + private String scientificName; + private Long areaId; + private String areaName; + private int checked; + private int count; + private String habitat; + private double confidence; + private Long mediaId; + private String mediaUrl; + private String metaUrl; + private int mediaType; + private int recordType; + private Integer favorite; + private String birdIcon; + private int isDeleted; +} diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/mapper/EsResultRecordDetailsMapper.java b/ai-bird-es/src/main/java/net/hzvtc/es/mapper/EsResultRecordDetailsMapper.java new file mode 100644 index 0000000..c3500cc --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/mapper/EsResultRecordDetailsMapper.java @@ -0,0 +1,20 @@ +package net.hzvtc.es.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.es.domain.EsResultRecordDetailsVo; + +public interface EsResultRecordDetailsMapper { + public List getResultRecordListForElastic(Map var1); + + public List getDeviceListByParam(Map var1); + + public List getAreaBirdSpeciesByParam(Map var1); + + public long getMediaUrlPrefixPathAmount(String var1); + + public List getMediaUrlPrefixPathListByParam(Map var1); +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/service/EsRecordReportService.java b/ai-bird-es/src/main/java/net/hzvtc/es/service/EsRecordReportService.java new file mode 100644 index 0000000..18564c6 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/service/EsRecordReportService.java @@ -0,0 +1,35 @@ +package net.hzvtc.es.service; + +import com.alibaba.fastjson.JSONObject; + +public interface EsRecordReportService { + public JSONObject getBirdDailyReportStatByParam(JSONObject var1); + + public JSONObject getBirdDailyReportMaxStatByParam(JSONObject var1); + + public String getBirdDataStatDailyFileByParam(JSONObject var1); + + public String getBirdDataStatWeeklyFileByParam(JSONObject var1); + + public boolean sendBirdDataStatEmail(JSONObject var1); + + public boolean sendBirdDataStatWeeklyEmail(JSONObject var1); + + public boolean sendBirdDataStatMonthlyEmail(JSONObject var1); + + public boolean sendBirdDataStatYearlyEmail(JSONObject var1); + + public JSONObject getSpeciesWeeklyReportByParam(JSONObject var1); + + public JSONObject getSpeciesMonthlyReportByParam(JSONObject var1); + + public JSONObject getSpeciesYearlyReportByParam(JSONObject var1); + + public JSONObject getSpeciesMediaListByParam(JSONObject var1); + + public String getBirdDataMonthlyStatFileByParam(JSONObject var1); + + public String getBirdDataYearlyStatFileByParam(JSONObject var1); +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/service/EsResultRecordDetailsService.java b/ai-bird-es/src/main/java/net/hzvtc/es/service/EsResultRecordDetailsService.java new file mode 100644 index 0000000..49d03c0 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/service/EsResultRecordDetailsService.java @@ -0,0 +1,53 @@ +package net.hzvtc.es.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.device.domain.DeviceInfo; + +public interface EsResultRecordDetailsService { + public TableDataInfo querySpeciesRecordListByParam(JSONObject var1, int var2); + + public TableDataInfo querySpeciesDataListByParam(JSONObject var1); + + public TableDataInfo getProtectedAreaSpeciesByQuery(JSONObject var1); + + public TableDataInfo getResultMediaListByParam(JSONObject var1); + + public int deleteDocumentById(String var1); + + public int updateDocumentCheckedById(String var1); + + public void bulkAddResultRecordDocument(); + + public void bulkAddResultRecordDocumentById(Long var1); + + public long getMaxResultRecordId(); + + public boolean updateResultRecordInfoById(JSONObject var1); + + public boolean updateResultRecordInfoByIds(JSONObject var1); + + public JSONObject getBirdAudioDailyStatListByParam(JSONObject var1); + + public JSONObject getBirdDailyStatListByParam(JSONObject var1); + + public JSONObject getBirdAudioMonthStatListByParam(JSONObject var1); + + public JSONObject getBirdAudioYearStatListByParam(JSONObject var1); + + public List getDeviceInfoListForPage(DeviceInfo var1); + + public JSONArray getAreaSpeciesListByParam(JSONObject var1); + + public JSONObject getAudioListByParam(JSONObject var1); + + public boolean updateDocumentStatusByParam(JSONObject var1); + + public JSONObject getSpeciesStatInfo(JSONObject var1); + + public long updateMediaUrlPrefixPathByParam(JSONObject var1); +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/CommonEsUtils.java b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/CommonEsUtils.java new file mode 100644 index 0000000..0627349 --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/CommonEsUtils.java @@ -0,0 +1,191 @@ +package net.hzvtc.es.service.impl; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch._types.SortOrder; +import co.elastic.clients.elasticsearch._types.aggregations.Aggregate; +import co.elastic.clients.elasticsearch._types.aggregations.BucketsPath; +import co.elastic.clients.elasticsearch._types.aggregations.CalendarInterval; +import co.elastic.clients.elasticsearch._types.aggregations.DateHistogramAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.MaxBucketAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.SumAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.TermsAggregation; +import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; +import co.elastic.clients.elasticsearch.core.SearchRequest; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.core.search.Hit; +import co.elastic.clients.elasticsearch.core.search.TrackHits; +import co.elastic.clients.json.JsonData; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.io.IOException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.hzvtc.es.domain.EsResultRecordDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CommonEsUtils { + private static final Logger log = LoggerFactory.getLogger(CommonEsUtils.class); + + public static JSONArray getSpeciesAggregateList(JSONObject param, String indexName, ElasticsearchClient elasticsearchClient, CalendarInterval calendarInterval) throws IOException { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index(indexName, new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_speciesId", a -> a.terms(TermsAggregation.of(ta -> ta.field("species_id").size(Integer.valueOf(100000)))).aggregations("by_calendarInterval", b -> b.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(calendarInterval))).aggregations("sum_count_field", s -> s.sum(SumAggregation.of(sa -> (SumAggregation.Builder)sa.field("count"))))))); + SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate bySpeciesAgg = (Aggregate)aggs.get("by_speciesId"); + JSONArray jsonArray = new JSONArray(); + bySpeciesAgg.lterms().buckets().array().forEach(speciesBucket -> { + Aggregate byCalendarInterval = (Aggregate)speciesBucket.aggregations().get("by_calendarInterval"); + byCalendarInterval.dateHistogram().buckets().array().forEach(hourBucket -> { + if (hourBucket.keyAsString() != null) { + JSONObject item = new JSONObject(); + ZonedDateTime zonedDateTime = ZonedDateTime.parse(hourBucket.keyAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME); + LocalDateTime dateTime = zonedDateTime.toLocalDateTime(); + if (calendarInterval == CalendarInterval.Hour) { + item.put("hour", (Object)dateTime.getHour()); + } else if (calendarInterval == CalendarInterval.Day) { + item.put("weekDay", (Object)dateTime.getDayOfWeek()); + } + item.put("speciesId", (Object)speciesBucket.key()); + Aggregate sumAgg = (Aggregate)hourBucket.aggregations().get("sum_count_field"); + item.put("count", (Object)((int)sumAgg.sum().value())); + jsonArray.add((Object)item); + } + }); + }); + return jsonArray; + } + + public static JSONArray getMaxMonthStatDataByParam(JSONObject param, String indexName, ElasticsearchClient elasticsearchClient, CalendarInterval calendarMonthInterval, CalendarInterval calendarDayInterval, CalendarInterval calendarHourInterval) throws IOException { + JSONArray array = new JSONArray(); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = new SearchRequest.Builder().index(indexName, new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("b_month", m -> m.dateHistogram(mh -> mh.field("record_time").timeZone("+08:00").calendarInterval(calendarMonthInterval).format("yyyy-MM")).aggregations("by_date", d -> d.dateHistogram(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(calendarDayInterval).format("yyyy-MM-dd")).aggregations("by_species_id", a -> a.terms(t -> t.field("species_id").size(Integer.valueOf(10000))).aggregations("hourly_sums", h -> h.dateHistogram(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(calendarHourInterval).minDocCount(Integer.valueOf(1))).aggregations("sum_per_hour", sa -> sa.sum(s -> (SumAggregation.Builder)s.field("count")))).aggregations("max_hourly_sum", maxBucket -> maxBucket.maxBucket(mb -> (MaxBucketAggregation.Builder)mb.bucketsPath(BucketsPath.of(bp -> bp.single("hourly_sums>sum_per_hour")))))))).build(); + SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate byMonthAgg = (Aggregate)aggs.get("b_month"); + byMonthAgg.dateHistogram().buckets().array().forEach(bucket -> { + JSONObject object = new JSONObject(); + String curDate = bucket.keyAsString(); + object.put("date", (Object)curDate); + if (curDate != null) { + String[] arr = curDate.split("-"); + object.put("weekDay", (Object)(Integer.parseInt(arr[1]) - 1)); + } + double[] max = new double[]{0.0}; + ((Aggregate)bucket.aggregations().get("by_date")).dateHistogram().buckets().array().forEach(subBucket -> { + double[] sum = new double[]{0.0}; + ((Aggregate)subBucket.aggregations().get("by_species_id")).lterms().buckets().array().forEach(item -> { + sum[0] = sum[0] + ((Aggregate)item.aggregations().get("max_hourly_sum")).bucketMetricValue().value(); + }); + if (sum[0] > max[0]) { + max[0] = sum[0]; + } + }); + object.put("count", (Object)max[0]); + array.add((Object)object); + }); + return array; + } + + public static JSONArray getMaxDateStatDataByParam(JSONObject param, String indexName, ElasticsearchClient elasticsearchClient, CalendarInterval calendarDayInterval, CalendarInterval calendarHourInterval, int type) throws IOException { + JSONArray array = new JSONArray(); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = new SearchRequest.Builder().index(indexName, new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_date", d -> d.dateHistogram(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(calendarDayInterval).format("yyyy-MM-dd")).aggregations("by_species_id", a -> a.terms(t -> t.field("species_id").size(Integer.valueOf(10000))).aggregations("hourly_sums", h -> h.dateHistogram(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(calendarHourInterval).minDocCount(Integer.valueOf(1))).aggregations("sum_per_hour", sa -> sa.sum(s -> (SumAggregation.Builder)s.field("count")))).aggregations("max_hourly_sum", maxBucket -> maxBucket.maxBucket(mb -> (MaxBucketAggregation.Builder)mb.bucketsPath(BucketsPath.of(bp -> bp.single("hourly_sums>sum_per_hour"))))))).build(); + SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate byDataAgg = (Aggregate)aggs.get("by_date"); + byDataAgg.dateHistogram().buckets().array().forEach(bucket -> { + JSONObject object = new JSONObject(); + String curDate = bucket.keyAsString(); + object.put("date", (Object)curDate); + if (type == 1) { + object.put("weekDay", (Object)CommonEsUtils.getWeekDay(curDate)); + } else if (type == 2) { + object.put("weekDay", (Object)CommonEsUtils.getMonthDay(curDate)); + } + AtomicReference sum = new AtomicReference(0.0); + ((Aggregate)bucket.aggregations().get("by_species_id")).lterms().buckets().array().forEach(subBucket -> sum.updateAndGet(v -> v + ((Aggregate)subBucket.aggregations().get("max_hourly_sum")).bucketMetricValue().value())); + object.put("count", (Object)sum.get().intValue()); + array.add((Object)object); + }); + return array; + } + + private static int getMonthDay(String dateString) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate date = LocalDate.parse(dateString, formatter); + return date.getDayOfMonth() - 1; + } + + private static int getWeekDay(String dateString) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate date = LocalDate.parse(dateString, formatter); + return date.getDayOfWeek().getValue() - 1; + } + + public static EsResultRecordDetails getResultRecordDetailsByParam(JSONObject param, String indexName, ElasticsearchClient elasticsearchClient) throws IOException { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchResponse response = elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index(indexName, new String[0]).query(q -> q.bool(boolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("favorite").order(SortOrder.Desc))).sort(sort -> sort.field(f -> f.field("id").order(SortOrder.Desc))).from(Integer.valueOf(0)).size(Integer.valueOf(1)), EsResultRecordDetails.class); + List hitList = response.hits().hits(); + Iterator iterator = hitList.iterator(); + if (iterator.hasNext()) { + Hit mapHit = (Hit)iterator.next(); + return (EsResultRecordDetails)mapHit.source(); + } + return null; + } + + public static long getSpeciesStatAmountByParam(JSONObject param, String indexName, ElasticsearchClient elasticsearchClient) throws IOException { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index(indexName, new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("sum_count_field", a -> a.sum(SumAggregation.of(ta -> (SumAggregation.Builder)ta.field("count"))))); + SearchResponse searchResponse = elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate sumAgg = (Aggregate)aggs.get("sum_count_field"); + return (long)sumAgg.sum().value(); + } + + public static BoolQuery.Builder createQuery(JSONObject param) { + Integer subType; + Integer notMediaType; + Integer mediaType; + String dateTo; + String dateFrom; + Long mediaId; + Long speciesId; + BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder(); + Long areaId = param.getLong("areaId"); + if (areaId != null) { + boolQueryBuilder.must(m -> m.match(t -> t.field("area_id").query(areaId.longValue()))); + } + if ((speciesId = param.getLong("speciesId")) != null) { + boolQueryBuilder.must(m -> m.match(t -> t.field("species_id").query(speciesId.longValue()))); + } + if ((mediaId = param.getLong("mediaId")) != null) { + boolQueryBuilder.must(m -> m.match(t -> t.field("media_id").query(mediaId.longValue()))); + } + if ((dateFrom = param.getString("dateFrom")) != null && !dateFrom.isEmpty()) { + boolQueryBuilder.must(m -> m.range(v -> v.field("record_time").format("yyyy-MM-dd").gte(JsonData.of((Object)dateFrom)).timeZone("+08:00"))); + } + if ((dateTo = param.getString("dateTo")) != null && !dateTo.isEmpty()) { + boolQueryBuilder.must(m -> m.range(v -> v.field("record_time").format("yyyy-MM-dd").lte(JsonData.of((Object)dateTo)).timeZone("+08:00"))); + } + if ((mediaType = param.getInteger("mediaType")) != null) { + boolQueryBuilder.must(m -> m.match(t -> t.field("media_type").query((long)mediaType.intValue()))); + } + if ((notMediaType = param.getInteger("notMediaType")) != null) { + boolQueryBuilder.mustNot(m -> m.match(t -> t.field("media_type").query((long)notMediaType.intValue()))); + } + if ((subType = param.getInteger("subType")) != null) { + boolQueryBuilder.must(m -> m.match(t -> t.field("sub_type").query((long)subType.intValue()))); + } + return boolQueryBuilder; + } +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsRecordReportServiceImpl.java b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsRecordReportServiceImpl.java new file mode 100644 index 0000000..702bace --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsRecordReportServiceImpl.java @@ -0,0 +1,1111 @@ +package net.hzvtc.es.service.impl; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch._types.SortOrder; +import co.elastic.clients.elasticsearch._types.aggregations.Aggregate; +import co.elastic.clients.elasticsearch._types.aggregations.CalendarInterval; +import co.elastic.clients.elasticsearch._types.aggregations.DateHistogramAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.SumAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.TermsAggregation; +import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; +import co.elastic.clients.elasticsearch.core.SearchRequest; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.core.search.Hit; +import co.elastic.clients.elasticsearch.core.search.TrackHits; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.email.service.EmailService; +import net.hzvtc.es.domain.EsResultRecordDetails; +import net.hzvtc.es.mapper.EsResultRecordDetailsMapper; +import net.hzvtc.es.service.EsRecordReportService; +import net.hzvtc.es.service.impl.CommonEsUtils; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +@Service +public class EsRecordReportServiceImpl +implements EsRecordReportService { + private static final Logger log = LoggerFactory.getLogger(EsRecordReportServiceImpl.class); + private static final Logger logger = LoggerFactory.getLogger(EsRecordReportService.class); + @Resource + private final EsResultRecordDetailsMapper esResultRecordDetailsMapper; + private final ElasticsearchClient elasticsearchClient; + private final EmailService emailService; + private final SpeciesDailyStatService speciesDailyStatService; + private final ProtectedAreaSpeciesService protectedAreaSpeciesService; + @Value(value="${hzvtc.dailyReportFilePath}") + private String dailyReportFilePath; + @Value(value="${hzvtc.dailyReportFileOutPath}") + private String dailyReportFileOutPath; + private final ProtectedAreaService protectedAreaService; + private final String indexName = "result_record_details"; + + @Override + public JSONObject getBirdDailyReportStatByParam(JSONObject param) { + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + param.put("calcDate", (Object)df.format(new Date())); + } + JSONObject result = new JSONObject(); + JSONArray deviceData = this.getSpeciesDailyAmountByDeviceId(param); + Object[] array = this.compactJSONArray(deviceData); + result.put("deviceData", (Object)deviceData); + Map map = this.createQueryMap(param); + List list = this.esResultRecordDetailsMapper.getAreaBirdSpeciesByParam(map); + JSONArray array1 = new JSONArray(); + JSONArray array2 = new JSONArray(); + Long areaId = (Long)map.get("areaId"); + param.clear(); + param.put("areaId", (Object)areaId); + param.put("calcDate", (Object)calcDate); + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + JSONObject obj = new JSONObject(); + Long id = item.getId(); + obj.put("id", (Object)id); + obj.put("name", (Object)item.getName()); + obj.put("list", (Object)this.filterArrayBySpeciesId(array, id)); + array1.add((Object)obj); + try { + JSONObject obj1 = new JSONObject(); + param.put("speciesId", (Object)item.getId()); + obj1.put("id", (Object)id); + obj1.put("name", (Object)item.getName()); + param.put("recordType", (Object)1); + JSONArray arr = this.getSpeciesHabitatAggregateList(param); + if (arr.isEmpty()) { + param.put("recordType", (Object)2); + arr = this.getSpeciesHabitatAggregateList(param); + } + obj1.put("list", (Object)arr); + array2.add((Object)obj1); + } + catch (IOException ex) { + logger.error("error", (Throwable)ex); + } + }); + } + result.put("speciesData", (Object)array1); + result.put("habitatData", (Object)array2); + result.put("mediaList", new ArrayList()); + return result; + } + + @Override + public JSONObject getBirdDailyReportMaxStatByParam(JSONObject param) { + return null; + } + + @Override + public String getBirdDataStatDailyFileByParam(JSONObject param) { + try { + AtomicInteger starRow; + SimpleDateFormat df; + Long areaId = param.getLong("areaId"); + String areaName = ""; + if (areaId == null) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(areaId); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook(Files.newInputStream(Paths.get(this.dailyReportFilePath + "daily_report_tmpl.xlsx", new String[0]), new OpenOption[0])); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + df = new SimpleDateFormat("yyyyMMddHHmmss"); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + calcDate); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u65e5\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u5206\u65f6\u76d1\u6d4b\u6570\u91cf"); + JSONObject result = this.getBirdDailyReportStatByParam(param); + JSONArray array = result.getJSONArray("deviceData"); + int[] sum = new int[]{0, 0, 0}; + if (array != null) { + int i; + starRow = new AtomicInteger(8); + array.forEach(data -> { + int i; + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] value = new int[]{0, 0, 0}; + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + int hour = element.getInteger("hour"); + int count = element.getInteger("count"); + if (hour <= 12) { + value[0] = value[0] + count; + } else { + value[1] = value[1] + count; + } + value[2] = Math.max(value[0], value[1]); + }); + } + for (i = 0; i < sum.length; ++i) { + int n = i; + sum[n] = sum[n] + value[i]; + } + for (i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + starRow.getAndIncrement(); + }); + int cell = 2; + for (i = 0; i < sum.length; ++i) { + sheet.getRow(28).getCell(cell++).setCellValue((double)sum[i]); + } + for (i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(8 + array.size() + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(32); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] value = new int[]{0, 0, 0, 0, 0}; + JSONArray subArray = obj.getJSONArray("list"); + if (subArray != null) { + subArray.stream().map(el -> (JSONObject)el).forEach(element -> { + String code = element.getString("habitat"); + int count = element.getInteger("count"); + if ("ground".equals(code)) { + value[0] = count; + } else if ("shoreside".equals(code)) { + value[1] = count; + } else if ("water".equals(code)) { + value[2] = count; + } else if ("tree".equals(code)) { + value[3] = count; + } else { + value[4] = count; + } + }); + } + for (int i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + List list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + XSSFCell xssfCell; + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] value = new int[11]; + JSONArray subArray = obj.getJSONArray("list"); + int[] index = new int[]{0}; + if (subArray != null) { + subArray.forEach(el -> { + if (index[0] >= 0 && index[0] < 11) { + value[index[0]] = (Integer)el; + } + index[0] = index[0] + 1; + }); + } + for (int i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + Arrays.sort(value); + int max = value[value.length - 1]; + XSSFRow row = sheet.getRow(starRow.get()); + if (row == null) { + row = sheet.createRow(starRow.get()); + } + if ((xssfCell = row.getCell(cell)) == null) { + xssfCell = row.createCell(cell); + } + xssfCell.setCellValue((double)max); + ++cell; + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5(\u65e5\u671f" + calcDate + ").xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + logger.error(ex.getMessage()); + return null; + } + } + + @Override + public String getBirdDataStatWeeklyFileByParam(JSONObject param) { + try { + List list; + AtomicInteger starRow; + String areaId = param.getString("areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "weekly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + dateBegin + "~" + dateEnd); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u5468\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("dateBegin", (Object)dateBegin); + param.put("dateEnd", (Object)dateEnd); + param.put("limit", (Object)8); + param.put("isCommon", (Object)1); + JSONObject result = this.getSpeciesWeeklyReportByParam(param); + JSONArray array = result.getJSONArray("areaData"); + if (array != null) { + int[] sum = new int[8]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + int weekday = element.getInteger("weekDay"); + counts[weekday] = element.getInteger("count"); + }); + } + int i = 0; + for (int val : counts) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + int n = i; + sum[n] = sum[n] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 9 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + int weekDay = element.getInteger("weekDay"); + counts[weekDay] = element.getInteger("count"); + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + String code = element.getString("habitat"); + int count = element.getInteger("count"); + if ("ground".equals(code)) { + counts[0] = count; + } else if ("shoreside".equals(code)) { + counts[1] = count; + } else if ("water".equals(code)) { + counts[2] = count; + } else if ("tree".equals(code)) { + counts[3] = count; + } else { + counts[4] = count; + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + dateBegin + "-" + dateEnd + ").xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + return null; + } + } + + @Override + public boolean sendBirdDataStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + String filePath = this.getBirdDataStatDailyFileByParam(param); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + calcDate, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5,\u8bf7\u67e5\u6536", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataStatWeeklyEmail(JSONObject param) { + String areaId = param.getString("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String areaCode = ""; + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + areaCode = data.getCode(); + param.put("areaCode", (Object)areaCode); + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + String filePath = this.getBirdDataStatWeeklyFileByParam(param); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + dateBegin + "~" + dateEnd, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + dateBegin + "~" + dateEnd + ",\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataStatMonthlyEmail(JSONObject param) { + String areaId = param.getString("areaId"); + if (areaId == null || areaId.isEmpty()) { + return false; + } + ProtectedArea data = null; + data = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String[] arr = calcDate.split("-"); + String filePath = this.getBirdDataMonthlyStatFileByParam(param); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u6708\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708", "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708,\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataStatYearlyEmail(JSONObject param) { + String filePath; + String areaId = param.getString("areaId"); + if (areaId == null || areaId.isEmpty()) { + return false; + } + ProtectedArea data = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + calcDate = df.format(new Date()); + } + if ((filePath = this.getBirdDataYearlyStatFileByParam(param)) != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5e74\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + calcDate + "\u5e74", "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + calcDate + "\u5e74,\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public JSONObject getSpeciesWeeklyReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + return result; + } + param.put("dateFrom", (Object)DateUtils.getFirstDayOfWeek((String)calcDate)); + param.put("dateTo", (Object)DateUtils.getLastDayOfWeek((String)calcDate)); + param.put("calcDate", null); + result.put("areaData", (Object)this.getDeviceDataStatByParam(param, 1)); + result.put("speciesData", (Object)this.getSpeciesDataStatByParam(param, 1)); + result.put("habitatData", (Object)this.getHabitatDataStatByParam(param)); + return result; + } + + @Override + public JSONObject getSpeciesMonthlyReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + return result; + } + param.put("dateFrom", (Object)DateUtils.getFirstDayOfMonth((String)calcDate)); + param.put("dateTo", (Object)DateUtils.getLastDayOfMonth((String)calcDate)); + int days = DateUtils.getDaysOfMonth((String)calcDate); + param.put("days", (Object)days); + param.put("calcDate", null); + result.put("areaData", (Object)this.getDeviceDataStatByParam(param, 2)); + result.put("speciesData", (Object)this.getSpeciesDataStatByParam(param, 2)); + result.put("habitatData", (Object)this.getHabitatDataStatByParam(param)); + result.put("days", (Object)days); + return result; + } + + @Override + public JSONObject getSpeciesYearlyReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + return result; + } + param.put("dateFrom", (Object)(calcDate + "-01-01")); + param.put("dateTo", (Object)(calcDate + "-12-31")); + param.put("calcDate", null); + result.put("areaData", (Object)this.getDeviceDataStatByParam(param, 3)); + result.put("speciesData", (Object)this.getSpeciesDataStatByParam(param, 3)); + result.put("habitatData", (Object)this.getHabitatDataStatByParam(param)); + return result; + } + + private JSONArray getHabitatDataStatByParam(JSONObject param) { + JSONArray array = new JSONArray(); + Map map = this.createQueryMap(param); + List list = this.esResultRecordDetailsMapper.getAreaBirdSpeciesByParam(map); + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + try { + param.put("speciesId", (Object)item.getId()); + JSONObject object = new JSONObject(); + JSONArray jsonArray = this.getSpeciesHabitatAggregateList(param); + object.put("list", (Object)jsonArray); + object.put("name", (Object)item.getName()); + object.put("id", (Object)item.getId()); + array.add((Object)object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + }); + } + return array; + } + + private JSONArray getSpeciesDataStatByParam(JSONObject param, int type) { + JSONArray array = new JSONArray(); + Map map = this.createQueryMap(param); + List list = this.esResultRecordDetailsMapper.getAreaBirdSpeciesByParam(map); + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + try { + param.put("speciesId", (Object)item.getId()); + JSONObject object = new JSONObject(); + JSONArray jsonArray = type != 3 ? CommonEsUtils.getMaxDateStatDataByParam(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Day, CalendarInterval.Hour, type) : CommonEsUtils.getMaxMonthStatDataByParam(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Month, CalendarInterval.Day, CalendarInterval.Hour); + if (type == 1) { + object.put("list", (Object)jsonArray); + } else if (type == 2) { + object.put("list", (Object)this.convertMonthArray(jsonArray, param.getInteger("days"))); + } else if (type == 3) { + object.put("list", (Object)this.convertYearArray(jsonArray)); + } + object.put("name", (Object)item.getName()); + object.put("id", (Object)item.getId()); + array.add((Object)object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + }); + } + return array; + } + + private JSONArray getDeviceDataStatByParam(JSONObject param, int type) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + JSONArray areaData = new JSONArray(); + List list = this.esResultRecordDetailsMapper.getDeviceListByParam(map); + list.forEach(item -> { + try { + param.put("deviceId", (Object)item.getId()); + JSONObject object = new JSONObject(); + object.put("name", (Object)item.getName()); + object.put("id", (Object)item.getId()); + JSONArray array = type != 3 ? CommonEsUtils.getMaxDateStatDataByParam(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Day, CalendarInterval.Hour, type) : CommonEsUtils.getMaxMonthStatDataByParam(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Month, CalendarInterval.Day, CalendarInterval.Hour); + if (type == 1) { + object.put("list", (Object)array); + } else if (type == 2) { + int days = param.getInteger("days"); + object.put("list", (Object)this.convertMonthArray(array, days)); + } else if (type == 3) { + object.put("list", (Object)this.convertYearArray(array)); + } + areaData.add((Object)object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + }); + return areaData; + } + + private int[] convertYearArray(JSONArray array) { + int[] counts = new int[12]; + array.forEach(item -> { + JSONObject obj = (JSONObject)item; + counts[obj.getInteger((String)"weekDay").intValue()] = ((JSONObject)item).getInteger("count"); + }); + return counts; + } + + private int[] convertMonthArray(JSONArray array, int days) { + int[] counts = new int[days]; + array.forEach(item -> { + JSONObject obj = (JSONObject)item; + counts[obj.getInteger((String)"weekDay").intValue()] = ((JSONObject)item).getInteger("count"); + }); + return counts; + } + + private Map createQueryMap(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + String isCommon = param.getString("isCommon"); + if (isCommon != null && !isCommon.isEmpty()) { + map.put("isCommon", Integer.parseInt(isCommon)); + } else { + map.put("isCommon", 1); + } + map.put("limit", 8); + return map; + } + + @Override + public JSONObject getSpeciesMediaListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Map map = this.createQueryMap(param); + List list = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByAreaId(map); + if (list == null) { + return result; + } + JSONObject queryMap = new JSONObject(); + list.forEach(item -> { + queryMap.clear(); + queryMap.put("areaId", map.get("areaId")); + queryMap.put("speciesId", (Object)item.getSpeciesId()); + item.setTotal(this.speciesDailyStatService.getSpeciesDailyStatAmountByParam((Map)queryMap)); + LocalDate now = LocalDate.now(); + queryMap.put("curDate", (Object)now.toString()); + item.setToday(this.speciesDailyStatService.getSpeciesDailyStatAmountByParam((Map)queryMap)); + queryMap.put("curDate", (Object)now.plusDays(-1L).toString()); + item.setYesterday(this.speciesDailyStatService.getSpeciesDailyStatAmountByParam((Map)queryMap)); + }); + result.put("list", (Object)list); + result.put("favoriteList", this.getFavoriteMediaList(param)); + return result; + } + + @Override + public String getBirdDataMonthlyStatFileByParam(JSONObject param) { + try { + List list; + AtomicInteger starRow; + String areaId = (String)param.get((Object)"areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "monthly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u6708\u62a5"); + String calcDate = (String)param.get((Object)"calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String[] arr = calcDate.split("-"); + param.put("year", (Object)Integer.parseInt(arr[0])); + param.put("month", (Object)Integer.parseInt(arr[1])); + int days = DateUtils.getDaysOfMonth((String)calcDate); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708"); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u6708\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("limit", (Object)8); + param.put("isCommon", (Object)1); + JSONObject result = this.getSpeciesMonthlyReportByParam(param); + JSONArray array = result.getJSONArray("areaData"); + if (array != null) { + int[] sum = new int[days + 1]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + int i = 0; + while (i < days) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + int n = days; + sum[n] = sum[n] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 8 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + for (int i = 0; i < days; ++i) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + String code = element.getString("habitat"); + int count = element.getInteger("count"); + if ("ground".equals(code)) { + counts[0] = count; + } else if ("shoreside".equals(code)) { + counts[1] = count; + } else if ("water".equals(code)) { + counts[2] = count; + } else if ("tree".equals(code)) { + counts[3] = count; + } else { + counts[4] = count; + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + arr[0] + "\u5e74" + arr[1] + "\u6708).xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + return null; + } + } + + @Override + public String getBirdDataYearlyStatFileByParam(JSONObject param) { + try { + List list; + AtomicInteger starRow; + String areaId = (String)param.get((Object)"areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.valueOf(Long.parseLong(areaId))); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "yearly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5e74\u62a5"); + String calcDate = (String)param.get((Object)"calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + calcDate = df.format(new Date()); + } + param.put("year", (Object)Integer.parseInt(calcDate)); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + calcDate + "\u5e74"); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u5e74\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("limit", (Object)8); + param.put("isCommon", (Object)1); + JSONObject result = this.getSpeciesYearlyReportByParam(param); + JSONArray array = result.getJSONArray("areaData"); + if (array != null) { + int[] sum = new int[13]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + int i = 0; + while (i < 12) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + sum[12] = sum[12] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 8 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + for (int i = 0; i < 12; ++i) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (JSONObject)el).forEach(element -> { + String code = element.getString("habitat"); + int count = element.getInteger("count"); + if ("ground".equals(code)) { + counts[0] = count; + } else if ("shoreside".equals(code)) { + counts[1] = count; + } else if ("water".equals(code)) { + counts[2] = count; + } else if ("tree".equals(code)) { + counts[3] = count; + } else { + counts[4] = count; + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + calcDate + "\u5e74).xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + private List getFavoriteMediaList(JSONObject param) { + Long areaId = param.getLong("areaId"); + param.clear(); + param.put("areaId", (Object)areaId); + param.put("favorite", (Object)1); + param.put("mediaType", (Object)3); + param.put("isDeleted", (Object)0); + List list = this.getMediaListByParam(param, 8); + return list; + } + + private List getMediaListByParam(JSONObject param, int length) { + try { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchResponse response = this.elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index("result_record_details", new String[0]).query(q -> q.bool(boolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("record_time").order(SortOrder.Desc))).from(Integer.valueOf(0)).size(Integer.valueOf(100)), EsResultRecordDetails.class); + List hitList = response.hits().hits(); + ArrayList list = new ArrayList(); + for (Hit mapHit : hitList) { + list.add(mapHit.source()); + } + ArrayList jsonObjects = new ArrayList(); + int count = 0; + for (EsResultRecordDetails esResultRecordDetails : list) { + if (esResultRecordDetails.getMetaUrl() == null || esResultRecordDetails.getMetaUrl().isEmpty()) continue; + JSONObject obj = new JSONObject(); + obj.put("mediaId", (Object)esResultRecordDetails.getMediaId()); + obj.put("mediaUrl", (Object)esResultRecordDetails.getMediaUrl()); + obj.put("metaUrl", (Object)esResultRecordDetails.getMetaUrl()); + jsonObjects.add(obj); + if (++count <= length) continue; + break; + } + return jsonObjects; + } + catch (IOException ex) { + logger.error(ex.getMessage()); + return null; + } + } + + private JSONArray getSpeciesDailyAmountByDeviceId(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + List list = this.esResultRecordDetailsMapper.getDeviceListByParam(map); + JSONArray deviceDataArray = new JSONArray(); + list.forEach(item -> { + param.put("deviceId", (Object)item.getId()); + param.put("recordType", (Object)1); + param.put("isDeleted", (Object)0); + try { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + JSONArray array = CommonEsUtils.getSpeciesAggregateList(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Hour); + if (!array.isEmpty()) { + JSONArray ids = new JSONArray(); + for (Object obj1 : array) { + JSONObject jsonObject = (JSONObject)obj1; + ids.add((Object)jsonObject.getLong("speciesId")); + } + param.put("ids", (Object)ids); + } else { + array = new JSONArray(); + } + param.put("recordType", (Object)2); + JSONArray array1 = CommonEsUtils.getSpeciesAggregateList(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Hour); + array.addAll((Collection)array1); + obj.put("list", (Object)array); + deviceDataArray.add((Object)obj); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + }); + return deviceDataArray; + } + + private Object[] compactJSONArray(JSONArray array) { + HashMap map = new HashMap(); + for (Object obj : array) { + JSONObject obj1 = (JSONObject)obj; + JSONArray a1 = obj1.getJSONArray("list"); + for (Object obj2 : a1) { + JSONObject obj3 = (JSONObject)obj2; + Long speciesId = obj3.getLong("speciesId"); + JSONObject data = (JSONObject)map.get(speciesId); + int[] amountArr = null; + if (data == null) { + data = new JSONObject(); + amountArr = new int[12]; + data.put("speciesId", (Object)speciesId); + } else { + amountArr = (int[])data.get((Object)"array"); + } + int hour = obj3.getInteger("hour"); + if ((hour -= 8) >= 0 && hour <= 11) { + int n = hour; + amountArr[n] = amountArr[n] + obj3.getInteger("count"); + } + data.put("array", (Object)amountArr); + map.put(speciesId, data); + } + } + return map.values().toArray(); + } + + private JSONArray getSpeciesHabitatAggregateList(JSONObject param) throws IOException { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index("result_record_details", new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_speciesId", a -> a.terms(TermsAggregation.of(ta -> ta.field("species_id").size(Integer.valueOf(100000)))).aggregations("by_habitat", b -> b.terms(TermsAggregation.of(ta -> ta.field("habitat"))).aggregations("by_hour", c -> c.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(CalendarInterval.Hour))).aggregations("sum_count_field", s -> s.sum(SumAggregation.of(sa -> (SumAggregation.Builder)sa.field("count")))))))); + SearchResponse searchResponse = this.elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate bySpeciesAgg = (Aggregate)aggs.get("by_speciesId"); + JSONArray jsonArray = new JSONArray(); + bySpeciesAgg.lterms().buckets().array().forEach(speciesBucket -> { + Aggregate byHabitatAgg = (Aggregate)speciesBucket.aggregations().get("by_habitat"); + byHabitatAgg.sterms().buckets().array().forEach(habitatBucket -> { + Aggregate byHourAgg = (Aggregate)habitatBucket.aggregations().get("by_hour"); + JSONObject item = new JSONObject(); + item.put("habitat", (Object)habitatBucket.key().stringValue()); + item.put("speciesId", (Object)speciesBucket.key()); + int[] max = new int[]{0}; + byHourAgg.dateHistogram().buckets().array().forEach(hourBucket -> { + Aggregate sumAgg = (Aggregate)hourBucket.aggregations().get("sum_count_field"); + if (max[0] < (int)sumAgg.sum().value()) { + max[0] = (int)sumAgg.sum().value(); + } + }); + item.put("count", (Object)max[0]); + jsonArray.add((Object)item); + }); + }); + return jsonArray; + } + + private JSONArray filterArrayBySpeciesId(Object[] array, Long id) { + for (Object obj : array) { + JSONObject jobj = (JSONObject)obj; + Long speciesId = jobj.getLong("speciesId"); + if (!Objects.equals(speciesId, id)) continue; + return jobj.getJSONArray("array"); + } + return new JSONArray(); + } + + @Lazy + public EsRecordReportServiceImpl(EsResultRecordDetailsMapper esResultRecordDetailsMapper, ElasticsearchClient elasticsearchClient, EmailService emailService, SpeciesDailyStatService speciesDailyStatService, ProtectedAreaSpeciesService protectedAreaSpeciesService, ProtectedAreaService protectedAreaService) { + this.esResultRecordDetailsMapper = esResultRecordDetailsMapper; + this.elasticsearchClient = elasticsearchClient; + this.emailService = emailService; + this.speciesDailyStatService = speciesDailyStatService; + this.protectedAreaSpeciesService = protectedAreaSpeciesService; + this.protectedAreaService = protectedAreaService; + } +} + + diff --git a/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsResultRecordDetailsServiceImpl.java b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsResultRecordDetailsServiceImpl.java new file mode 100644 index 0000000..672222f --- /dev/null +++ b/ai-bird-es/src/main/java/net/hzvtc/es/service/impl/EsResultRecordDetailsServiceImpl.java @@ -0,0 +1,885 @@ +package net.hzvtc.es.service.impl; + +import co.elastic.clients.elasticsearch.ElasticsearchClient; +import co.elastic.clients.elasticsearch._types.SortOrder; +import co.elastic.clients.elasticsearch._types.aggregations.Aggregate; +import co.elastic.clients.elasticsearch._types.aggregations.CalendarInterval; +import co.elastic.clients.elasticsearch._types.aggregations.DateHistogramAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.MaxAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.SumAggregation; +import co.elastic.clients.elasticsearch._types.aggregations.TermsAggregation; +import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery; +import co.elastic.clients.elasticsearch.core.BulkRequest; +import co.elastic.clients.elasticsearch.core.BulkResponse; +import co.elastic.clients.elasticsearch.core.CountRequest; +import co.elastic.clients.elasticsearch.core.CountResponse; +import co.elastic.clients.elasticsearch.core.SearchRequest; +import co.elastic.clients.elasticsearch.core.SearchResponse; +import co.elastic.clients.elasticsearch.core.UpdateByQueryRequest; +import co.elastic.clients.elasticsearch.core.UpdateRequest; +import co.elastic.clients.elasticsearch.core.bulk.BulkOperation; +import co.elastic.clients.elasticsearch.core.bulk.IndexOperation; +import co.elastic.clients.elasticsearch.core.search.Hit; +import co.elastic.clients.elasticsearch.core.search.TrackHits; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedAreaSpecies; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.service.BirdMediaService; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.utils.CommonUtils; +import net.hzvtc.common.utils.PageUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.es.domain.EsResultData; +import net.hzvtc.es.domain.EsResultRecordDetails; +import net.hzvtc.es.domain.EsResultRecordDetailsVo; +import net.hzvtc.es.mapper.EsResultRecordDetailsMapper; +import net.hzvtc.es.service.EsResultRecordDetailsService; +import net.hzvtc.es.service.impl.CommonEsUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +@Service(value="esResultRecordDetailsService") +public class EsResultRecordDetailsServiceImpl +implements EsResultRecordDetailsService { + private static final Logger log = LoggerFactory.getLogger(EsResultRecordDetailsServiceImpl.class); + private static final Logger logger = LoggerFactory.getLogger(EsResultRecordDetailsService.class); + private final ElasticsearchClient elasticsearchClient; + private final BirdSpeciesService birdSpeciesService; + private final BirdMediaService birdMediaService; + private final DeviceInfoService deviceInfoService; + private final ProtectedAreaSpeciesService protectedAreaSpeciesService; + @Resource + private final EsResultRecordDetailsMapper esResultRecordDetailsMapper; + private final String indexName = "result_record_details"; + private final String indexDataName = "record_data_2030"; + private final String indexDataNewName = "record_data_new_2030"; + @Value(value="${hzvtc.fileServerUrl}") + private String fileServerUrl; + + @Override + public TableDataInfo querySpeciesRecordListByParam(JSONObject param, int type) { + Integer pageSize; + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + Integer pageNum = param.getInteger("pageNum"); + if (pageNum == null) { + pageNum = 1; + } + if ((pageSize = param.getInteger("pageSize")) == null) { + pageSize = 10; + } + int pageFrom = (pageNum - 1) * pageSize; + try { + Integer finalPageSize = pageSize; + SearchResponse response = this.elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index("result_record_details", new String[0]).query(q -> q.bool(boolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("record_time").order(SortOrder.Desc))).from(Integer.valueOf(pageFrom)).size(finalPageSize), EsResultRecordDetails.class); + List hitList = response.hits().hits(); + List list = new ArrayList(); + for (Hit mapHit : hitList) { + list.add(mapHit.source()); + } + if (type == 1) { + list = list.stream().peek(item -> item.setBirdIcon(this.birdMediaService.getBirdIconImageBySpeciesId(item.getSpeciesId()))).collect(Collectors.toList()); + } + long total = response.hits().total() != null ? response.hits().total().value() : 0L; + return this.getTableDataInfo(list, total); + } + catch (IOException e) { + logger.error(e.getMessage()); + return null; + } + } + + @Override + public TableDataInfo querySpeciesDataListByParam(JSONObject param) { + Integer pageSize; + log.info("querySpeciesDataListByParam param:{}", (Object)param); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + Integer mediaType = param.getInteger("mediaType"); + Integer subType = param.getInteger("subType"); + Integer pageNum = param.getInteger("pageNum"); + if (pageNum == null) { + pageNum = 1; + } + if ((pageSize = param.getInteger("pageSize")) == null) { + pageSize = 10; + } + int pageFrom = (pageNum - 1) * pageSize; + try { + Integer finalPageSize = pageSize; + SearchResponse response = this.elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index("record_data_2030", new String[0]).query(q -> q.bool(boolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("record_time").order(SortOrder.Desc))).from(Integer.valueOf(pageFrom)).size(finalPageSize), EsResultData.class); + List hitList = response.hits().hits(); + ArrayList list = new ArrayList(); + if (mediaType != null && mediaType == 4 && subType != null && subType == 2) { + for (Hit mapHit : hitList) { + EsResultData esResultData = (EsResultData)mapHit.source(); + Long speciesId = esResultData.getSpeciesId(); + if (speciesId != null) { + BirdSpecies birdSpecies = this.birdSpeciesService.selectBirdSpeciesById(speciesId); + esResultData.setBirdSpecies(birdSpecies); + } + list.add(esResultData); + } + } else { + for (Hit mapHit : hitList) { + list.add(mapHit.source()); + } + } + long total = response.hits().total() != null ? response.hits().total().value() : 0L; + return this.getTableDataInfo(list, total); + } + catch (IOException e) { + logger.error(e.getMessage()); + e.printStackTrace(); + return null; + } + } + + private ResultMedia getLastMediaInfoByParam(JSONObject param) { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + try { + SearchResponse response = this.elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index("result_record_details", new String[0]).query(q -> q.bool(boolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("record_time").order(SortOrder.Desc))).from(Integer.valueOf(0)).size(Integer.valueOf(1)), EsResultRecordDetails.class); + List hitList = response.hits().hits(); + ArrayList list = new ArrayList(); + for (Hit mapHit : hitList) { + list.add(mapHit.source()); + } + if (!list.isEmpty()) { + ResultMedia data = new ResultMedia(); + if (((EsResultRecordDetails)list.get(0)).getRecordTime() != null) { + data.setTime(Date.from(((EsResultRecordDetails)list.get(0)).getRecordTime().toInstant())); + } + return data; + } + } + catch (IOException e) { + logger.error(e.getMessage()); + } + return null; + } + + @Override + public TableDataInfo getProtectedAreaSpeciesByQuery(JSONObject param) { + HashMap map = new HashMap(); + Integer pageNum = param.getInteger("pageNum"); + Integer pageSize = param.getInteger("pageSize"); + PageUtils.startPage((Integer)pageNum, (Integer)pageSize); + String name = param.getString("name"); + map.put("name", name); + Long initAreaId = param.getLong("initAreaId"); + if (initAreaId != null) { + map.put("areaId", initAreaId); + } + List birdSpecies = this.birdSpeciesService.getBirdSpeciesListByQuery(map); + TableDataInfo rspData = new TableDataInfo(); + rspData.setCode(200); + rspData.setMsg("\u67e5\u8be2\u6210\u529f"); + rspData.setTotal(new PageInfo(birdSpecies).getTotal()); + ArrayList list = new ArrayList(); + for (BirdSpecies item : birdSpecies) { + ProtectedAreaSpecies data = new ProtectedAreaSpecies(); + data.setSpeciesId(item.getId()); + data.setBirdSpecies(item); + param.put("speciesId", (Object)item.getId()); + try { + EsResultRecordDetails resultRecordDetails = CommonEsUtils.getResultRecordDetailsByParam(param, "result_record_details", this.elasticsearchClient); + if (resultRecordDetails != null) { + data.setAreaName(resultRecordDetails.getAreaName()); + if (resultRecordDetails.getRecordTime() != null) { + data.setUpdateTime(Date.from(resultRecordDetails.getRecordTime().toInstant())); + } + } else { + data.setAreaName("\u5f53\u524d\u672a\u76d1\u6d4b\u5230"); + } + list.add(data); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + } + rspData.setRows(list); + return rspData; + } + + @Override + public TableDataInfo getResultMediaListByParam(JSONObject jsonObject) { + Long mediaId = jsonObject.getLong("mediaId"); + String[] sources = new String[]{"id", "record_time", "species_name", "species_id", "device_id", "media_id", "media_url", "meta_url", "media_type", "favorite", "is_deleted"}; + BoolQuery.Builder boolQueryBuilder = null; + Integer pageNum = null; + Integer pageSize = null; + if (mediaId != null) { + JSONObject param = new JSONObject(); + param.put("mediaId", (Object)mediaId); + pageNum = 1; + pageSize = 1; + boolQueryBuilder = CommonEsUtils.createQuery(param); + } else { + Integer type; + pageNum = jsonObject.getInteger("pageNum"); + if (pageNum == null) { + pageNum = 1; + } + if ((pageSize = jsonObject.getInteger("pageSize")) == null) { + pageSize = 10; + } + if ((type = jsonObject.getInteger("type")) == null || 1 != type) { + jsonObject.put("isDeleted", (Object)0); + } + boolQueryBuilder = CommonEsUtils.createQuery(jsonObject); + } + int pageFrom = (pageNum - 1) * pageSize; + try { + BoolQuery.Builder finalBoolQueryBuilder = boolQueryBuilder; + Integer finalPageSize = pageSize; + SearchResponse response = this.elasticsearchClient.search(s -> s.trackTotalHits((TrackHits)new TrackHits.Builder().enabled(Boolean.valueOf(true)).build()).index("result_record_details", new String[0]).query(q -> q.bool(finalBoolQueryBuilder.build())).sort(sort -> sort.field(f -> f.field("record_time").order(SortOrder.Desc))).source(sc -> sc.filter(f -> f.includes(Arrays.asList(sources)))).from(Integer.valueOf(pageFrom)).size(finalPageSize), EsResultRecordDetails.class); + List hitList = response.hits().hits(); + long total = response.hits().total() != null ? response.hits().total().value() : 0L; + ArrayList list = new ArrayList(); + for (Hit mapHit : hitList) { + list.add(mapHit.source()); + } + return this.getTableDataInfo(list, total); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + return this.getTableDataInfo(new ArrayList(), 0L); + } + } + + @Override + public int deleteDocumentById(String ids) { + return this.updateDocumentsByParam(ids, 0); + } + + private int updateDocumentsByParam(String ids, int type) { + try { + String[] arr = ids.split(","); + HashMap params = new HashMap(); + if (type == 0) { + params.put("is_deleted", 1); + } else { + params.put("checked", 1); + } + for (String id : arr) { + UpdateRequest request = UpdateRequest.of(builder -> builder.index("result_record_details").id(id).doc((Object)params)); + this.elasticsearchClient.update(request, Map.class); + } + return 1; + } + catch (Exception ex) { + logger.error(ex.getMessage()); + return 0; + } + } + + @Override + public int updateDocumentCheckedById(String ids) { + return this.updateDocumentsByParam(ids, 1); + } + + @Override + public void bulkAddResultRecordDocument() { + long maxValue = this.getMaxResultRecordId(); + this.processResultRecordDocument(maxValue); + } + + private void processResultRecordDocument(Long id) { + HashMap param = new HashMap(); + param.put("recordId", id); + List list = this.esResultRecordDetailsMapper.getResultRecordListForElastic(param); + if (!list.isEmpty()) { + ArrayList operations = new ArrayList(); + list.forEach(data -> operations.add(new BulkOperation.Builder().index(((IndexOperation.Builder)((IndexOperation.Builder)new IndexOperation.Builder().index("result_record_details")).id(String.valueOf(data.getId()))).document(data).build()).build())); + try { + BulkRequest bulkRequest = new BulkRequest.Builder().operations(operations).build(); + BulkResponse bulkResponse = this.elasticsearchClient.bulk(bulkRequest); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + } + } + + @Override + public void bulkAddResultRecordDocumentById(Long id) { + this.processResultRecordDocument(id); + } + + @Override + public long getMaxResultRecordId() { + try { + SearchResponse searchResponse = this.elasticsearchClient.search(s -> s.index("result_record_details", new String[0]).size(Integer.valueOf(0)).aggregations("max_value", a -> a.max(m -> (MaxAggregation.Builder)m.field("record_id"))), Void.class); + Map aggregations = searchResponse.aggregations(); + long maxValue = 0L; + if (aggregations != null && aggregations.containsKey("max_value")) { + Aggregate maxAgg = (Aggregate)aggregations.get("max_value"); + maxValue = (long)maxAgg.max().value(); + } + return maxValue; + } + catch (IOException ex) { + logger.error(ex.getMessage()); + return 0L; + } + } + + @Override + public boolean updateResultRecordInfoById(JSONObject object) { + return this.updateResultRecordEsDocument(object); + } + + private boolean updateResultRecordEsDocument(JSONObject object) { + String speciesName; + Integer isDeleted; + Integer favorite; + Long speciesId; + HashMap params = new HashMap(); + String docId = object.getString("detailsId"); + Integer checked = object.getInteger("checked"); + if (checked != null) { + params.put("checked", checked); + } + if ((speciesId = object.getLong("speciesId")) != null) { + params.put("species_id", speciesId); + } + if ((favorite = object.getInteger("favorite")) != null) { + params.put("favorite", favorite); + } + if ((isDeleted = object.getInteger("isDeleted")) != null) { + params.put("is_deleted", isDeleted); + } + if ((speciesName = object.getString("speciesName")) != null) { + params.put("species_name", speciesName); + } + UpdateRequest request = UpdateRequest.of(builder -> builder.index("result_record_details").id(docId).doc((Object)params)); + try { + this.elasticsearchClient.update(request, Map.class); + return true; + } + catch (IOException ex) { + logger.error(ex.getMessage()); + return false; + } + } + + @Override + public boolean updateResultRecordInfoByIds(JSONObject object) { + String[] arr; + String ids = object.getString("location"); + for (String detailsId : arr = ids.split(",")) { + object.put("detailsId", (Object)detailsId); + this.updateResultRecordEsDocument(object); + } + return true; + } + + @Override + public JSONObject getBirdAudioDailyStatListByParam(JSONObject param) { + param.put("mediaType", (Object)1); + return this.getDailyAggregateListByParam(param, 0); + } + + private JSONObject getDailyAggregateListByParam(JSONObject param, int type) { + JSONObject result = new JSONObject(); + try { + JSONArray jsonArray = CommonEsUtils.getSpeciesAggregateList(param, "result_record_details", this.elasticsearchClient, CalendarInterval.Hour); + HashMap map = new HashMap(); + int[] hourAmount = new int[24]; + for (Object obj2 : jsonArray) { + int hour; + JSONObject item = (JSONObject)obj2; + int n = hour = item.getInteger("hour").intValue(); + hourAmount[n] = hourAmount[n] + item.getInteger("count"); + Long speciesId = item.getLong("speciesId"); + JSONObject objItem = (JSONObject)map.get(speciesId); + int data1 = 0; + int data2 = 0; + if (type == 0) { + if (objItem == null) { + objItem = new JSONObject(); + } else { + data1 = objItem.getInteger("data1"); + data2 = objItem.getInteger("data2"); + } + hour = item.getInteger("hour"); + if (hour < 18 && hour >= 6) { + data1 += item.getInteger("count").intValue(); + } else { + data2 += item.getInteger("count").intValue(); + } + } else if (type == 1) { + if (objItem == null) { + objItem = new JSONObject(); + } else { + data1 = objItem.getInteger("data1"); + data2 = objItem.getInteger("data2"); + } + hour = item.getInteger("hour"); + int count = item.getInteger("count"); + if (hour <= 12) { + if (count > data1) { + data1 = count; + } + } else if (count > data2) { + data2 = count; + } + } + objItem.put("id", (Object)speciesId); + objItem.put("data1", (Object)data1); + objItem.put("data2", (Object)data2); + objItem.put("dataAll", (Object)(data1 + data2)); + map.put(speciesId, objItem); + } + result.put("hourAmount", (Object)hourAmount); + Object[] array = map.values().toArray(); + JSONArray list = new JSONArray(); + for (Object obj3 : array) { + JSONObject objItem = (JSONObject)obj3; + Long id = objItem.getLong("id"); + BirdSpecies birdSpecies = this.birdSpeciesService.selectBirdSpeciesForEsById(id); + objItem.put("name", (Object)birdSpecies.getName()); + objItem.put("familyId", (Object)birdSpecies.getFamilyId()); + objItem.put("familyName", (Object)birdSpecies.getFamilyName()); + objItem.put("code", (Object)birdSpecies.getSpeciesType()); + objItem.put("codeName", (Object)birdSpecies.getSpeciesTypeName()); + list.add((Object)objItem); + } + list.sort(Comparator.comparing(obj -> ((JSONObject)obj).getInteger("dataAll")).reversed()); + result.put("list", (Object)list); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + return result; + } + + @Override + public JSONObject getBirdDailyStatListByParam(JSONObject param) { + param.put("recordType", (Object)1); + JSONObject object = this.getDailyAggregateListByParam(param, 1); + JSONArray array = object.getJSONArray("list"); + if (array != null && !array.isEmpty()) { + JSONArray ids = new JSONArray(); + for (Object obj2 : array) { + JSONObject jsonObject = (JSONObject)obj2; + ids.add((Object)jsonObject.getLong("id")); + } + param.put("ids", (Object)ids); + } else { + array = new JSONArray(); + } + param.put("recordType", (Object)2); + JSONObject subObj = this.getDailyAggregateListByParam(param, 1); + if (subObj.getJSONArray("list") != null) { + array.addAll((Collection)subObj.getJSONArray("list")); + } + array.sort(Comparator.comparing(obj -> ((JSONObject)obj).getInteger("dataAll")).reversed()); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getBirdAudioMonthStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + param.put("mediaType", (Object)1); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index("result_record_details", new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_month", a -> a.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(CalendarInterval.Month))).aggregations("by_hour", b -> b.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(CalendarInterval.Hour))).aggregations("sum_count_field", s -> s.sum(SumAggregation.of(sa -> (SumAggregation.Builder)sa.field("count"))))))); + try { + SearchResponse searchResponse = this.elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate byMonthAgg = (Aggregate)aggs.get("by_month"); + JSONArray jsonArray = new JSONArray(); + byMonthAgg.dateHistogram().buckets().array().forEach(monthBucket -> { + String month = monthBucket.keyAsString(); + Aggregate byHourAgg = (Aggregate)monthBucket.aggregations().get("by_hour"); + byHourAgg.dateHistogram().buckets().array().forEach(hourBucket -> { + String hour = hourBucket.keyAsString(); + if (month != null && hour != null) { + JSONObject item = new JSONObject(); + ZonedDateTime zonedDateTime = ZonedDateTime.parse(month, DateTimeFormatter.ISO_OFFSET_DATE_TIME); + LocalDateTime dateTime = zonedDateTime.toLocalDateTime(); + item.put("month", (Object)dateTime.getMonth().getValue()); + zonedDateTime = ZonedDateTime.parse(hour, DateTimeFormatter.ISO_OFFSET_DATE_TIME); + dateTime = zonedDateTime.toLocalDateTime(); + item.put("hour", (Object)dateTime.getHour()); + Aggregate sumAgg = (Aggregate)hourBucket.aggregations().get("sum_count_field"); + item.put("count", (Object)((int)sumAgg.sum().value())); + jsonArray.add((Object)item); + } + }); + }); + HashMap map = new HashMap(); + for (Object obj2 : jsonArray) { + JSONObject item = (JSONObject)obj2; + Integer month = item.getInteger("month"); + JSONObject objItem = (JSONObject)map.get(month); + int data1 = 0; + int data2 = 0; + if (objItem == null) { + objItem = new JSONObject(); + } else { + data1 = objItem.getInteger("data1"); + data2 = objItem.getInteger("data2"); + } + Integer hour = item.getInteger("hour"); + if (hour < 18 && hour >= 6) { + data1 += item.getInteger("count").intValue(); + } else { + data2 += item.getInteger("count").intValue(); + } + objItem.put("month", (Object)month); + objItem.put("data1", (Object)data1); + objItem.put("data2", (Object)data2); + objItem.put("dataAll", (Object)(data1 + data2)); + map.put(month, objItem); + } + Object[] array = map.values().toArray(); + JSONArray list = new JSONArray(); + for (Object obj3 : array) { + JSONObject objItem = (JSONObject)obj3; + list.add((Object)objItem); + } + list.sort(Comparator.comparing(obj -> ((JSONObject)obj).getInteger("month"))); + result.put("list", (Object)array); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + return result; + } + + @Override + public JSONObject getBirdAudioYearStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + param.put("mediaType", (Object)1); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index("result_record_details", new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_year", a -> a.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(CalendarInterval.Year))).aggregations("by_month", b -> b.dateHistogram(DateHistogramAggregation.of(dh -> dh.field("record_time").timeZone("+08:00").calendarInterval(CalendarInterval.Month))).aggregations("sum_count_field", s -> s.sum(SumAggregation.of(sa -> (SumAggregation.Builder)sa.field("count"))))))); + try { + SearchResponse searchResponse = this.elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate byYearAgg = (Aggregate)aggs.get("by_year"); + JSONArray jsonArray = new JSONArray(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX+08:00"); + byYearAgg.dateHistogram().buckets().array().forEach(yearBucket -> { + String year = yearBucket.keyAsString(); + Aggregate byMonthAgg = (Aggregate)yearBucket.aggregations().get("by_month"); + byMonthAgg.dateHistogram().buckets().array().forEach(hourBucket -> { + String month = hourBucket.keyAsString(); + if (year != null && month != null) { + JSONObject item = new JSONObject(); + ZonedDateTime zonedDateTime = ZonedDateTime.parse(year, DateTimeFormatter.ISO_OFFSET_DATE_TIME); + LocalDateTime dateTime = zonedDateTime.toLocalDateTime(); + item.put("year", (Object)dateTime.getYear()); + zonedDateTime = ZonedDateTime.parse(month, DateTimeFormatter.ISO_OFFSET_DATE_TIME); + dateTime = zonedDateTime.toLocalDateTime(); + item.put("month", (Object)dateTime.getMonth().getValue()); + Aggregate sumAgg = (Aggregate)hourBucket.aggregations().get("sum_count_field"); + item.put("count", (Object)((int)sumAgg.sum().value())); + jsonArray.add((Object)item); + } + }); + }); + HashMap map = new HashMap(); + for (Object obj2 : jsonArray) { + JSONObject item = (JSONObject)obj2; + Integer year = item.getInteger("year"); + JSONObject objItem = (JSONObject)map.get(year); + int data1 = 0; + int data2 = 0; + int data3 = 0; + int data4 = 0; + if (objItem == null) { + objItem = new JSONObject(); + } else { + data1 = objItem.getInteger("data1"); + data2 = objItem.getInteger("data2"); + data3 = objItem.getInteger("data3"); + data4 = objItem.getInteger("data4"); + } + Integer month = item.getInteger("month"); + if (month < 4 && month >= 1) { + data1 += item.getInteger("count").intValue(); + } else if (month < 7 && month >= 4) { + data2 += item.getInteger("count").intValue(); + } else if (month < 10 && month >= 7) { + data3 += item.getInteger("count").intValue(); + } else { + data4 += item.getInteger("count").intValue(); + } + objItem.put("year", (Object)year); + objItem.put("data1", (Object)data1); + objItem.put("data2", (Object)data2); + objItem.put("data3", (Object)data3); + objItem.put("data4", (Object)data4); + map.put(year, objItem); + } + Object[] array = map.values().toArray(); + JSONArray list = new JSONArray(); + for (Object obj3 : array) { + JSONObject objItem = (JSONObject)obj3; + list.add((Object)objItem); + } + list.sort(Comparator.comparing(obj -> ((JSONObject)obj).getInteger("year"))); + result.put("list", (Object)array); + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + return result; + } + + @Override + public List getDeviceInfoListForPage(DeviceInfo deviceInfo) { + List list = this.deviceInfoService.getDeviceInfoListForPage(deviceInfo); + JSONObject param = new JSONObject(); + param.put("isDeleted", (Object)0); + list.forEach(item -> { + param.put("deviceId", (Object)item.getId()); + if (Objects.equals(item.getDeviceType(), "1")) { + param.put("mediaType", (Object)3); + } else { + param.put("mediaType", (Object)1); + } + item.setResultMedia(this.getLastMediaInfoByParam(param)); + }); + return list; + } + + @Override + public JSONArray getAreaSpeciesListByParam(JSONObject param) { + JSONArray array = new JSONArray(); + param.put("isDeleted", (Object)0); + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + SearchRequest searchRequest = SearchRequest.of(builder -> builder.index("result_record_details", new String[0]).size(Integer.valueOf(0)).query(q -> q.bool(boolQueryBuilder.build())).aggregations("by_species_id", a -> a.terms(TermsAggregation.of(dh -> dh.field("species_id").size(Integer.valueOf(10000)))))); + try { + ArrayList list = new ArrayList(); + SearchResponse searchResponse = this.elasticsearchClient.search(searchRequest, Void.class); + Map aggs = searchResponse.aggregations(); + Aggregate bySpeciesIdAgg = (Aggregate)aggs.get("by_species_id"); + bySpeciesIdAgg.lterms().buckets().array().forEach(idBucket -> list.add(idBucket.key())); + HashMap map = new HashMap(); + if (!list.isEmpty()) { + map.put("list", list); + List birdSpecies = this.birdSpeciesService.getSpeciesSelectListByParam(map); + if (birdSpecies != null && !birdSpecies.isEmpty()) { + birdSpecies.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("speciesId", (Object)item.getId()); + obj.put("speciesName", (Object)item.getName()); + array.add((Object)obj); + }); + List ids = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByParams(param); + if (ids != null && !ids.isEmpty()) { + CommonUtils.sortArrayByParam((JSONArray)array, (List)ids); + } + } + } + } + catch (IOException ex) { + logger.error(ex.getMessage()); + } + return array; + } + + @Override + public JSONObject getAudioListByParam(JSONObject object) { + Long areaId = this.getAreaId(); + if (areaId == null) { + return new JSONObject(); + } + object.put("areaId", (Object)areaId); + String calcDate = object.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + object.put("calcDate", (Object)calcDate); + object.put("mediaType", (Object)1); + TableDataInfo tableDataInfo = this.getResultMediaListByParam(object); + List list = tableDataInfo.getRows(); + ArrayList array = new ArrayList(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + for (Object eitem : list) { + JSONObject obj = new JSONObject(); + EsResultRecordDetails item = (EsResultRecordDetails)eitem; + obj.put("speciesName", (Object)item.getSpeciesName()); + obj.put("scientificName", (Object)item.getScientificName()); + obj.put("speciesId", (Object)item.getSpeciesId()); + obj.put("deviceId", (Object)item.getDeviceId()); + obj.put("time", (Object)(item.getRecordTime() == null ? "" : item.getRecordTime().withZoneSameInstant(ZoneId.of("Asia/Shanghai")).format(formatter))); + String url = item.getMediaUrl(); + if (url != null) { + if (url.startsWith("/")) { + obj.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + obj.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + } + if ((url = item.getMetaUrl()) != null) { + if (url.startsWith("/")) { + obj.put("imgPath", (Object)(this.fileServerUrl + url)); + } else { + obj.put("imgPath", (Object)(this.fileServerUrl + "/" + url)); + } + } + array.add(obj); + } + JSONObject result = new JSONObject(); + result.put("total", (Object)tableDataInfo.getTotal()); + result.put("row", array); + return result; + } + + private Long getAreaId() { + Set set = SecurityUtils.getLoginUser().getAreaIds(); + if (set == null || set.isEmpty()) { + return null; + } + ArrayList ids = new ArrayList(set); + return (Long)ids.get(0); + } + + @Override + public boolean updateDocumentStatusByParam(JSONObject param) { + try { + Long mediaId = param.getLong("mediaId"); + int type = param.getInteger("type"); + String fieldName = ""; + Integer fieldValue = null; + if (type == 0) { + fieldName = "is_deleted"; + fieldValue = param.getInteger("isDeleted"); + } else { + fieldName = "favorite"; + fieldValue = param.getInteger("favorite"); + } + String finalFieldName = fieldName; + Integer finalFieldValue = fieldValue; + UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest.Builder().index("result_record_details", new String[0]).query(q -> q.term(t -> t.field("media_id").value(mediaId.longValue()))).script(s -> s.inline(i -> i.source("ctx._source['" + finalFieldName + "'] = '" + finalFieldValue + "';"))).build(); + this.elasticsearchClient.updateByQuery(updateByQueryRequest); + return true; + } + catch (IOException ex) { + logger.error(ex.getMessage()); + return false; + } + } + + @Override + public JSONObject getSpeciesStatInfo(JSONObject param) { + JSONObject result = new JSONObject(); + if (param == null) { + param = new JSONObject(); + } + param.put("mediaType", (Object)1); + result.put("audioAmount", (Object)this.getSpeciesStatAmount(param)); + param.put("mediaType", (Object)2); + result.put("imageAmount", (Object)this.getSpeciesStatAmount(param)); + param.put("mediaType", (Object)3); + result.put("videoAmount", (Object)this.getSpeciesStatAmount(param)); + param.put("mediaType", (Object)5); + result.put("textAmount", (Object)this.getSpeciesStatAmount(param)); + return result; + } + + @Override + public long updateMediaUrlPrefixPathByParam(JSONObject param) { + HashMap map = new HashMap(); + String path = param.getString("path"); + if (path == null || path.isEmpty()) { + return 0L; + } + map.put("path", path); + long total = this.esResultRecordDetailsMapper.getMediaUrlPrefixPathAmount(path); + if (total == 0L) { + return 0L; + } + int size = 1000; + map.put("size", size); + long totalPage = total % (long)size == 0L ? total / (long)size : total % (long)size + 1L; + int i = 0; + while ((long)i < totalPage) { + map.put("from", i * size); + List list = this.esResultRecordDetailsMapper.getMediaUrlPrefixPathListByParam(map); + HashMap params = new HashMap(); + list.forEach(item -> { + String url = item.getMediaUrl().replace(path, ""); + params.put("media_url", url); + this.updateEsDocumentByParam(item.getId().toString(), params); + }); + ++i; + } + return total; + } + + private void updateEsDocumentByParam(String id, Map params) { + try { + UpdateRequest request = UpdateRequest.of(builder -> builder.index("result_record_details").id(id).doc((Object)params).detectNoop(Boolean.valueOf(false))); + this.elasticsearchClient.update(request, Map.class); + } + catch (Exception ex) { + logger.error(ex.getMessage()); + } + } + + private long getSpeciesStatAmount(JSONObject param) { + BoolQuery.Builder boolQueryBuilder = CommonEsUtils.createQuery(param); + CountRequest countRequest = CountRequest.of(builder -> builder.index("record_data_2030", new String[0]).query(q -> q.bool(boolQueryBuilder.build()))); + try { + CountResponse response = this.elasticsearchClient.count(countRequest); + return response.count(); + } + catch (Exception ex) { + logger.error("error", (Throwable)ex); + return 0L; + } + } + + private TableDataInfo getTableDataInfo(List list, long total) { + TableDataInfo tableDataInfo = new TableDataInfo(); + tableDataInfo.setRows(list); + tableDataInfo.setTotal(total); + tableDataInfo.setCode(200); + tableDataInfo.setMsg("\u67e5\u8be2\u6210\u529f"); + return tableDataInfo; + } + + @Lazy + public EsResultRecordDetailsServiceImpl(ElasticsearchClient elasticsearchClient, BirdSpeciesService birdSpeciesService, BirdMediaService birdMediaService, DeviceInfoService deviceInfoService, ProtectedAreaSpeciesService protectedAreaSpeciesService, EsResultRecordDetailsMapper esResultRecordDetailsMapper) { + this.elasticsearchClient = elasticsearchClient; + this.birdSpeciesService = birdSpeciesService; + this.birdMediaService = birdMediaService; + this.deviceInfoService = deviceInfoService; + this.protectedAreaSpeciesService = protectedAreaSpeciesService; + this.esResultRecordDetailsMapper = esResultRecordDetailsMapper; + } +} + + diff --git a/ai-bird-es/src/main/resources/mapper/EsResultRecordDetailsMapper.xml b/ai-bird-es/src/main/resources/mapper/EsResultRecordDetailsMapper.xml new file mode 100644 index 0000000..9995cef --- /dev/null +++ b/ai-bird-es/src/main/resources/mapper/EsResultRecordDetailsMapper.xml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-framework/pom.xml b/ai-bird-framework/pom.xml new file mode 100644 index 0000000..56958bc --- /dev/null +++ b/ai-bird-framework/pom.xml @@ -0,0 +1,64 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + + ai-bird-framework + + + framework框架核心 + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springframework.boot + spring-boot-starter-aop + + + + + com.alibaba + druid-spring-boot-starter + + + + + com.github.penggle + kaptcha + + + javax.servlet-api + javax.servlet + + + + + + + com.github.oshi + oshi-core + + + + + net.hzvtc + ai-bird-system + + + + + \ No newline at end of file diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataScopeAspect.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataScopeAspect.java new file mode 100644 index 0000000..dfe312d --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataScopeAspect.java @@ -0,0 +1,149 @@ +package net.hzvtc.framework.aspectj; + +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.springframework.stereotype.Component; +import net.hzvtc.common.annotation.DataScope; + +/** + * 数据过滤处理 + * + * @author admin + */ +@Aspect +@Component +public class DataScopeAspect +{ + /** + * 全部数据权限 + */ + public static final String DATA_SCOPE_ALL = "1"; + + /** + * 自定数据权限 + */ + public static final String DATA_SCOPE_CUSTOM = "2"; + + /** + * 部门数据权限 + */ + public static final String DATA_SCOPE_DEPT = "3"; + + /** + * 部门及以下数据权限 + */ + public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; + + /** + * 仅本人数据权限 + */ + public static final String DATA_SCOPE_SELF = "5"; + + /** + * 数据权限过滤关键字 + */ + public static final String DATA_SCOPE = "dataScope"; + + @Before("@annotation(controllerDataScope)") + public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable + { + clearDataScope(point); + handleDataScope(point, controllerDataScope); + } + + protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) + { + // 获取当前的用户 + LoginUser loginUser = SecurityUtils.getLoginUser(); + if (StringUtils.isNotNull(loginUser)) + { + SysUser currentUser = loginUser.getUser(); + // 如果是超级管理员,则不过滤数据 + if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) + { + dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), + controllerDataScope.userAlias()); + } + } + } + + /** + * 数据范围过滤 + * + * @param joinPoint 切点 + * @param user 用户 + * @param userAlias 别名 + */ + public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) + { + StringBuilder sqlString = new StringBuilder(); + + for (SysRole role : user.getRoles()) + { + String dataScope = role.getDataScope(); + 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(" OR 1=0 "); + } + } + } + + 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) + { + Object params = joinPoint.getArgs()[0]; + if (StringUtils.isNotNull(params) && params instanceof BaseEntity) + { + BaseEntity baseEntity = (BaseEntity) params; + baseEntity.getParams().put(DATA_SCOPE, ""); + } + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataSourceAspect.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataSourceAspect.java new file mode 100644 index 0000000..eb1ba0d --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/DataSourceAspect.java @@ -0,0 +1,73 @@ +package net.hzvtc.framework.aspectj; + +import java.util.Objects; + +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.framework.datasource.DynamicDataSourceContextHolder; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; +import net.hzvtc.common.annotation.DataSource; + +/** + * 多数据源处理 + * + * @author admin + */ +@Aspect +@Order(1) +@Component +public class DataSourceAspect +{ + protected Logger logger = LoggerFactory.getLogger(getClass()); + + @Pointcut("@annotation(net.hzvtc.common.annotation.DataSource)" + + "|| @within(net.hzvtc.common.annotation.DataSource)") + public void dsPointCut() + { + + } + + @Around("dsPointCut()") + public Object around(ProceedingJoinPoint point) throws Throwable + { + DataSource dataSource = getDataSource(point); + + if (StringUtils.isNotNull(dataSource)) + { + DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name()); + } + + try + { + return point.proceed(); + } + finally + { + // 销毁数据源 在执行方法之后 + DynamicDataSourceContextHolder.clearDataSourceType(); + } + } + + /** + * 获取需要切换的数据源 + */ + public DataSource getDataSource(ProceedingJoinPoint point) + { + MethodSignature signature = (MethodSignature) point.getSignature(); + DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class); + if (Objects.nonNull(dataSource)) + { + return dataSource; + } + + return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/LogAspect.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/LogAspect.java new file mode 100644 index 0000000..c52487a --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/LogAspect.java @@ -0,0 +1,219 @@ +package net.hzvtc.framework.aspectj; + +import java.util.Collection; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.enums.BusinessStatus; +import net.hzvtc.common.enums.HttpMethod; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.ip.IpUtils; +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 org.springframework.web.servlet.HandlerMapping; +import com.alibaba.fastjson.JSON; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.framework.manager.AsyncManager; +import net.hzvtc.framework.manager.factory.AsyncFactory; +import net.hzvtc.system.domain.SysOperLog; + +/** + * 操作日志记录处理 + * + * @author admin + */ +@Aspect +@Component +public class LogAspect +{ + private static final Logger log = LoggerFactory.getLogger(LogAspect.class); + + /** + * 处理完请求后执行 + * + * @param joinPoint 切点 + */ + @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult") + public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) + { + handleLog(joinPoint, controllerLog, null, jsonResult); + } + + /** + * 拦截异常操作 + * + * @param joinPoint 切点 + * @param e 异常 + */ + @AfterThrowing(value = "@annotation(controllerLog)", throwing = "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 + { + + // 获取当前的用户 + LoginUser loginUser = SecurityUtils.getLoginUser(); + + // *========数据库日志=========*// + SysOperLog operLog = new SysOperLog(); + operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); + // 请求的地址 + String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); + operLog.setOperIp(ip); + operLog.setOperUrl(ServletUtils.getRequest().getRequestURI()); + if (loginUser != null) + { + operLog.setOperName(loginUser.getUsername()); + } + + if (e != null) + { + operLog.setStatus(BusinessStatus.FAIL.ordinal()); + operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); + } + // 设置方法名称 + String className = joinPoint.getTarget().getClass().getName(); + String methodName = joinPoint.getSignature().getName(); + operLog.setMethod(className + "." + methodName + "()"); + // 设置请求方式 + operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); + // 处理设置注解上的参数 + getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult); + // 保存数据库 + AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); + } + catch (Exception exp) + { + // 记录本地异常日志 + log.error("==前置通知异常=="); + log.error("异常信息:{}", exp.getMessage()); + exp.printStackTrace(); + } + } + + /** + * 获取注解中对方法的描述信息 用于Controller层注解 + * + * @param log 日志 + * @param operLog 操作日志 + * @throws Exception + */ + public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception + { + // 设置action动作 + operLog.setBusinessType(log.businessType().ordinal()); + // 设置标题 + operLog.setTitle(log.title()); + // 设置操作人类别 + operLog.setOperatorType(log.operatorType().ordinal()); + // 是否需要保存request,参数和值 + if (log.isSaveRequestData()) + { + // 获取参数的信息,传入到数据库中。 + setRequestValue(joinPoint, operLog); + } + // 是否需要保存response,参数和值 + 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 + { + String requestMethod = operLog.getRequestMethod(); + if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) + { + String params = argsArrayToString(joinPoint.getArgs()); + operLog.setOperParam(StringUtils.substring(params, 0, 2000)); + } + else + { + Map paramsMap = (Map) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); + operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000)); + } + } + + /** + * 参数拼装 + */ + private String argsArrayToString(Object[] paramsArray) + { + String params = ""; + if (paramsArray != null && paramsArray.length > 0) + { + for (Object o : paramsArray) + { + if (StringUtils.isNotNull(o) && !isFilterObject(o)) + { + try + { + Object jsonObj = JSON.toJSON(o); + params += jsonObj.toString() + " "; + } + catch (Exception e) + { + } + } + } + } + return params.trim(); + } + + /** + * 判断是否需要过滤的对象。 + * + * @param o 对象信息。 + * @return 如果是需要过滤的对象,则返回true;否则返回false。 + */ + @SuppressWarnings("rawtypes") + public boolean isFilterObject(final Object o) + { + Class clazz = o.getClass(); + if (clazz.isArray()) + { + return clazz.getComponentType().isAssignableFrom(MultipartFile.class); + } + else if (Collection.class.isAssignableFrom(clazz)) + { + Collection collection = (Collection) o; + for (Object value : collection) + { + return value instanceof MultipartFile; + } + } + else if (Map.class.isAssignableFrom(clazz)) + { + Map map = (Map) o; + for (Object value : map.entrySet()) + { + Map.Entry entry = (Map.Entry) value; + return entry.getValue() instanceof MultipartFile; + } + } + return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse + || o instanceof BindingResult; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/RateLimiterAspect.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/RateLimiterAspect.java new file mode 100644 index 0000000..328e9dc --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/aspectj/RateLimiterAspect.java @@ -0,0 +1,92 @@ +package net.hzvtc.framework.aspectj; + +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; + +import net.hzvtc.common.enums.LimitType; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.ip.IpUtils; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.reflect.MethodSignature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 net.hzvtc.common.annotation.RateLimiter; + +/** + * 限流处理 + * + * @author admin + */ +@Aspect +@Component +public class RateLimiterAspect +{ + private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); + + private RedisTemplate redisTemplate; + + private RedisScript limitScript; + + @Autowired + public void setRedisTemplate1(RedisTemplate redisTemplate) + { + this.redisTemplate = redisTemplate; + } + + @Autowired + public void setLimitScript(RedisScript limitScript) + { + this.limitScript = limitScript; + } + + @Before("@annotation(rateLimiter)") + public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable + { + String key = rateLimiter.key(); + int time = rateLimiter.time(); + int count = rateLimiter.count(); + + String combineKey = getCombineKey(rateLimiter, point); + List keys = Collections.singletonList(combineKey); + try + { + Long number = redisTemplate.execute(limitScript, keys, count, time); + if (StringUtils.isNull(number) || number.intValue() > count) + { + throw new ServiceException("访问过于频繁,请稍候再试"); + } + log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), key); + } + catch (ServiceException e) + { + throw e; + } + catch (Exception e) + { + throw new RuntimeException("服务器限流异常,请稍候再试"); + } + } + + public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) + { + StringBuffer stringBuffer = new StringBuffer(rateLimiter.key()); + if (rateLimiter.limitType() == LimitType.IP) + { + stringBuffer.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append("-"); + } + MethodSignature signature = (MethodSignature) point.getSignature(); + Method method = signature.getMethod(); + Class targetClass = method.getDeclaringClass(); + stringBuffer.append(targetClass.getName()).append("-").append(method.getName()); + return stringBuffer.toString(); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ApplicationConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ApplicationConfig.java new file mode 100644 index 0000000..442d3b8 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ApplicationConfig.java @@ -0,0 +1,30 @@ +package net.hzvtc.framework.config; + +import java.util.TimeZone; +import org.mybatis.spring.annotation.MapperScan; +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; + +/** + * 程序注解配置 + * + * @author admin + */ +@Configuration +// 表示通过aop框架暴露该代理对象,AopContext能够访问 +@EnableAspectJAutoProxy(exposeProxy = true) +// 指定要扫描的Mapper类的包的路径 +@MapperScan("net.hzvtc.**.mapper") +public class ApplicationConfig +{ + /** + * 时区配置 + */ + @Bean + public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() + { + return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault()); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/CaptchaConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/CaptchaConfig.java new file mode 100644 index 0000000..369f21a --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/CaptchaConfig.java @@ -0,0 +1,83 @@ +package net.hzvtc.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 static com.google.code.kaptcha.Constants.*; + +/** + * 验证码配置 + * + * @author admin + */ +@Configuration +public class CaptchaConfig +{ + @Bean(name = "captchaProducer") + public DefaultKaptcha getKaptchaBean() + { + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + Properties properties = new Properties(); + // 是否有边框 默认为true 我们可以自己设置yes,no + properties.setProperty(KAPTCHA_BORDER, "yes"); + // 验证码文本字符颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black"); + // 验证码图片宽度 默认为200 + properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); + // 验证码图片高度 默认为50 + properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); + // 验证码文本字符大小 默认为40 + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38"); + // KAPTCHA_SESSION_KEY + properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode"); + // 验证码文本字符长度 默认为5 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4"); + // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); + // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy + properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); + Config config = new Config(properties); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } + + @Bean(name = "captchaProducerMath") + public DefaultKaptcha getKaptchaBeanMath() + { + DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); + Properties properties = new Properties(); + // 是否有边框 默认为true 我们可以自己设置yes,no + properties.setProperty(KAPTCHA_BORDER, "yes"); + // 边框颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90"); + // 验证码文本字符颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue"); + // 验证码图片宽度 默认为200 + properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); + // 验证码图片高度 默认为50 + properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); + // 验证码文本字符大小 默认为40 + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35"); + // KAPTCHA_SESSION_KEY + properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath"); + // 验证码文本生成器 + properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "net.hzvtc.framework.config.KaptchaTextCreator"); + // 验证码文本字符间距 默认为2 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3"); + // 验证码文本字符长度 默认为5 + properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6"); + // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) + properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); + // 验证码噪点颜色 默认为Color.BLACK + properties.setProperty(KAPTCHA_NOISE_COLOR, "white"); + // 干扰实现类 + properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise"); + // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy + properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); + Config config = new Config(properties); + defaultKaptcha.setConfig(config); + return defaultKaptcha; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/DruidConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/DruidConfig.java new file mode 100644 index 0000000..f8d0979 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/DruidConfig.java @@ -0,0 +1,127 @@ +package net.hzvtc.framework.config; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.sql.DataSource; + +import net.hzvtc.common.enums.DataSourceType; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.framework.config.properties.DruidProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; +import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; +import com.alibaba.druid.util.Utils; +import net.hzvtc.framework.datasource.DynamicDataSource; + +/** + * druid 配置多数据源 + * + * @author admin + */ +@Configuration +public class DruidConfig +{ + @Bean + @ConfigurationProperties("spring.datasource.druid.master") + public DataSource masterDataSource(DruidProperties druidProperties) + { + DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); + return druidProperties.dataSource(dataSource); + } + + @Bean + @ConfigurationProperties("spring.datasource.druid.slave") + @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") + public DataSource slaveDataSource(DruidProperties druidProperties) + { + DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); + return druidProperties.dataSource(dataSource); + } + + @Bean(name = "dynamicDataSource") + @Primary + public DynamicDataSource dataSource(DataSource masterDataSource) + { + Map targetDataSources = new HashMap<>(); + targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource); + setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource"); + return new DynamicDataSource(masterDataSource, targetDataSources); + } + + /** + * 设置数据源 + * + * @param targetDataSources 备选数据源集合 + * @param sourceName 数据源名称 + * @param beanName bean名称 + */ + public void setDataSource(Map targetDataSources, String sourceName, String beanName) + { + try + { + DataSource dataSource = SpringUtils.getBean(beanName); + targetDataSources.put(sourceName, dataSource); + } + catch (Exception e) + { + } + } + + /** + * 去除监控页面底部的广告 + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Bean + @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true") + public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) + { + // 获取web监控页面的参数 + DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); + // 提取common.js的配置路径 + String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; + String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); + final String filePath = "support/http/resources/js/common.js"; + // 创建filter进行过滤 + Filter filter = new Filter() + { + @Override + public void init(javax.servlet.FilterConfig filterConfig) throws ServletException + { + } + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException + { + chain.doFilter(request, response); + // 重置缓冲区,响应头不会被重置 + response.resetBuffer(); + // 获取common.js + String text = Utils.readFromResource(filePath); + // 正则替换banner, 除去底部的广告信息 + text = text.replaceAll("
", ""); + text = text.replaceAll("powered.*?shrek.wang", ""); + response.getWriter().write(text); + } + @Override + public void destroy() + { + } + }; + FilterRegistrationBean registrationBean = new FilterRegistrationBean(); + registrationBean.setFilter(filter); + registrationBean.addUrlPatterns(commonJsPattern); + return registrationBean; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FastJson2JsonRedisSerializer.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FastJson2JsonRedisSerializer.java new file mode 100644 index 0000000..a91a163 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FastJson2JsonRedisSerializer.java @@ -0,0 +1,62 @@ +package net.hzvtc.framework.config; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.parser.ParserConfig; +import com.alibaba.fastjson.serializer.SerializerFeature; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; +import org.springframework.util.Assert; + +import java.nio.charset.Charset; + +/** + * Redis使用FastJson序列化 + * + * @author admin + */ +public class FastJson2JsonRedisSerializer implements RedisSerializer { + public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + + static { + ParserConfig.getGlobalInstance().setAutoTypeSupport(true); + } + + @SuppressWarnings("unused") + private ObjectMapper objectMapper = new ObjectMapper(); + private Class clazz; + + public FastJson2JsonRedisSerializer(Class clazz) { + super(); + this.clazz = clazz; + } + + @Override + public byte[] serialize(T t) throws SerializationException { + if (t == null) { + return new byte[0]; + } + return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); + } + + @Override + public T deserialize(byte[] bytes) throws SerializationException { + if (bytes == null || bytes.length <= 0) { + return null; + } + String str = new String(bytes, DEFAULT_CHARSET); + + return JSON.parseObject(str, clazz); + } + + public void setObjectMapper(ObjectMapper objectMapper) { + Assert.notNull(objectMapper, "'objectMapper' must not be null"); + this.objectMapper = objectMapper; + } + + protected JavaType getJavaType(Class clazz) { + return TypeFactory.defaultInstance().constructType(clazz); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FilterConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FilterConfig.java new file mode 100644 index 0000000..79d5100 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/FilterConfig.java @@ -0,0 +1,59 @@ +package net.hzvtc.framework.config; + +import java.util.HashMap; +import java.util.Map; +import javax.servlet.DispatcherType; + +import net.hzvtc.common.filter.RepeatableFilter; +import net.hzvtc.common.filter.XssFilter; +import net.hzvtc.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; + +/** + * Filter配置 + * + * @author admin + */ +@Configuration +public class FilterConfig +{ + @Value("${xss.excludes}") + private String excludes; + + @Value("${xss.urlPatterns}") + private String urlPatterns; + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Bean + @ConditionalOnProperty(value = "xss.enabled", havingValue = "true") + public FilterRegistrationBean xssFilterRegistration() + { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setDispatcherTypes(DispatcherType.REQUEST); + registration.setFilter(new XssFilter()); + registration.addUrlPatterns(StringUtils.split(urlPatterns, ",")); + registration.setName("xssFilter"); + registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE); + Map initParameters = new HashMap(); + initParameters.put("excludes", excludes); + registration.setInitParameters(initParameters); + return registration; + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Bean + public FilterRegistrationBean someFilterRegistration() + { + FilterRegistrationBean registration = new FilterRegistrationBean(); + registration.setFilter(new RepeatableFilter()); + registration.addUrlPatterns("/*"); + registration.setName("repeatableFilter"); + registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); + return registration; + } + +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/KaptchaTextCreator.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/KaptchaTextCreator.java new file mode 100644 index 0000000..7a474a9 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/KaptchaTextCreator.java @@ -0,0 +1,75 @@ +package net.hzvtc.framework.config; + +import java.util.Random; +import com.google.code.kaptcha.text.impl.DefaultTextCreator; + +/** + * 验证码文本生成器 + * + * @author admin + */ +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() + { + Integer result = 0; + Random random = new Random(); + int x = random.nextInt(10); + int y = random.nextInt(10); + StringBuilder suChinese = new StringBuilder(); + int randomoperands = (int) Math.round(Math.random() * 2); + 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) + { + result = y / x; + suChinese.append(CNUMBERS[y]); + suChinese.append("/"); + suChinese.append(CNUMBERS[x]); + } + else + { + result = x + y; + suChinese.append(CNUMBERS[x]); + suChinese.append("+"); + suChinese.append(CNUMBERS[y]); + } + } + else if (randomoperands == 2) + { + if (x >= y) + { + result = x - y; + suChinese.append(CNUMBERS[x]); + suChinese.append("-"); + suChinese.append(CNUMBERS[y]); + } + else + { + result = y - x; + suChinese.append(CNUMBERS[y]); + suChinese.append("-"); + suChinese.append(CNUMBERS[x]); + } + } + else + { + result = x + y; + suChinese.append(CNUMBERS[x]); + suChinese.append("+"); + suChinese.append(CNUMBERS[y]); + } + suChinese.append("=?@" + result); + return suChinese.toString(); + } +} \ No newline at end of file diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/MyBatisConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/MyBatisConfig.java new file mode 100644 index 0000000..23da432 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/MyBatisConfig.java @@ -0,0 +1,133 @@ +package net.hzvtc.framework.config; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import javax.sql.DataSource; + +import net.hzvtc.common.utils.StringUtils; +import org.apache.ibatis.io.VFS; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.core.type.classreading.CachingMetadataReaderFactory; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.classreading.MetadataReaderFactory; +import org.springframework.util.ClassUtils; + +/** + * Mybatis支持*匹配扫描包 + * + * @author admin + */ +@Configuration +public class MyBatisConfig +{ + @Autowired + private Environment env; + + static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; + + public static String setTypeAliasesPackage(String typeAliasesPackage) + { + ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); + MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); + List allResult = new ArrayList(); + try + { + for (String aliasesPackage : typeAliasesPackage.split(",")) + { + List result = new ArrayList(); + aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; + Resource[] resources = resolver.getResources(aliasesPackage); + if (resources != null && resources.length > 0) + { + MetadataReader metadataReader = null; + for (Resource resource : resources) + { + if (resource.isReadable()) + { + metadataReader = metadataReaderFactory.getMetadataReader(resource); + try + { + result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); + } + catch (ClassNotFoundException e) + { + e.printStackTrace(); + } + } + } + } + if (result.size() > 0) + { + HashSet hashResult = new HashSet(result); + allResult.addAll(hashResult); + } + } + if (allResult.size() > 0) + { + typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); + } + else + { + throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); + } + } + catch (IOException e) + { + e.printStackTrace(); + } + return typeAliasesPackage; + } + + public Resource[] resolveMapperLocations(String[] mapperLocations) + { + ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); + List resources = new ArrayList(); + if (mapperLocations != null) + { + for (String mapperLocation : mapperLocations) + { + try + { + Resource[] mappers = resourceResolver.getResources(mapperLocation); + resources.addAll(Arrays.asList(mappers)); + } + catch (IOException e) + { + // ignore + } + } + } + return resources.toArray(new Resource[resources.size()]); + } + + @Bean + public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception + { + String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); + String mapperLocations = env.getProperty("mybatis.mapperLocations"); + String configLocation = env.getProperty("mybatis.configLocation"); + typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage); + VFS.addImplClass(SpringBootVFS.class); + + final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); + sessionFactory.setDataSource(dataSource); + sessionFactory.setTypeAliasesPackage(typeAliasesPackage); + sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ","))); + sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); + return sessionFactory.getObject(); + } +} \ No newline at end of file diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/RedisConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/RedisConfig.java new file mode 100644 index 0000000..7d9f8c7 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/RedisConfig.java @@ -0,0 +1,79 @@ +package net.hzvtc.framework.config; + +import org.springframework.cache.annotation.CachingConfigurerSupport; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.data.redis.serializer.StringRedisSerializer; +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; + +/** + * redis配置 + * + * @author admin + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport +{ + @Bean + @SuppressWarnings(value = { "unchecked", "rawtypes" }) + public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) + { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + + FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); + + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); + serializer.setObjectMapper(mapper); + + // 使用StringRedisSerializer来序列化和反序列化redis的key值 + template.setKeySerializer(new StringRedisSerializer()); + template.setValueSerializer(serializer); + + // Hash的key也采用StringRedisSerializer的序列化方式 + template.setHashKeySerializer(new StringRedisSerializer()); + template.setHashValueSerializer(serializer); + + template.afterPropertiesSet(); + return template; + } + + @Bean + public DefaultRedisScript limitScript() + { + DefaultRedisScript redisScript = new DefaultRedisScript<>(); + redisScript.setScriptText(limitScriptText()); + redisScript.setResultType(Long.class); + return redisScript; + } + + /** + * 限流脚本 + */ + private String limitScriptText() + { + return "local key = KEYS[1]\n" + + "local count = tonumber(ARGV[1])\n" + + "local time = tonumber(ARGV[2])\n" + + "local current = redis.call('get', key);\n" + + "if current and tonumber(current) > count then\n" + + " return tonumber(current);\n" + + "end\n" + + "current = redis.call('incr', key)\n" + + "if tonumber(current) == 1 then\n" + + " redis.call('expire', key, time)\n" + + "end\n" + + "return tonumber(current);"; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ResourcesConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ResourcesConfig.java new file mode 100644 index 0000000..786d149 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ResourcesConfig.java @@ -0,0 +1,66 @@ +package net.hzvtc.framework.config; + +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.framework.interceptor.RepeatSubmitInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +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; + +/** + * 通用配置 + * + * @author admin + */ +@Configuration +public class ResourcesConfig implements WebMvcConfigurer { + @Autowired + private RepeatSubmitInterceptor repeatSubmitInterceptor; + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + /** 本地文件上传路径 */ + registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**") + .addResourceLocations("file:" + AiBirdSysConfig.getProfile() + "/"); + + /** swagger配置 */ + registry.addResourceHandler("/swagger-ui/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/"); + } + + /** + * 自定义拦截规则 + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); + } + + /** + * 跨域配置 + */ + @Bean + public CorsFilter corsFilter() { + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(true); + // 设置访问源地址 + config.addAllowedOriginPattern("*"); + // 设置访问源请求头 + config.addAllowedHeader("*"); + // 设置访问源请求方法 + config.addAllowedMethod("*"); + // 有效期 1800秒 + config.setMaxAge(1800L); + // 添加映射路径,拦截一切请求 + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/**", config); + // 返回新的CorsFilter + return new CorsFilter(source); + } +} \ No newline at end of file diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/SecurityConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/SecurityConfig.java new file mode 100644 index 0000000..6654da6 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/SecurityConfig.java @@ -0,0 +1,149 @@ +package net.hzvtc.framework.config; + +import net.hzvtc.framework.security.filter.JwtAuthenticationTokenFilter; +import net.hzvtc.framework.security.handle.AuthenticationEntryPointImpl; +import net.hzvtc.framework.security.handle.LogoutSuccessHandlerImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +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; + +/** + * spring security配置 + * + * @author admin + */ +@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter { + /** + * 自定义用户认证逻辑 + */ + @Autowired + private UserDetailsService userDetailsService; + + /** + * 认证失败处理类 + */ + @Autowired + private AuthenticationEntryPointImpl unauthorizedHandler; + + /** + * 退出处理类 + */ + @Autowired + private LogoutSuccessHandlerImpl logoutSuccessHandler; + + /** + * token认证过滤器 + */ + @Autowired + private JwtAuthenticationTokenFilter authenticationTokenFilter; + + /** + * 跨域过滤器 + */ + @Autowired + private CorsFilter corsFilter; + + /** + * 解决 无法直接注入 AuthenticationManager + * + * @return + * @throws Exception + */ + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + /** + * anyRequest | 匹配所有请求路径 + * access | SpringEl表达式结果为true时可以访问 + * anonymous | 匿名可以访问 + * denyAll | 用户不能访问 + * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录) + * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问 + * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问 + * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问 + * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问 + * hasRole | 如果有参数,参数表示角色,则其角色可以访问 + * permitAll | 用户可以任意访问 + * rememberMe | 允许通过remember-me登录的用户访问 + * authenticated | 用户登录后可访问 + */ + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception { + httpSecurity + // CSRF禁用,因为不使用session + .csrf().disable() + // 认证失败处理类 + .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() + // 基于token,所以不需要session + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() + // 过滤请求 + .authorizeRequests() + // 对于登录login 注册register 验证码captchaImage 允许匿名访问 + .antMatchers("/login", "/web/api/getToken", "/appCaptchaImage", "/captchaImage", "/appUpdate", + "/web/species/api/recordAudioList", + "/web/species/api/mediaAudioList", + "/dataCheck/checkRecord/maxId", + "/dataCheck/checkRecord/pushFileToServer", + "/web/ssoLogin", + "/dth/ssoLogin", + "/sm2login", + "/register", + "/web/getPublicKey", + "/dataCheck/checkRecord/savePushDataList").anonymous() + .antMatchers( + HttpMethod.GET, + "/", + "/*.html", + "/**/*.html", + "/**/*.css", + "/**/*.js", + "/profile/**" + ).permitAll() + .antMatchers("/swagger-ui.html").anonymous() + .antMatchers("/swagger-resources/**").anonymous() + .antMatchers("/webjars/**").anonymous() + .antMatchers("/*/api-docs").anonymous() + .antMatchers("/druid/**").anonymous() + // 除上面外的所有请求全部需要鉴权认证 + .anyRequest().authenticated() + .and() + .headers().frameOptions().disable(); + httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); + // 添加JWT filter + httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); + // 添加CORS filter + httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class); + httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); + } + + /** + * 强散列哈希加密实现 + */ + @Bean + public BCryptPasswordEncoder bCryptPasswordEncoder() { + return new BCryptPasswordEncoder(); + } + + /** + * 身份认证接口 + */ + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ServerConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ServerConfig.java new file mode 100644 index 0000000..4e111a9 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ServerConfig.java @@ -0,0 +1,33 @@ +package net.hzvtc.framework.config; + +import javax.servlet.http.HttpServletRequest; + +import net.hzvtc.common.utils.ServletUtils; +import org.springframework.stereotype.Component; + +/** + * 服务相关配置 + * + * @author admin + */ +@Component +public class ServerConfig +{ + /** + * 获取完整的请求路径,包括:域名,端口,上下文访问路径 + * + * @return 服务地址 + */ + public String getUrl() + { + HttpServletRequest request = ServletUtils.getRequest(); + return getDomain(request); + } + + 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(); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ThreadPoolConfig.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ThreadPoolConfig.java new file mode 100644 index 0000000..d95b356 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/ThreadPoolConfig.java @@ -0,0 +1,63 @@ +package net.hzvtc.framework.config; + +import net.hzvtc.common.utils.Threads; +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; + +/** + * 线程池配置 + * + * @author admin + **/ +@Configuration +public class ThreadPoolConfig +{ + // 核心线程池大小 + private int corePoolSize = 50; + + // 最大可创建的线程数 + private int maxPoolSize = 200; + + // 队列最大长度 + private int queueCapacity = 1000; + + // 线程池维护线程所允许的空闲时间 + private int keepAliveSeconds = 300; + + @Bean(name = "threadPoolTaskExecutor") + public ThreadPoolTaskExecutor threadPoolTaskExecutor() + { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setMaxPoolSize(maxPoolSize); + executor.setCorePoolSize(corePoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setKeepAliveSeconds(keepAliveSeconds); + // 线程池对拒绝任务(无线程可用)的处理策略 + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + return executor; + } + + /** + * 执行周期性或定时任务 + */ + @Bean(name = "scheduledExecutorService") + protected ScheduledExecutorService scheduledExecutorService() + { + return new ScheduledThreadPoolExecutor(corePoolSize, + new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(), + new ThreadPoolExecutor.CallerRunsPolicy()) + { + @Override + protected void afterExecute(Runnable r, Throwable t) + { + super.afterExecute(r, t); + Threads.printException(r, t); + } + }; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/config/properties/DruidProperties.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/properties/DruidProperties.java new file mode 100644 index 0000000..39a6be2 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/config/properties/DruidProperties.java @@ -0,0 +1,77 @@ +package net.hzvtc.framework.config.properties; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; +import com.alibaba.druid.pool.DruidDataSource; + +/** + * druid 配置属性 + * + * @author admin + */ +@Configuration +public class DruidProperties +{ + @Value("${spring.datasource.druid.initialSize}") + private int initialSize; + + @Value("${spring.datasource.druid.minIdle}") + private int minIdle; + + @Value("${spring.datasource.druid.maxActive}") + private int maxActive; + + @Value("${spring.datasource.druid.maxWait}") + private int maxWait; + + @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}") + private int timeBetweenEvictionRunsMillis; + + @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}") + private int minEvictableIdleTimeMillis; + + @Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}") + private int maxEvictableIdleTimeMillis; + + @Value("${spring.datasource.druid.validationQuery}") + private String validationQuery; + + @Value("${spring.datasource.druid.testWhileIdle}") + private boolean testWhileIdle; + + @Value("${spring.datasource.druid.testOnBorrow}") + private boolean testOnBorrow; + + @Value("${spring.datasource.druid.testOnReturn}") + private boolean testOnReturn; + + public DruidDataSource dataSource(DruidDataSource datasource) + { + /** 配置初始化大小、最小、最大 */ + datasource.setInitialSize(initialSize); + datasource.setMaxActive(maxActive); + datasource.setMinIdle(minIdle); + + /** 配置获取连接等待超时的时间 */ + datasource.setMaxWait(maxWait); + + /** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */ + datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); + + /** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */ + datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); + datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis); + + /** + * 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。 + */ + datasource.setValidationQuery(validationQuery); + /** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */ + datasource.setTestWhileIdle(testWhileIdle); + /** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */ + datasource.setTestOnBorrow(testOnBorrow); + /** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */ + datasource.setTestOnReturn(testOnReturn); + return datasource; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSource.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSource.java new file mode 100644 index 0000000..0495010 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSource.java @@ -0,0 +1,26 @@ +package net.hzvtc.framework.datasource; + +import java.util.Map; +import javax.sql.DataSource; +import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; + +/** + * 动态数据源 + * + * @author admin + */ +public class DynamicDataSource extends AbstractRoutingDataSource +{ + public DynamicDataSource(DataSource defaultTargetDataSource, Map targetDataSources) + { + super.setDefaultTargetDataSource(defaultTargetDataSource); + super.setTargetDataSources(targetDataSources); + super.afterPropertiesSet(); + } + + @Override + protected Object determineCurrentLookupKey() + { + return DynamicDataSourceContextHolder.getDataSourceType(); + } +} \ No newline at end of file diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSourceContextHolder.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSourceContextHolder.java new file mode 100644 index 0000000..230c945 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/DynamicDataSourceContextHolder.java @@ -0,0 +1,45 @@ +package net.hzvtc.framework.datasource; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 数据源切换处理 + * + * @author admin + */ +public class DynamicDataSourceContextHolder +{ + public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); + + /** + * 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本, + * 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。 + */ + private static final ThreadLocal CONTEXT_HOLDER = new ThreadLocal<>(); + + /** + * 设置数据源的变量 + */ + 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() + { + CONTEXT_HOLDER.remove(); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/MySqlDialectCustom.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/MySqlDialectCustom.java new file mode 100644 index 0000000..3501f34 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/datasource/MySqlDialectCustom.java @@ -0,0 +1,24 @@ +package net.hzvtc.framework.datasource; + +import com.github.pagehelper.Page; +import com.github.pagehelper.dialect.helper.MySqlDialect; +import org.apache.ibatis.cache.CacheKey; + +import java.util.regex.Pattern; + +public class MySqlDialectCustom extends MySqlDialect { + @Override + public String getPageSql(String sql, Page page, CacheKey pageKey) { + Pattern compileFixed = Pattern.compile("/\\*fixed\\*/"); + String compileLimit = "/\\*limit\\*/"; + if (compileFixed.matcher(sql).find()) { + if (page.getStartRow() == 0) { + sql = sql.replaceFirst(compileLimit, " LIMIT ? "); + } else { + sql = sql.replaceFirst(compileLimit, " LIMIT ?, ? "); + } + return sql; + } + return super.getPageSql(sql, page, pageKey); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/RepeatSubmitInterceptor.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/RepeatSubmitInterceptor.java new file mode 100644 index 0000000..884a2b8 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/RepeatSubmitInterceptor.java @@ -0,0 +1,56 @@ +package net.hzvtc.framework.interceptor; + +import java.lang.reflect.Method; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.ServletUtils; +import org.springframework.stereotype.Component; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.HandlerInterceptor; +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.annotation.RepeatSubmit; + +/** + * 防止重复提交拦截器 + * + * @author admin + */ +@Component +public abstract class RepeatSubmitInterceptor implements HandlerInterceptor +{ + @Override + 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)) + { + AjaxResult ajaxResult = AjaxResult.error(annotation.message()); + ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult)); + return false; + } + } + return true; + } + else + { + return true; + } + } + + /** + * 验证是否重复提交由子类实现具体的防重复提交的规则 + * + * @param request + * @return + * @throws Exception + */ + public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation); +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/impl/SameUrlDataInterceptor.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/impl/SameUrlDataInterceptor.java new file mode 100644 index 0000000..91c95c1 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/interceptor/impl/SameUrlDataInterceptor.java @@ -0,0 +1,111 @@ +package net.hzvtc.framework.interceptor.impl; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.servlet.http.HttpServletRequest; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.filter.RepeatedlyRequestWrapper; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.http.HttpHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.annotation.RepeatSubmit; +import net.hzvtc.framework.interceptor.RepeatSubmitInterceptor; + +/** + * 判断请求url和数据是否和上一次相同, + * 如果和上次相同,则是重复提交表单。 有效时间为10秒内。 + * + * @author admin + */ +@Component +public class SameUrlDataInterceptor extends RepeatSubmitInterceptor +{ + public final String REPEAT_PARAMS = "repeatParams"; + + public final String REPEAT_TIME = "repeatTime"; + + // 令牌自定义标识 + @Value("${token.header}") + private String header; + + @Autowired + private RedisCache redisCache; + + @SuppressWarnings("unchecked") + @Override + public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) + { + String nowParams = ""; + if (request instanceof RepeatedlyRequestWrapper) + { + RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request; + nowParams = HttpHelper.getBodyString(repeatedlyRequest); + } + + // body参数为空,获取Parameter的数据 + if (StringUtils.isEmpty(nowParams)) + { + nowParams = JSONObject.toJSONString(request.getParameterMap()); + } + Map nowDataMap = new HashMap(); + nowDataMap.put(REPEAT_PARAMS, nowParams); + nowDataMap.put(REPEAT_TIME, System.currentTimeMillis()); + + // 请求地址(作为存放cache的key值) + String url = request.getRequestURI(); + + // 唯一值(没有消息头则使用请求地址) + String submitKey = StringUtils.trimToEmpty(request.getHeader(header)); + + // 唯一标识(指定key + url + 消息头) + String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + url + submitKey; + + Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); + if (sessionObj != null) + { + Map sessionMap = (Map) sessionObj; + if (sessionMap.containsKey(url)) + { + Map preDataMap = (Map) sessionMap.get(url); + if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) + { + return true; + } + } + } + Map cacheMap = new HashMap(); + cacheMap.put(url, nowDataMap); + redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS); + return false; + } + + /** + * 判断参数是否相同 + */ + 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); + } + + /** + * 判断两次间隔时间 + */ + 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) + { + return true; + } + return false; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/AsyncManager.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/AsyncManager.java new file mode 100644 index 0000000..de071ce --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/AsyncManager.java @@ -0,0 +1,55 @@ +package net.hzvtc.framework.manager; + +import java.util.TimerTask; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import net.hzvtc.common.utils.Threads; +import net.hzvtc.common.utils.spring.SpringUtils; + +/** + * 异步任务管理器 + * + * @author admin + */ +public class AsyncManager +{ + /** + * 操作延迟10毫秒 + */ + private final int OPERATE_DELAY_TIME = 10; + + /** + * 异步操作任务调度线程池 + */ + private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService"); + + /** + * 单例模式 + */ + private AsyncManager(){} + + private static AsyncManager me = new AsyncManager(); + + public static AsyncManager me() + { + return me; + } + + /** + * 执行任务 + * + * @param task 任务 + */ + public void execute(TimerTask task) + { + executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS); + } + + /** + * 停止任务线程池 + */ + public void shutdown() + { + Threads.shutdownAndAwaitTermination(executor); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/ShutdownManager.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/ShutdownManager.java new file mode 100644 index 0000000..d1c373a --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/ShutdownManager.java @@ -0,0 +1,39 @@ +package net.hzvtc.framework.manager; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import javax.annotation.PreDestroy; + +/** + * 确保应用退出时能关闭后台线程 + * + * @author admin + */ +@Component +public class ShutdownManager +{ + private static final Logger logger = LoggerFactory.getLogger("sys-user"); + + @PreDestroy + public void destroy() + { + shutdownAsyncManager(); + } + + /** + * 停止异步执行任务 + */ + private void shutdownAsyncManager() + { + try + { + logger.info("====关闭后台任务任务线程池===="); + AsyncManager.me().shutdown(); + } + catch (Exception e) + { + logger.error(e.getMessage(), e); + } + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/factory/AsyncFactory.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/factory/AsyncFactory.java new file mode 100644 index 0000000..ba9af82 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/manager/factory/AsyncFactory.java @@ -0,0 +1,103 @@ +package net.hzvtc.framework.manager.factory; + +import java.util.TimerTask; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.utils.LogUtils; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.ip.AddressUtils; +import net.hzvtc.common.utils.ip.IpUtils; +import net.hzvtc.common.utils.spring.SpringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import net.hzvtc.system.domain.SysLogininfor; +import net.hzvtc.system.domain.SysOperLog; +import net.hzvtc.system.service.SysLogininforService; +import net.hzvtc.system.service.SysOperLogService; +import eu.bitwalker.useragentutils.UserAgent; + +/** + * 异步工厂(产生任务用) + * + * @author admin + */ +public class AsyncFactory +{ + private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); + + /** + * 记录登录信息 + * + * @param username 用户名 + * @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 UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); + final String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); + return new TimerTask() + { + @Override + public void run() + { + String address = AddressUtils.getRealAddressByIP(ip); + StringBuilder s = new StringBuilder(); + s.append(LogUtils.getBlock(ip)); + s.append(address); + s.append(LogUtils.getBlock(username)); + s.append(LogUtils.getBlock(status)); + s.append(LogUtils.getBlock(message)); + // 打印信息到日志 + sys_user_logger.info(s.toString(), args); + // 获取客户端操作系统 + String os = userAgent.getOperatingSystem().getName(); + // 获取客户端浏览器 + String browser = userAgent.getBrowser().getName(); + // 封装对象 + SysLogininfor logininfor = new SysLogininfor(); + logininfor.setUserName(username); + logininfor.setIpaddr(ip); + logininfor.setLoginLocation(address); + logininfor.setBrowser(browser); + logininfor.setOs(os); + logininfor.setMsg(message); + // 日志状态 + if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) + { + logininfor.setStatus(Constants.SUCCESS); + } + else if (Constants.LOGIN_FAIL.equals(status)) + { + logininfor.setStatus(Constants.FAIL); + } + // 插入数据 + SpringUtils.getBean(SysLogininforService.class).insertLogininfor(logininfor); + } + }; + } + + /** + * 操作日志记录 + * + * @param operLog 操作日志信息 + * @return 任务task + */ + public static TimerTask recordOper(final SysOperLog operLog) + { + return new TimerTask() + { + @Override + public void run() + { + // 远程查询操作地点 + operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); + SpringUtils.getBean(SysOperLogService.class).insertOperlog(operLog); + } + }; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/security/filter/JwtAuthenticationTokenFilter.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/filter/JwtAuthenticationTokenFilter.java new file mode 100644 index 0000000..37dbe19 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/filter/JwtAuthenticationTokenFilter.java @@ -0,0 +1,45 @@ +package net.hzvtc.framework.security.filter; + +import java.io.IOException; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.web.filter.OncePerRequestFilter; +import net.hzvtc.framework.web.service.TokenService; + +/** + * token过滤器 验证token有效性 + * + * @author admin + */ +@Component +public class JwtAuthenticationTokenFilter extends OncePerRequestFilter +{ + @Autowired + private TokenService tokenService; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException + { + LoginUser loginUser = tokenService.getLoginUser(request); + 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)); + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + chain.doFilter(request, response); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/AuthenticationEntryPointImpl.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/AuthenticationEntryPointImpl.java new file mode 100644 index 0000000..4f635af --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/AuthenticationEntryPointImpl.java @@ -0,0 +1,35 @@ +package net.hzvtc.framework.security.handle; + +import java.io.IOException; +import java.io.Serializable; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; +import com.alibaba.fastjson.JSON; + +/** + * 认证失败处理类 返回未授权 + * + * @author admin + */ +@Component +public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable +{ + private static final long serialVersionUID = -8970718410437077606L; + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) + throws IOException + { + int code = HttpStatus.UNAUTHORIZED; + String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI()); + ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg))); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/LogoutSuccessHandlerImpl.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/LogoutSuccessHandlerImpl.java new file mode 100644 index 0000000..f8b0581 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/security/handle/LogoutSuccessHandlerImpl.java @@ -0,0 +1,54 @@ +package net.hzvtc.framework.security.handle; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import com.alibaba.fastjson.JSON; +import net.hzvtc.framework.manager.AsyncManager; +import net.hzvtc.framework.manager.factory.AsyncFactory; +import net.hzvtc.framework.web.service.TokenService; + +/** + * 自定义退出处理类 返回成功 + * + * @author admin + */ +@Configuration +public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler +{ + @Autowired + private TokenService tokenService; + + /** + * 退出处理 + * + * @return + */ + @Override + public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) + throws IOException, ServletException + { + LoginUser loginUser = tokenService.getLoginUser(request); + if (StringUtils.isNotNull(loginUser)) + { + String userName = loginUser.getUsername(); + // 删除用户缓存记录 + tokenService.delLoginUser(loginUser.getToken()); + // 记录用户退出日志 + AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功")); + } + ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(HttpStatus.SUCCESS, "退出成功"))); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/Server.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/Server.java new file mode 100644 index 0000000..a08a779 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/Server.java @@ -0,0 +1,240 @@ +package net.hzvtc.framework.web.domain; + +import java.net.UnknownHostException; +import java.util.LinkedList; +import java.util.List; +import java.util.Properties; +import net.hzvtc.common.utils.Arith; +import net.hzvtc.common.utils.ip.IpUtils; +import net.hzvtc.framework.web.domain.server.Cpu; +import net.hzvtc.framework.web.domain.server.Jvm; +import net.hzvtc.framework.web.domain.server.Mem; +import net.hzvtc.framework.web.domain.server.Sys; +import net.hzvtc.framework.web.domain.server.SysFile; +import oshi.SystemInfo; +import oshi.hardware.CentralProcessor; +import oshi.hardware.CentralProcessor.TickType; +import oshi.hardware.GlobalMemory; +import oshi.hardware.HardwareAbstractionLayer; +import oshi.software.os.FileSystem; +import oshi.software.os.OSFileStore; +import oshi.software.os.OperatingSystem; +import oshi.util.Util; + +/** + * 服务器相关信息 + * + * @author admin + */ +public class Server +{ + private static final int OSHI_WAIT_SECOND = 1000; + + /** + * CPU相关信息 + */ + private Cpu cpu = new Cpu(); + + /** + * 內存相关信息 + */ + private Mem mem = new Mem(); + + /** + * JVM相关信息 + */ + private Jvm jvm = new Jvm(); + + /** + * 服务器相关信息 + */ + private Sys sys = new Sys(); + + /** + * 磁盘相关信息 + */ + private List sysFiles = new LinkedList(); + + public Cpu getCpu() + { + return cpu; + } + + public void setCpu(Cpu cpu) + { + this.cpu = cpu; + } + + public Mem getMem() + { + return mem; + } + + public void setMem(Mem mem) + { + this.mem = mem; + } + + public Jvm getJvm() + { + return jvm; + } + + public void setJvm(Jvm jvm) + { + this.jvm = jvm; + } + + public Sys getSys() + { + return sys; + } + + public void setSys(Sys sys) + { + this.sys = sys; + } + + public List getSysFiles() + { + return sysFiles; + } + + public void setSysFiles(List sysFiles) + { + this.sysFiles = sysFiles; + } + + public void copyTo() throws Exception + { + SystemInfo si = new SystemInfo(); + HardwareAbstractionLayer hal = si.getHardware(); + + setCpuInfo(hal.getProcessor()); + + setMemInfo(hal.getMemory()); + + setSysInfo(); + + setJvmInfo(); + + setSysFiles(si.getOperatingSystem()); + } + + /** + * 设置CPU信息 + */ + private void setCpuInfo(CentralProcessor processor) + { + // CPU信息 + long[] prevTicks = processor.getSystemCpuLoadTicks(); + Util.sleep(OSHI_WAIT_SECOND); + long[] ticks = processor.getSystemCpuLoadTicks(); + long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()]; + long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()]; + long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()]; + long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()]; + long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()]; + long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()]; + long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()]; + long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()]; + long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal; + cpu.setCpuNum(processor.getLogicalProcessorCount()); + cpu.setTotal(totalCpu); + cpu.setSys(cSys); + cpu.setUsed(user); + cpu.setWait(iowait); + cpu.setFree(idle); + } + + /** + * 设置内存信息 + */ + private void setMemInfo(GlobalMemory memory) + { + mem.setTotal(memory.getTotal()); + mem.setUsed(memory.getTotal() - memory.getAvailable()); + mem.setFree(memory.getAvailable()); + } + + /** + * 设置服务器信息 + */ + private void setSysInfo() + { + Properties props = System.getProperties(); + sys.setComputerName(IpUtils.getHostName()); + sys.setComputerIp(IpUtils.getHostIp()); + sys.setOsName(props.getProperty("os.name")); + sys.setOsArch(props.getProperty("os.arch")); + sys.setUserDir(props.getProperty("user.dir")); + } + + /** + * 设置Java虚拟机 + */ + private void setJvmInfo() throws UnknownHostException + { + Properties props = System.getProperties(); + jvm.setTotal(Runtime.getRuntime().totalMemory()); + jvm.setMax(Runtime.getRuntime().maxMemory()); + jvm.setFree(Runtime.getRuntime().freeMemory()); + jvm.setVersion(props.getProperty("java.version")); + 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) + { + long kb = 1024; + long mb = kb * 1024; + long gb = mb * 1024; + if (size >= gb) + { + return String.format("%.1f GB", (float) size / gb); + } + else if (size >= mb) + { + float f = (float) size / mb; + return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); + } + else if (size >= kb) + { + float f = (float) size / kb; + return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); + } + else + { + return String.format("%d B", size); + } + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Cpu.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Cpu.java new file mode 100644 index 0000000..0f3e4fd --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Cpu.java @@ -0,0 +1,101 @@ +package net.hzvtc.framework.web.domain.server; + +import net.hzvtc.common.utils.Arith; + +/** + * CPU相关信息 + * + * @author admin + */ +public class Cpu +{ + /** + * 核心数 + */ + private int cpuNum; + + /** + * CPU总的使用率 + */ + private double total; + + /** + * CPU系统使用率 + */ + private double sys; + + /** + * CPU用户使用率 + */ + private double used; + + /** + * CPU当前等待率 + */ + private double wait; + + /** + * CPU当前空闲率 + */ + private double free; + + public int getCpuNum() + { + return cpuNum; + } + + public void setCpuNum(int cpuNum) + { + this.cpuNum = cpuNum; + } + + public double getTotal() + { + return Arith.round(Arith.mul(total, 100), 2); + } + + public void setTotal(double total) + { + this.total = total; + } + + public double getSys() + { + return Arith.round(Arith.mul(sys / total, 100), 2); + } + + public void setSys(double sys) + { + this.sys = sys; + } + + public double getUsed() + { + return Arith.round(Arith.mul(used / total, 100), 2); + } + + public void setUsed(double used) + { + this.used = used; + } + + public double getWait() + { + return Arith.round(Arith.mul(wait / total, 100), 2); + } + + public void setWait(double wait) + { + this.wait = wait; + } + + public double getFree() + { + return Arith.round(Arith.mul(free / total, 100), 2); + } + + public void setFree(double free) + { + this.free = free; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Jvm.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Jvm.java new file mode 100644 index 0000000..73d4ede --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Jvm.java @@ -0,0 +1,122 @@ +package net.hzvtc.framework.web.domain.server; + +import java.lang.management.ManagementFactory; +import net.hzvtc.common.utils.Arith; +import net.hzvtc.common.utils.DateUtils; + +/** + * JVM相关信息 + * + * @author admin + */ +public class Jvm +{ + /** + * 当前JVM占用的内存总数(M) + */ + private double total; + + /** + * JVM最大可用内存总数(M) + */ + private double max; + + /** + * JVM空闲内存(M) + */ + private double free; + + /** + * JDK版本 + */ + private String version; + + /** + * JDK路径 + */ + private String home; + + public double getTotal() + { + return Arith.div(total, (1024 * 1024), 2); + } + + public void setTotal(double total) + { + this.total = total; + } + + public double getMax() + { + return Arith.div(max, (1024 * 1024), 2); + } + + public void setMax(double max) + { + this.max = max; + } + + public double getFree() + { + return Arith.div(free, (1024 * 1024), 2); + } + + public void setFree(double free) + { + this.free = free; + } + + public double getUsed() + { + return Arith.div(total - free, (1024 * 1024), 2); + } + + public double getUsage() + { + return Arith.mul(Arith.div(total - free, total, 4), 100); + } + + /** + * 获取JDK名称 + */ + public String getName() + { + return ManagementFactory.getRuntimeMXBean().getVmName(); + } + + public String getVersion() + { + return version; + } + + public void setVersion(String version) + { + this.version = version; + } + + public String getHome() + { + return home; + } + + public void setHome(String home) + { + this.home = home; + } + + /** + * JDK启动时间 + */ + public String getStartTime() + { + return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getServerStartDate()); + } + + /** + * JDK运行时间 + */ + public String getRunTime() + { + return DateUtils.getDatePoor(DateUtils.getNowDate(), DateUtils.getServerStartDate()); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Mem.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Mem.java new file mode 100644 index 0000000..01e7665 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Mem.java @@ -0,0 +1,61 @@ +package net.hzvtc.framework.web.domain.server; + +import net.hzvtc.common.utils.Arith; + +/** + * 內存相关信息 + * + * @author admin + */ +public class Mem +{ + /** + * 内存总量 + */ + private double total; + + /** + * 已用内存 + */ + private double used; + + /** + * 剩余内存 + */ + private double free; + + public double getTotal() + { + return Arith.div(total, (1024 * 1024 * 1024), 2); + } + + public void setTotal(long total) + { + this.total = total; + } + + public double getUsed() + { + return Arith.div(used, (1024 * 1024 * 1024), 2); + } + + public void setUsed(long used) + { + this.used = used; + } + + public double getFree() + { + return Arith.div(free, (1024 * 1024 * 1024), 2); + } + + public void setFree(long free) + { + this.free = free; + } + + public double getUsage() + { + return Arith.mul(Arith.div(used, total, 4), 100); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Sys.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Sys.java new file mode 100644 index 0000000..88fc983 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/Sys.java @@ -0,0 +1,84 @@ +package net.hzvtc.framework.web.domain.server; + +/** + * 系统相关信息 + * + * @author admin + */ +public class Sys +{ + /** + * 服务器名称 + */ + private String computerName; + + /** + * 服务器Ip + */ + private String computerIp; + + /** + * 项目路径 + */ + private String userDir; + + /** + * 操作系统 + */ + private String osName; + + /** + * 系统架构 + */ + private String osArch; + + public String getComputerName() + { + return computerName; + } + + public void setComputerName(String computerName) + { + this.computerName = computerName; + } + + public String getComputerIp() + { + return computerIp; + } + + public void setComputerIp(String computerIp) + { + this.computerIp = computerIp; + } + + public String getUserDir() + { + return userDir; + } + + public void setUserDir(String userDir) + { + this.userDir = userDir; + } + + public String getOsName() + { + return osName; + } + + public void setOsName(String osName) + { + this.osName = osName; + } + + public String getOsArch() + { + return osArch; + } + + public void setOsArch(String osArch) + { + this.osArch = osArch; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/SysFile.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/SysFile.java new file mode 100644 index 0000000..eaafd00 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/domain/server/SysFile.java @@ -0,0 +1,114 @@ +package net.hzvtc.framework.web.domain.server; + +/** + * 系统文件相关信息 + * + * @author admin + */ +public class SysFile +{ + /** + * 盘符路径 + */ + private String dirName; + + /** + * 盘符类型 + */ + private String sysTypeName; + + /** + * 文件类型 + */ + private String typeName; + + /** + * 总大小 + */ + private String total; + + /** + * 剩余大小 + */ + private String free; + + /** + * 已经使用量 + */ + private String used; + + /** + * 资源的使用率 + */ + private double usage; + + public String getDirName() + { + return dirName; + } + + public void setDirName(String dirName) + { + this.dirName = dirName; + } + + public String getSysTypeName() + { + return sysTypeName; + } + + public void setSysTypeName(String sysTypeName) + { + this.sysTypeName = sysTypeName; + } + + public String getTypeName() + { + return typeName; + } + + public void setTypeName(String typeName) + { + this.typeName = typeName; + } + + public String getTotal() + { + return total; + } + + public void setTotal(String total) + { + this.total = total; + } + + public String getFree() + { + return free; + } + + public void setFree(String free) + { + this.free = free; + } + + public String getUsed() + { + return used; + } + + public void setUsed(String used) + { + this.used = used; + } + + public double getUsage() + { + return usage; + } + + public void setUsage(double usage) + { + this.usage = usage; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/exception/GlobalExceptionHandler.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..5fd6847 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/exception/GlobalExceptionHandler.java @@ -0,0 +1,106 @@ +package net.hzvtc.framework.web.exception; + +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.exception.DemoModeException; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.validation.BindException; +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 javax.servlet.http.HttpServletRequest; + +/** + * 全局异常处理器 + * + * @author admin + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 权限校验异常 + */ + @ExceptionHandler(AccessDeniedException.class) + public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage()); + return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权"); + } + + /** + * 请求方式不支持 + */ + @ExceptionHandler(HttpRequestMethodNotSupportedException.class) + public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, + HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()); + return AjaxResult.error(e.getMessage()); + } + + /** + * 业务异常 + */ + @ExceptionHandler(ServiceException.class) + 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()); + } + + /** + * 拦截未知的运行时异常 + */ + @ExceptionHandler(RuntimeException.class) + public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生未知异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 系统异常 + */ + @ExceptionHandler(Exception.class) + public AjaxResult handleException(Exception e, HttpServletRequest request) { + String requestURI = request.getRequestURI(); + log.error("请求地址'{}',发生系统异常.", requestURI, e); + return AjaxResult.error(e.getMessage()); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(BindException.class) + public AjaxResult handleBindException(BindException e) { + log.error(e.getMessage(), e); + String message = e.getAllErrors().get(0).getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 自定义验证异常 + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { + log.error(e.getMessage(), e); + String message = e.getBindingResult().getFieldError().getDefaultMessage(); + return AjaxResult.error(message); + } + + /** + * 演示模式异常 + */ + @ExceptionHandler(DemoModeException.class) + public AjaxResult handleDemoModeException(DemoModeException e) { + return AjaxResult.error("演示模式,不允许操作"); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/PermissionService.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/PermissionService.java new file mode 100644 index 0000000..8177978 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/PermissionService.java @@ -0,0 +1,166 @@ +package net.hzvtc.framework.web.service; + +import java.util.Set; + +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; + +/** + * 首创 自定义权限实现,ss取自SpringSecurity首字母 + * + * @author admin + */ +@Service("ss") +public class PermissionService +{ + /** 所有权限标识 */ + private static final String ALL_PERMISSION = "*:*:*"; + + /** 管理员角色权限标识 */ + private static final String SUPER_ADMIN = "admin"; + + private static final String ROLE_DELIMETER = ","; + + private static final String PERMISSION_DELIMETER = ","; + + /** + * 验证用户是否具备某权限 + * + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + public boolean hasPermi(String permission) + { + if (StringUtils.isEmpty(permission)) + { + return false; + } + LoginUser loginUser = SecurityUtils.getLoginUser(); + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) + { + return false; + } + return hasPermissions(loginUser.getPermissions(), permission); + } + + /** + * 验证用户是否不具备某权限,与 hasPermi逻辑相反 + * + * @param permission 权限字符串 + * @return 用户是否不具备某权限 + */ + public boolean lacksPermi(String permission) + { + return hasPermi(permission) != true; + } + + /** + * 验证用户是否具有以下任意一个权限 + * + * @param permissions 以 PERMISSION_NAMES_DELIMETER 为分隔符的权限列表 + * @return 用户是否具有以下任意一个权限 + */ + public boolean hasAnyPermi(String permissions) + { + if (StringUtils.isEmpty(permissions)) + { + return false; + } + LoginUser loginUser = SecurityUtils.getLoginUser(); + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) + { + return false; + } + Set authorities = loginUser.getPermissions(); + for (String permission : permissions.split(PERMISSION_DELIMETER)) + { + if (permission != null && hasPermissions(authorities, permission)) + { + return true; + } + } + return false; + } + + /** + * 判断用户是否拥有某个角色 + * + * @param role 角色字符串 + * @return 用户是否具备某角色 + */ + public boolean hasRole(String role) + { + if (StringUtils.isEmpty(role)) + { + return false; + } + LoginUser loginUser = SecurityUtils.getLoginUser(); + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) + { + return false; + } + for (SysRole sysRole : loginUser.getUser().getRoles()) + { + String roleKey = sysRole.getRoleKey(); + if (SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) + { + return true; + } + } + return false; + } + + /** + * 验证用户是否不具备某角色,与 isRole逻辑相反。 + * + * @param role 角色名称 + * @return 用户是否不具备某角色 + */ + public boolean lacksRole(String role) + { + return hasRole(role) != true; + } + + /** + * 验证用户是否具有以下任意一个角色 + * + * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 + * @return 用户是否具有以下任意一个角色 + */ + public boolean hasAnyRoles(String roles) + { + if (StringUtils.isEmpty(roles)) + { + return false; + } + LoginUser loginUser = SecurityUtils.getLoginUser(); + if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) + { + return false; + } + for (String role : roles.split(ROLE_DELIMETER)) + { + if (hasRole(role)) + { + return true; + } + } + return false; + } + + /** + * 判断是否包含权限 + * + * @param permissions 权限列表 + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + private boolean hasPermissions(Set permissions, String permission) + { + return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission)); + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysLoginService.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysLoginService.java new file mode 100644 index 0000000..9ae7453 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysLoginService.java @@ -0,0 +1,101 @@ +package net.hzvtc.framework.web.service; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.exception.user.CaptchaException; +import net.hzvtc.common.exception.user.CaptchaExpireException; +import net.hzvtc.common.exception.user.UserNoLoginPermissionException; +import net.hzvtc.common.exception.user.UserPasswordNotMatchException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.MessageUtils; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.ip.IpUtils; +import net.hzvtc.framework.manager.AsyncManager; +import net.hzvtc.framework.manager.factory.AsyncFactory; +import net.hzvtc.framework.web.service.TokenService; +import net.hzvtc.system.service.SysConfigService; +import net.hzvtc.system.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.BadCredentialsException; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +@Component +public class SysLoginService { + @Autowired + private TokenService tokenService; + @Resource + private AuthenticationManager authenticationManager; + @Autowired + private RedisCache redisCache; + @Autowired + private SysUserService userService; + @Autowired + private SysConfigService configService; + + public String ssoLogin(String token) { + return null; + } + + public String login(String username, String password, String code, String uuid, int loginType) { + boolean captchaOnOff = this.configService.selectCaptchaOnOff(); + if (captchaOnOff && (loginType == 0 || loginType == 2)) { + this.validateCaptcha(username, code, uuid); + } + Authentication authentication = null; + try { + authentication = this.authenticationManager.authenticate((Authentication)new UsernamePasswordAuthenticationToken((Object)username, (Object)password)); + } + catch (Exception e) { + if (e instanceof BadCredentialsException) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", MessageUtils.message((String)"user.password.not.match", (Object[])new Object[0]), new Object[0])); + throw new UserPasswordNotMatchException(); + } + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", e.getMessage(), new Object[0])); + throw new ServiceException(e.getMessage()); + } + LoginUser loginUser = (LoginUser)authentication.getPrincipal(); + if (loginType == 0) { + if (loginUser.getPortalLogin() != 1) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", MessageUtils.message((String)"no.portal.login", (Object[])new Object[0]), new Object[0])); + throw new UserNoLoginPermissionException(); + } + } else if (loginType == 1 && loginUser.getWebLogin() != 1) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", MessageUtils.message((String)"no.web.login", (Object[])new Object[0]), new Object[0])); + throw new UserNoLoginPermissionException(); + } + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Success", MessageUtils.message((String)"user.login.success", (Object[])new Object[0]), new Object[0])); + this.recordLoginInfo(loginUser.getUserId()); + return this.tokenService.createToken(loginUser); + } + + public void validateCaptcha(String username, String code, String uuid) { + String verifyKey = "captcha_codes:" + uuid; + String captcha = (String)this.redisCache.getCacheObject(verifyKey); + this.redisCache.deleteObject(verifyKey); + if (captcha == null) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", MessageUtils.message((String)"user.jcaptcha.expire", (Object[])new Object[0]), new Object[0])); + throw new CaptchaExpireException(); + } + if (!code.equalsIgnoreCase(captcha)) { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, "Error", MessageUtils.message((String)"user.jcaptcha.error", (Object[])new Object[0]), new Object[0])); + throw new CaptchaException(); + } + } + + public void recordLoginInfo(Long userId) { + SysUser sysUser = new SysUser(); + sysUser.setUserId(userId); + sysUser.setLoginIp(IpUtils.getIpAddr((HttpServletRequest)ServletUtils.getRequest())); + sysUser.setLoginDate(DateUtils.getNowDate()); + this.userService.updateUserProfile(sysUser); + } +} + + diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysPermissionService.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysPermissionService.java new file mode 100644 index 0000000..1006b36 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysPermissionService.java @@ -0,0 +1,62 @@ +package net.hzvtc.framework.web.service; + +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.system.service.SysMenuService; +import net.hzvtc.system.service.SysRoleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.util.HashSet; +import java.util.Set; + +/** + * 用户权限处理 + * + * @author admin + */ +@Component +public class SysPermissionService { + @Autowired + private SysRoleService roleService; + + @Autowired + private SysMenuService menuService; + + /** + * 获取角色数据权限 + * + * @param user 用户信息 + * @return 角色权限信息 + */ + public Set getRolePermission(SysUser user) { + Set roles = new HashSet(); + // 管理员拥有所有权限 + if (user.isAdmin()) { + roles.add("admin"); + } else { + SysRole sysRole = new SysRole(); + sysRole.setUserId(user.getUserId()); + sysRole.setSysId(user.getSysId()); + roles.addAll(roleService.selectRolePermissionByUserId(sysRole)); + } + return roles; + } + + /** + * 获取菜单数据权限 + * + * @param user 用户信息 + * @return 菜单权限信息 + */ + public Set getMenuPermission(SysUser user) { + Set perms = new HashSet(); + // 管理员拥有所有权限 + if (user.isAdmin()) { + perms.add("*:*:*"); + } else { + perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId())); + } + return perms; + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysRegisterService.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysRegisterService.java new file mode 100644 index 0000000..6cf8295 --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/SysRegisterService.java @@ -0,0 +1,97 @@ +package net.hzvtc.framework.web.service; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.RegisterBody; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.exception.user.CaptchaException; +import net.hzvtc.common.exception.user.CaptchaExpireException; +import net.hzvtc.common.utils.MessageUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.framework.manager.AsyncManager; +import net.hzvtc.framework.manager.factory.AsyncFactory; +import net.hzvtc.system.service.SysConfigService; +import net.hzvtc.system.service.SysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * 注册校验方法 + * + * @author admin + */ +@Component +public class SysRegisterService { + @Autowired + private SysUserService userService; + + @Autowired + private SysConfigService configService; + + @Autowired + private RedisCache redisCache; + + /** + * 注册 + */ + public String register(RegisterBody registerBody) { + String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword(); + + boolean captchaOnOff = configService.selectCaptchaOnOff(); + // 验证码开关 + if (captchaOnOff) { + validateCaptcha(username, registerBody.getCode(), registerBody.getUuid()); + } + + if (StringUtils.isEmpty(username)) { + msg = "用户名不能为空"; + } else if (StringUtils.isEmpty(password)) { + msg = "用户密码不能为空"; + } 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) { + msg = "密码长度必须在5到20个字符之间"; + } else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(username))) { + msg = "保存用户'" + username + "'失败,注册账号已存在"; + } else { + SysUser sysUser = new SysUser(); + sysUser.setUserName(username); + sysUser.setNickName(registerBody.getName()); + sysUser.setPhonenumber(registerBody.getTelephone()); + sysUser.setUserType(registerBody.getUserType()); + sysUser.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword())); + boolean regFlag = userService.registerUser(sysUser); + if (!regFlag) { + msg = "注册失败,请联系系统管理人员"; + } else { + AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, + MessageUtils.message("user.register.success"))); + } + } + return msg; + } + + /** + * 校验验证码 + * + * @param username 用户名 + * @param code 验证码 + * @param uuid 唯一标识 + * @return 结果 + */ + public void validateCaptcha(String username, String code, String uuid) { + String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; + String captcha = redisCache.getCacheObject(verifyKey); + redisCache.deleteObject(verifyKey); + if (captcha == null) { + throw new CaptchaExpireException(); + } + if (!code.equalsIgnoreCase(captcha)) { + throw new CaptchaException(); + } + } +} diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/TokenService.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/TokenService.java new file mode 100644 index 0000000..56233eb --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/TokenService.java @@ -0,0 +1,132 @@ +package net.hzvtc.framework.web.service; + +import eu.bitwalker.useragentutils.UserAgent; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.security.Keys; +import io.jsonwebtoken.security.SecureDigestAlgorithm; +import java.security.Key; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import javax.crypto.SecretKey; +import javax.servlet.http.HttpServletRequest; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.utils.ServletUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.ip.AddressUtils; +import net.hzvtc.common.utils.ip.IpUtils; +import net.hzvtc.common.utils.uuid.IdUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class TokenService { + protected static final long MILLIS_SECOND = 1000L; + protected static final long MILLIS_MINUTE = 60000L; + private static final Long MILLIS_MINUTE_TEN = 1200000L; + @Value(value="${token.header}") + private String header; + @Value(value="${token.secret}") + private String secret; + @Value(value="${token.expireTime}") + private int expireTime; + @Autowired + private RedisCache redisCache; + + public LoginUser getLoginUser(HttpServletRequest request) { + String token = this.getToken(request); + if (StringUtils.isNotEmpty((String)token)) { + try { + Claims claims = this.parseToken(token); + String uuid = (String)claims.get((Object)"login_user_key"); + String userKey = this.getTokenKey(uuid); + LoginUser user = (LoginUser)this.redisCache.getCacheObject(userKey); + return user; + } + catch (Exception exception) { + // empty catch block + } + } + return null; + } + + public void setLoginUser(LoginUser loginUser) { + if (StringUtils.isNotNull((Object)loginUser) && StringUtils.isNotEmpty((String)loginUser.getToken())) { + this.refreshToken(loginUser); + } + } + + public void delLoginUser(String token) { + if (StringUtils.isNotEmpty((String)token)) { + String userKey = this.getTokenKey(token); + this.redisCache.deleteObject(userKey); + } + } + + public String createToken(LoginUser loginUser) { + String token = IdUtils.fastUUID(); + loginUser.setToken(token); + this.setUserAgent(loginUser); + this.refreshToken(loginUser); + HashMap claims = new HashMap(); + claims.put("login_user_key", token); + return this.createToken(claims); + } + + public void verifyToken(LoginUser loginUser) { + long currentTime; + long expireTime = loginUser.getExpireTime(); + if (expireTime - (currentTime = System.currentTimeMillis()) <= MILLIS_MINUTE_TEN) { + this.refreshToken(loginUser); + } + } + + public void refreshToken(LoginUser loginUser) { + loginUser.setLoginTime(Long.valueOf(System.currentTimeMillis())); + loginUser.setExpireTime(Long.valueOf(loginUser.getLoginTime() + (long)this.expireTime * 60000L)); + String userKey = this.getTokenKey(loginUser.getToken()); + this.redisCache.setCacheObject(userKey, (Object)loginUser, Integer.valueOf(this.expireTime), TimeUnit.MINUTES); + } + + public void setUserAgent(LoginUser loginUser) { + UserAgent userAgent = UserAgent.parseUserAgentString((String)ServletUtils.getRequest().getHeader("User-Agent")); + String ip = IpUtils.getIpAddr((HttpServletRequest)ServletUtils.getRequest()); + loginUser.setIpaddr(ip); + loginUser.setLoginLocation(AddressUtils.getRealAddressByIP((String)ip)); + loginUser.setBrowser(userAgent.getBrowser().getName()); + loginUser.setOs(userAgent.getOperatingSystem().getName()); + } + + private String createToken(Map claims) { + SecretKey key = Keys.hmacShaKeyFor((byte[])this.secret.getBytes()); + String token = Jwts.builder().claims(claims).signWith((Key)key, (SecureDigestAlgorithm)Jwts.SIG.HS512).compact(); + return token; + } + + private Claims parseToken(String token) { + SecretKey key = Keys.hmacShaKeyFor((byte[])this.secret.getBytes()); + return (Claims)Jwts.parser().verifyWith(key).build().parseSignedClaims((CharSequence)token).getPayload(); + } + + public String getUsernameFromToken(String token) { + Claims claims = this.parseToken(token); + return claims.getSubject(); + } + + private String getToken(HttpServletRequest request) { + String token = request.getHeader(this.header); + if (StringUtils.isNotEmpty((String)token) && token.startsWith("Bearer ")) { + token = token.replace("Bearer ", ""); + } + return token; + } + + private String getTokenKey(String uuid) { + return "login_tokens:" + uuid; + } +} + + diff --git a/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/UserDetailsServiceImpl.java b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/UserDetailsServiceImpl.java new file mode 100644 index 0000000..243053e --- /dev/null +++ b/ai-bird-framework/src/main/java/net/hzvtc/framework/web/service/UserDetailsServiceImpl.java @@ -0,0 +1,70 @@ +package net.hzvtc.framework.web.service; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.enums.UserStatus; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.system.service.SysRoleService; +import net.hzvtc.system.service.SysUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +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 java.util.List; + +/** + * 用户验证处理 + * + * @author admin + */ +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class); + + @Autowired + private SysUserService userService; + + @Autowired + private SysPermissionService permissionService; + + @Autowired + private SysRoleService sysRoleService; + + @Autowired + private ProtectedAreaService protectedAreaService; + + @Autowired + private DeviceInfoService deviceInfoService; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + SysUser user = userService.selectUserByUserName(username); + if (StringUtils.isNull(user)) { + log.info("登录用户:{} 不存在.", username); +// throw new ServiceException("登录用户:" + username + " 不存在"); + throw new ServiceException("帐号或密码错误!"); + } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) { + log.info("登录用户:{} 已被删除.", username); + throw new ServiceException("对不起,您的账号:" + username + " 已被删除"); + } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) { + log.info("登录用户:{} 已被停用.", username); + throw new ServiceException("对不起,您的账号:" + username + " 已停用"); + } + return createLoginUser(user); + } + + public UserDetails createLoginUser(SysUser user) { + List areaList = protectedAreaService.getAreaListByUserId(user.getUserId()); + List deviceList = deviceInfoService.getDeviceInfoListByUserId(user.getUserId()); + return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user), + user.getWebLogin(), user.getPortalLogin(), areaList, deviceList); + } +} diff --git a/ai-bird-generator/pom.xml b/ai-bird-generator/pom.xml new file mode 100644 index 0000000..eadf5f5 --- /dev/null +++ b/ai-bird-generator/pom.xml @@ -0,0 +1,40 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + + ai-bird-generator + + + generator代码生成 + + + + + + + org.apache.velocity + velocity-engine-core + + + + + commons-collections + commons-collections + + + + + net.hzvtc + ai-bird-common + + + + + \ No newline at end of file diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/config/GenConfig.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/config/GenConfig.java new file mode 100644 index 0000000..43907db --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/config/GenConfig.java @@ -0,0 +1,73 @@ +package net.hzvtc.generator.config; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +/** + * 读取代码生成相关配置 + * + * @author admin + */ +@Component +@ConfigurationProperties(prefix = "gen") +@PropertySource(value = { "classpath:generator.yml" }) +public class GenConfig +{ + /** 作者 */ + public static String author; + + /** 生成包路径 */ + public static String packageName; + + /** 自动去除表前缀,默认是false */ + public static boolean autoRemovePre; + + /** 表前缀(类名不会包含表前缀) */ + public static String tablePrefix; + + public static String getAuthor() + { + return author; + } + + @Value("${author}") + public void setAuthor(String author) + { + GenConfig.author = author; + } + + public static String getPackageName() + { + return packageName; + } + + @Value("${packageName}") + public void setPackageName(String packageName) + { + GenConfig.packageName = packageName; + } + + public static boolean getAutoRemovePre() + { + return autoRemovePre; + } + + @Value("${autoRemovePre}") + public void setAutoRemovePre(boolean autoRemovePre) + { + GenConfig.autoRemovePre = autoRemovePre; + } + + public static String getTablePrefix() + { + return tablePrefix; + } + + @Value("${tablePrefix}") + public void setTablePrefix(String tablePrefix) + { + GenConfig.tablePrefix = tablePrefix; + } +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/controller/GenController.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/controller/GenController.java new file mode 100644 index 0000000..c63d307 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/controller/GenController.java @@ -0,0 +1,194 @@ +package net.hzvtc.generator.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.generator.domain.GenTable; +import net.hzvtc.generator.domain.GenTableColumn; +import net.hzvtc.generator.service.GenTableColumnService; +import net.hzvtc.generator.service.GenTableService; +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 代码生成 操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/tool/gen") +public class GenController extends BaseController { + @Autowired + private GenTableService genTableService; + + @Autowired + private GenTableColumnService genTableColumnService; + + /** + * 查询代码生成列表 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:list')") + @GetMapping("/list") + public TableDataInfo genList(GenTable genTable) { + startPage(); + List list = genTableService.selectGenTableList(genTable); + return getDataTable(list); + } + + /** + * 修改代码生成业务 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:query')") + @GetMapping(value = "/{talbleId}") + public AjaxResult getInfo(@PathVariable Long talbleId) { + GenTable table = genTableService.selectGenTableById(talbleId); + List tables = genTableService.selectGenTableAll(); + List list = genTableColumnService.selectGenTableColumnListByTableId(talbleId); + Map map = new HashMap(); + map.put("info", table); + map.put("rows", list); + map.put("tables", tables); + return AjaxResult.success(map); + } + + /** + * 查询数据库列表 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:list')") + @GetMapping("/db/list") + public TableDataInfo dataList(GenTable genTable) { + startPage(); + List list = genTableService.selectDbTableList(genTable); + return getDataTable(list); + } + + /** + * 查询数据表字段列表 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:list')") + @GetMapping(value = "/column/{talbleId}") + public TableDataInfo columnList(Long tableId) { + TableDataInfo dataInfo = new TableDataInfo(); + List list = genTableColumnService.selectGenTableColumnListByTableId(tableId); + dataInfo.setRows(list); + dataInfo.setTotal(list.size()); + return dataInfo; + } + + /** + * 导入表结构(保存) + */ + @PreAuthorize("@ss.hasPermi('tool:gen:import')") + @Log(title = "代码生成", businessType = BusinessType.IMPORT) + @PostMapping("/importTable") + public AjaxResult importTableSave(String tables) { + String[] tableNames = Convert.toStrArray(tables); + // 查询表信息 + List tableList = genTableService.selectDbTableListByNames(tableNames); + genTableService.importGenTable(tableList); + return AjaxResult.success(); + } + + /** + * 修改保存代码生成业务 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:edit')") + @Log(title = "代码生成", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult editSave(@Validated @RequestBody GenTable genTable) { + genTableService.validateEdit(genTable); + genTableService.updateGenTable(genTable); + return AjaxResult.success(); + } + + /** + * 删除代码生成 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:remove')") + @Log(title = "代码生成", businessType = BusinessType.DELETE) + @DeleteMapping("/{tableIds}") + public AjaxResult remove(@PathVariable Long[] tableIds) { + genTableService.deleteGenTableByIds(tableIds); + return AjaxResult.success(); + } + + /** + * 预览代码 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:preview')") + @GetMapping("/preview/{tableId}") + public AjaxResult preview(@PathVariable("tableId") Long tableId) throws IOException { + Map dataMap = genTableService.previewCode(tableId); + return AjaxResult.success(dataMap); + } + + /** + * 生成代码(下载方式) + */ + @PreAuthorize("@ss.hasPermi('tool:gen:code')") + @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @GetMapping("/download/{tableName}") + public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { + byte[] data = genTableService.downloadCode(tableName); + genCode(response, data); + } + + /** + * 生成代码(自定义路径) + */ + @PreAuthorize("@ss.hasPermi('tool:gen:code')") + @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @GetMapping("/genCode/{tableName}") + public AjaxResult genCode(@PathVariable("tableName") String tableName) { + genTableService.generatorCode(tableName); + return AjaxResult.success(); + } + + /** + * 同步数据库 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:edit')") + @Log(title = "代码生成", businessType = BusinessType.UPDATE) + @GetMapping("/synchDb/{tableName}") + public AjaxResult synchDb(@PathVariable("tableName") String tableName) { + genTableService.synchDb(tableName); + return AjaxResult.success(); + } + + /** + * 批量生成代码 + */ + @PreAuthorize("@ss.hasPermi('tool:gen:code')") + @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @GetMapping("/batchGenCode") + public void batchGenCode(HttpServletResponse response, String tables) throws IOException { + String[] tableNames = Convert.toStrArray(tables); + byte[] data = genTableService.downloadCode(tableNames); + genCode(response, data); + } + + /** + * 生成zip文件 + */ + private void genCode(HttpServletResponse response, byte[] data) throws IOException { + response.reset(); + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Access-Control-Expose-Headers", "Content-Disposition"); + response.setHeader("Content-Disposition", "attachment; filename=\"AiBirdSys.zip\""); + response.addHeader("Content-Length", "" + data.length); + response.setContentType("application/octet-stream; charset=UTF-8"); + IOUtils.write(data, response.getOutputStream()); + } +} \ No newline at end of file diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTable.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTable.java new file mode 100644 index 0000000..0cf01ca --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTable.java @@ -0,0 +1,365 @@ +package net.hzvtc.generator.domain; + +import net.hzvtc.common.constant.GenConstants; +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.common.utils.StringUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.ibatis.type.Alias; + +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import java.util.List; + +/** + * 业务表 gen_table + * + * @author admin + */ +@Alias("GenTable") +public class GenTable extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + private Long tableId; + + /** + * 表名称 + */ + @NotBlank(message = "表名称不能为空") + private String tableName; + + /** + * 表描述 + */ + @NotBlank(message = "表描述不能为空") + private String tableComment; + + /** + * 关联父表的表名 + */ + private String subTableName; + + /** + * 本表关联父表的外键名 + */ + private String subTableFkName; + + /** + * 实体类名称(首字母大写) + */ + @NotBlank(message = "实体类名称不能为空") + private String className; + + /** + * 使用的模板(crud单表操作 tree树表操作 sub主子表操作) + */ + private String tplCategory; + + /** + * 生成包路径 + */ + @NotBlank(message = "生成包路径不能为空") + private String packageName; + + /** + * 生成模块名 + */ + @NotBlank(message = "生成模块名不能为空") + private String moduleName; + + /** + * 生成业务名 + */ + @NotBlank(message = "生成业务名不能为空") + private String businessName; + + /** + * 生成功能名 + */ + @NotBlank(message = "生成功能名不能为空") + private String functionName; + + /** + * 生成作者 + */ + @NotBlank(message = "作者不能为空") + private String functionAuthor; + + /** + * 生成代码方式(0zip压缩包 1自定义路径) + */ + private String genType; + + /** + * 生成路径(不填默认项目路径) + */ + private String genPath; + + /** + * 主键信息 + */ + private GenTableColumn pkColumn; + + /** + * 子表信息 + */ + private GenTable subTable; + + /** + * 表列信息 + */ + @Valid + private List columns; + + /** + * 其它生成选项 + */ + private String options; + + /** + * 树编码字段 + */ + private String treeCode; + + /** + * 树父编码字段 + */ + private String treeParentCode; + + /** + * 树名称字段 + */ + private String treeName; + + /** + * 上级菜单ID字段 + */ + private String parentMenuId; + + /** + * 上级菜单名称字段 + */ + private String parentMenuName; + + public static boolean isSub(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_SUB, tplCategory); + } + + public static boolean isTree(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); + } + + public static boolean isCrud(String tplCategory) { + return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); + } + + public static boolean isSuperColumn(String tplCategory, String javaField) { + if (isTree(tplCategory)) { + return StringUtils.equalsAnyIgnoreCase(javaField, + ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY)); + } + return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); + } + + public Long getTableId() { + return tableId; + } + + public void setTableId(Long tableId) { + this.tableId = tableId; + } + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getTableComment() { + return tableComment; + } + + public void setTableComment(String tableComment) { + this.tableComment = tableComment; + } + + public String getSubTableName() { + return subTableName; + } + + public void setSubTableName(String subTableName) { + this.subTableName = subTableName; + } + + public String getSubTableFkName() { + return subTableFkName; + } + + public void setSubTableFkName(String subTableFkName) { + this.subTableFkName = subTableFkName; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getTplCategory() { + return tplCategory; + } + + public void setTplCategory(String tplCategory) { + this.tplCategory = tplCategory; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public String getBusinessName() { + return businessName; + } + + public void setBusinessName(String businessName) { + this.businessName = businessName; + } + + public String getFunctionName() { + return functionName; + } + + public void setFunctionName(String functionName) { + this.functionName = functionName; + } + + public String getFunctionAuthor() { + return functionAuthor; + } + + public void setFunctionAuthor(String functionAuthor) { + this.functionAuthor = functionAuthor; + } + + public String getGenType() { + return genType; + } + + public void setGenType(String genType) { + this.genType = genType; + } + + public String getGenPath() { + return genPath; + } + + public void setGenPath(String genPath) { + this.genPath = genPath; + } + + public GenTableColumn getPkColumn() { + return pkColumn; + } + + public void setPkColumn(GenTableColumn pkColumn) { + this.pkColumn = pkColumn; + } + + public GenTable getSubTable() { + return subTable; + } + + public void setSubTable(GenTable subTable) { + this.subTable = subTable; + } + + public List getColumns() { + return columns; + } + + public void setColumns(List columns) { + this.columns = columns; + } + + public String getOptions() { + return options; + } + + public void setOptions(String options) { + this.options = options; + } + + public String getTreeCode() { + return treeCode; + } + + public void setTreeCode(String treeCode) { + this.treeCode = treeCode; + } + + public String getTreeParentCode() { + return treeParentCode; + } + + public void setTreeParentCode(String treeParentCode) { + this.treeParentCode = treeParentCode; + } + + public String getTreeName() { + return treeName; + } + + public void setTreeName(String treeName) { + this.treeName = treeName; + } + + public String getParentMenuId() { + return parentMenuId; + } + + public void setParentMenuId(String parentMenuId) { + this.parentMenuId = parentMenuId; + } + + public String getParentMenuName() { + return parentMenuName; + } + + public void setParentMenuName(String parentMenuName) { + this.parentMenuName = parentMenuName; + } + + public boolean isSub() { + return isSub(tplCategory); + } + + public boolean isTree() { + return isTree(tplCategory); + } + + public boolean isCrud() { + return isCrud(tplCategory); + } + + public boolean isSuperColumn(String javaField) { + return isSuperColumn(tplCategory, javaField); + } +} \ No newline at end of file diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTableColumn.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTableColumn.java new file mode 100644 index 0000000..2c5b86a --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/domain/GenTableColumn.java @@ -0,0 +1,350 @@ +package net.hzvtc.generator.domain; + +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.common.utils.StringUtils; +import org.apache.ibatis.type.Alias; + +import javax.validation.constraints.NotBlank; + +/** + * 代码生成业务字段表 gen_table_column + * + * @author admin + */ +@Alias("GenTableColumn") +public class GenTableColumn extends BaseEntity { + private static final long serialVersionUID = 1L; + + /** + * 编号 + */ + private Long columnId; + + /** + * 归属表编号 + */ + private Long tableId; + + /** + * 列名称 + */ + private String columnName; + + /** + * 列描述 + */ + private String columnComment; + + /** + * 列类型 + */ + private String columnType; + + /** + * JAVA类型 + */ + private String javaType; + + /** + * JAVA字段名 + */ + @NotBlank(message = "Java属性不能为空") + private String javaField; + + /** + * 是否主键(1是) + */ + private String isPk; + + /** + * 是否自增(1是) + */ + private String isIncrement; + + /** + * 是否必填(1是) + */ + private String isRequired; + + /** + * 是否为插入字段(1是) + */ + private String isInsert; + + /** + * 是否编辑字段(1是) + */ + private String isEdit; + + /** + * 是否列表字段(1是) + */ + private String isList; + + /** + * 是否查询字段(1是) + */ + private String isQuery; + + /** + * 查询方式(EQ等于、NE不等于、GT大于、LT小于、LIKE模糊、BETWEEN范围) + */ + private String queryType; + + /** + * 显示类型(input文本框、textarea文本域、select下拉框、checkbox复选框、radio单选框、datetime日期控件、image图片上传控件、upload文件上传控件、editor富文本控件) + */ + private String htmlType; + + /** + * 字典类型 + */ + private String dictType; + + /** + * 排序 + */ + private Integer sort; + + public static boolean isSuperColumn(String javaField) { + return StringUtils.equalsAnyIgnoreCase(javaField, + // BaseEntity + "createBy", "createTime", "updateBy", "updateTime", "remark", + // TreeEntity + "parentName", "parentId", "orderNum", "ancestors"); + } + + public static boolean isUsableColumn(String javaField) { + // isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单 + return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark"); + } + + public Long getColumnId() { + return columnId; + } + + public void setColumnId(Long columnId) { + this.columnId = columnId; + } + + public Long getTableId() { + return tableId; + } + + public void setTableId(Long tableId) { + this.tableId = tableId; + } + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getColumnComment() { + return columnComment; + } + + public void setColumnComment(String columnComment) { + this.columnComment = columnComment; + } + + public String getColumnType() { + return columnType; + } + + public void setColumnType(String columnType) { + this.columnType = columnType; + } + + public String getJavaType() { + return javaType; + } + + public void setJavaType(String javaType) { + this.javaType = javaType; + } + + public String getJavaField() { + return javaField; + } + + public void setJavaField(String javaField) { + this.javaField = javaField; + } + + public String getCapJavaField() { + return StringUtils.capitalize(javaField); + } + + public String getIsPk() { + return isPk; + } + + public void setIsPk(String isPk) { + this.isPk = isPk; + } + + public boolean isPk() { + return isPk(isPk); + } + + public boolean isPk(String isPk) { + return isPk != null && StringUtils.equals("1", isPk); + } + + public String getIsIncrement() { + return isIncrement; + } + + public void setIsIncrement(String isIncrement) { + this.isIncrement = isIncrement; + } + + public boolean isIncrement() { + return isIncrement(isIncrement); + } + + public boolean isIncrement(String isIncrement) { + return isIncrement != null && StringUtils.equals("1", isIncrement); + } + + public String getIsRequired() { + return isRequired; + } + + public void setIsRequired(String isRequired) { + this.isRequired = isRequired; + } + + public boolean isRequired() { + return isRequired(isRequired); + } + + public boolean isRequired(String isRequired) { + return isRequired != null && StringUtils.equals("1", isRequired); + } + + public String getIsInsert() { + return isInsert; + } + + public void setIsInsert(String isInsert) { + this.isInsert = isInsert; + } + + public boolean isInsert() { + return isInsert(isInsert); + } + + public boolean isInsert(String isInsert) { + return isInsert != null && StringUtils.equals("1", isInsert); + } + + public String getIsEdit() { + return isEdit; + } + + public void setIsEdit(String isEdit) { + this.isEdit = isEdit; + } + + public boolean isEdit() { + return isInsert(isEdit); + } + + public boolean isEdit(String isEdit) { + return isEdit != null && StringUtils.equals("1", isEdit); + } + + public String getIsList() { + return isList; + } + + public void setIsList(String isList) { + this.isList = isList; + } + + public boolean isList() { + return isList(isList); + } + + public boolean isList(String isList) { + return isList != null && StringUtils.equals("1", isList); + } + + public String getIsQuery() { + return isQuery; + } + + public void setIsQuery(String isQuery) { + this.isQuery = isQuery; + } + + public boolean isQuery() { + return isQuery(isQuery); + } + + public boolean isQuery(String isQuery) { + return isQuery != null && StringUtils.equals("1", isQuery); + } + + public String getQueryType() { + return queryType; + } + + public void setQueryType(String queryType) { + this.queryType = queryType; + } + + public String getHtmlType() { + return htmlType; + } + + public void setHtmlType(String htmlType) { + this.htmlType = htmlType; + } + + public String getDictType() { + return dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + public Integer getSort() { + return sort; + } + + public void setSort(Integer sort) { + this.sort = sort; + } + + public boolean isSuperColumn() { + return isSuperColumn(javaField); + } + + public boolean isUsableColumn() { + return isUsableColumn(javaField); + } + + public String readConverterExp() { + String remarks = StringUtils.substringBetween(columnComment, "(", ")"); + StringBuffer sb = new StringBuffer(); + if (StringUtils.isNotEmpty(remarks)) { + for (String value : remarks.split(" ")) { + if (StringUtils.isNotEmpty(value)) { + Object startStr = value.subSequence(0, 1); + String endStr = value.substring(1); + sb.append("").append(startStr).append("=").append(endStr).append(","); + } + } + return sb.deleteCharAt(sb.length() - 1).toString(); + } else { + return columnComment; + } + } +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableColumnMapper.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableColumnMapper.java new file mode 100644 index 0000000..6118e55 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableColumnMapper.java @@ -0,0 +1,60 @@ +package net.hzvtc.generator.mapper; + +import java.util.List; +import net.hzvtc.generator.domain.GenTableColumn; + +/** + * 业务字段 数据层 + * + * @author admin + */ +public interface GenTableColumnMapper +{ + /** + * 根据表名称查询列信息 + * + * @param tableName 表名称 + * @return 列信息 + */ + public List selectDbTableColumnsByName(String tableName); + + /** + * 查询业务字段列表 + * + * @param tableId 业务字段编号 + * @return 业务字段集合 + */ + public List selectGenTableColumnListByTableId(Long tableId); + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int insertGenTableColumn(GenTableColumn genTableColumn); + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int updateGenTableColumn(GenTableColumn genTableColumn); + + /** + * 删除业务字段 + * + * @param genTableColumns 列数据 + * @return 结果 + */ + public int deleteGenTableColumns(List genTableColumns); + + /** + * 批量删除业务字段 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableColumnByIds(Long[] ids); +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableMapper.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableMapper.java new file mode 100644 index 0000000..34a983f --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/mapper/GenTableMapper.java @@ -0,0 +1,83 @@ +package net.hzvtc.generator.mapper; + +import java.util.List; +import net.hzvtc.generator.domain.GenTable; + +/** + * 业务 数据层 + * + * @author admin + */ +public interface GenTableMapper +{ + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + public List selectGenTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + public List selectDbTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + public List selectDbTableListByNames(String[] tableNames); + + /** + * 查询所有表信息 + * + * @return 表信息集合 + */ + public List selectGenTableAll(); + + /** + * 查询表ID业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + public GenTable selectGenTableById(Long id); + + /** + * 查询表名称业务信息 + * + * @param tableName 表名称 + * @return 业务信息 + */ + public GenTable selectGenTableByName(String tableName); + + /** + * 新增业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public int insertGenTable(GenTable genTable); + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public int updateGenTable(GenTable genTable); + + /** + * 批量删除业务 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableByIds(Long[] ids); +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnService.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnService.java new file mode 100644 index 0000000..b7c200a --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnService.java @@ -0,0 +1,44 @@ +package net.hzvtc.generator.service; + +import net.hzvtc.generator.domain.GenTableColumn; + +import java.util.List; + +/** + * 业务字段 服务层 + * + * @author admin + */ +public interface GenTableColumnService { + /** + * 查询业务字段列表 + * + * @param tableId 业务字段编号 + * @return 业务字段集合 + */ + public List selectGenTableColumnListByTableId(Long tableId); + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int insertGenTableColumn(GenTableColumn genTableColumn); + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + public int updateGenTableColumn(GenTableColumn genTableColumn); + + /** + * 删除业务字段信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteGenTableColumnByIds(String ids); +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnServiceImpl.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnServiceImpl.java new file mode 100644 index 0000000..d6d54b0 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableColumnServiceImpl.java @@ -0,0 +1,64 @@ +package net.hzvtc.generator.service; + +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.generator.domain.GenTableColumn; +import net.hzvtc.generator.mapper.GenTableColumnMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 业务字段 服务层实现 + * + * @author admin + */ +@Service +public class GenTableColumnServiceImpl implements GenTableColumnService { + @Autowired + private GenTableColumnMapper genTableColumnMapper; + + /** + * 查询业务字段列表 + * + * @param tableId 业务字段编号 + * @return 业务字段集合 + */ + @Override + public List selectGenTableColumnListByTableId(Long tableId) { + return genTableColumnMapper.selectGenTableColumnListByTableId(tableId); + } + + /** + * 新增业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + @Override + public int insertGenTableColumn(GenTableColumn genTableColumn) { + return genTableColumnMapper.insertGenTableColumn(genTableColumn); + } + + /** + * 修改业务字段 + * + * @param genTableColumn 业务字段信息 + * @return 结果 + */ + @Override + public int updateGenTableColumn(GenTableColumn genTableColumn) { + return genTableColumnMapper.updateGenTableColumn(genTableColumn); + } + + /** + * 删除业务字段对象 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteGenTableColumnByIds(String ids) { + return genTableColumnMapper.deleteGenTableColumnByIds(Convert.toLongArray(ids)); + } +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableService.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableService.java new file mode 100644 index 0000000..a4b51f7 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableService.java @@ -0,0 +1,121 @@ +package net.hzvtc.generator.service; + +import net.hzvtc.generator.domain.GenTable; + +import java.util.List; +import java.util.Map; + +/** + * 业务 服务层 + * + * @author admin + */ +public interface GenTableService { + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + public List selectGenTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + public List selectDbTableList(GenTable genTable); + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + public List selectDbTableListByNames(String[] tableNames); + + /** + * 查询所有表信息 + * + * @return 表信息集合 + */ + public List selectGenTableAll(); + + /** + * 查询业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + public GenTable selectGenTableById(Long id); + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + public void updateGenTable(GenTable genTable); + + /** + * 删除业务信息 + * + * @param tableIds 需要删除的表数据ID + * @return 结果 + */ + public void deleteGenTableByIds(Long[] tableIds); + + /** + * 导入表结构 + * + * @param tableList 导入表列表 + */ + public void importGenTable(List tableList); + + /** + * 预览代码 + * + * @param tableId 表编号 + * @return 预览数据列表 + */ + public Map previewCode(Long tableId); + + /** + * 生成代码(下载方式) + * + * @param tableName 表名称 + * @return 数据 + */ + public byte[] downloadCode(String tableName); + + /** + * 生成代码(自定义路径) + * + * @param tableName 表名称 + * @return 数据 + */ + public void generatorCode(String tableName); + + /** + * 同步数据库 + * + * @param tableName 表名称 + */ + public void synchDb(String tableName); + + /** + * 批量生成代码(下载方式) + * + * @param tableNames 表数组 + * @return 数据 + */ + public byte[] downloadCode(String[] tableNames); + + /** + * 修改保存参数校验 + * + * @param genTable 业务信息 + */ + public void validateEdit(GenTable genTable); +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableServiceImpl.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableServiceImpl.java new file mode 100644 index 0000000..5bdd24d --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/service/GenTableServiceImpl.java @@ -0,0 +1,447 @@ +package net.hzvtc.generator.service; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.GenConstants; +import net.hzvtc.common.core.text.CharsetKit; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.generator.domain.GenTable; +import net.hzvtc.generator.domain.GenTableColumn; +import net.hzvtc.generator.mapper.GenTableColumnMapper; +import net.hzvtc.generator.mapper.GenTableMapper; +import net.hzvtc.generator.util.GenUtils; +import net.hzvtc.generator.util.VelocityInitializer; +import net.hzvtc.generator.util.VelocityUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 业务 服务层实现 + * + * @author admin + */ +@Service +public class GenTableServiceImpl implements GenTableService { + private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class); + + @Resource + private GenTableMapper genTableMapper; + + @Resource + private GenTableColumnMapper genTableColumnMapper; + + /** + * 获取代码生成地址 + * + * @param table 业务表信息 + * @param template 模板文件路径 + * @return 生成地址 + */ + public static String getGenPath(GenTable table, String template) { + String genPath = table.getGenPath(); + if (StringUtils.equals(genPath, "/")) { + return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table); + } + return genPath + File.separator + VelocityUtils.getFileName(template, table); + } + + /** + * 查询业务信息 + * + * @param id 业务ID + * @return 业务信息 + */ + @Override + public GenTable selectGenTableById(Long id) { + GenTable genTable = genTableMapper.selectGenTableById(id); + setTableFromOptions(genTable); + return genTable; + } + + /** + * 查询业务列表 + * + * @param genTable 业务信息 + * @return 业务集合 + */ + @Override + public List selectGenTableList(GenTable genTable) { + return genTableMapper.selectGenTableList(genTable); + } + + /** + * 查询据库列表 + * + * @param genTable 业务信息 + * @return 数据库表集合 + */ + @Override + public List selectDbTableList(GenTable genTable) { + return genTableMapper.selectDbTableList(genTable); + } + + /** + * 查询据库列表 + * + * @param tableNames 表名称组 + * @return 数据库表集合 + */ + @Override + public List selectDbTableListByNames(String[] tableNames) { + return genTableMapper.selectDbTableListByNames(tableNames); + } + + /** + * 查询所有表信息 + * + * @return 表信息集合 + */ + @Override + public List selectGenTableAll() { + return genTableMapper.selectGenTableAll(); + } + + /** + * 修改业务 + * + * @param genTable 业务信息 + * @return 结果 + */ + @Override + @Transactional + public void updateGenTable(GenTable genTable) { + String options = JSON.toJSONString(genTable.getParams()); + genTable.setOptions(options); + int row = genTableMapper.updateGenTable(genTable); + if (row > 0) { + for (GenTableColumn cenTableColumn : genTable.getColumns()) { + genTableColumnMapper.updateGenTableColumn(cenTableColumn); + } + } + } + + /** + * 删除业务对象 + * + * @param tableIds 需要删除的数据ID + * @return 结果 + */ + @Override + @Transactional + public void deleteGenTableByIds(Long[] tableIds) { + genTableMapper.deleteGenTableByIds(tableIds); + genTableColumnMapper.deleteGenTableColumnByIds(tableIds); + } + + /** + * 导入表结构 + * + * @param tableList 导入表列表 + */ + @Override + @Transactional + public void importGenTable(List tableList) { + String operName = SecurityUtils.getUsername(); + try { + for (GenTable table : tableList) { + String tableName = table.getTableName(); + GenUtils.initTable(table, operName); + int row = genTableMapper.insertGenTable(table); + if (row > 0) { + // 保存列信息 + List genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); + for (GenTableColumn column : genTableColumns) { + GenUtils.initColumnField(column, table); + genTableColumnMapper.insertGenTableColumn(column); + } + } + } + } catch (Exception e) { + throw new ServiceException("导入失败:" + e.getMessage()); + } + } + + /** + * 预览代码 + * + * @param tableId 表编号 + * @return 预览数据列表 + */ + @Override + public Map previewCode(Long tableId) { + Map dataMap = new LinkedHashMap<>(); + // 查询表信息 + GenTable table = genTableMapper.selectGenTableById(tableId); + // 设置主子表信息 + setSubTable(table); + // 设置主键列信息 + setPkColumn(table); + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 获取模板列表 + List templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + dataMap.put(template, sw.toString()); + } + return dataMap; + } + + /** + * 生成代码(下载方式) + * + * @param tableName 表名称 + * @return 数据 + */ + @Override + public byte[] downloadCode(String tableName) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + generatorCode(tableName, zip); + IOUtils.closeQuietly(zip); + return outputStream.toByteArray(); + } + + /** + * 生成代码(自定义路径) + * + * @param tableName 表名称 + */ + @Override + public void generatorCode(String tableName) { + // 查询表信息 + GenTable table = genTableMapper.selectGenTableByName(tableName); + // 设置主子表信息 + setSubTable(table); + // 设置主键列信息 + setPkColumn(table); + + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 获取模板列表 + List templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { + // 渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + try { + String path = getGenPath(table, template); + FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8); + } catch (IOException e) { + throw new ServiceException("渲染模板失败,表名:" + table.getTableName()); + } + } + } + } + + /** + * 同步数据库 + * + * @param tableName 表名称 + */ + @Override + @Transactional + public void synchDb(String tableName) { + GenTable table = genTableMapper.selectGenTableByName(tableName); + List tableColumns = table.getColumns(); + Map tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity())); + + List dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName); + if (StringUtils.isEmpty(dbTableColumns)) { + throw new ServiceException("同步数据失败,原表结构不存在"); + } + List dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); + + dbTableColumns.forEach(column -> { + GenUtils.initColumnField(column, table); + if (tableColumnMap.containsKey(column.getColumnName())) { + GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName()); + column.setColumnId(prevColumn.getColumnId()); + if (column.isList()) { + // 如果是列表,继续保留字典类型 + column.setDictType(prevColumn.getDictType()); + } + genTableColumnMapper.updateGenTableColumn(column); + } else { + genTableColumnMapper.insertGenTableColumn(column); + } + }); + + List delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList()); + if (StringUtils.isNotEmpty(delColumns)) { + genTableColumnMapper.deleteGenTableColumns(delColumns); + } + } + + /** + * 批量生成代码(下载方式) + * + * @param tableNames 表数组 + * @return 数据 + */ + @Override + public byte[] downloadCode(String[] tableNames) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + for (String tableName : tableNames) { + generatorCode(tableName, zip); + } + IOUtils.closeQuietly(zip); + return outputStream.toByteArray(); + } + + /** + * 查询表信息并生成代码 + */ + private void generatorCode(String tableName, ZipOutputStream zip) { + // 查询表信息 + GenTable table = genTableMapper.selectGenTableByName(tableName); + // 设置主子表信息 + setSubTable(table); + // 设置主键列信息 + setPkColumn(table); + + VelocityInitializer.initVelocity(); + + VelocityContext context = VelocityUtils.prepareContext(table); + + // 获取模板列表 + List templates = VelocityUtils.getTemplateList(table.getTplCategory()); + for (String template : templates) { + // 渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, Constants.UTF8); + tpl.merge(context, sw); + try { + // 添加到zip + zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table))); + IOUtils.write(sw.toString(), zip, Constants.UTF8); + IOUtils.closeQuietly(sw); + zip.flush(); + zip.closeEntry(); + } catch (IOException e) { + log.error("渲染模板失败,表名:" + table.getTableName(), e); + } + } + } + + /** + * 修改保存参数校验 + * + * @param genTable 业务信息 + */ + @Override + public void validateEdit(GenTable genTable) { + if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) { + String options = JSON.toJSONString(genTable.getParams()); + JSONObject paramsObj = JSONObject.parseObject(options); + if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) { + throw new ServiceException("树编码字段不能为空"); + } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) { + throw new ServiceException("树父编码字段不能为空"); + } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) { + throw new ServiceException("树名称字段不能为空"); + } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) { + if (StringUtils.isEmpty(genTable.getSubTableName())) { + throw new ServiceException("关联子表的表名不能为空"); + } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) { + throw new ServiceException("子表关联的外键名不能为空"); + } + } + } + } + + /** + * 设置主键列信息 + * + * @param table 业务表信息 + */ + public void setPkColumn(GenTable table) { + for (GenTableColumn column : table.getColumns()) { + if (column.isPk()) { + table.setPkColumn(column); + break; + } + } + if (StringUtils.isNull(table.getPkColumn())) { + table.setPkColumn(table.getColumns().get(0)); + } + if (GenConstants.TPL_SUB.equals(table.getTplCategory())) { + for (GenTableColumn column : table.getSubTable().getColumns()) { + if (column.isPk()) { + table.getSubTable().setPkColumn(column); + break; + } + } + if (StringUtils.isNull(table.getSubTable().getPkColumn())) { + table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0)); + } + } + } + + /** + * 设置主子表信息 + * + * @param table 业务表信息 + */ + public void setSubTable(GenTable table) { + String subTableName = table.getSubTableName(); + if (StringUtils.isNotEmpty(subTableName)) { + table.setSubTable(genTableMapper.selectGenTableByName(subTableName)); + } + } + + /** + * 设置代码生成其他选项值 + * + * @param genTable 设置后的生成对象 + */ + public void setTableFromOptions(GenTable genTable) { + JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions()); + if (StringUtils.isNotNull(paramsObj)) { + String treeCode = paramsObj.getString(GenConstants.TREE_CODE); + String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE); + String treeName = paramsObj.getString(GenConstants.TREE_NAME); + String parentMenuId = paramsObj.getString(GenConstants.PARENT_MENU_ID); + String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME); + + genTable.setTreeCode(treeCode); + genTable.setTreeParentCode(treeParentCode); + genTable.setTreeName(treeName); + genTable.setParentMenuId(parentMenuId); + genTable.setParentMenuName(parentMenuName); + } + } +} \ No newline at end of file diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/util/GenUtils.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/GenUtils.java new file mode 100644 index 0000000..1af72b3 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/GenUtils.java @@ -0,0 +1,259 @@ +package net.hzvtc.generator.util; + +import java.util.Arrays; + +import net.hzvtc.common.constant.GenConstants; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.generator.domain.GenTable; +import net.hzvtc.generator.domain.GenTableColumn; +import org.apache.commons.lang3.RegExUtils; +import net.hzvtc.generator.config.GenConfig; + +/** + * 代码生成器 工具类 + * + * @author admin + */ +public class GenUtils +{ + /** + * 初始化表信息 + */ + public static void initTable(GenTable genTable, String operName) + { + genTable.setClassName(convertClassName(genTable.getTableName())); + genTable.setPackageName(GenConfig.getPackageName()); + genTable.setModuleName(getModuleName(GenConfig.getPackageName())); + genTable.setBusinessName(getBusinessName(genTable.getTableName())); + genTable.setFunctionName(replaceText(genTable.getTableComment())); + genTable.setFunctionAuthor(GenConfig.getAuthor()); + genTable.setCreateBy(operName); + } + + /** + * 初始化列属性字段 + */ + public static void initColumnField(GenTableColumn column, GenTable table) + { + String dataType = getDbType(column.getColumnType()); + String columnName = column.getColumnName(); + column.setTableId(table.getTableId()); + column.setCreateBy(table.getCreateBy()); + // 设置java字段名 + column.setJavaField(StringUtils.toCamelCase(columnName)); + // 设置默认类型 + column.setJavaType(GenConstants.TYPE_STRING); + + if (arraysContains(GenConstants.COLUMNTYPE_STR, dataType) || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType)) + { + // 字符串长度超过500设置为文本域 + Integer columnLength = getColumnLength(column.getColumnType()); + String htmlType = columnLength >= 500 || arraysContains(GenConstants.COLUMNTYPE_TEXT, dataType) ? GenConstants.HTML_TEXTAREA : GenConstants.HTML_INPUT; + column.setHtmlType(htmlType); + } + else if (arraysContains(GenConstants.COLUMNTYPE_TIME, dataType)) + { + column.setJavaType(GenConstants.TYPE_DATE); + column.setHtmlType(GenConstants.HTML_DATETIME); + } + else if (arraysContains(GenConstants.COLUMNTYPE_NUMBER, dataType)) + { + column.setHtmlType(GenConstants.HTML_INPUT); + + // 如果是浮点型 统一用BigDecimal + String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); + if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) + { + column.setJavaType(GenConstants.TYPE_BIGDECIMAL); + } + // 如果是整形 + else if (str != null && str.length == 1 && Integer.parseInt(str[0]) <= 10) + { + column.setJavaType(GenConstants.TYPE_INTEGER); + } + // 长整形 + else + { + column.setJavaType(GenConstants.TYPE_LONG); + } + } + + // 插入字段(默认所有字段都需要插入) + column.setIsInsert(GenConstants.REQUIRE); + + // 编辑字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_EDIT, columnName) && !column.isPk()) + { + column.setIsEdit(GenConstants.REQUIRE); + } + // 列表字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_LIST, columnName) && !column.isPk()) + { + column.setIsList(GenConstants.REQUIRE); + } + // 查询字段 + if (!arraysContains(GenConstants.COLUMNNAME_NOT_QUERY, columnName) && !column.isPk()) + { + column.setIsQuery(GenConstants.REQUIRE); + } + + // 查询字段类型 + if (StringUtils.endsWithIgnoreCase(columnName, "name")) + { + column.setQueryType(GenConstants.QUERY_LIKE); + } + // 状态字段设置单选框 + if (StringUtils.endsWithIgnoreCase(columnName, "status")) + { + column.setHtmlType(GenConstants.HTML_RADIO); + } + // 类型&性别字段设置下拉框 + else if (StringUtils.endsWithIgnoreCase(columnName, "type") + || StringUtils.endsWithIgnoreCase(columnName, "sex")) + { + column.setHtmlType(GenConstants.HTML_SELECT); + } + // 图片字段设置图片上传控件 + else if (StringUtils.endsWithIgnoreCase(columnName, "image")) + { + column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD); + } + // 文件字段设置文件上传控件 + else if (StringUtils.endsWithIgnoreCase(columnName, "file")) + { + column.setHtmlType(GenConstants.HTML_FILE_UPLOAD); + } + // 内容字段设置富文本控件 + else if (StringUtils.endsWithIgnoreCase(columnName, "content")) + { + column.setHtmlType(GenConstants.HTML_EDITOR); + } + } + + /** + * 校验数组是否包含指定值 + * + * @param arr 数组 + * @param targetValue 值 + * @return 是否包含 + */ + public static boolean arraysContains(String[] arr, String targetValue) + { + return Arrays.asList(arr).contains(targetValue); + } + + /** + * 获取模块名 + * + * @param packageName 包名 + * @return 模块名 + */ + public static String getModuleName(String packageName) + { + int lastIndex = packageName.lastIndexOf("."); + int nameLength = packageName.length(); + String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); + return moduleName; + } + + /** + * 获取业务名 + * + * @param tableName 表名 + * @return 业务名 + */ + public static String getBusinessName(String tableName) + { + int lastIndex = tableName.lastIndexOf("_"); + int nameLength = tableName.length(); + String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength); + return businessName; + } + + /** + * 表名转换成Java类名 + * + * @param tableName 表名称 + * @return 类名 + */ + public static String convertClassName(String tableName) + { + boolean autoRemovePre = GenConfig.getAutoRemovePre(); + String tablePrefix = GenConfig.getTablePrefix(); + if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) + { + String[] searchList = StringUtils.split(tablePrefix, ","); + tableName = replaceFirst(tableName, searchList); + } + return StringUtils.convertToCamelCase(tableName); + } + + /** + * 批量替换前缀 + * + * @param replacementm 替换值 + * @param searchList 替换列表 + * @return + */ + public static String replaceFirst(String replacementm, String[] searchList) + { + String text = replacementm; + for (String searchString : searchList) + { + if (replacementm.startsWith(searchString)) + { + text = replacementm.replaceFirst(searchString, ""); + break; + } + } + return text; + } + + /** + * 关键字替换 + * + * @param text 需要被替换的名字 + * @return 替换后的名字 + */ + public static String replaceText(String text) + { + return RegExUtils.replaceAll(text, "(?:表|AiBirdSys)", ""); + } + + /** + * 获取数据库类型字段 + * + * @param columnType 列类型 + * @return 截取后的列类型 + */ + public static String getDbType(String columnType) + { + if (StringUtils.indexOf(columnType, "(") > 0) + { + return StringUtils.substringBefore(columnType, "("); + } + else + { + return columnType; + } + } + + /** + * 获取字段长度 + * + * @param columnType 列类型 + * @return 截取后的列类型 + */ + public static Integer getColumnLength(String columnType) + { + if (StringUtils.indexOf(columnType, "(") > 0) + { + String length = StringUtils.substringBetween(columnType, "(", ")"); + return Integer.valueOf(length); + } + else + { + return 0; + } + } +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityInitializer.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityInitializer.java new file mode 100644 index 0000000..de9361b --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityInitializer.java @@ -0,0 +1,35 @@ +package net.hzvtc.generator.util; + +import java.util.Properties; + +import net.hzvtc.common.constant.Constants; +import org.apache.velocity.app.Velocity; + +/** + * VelocityEngine工厂 + * + * @author admin + */ +public class VelocityInitializer +{ + /** + * 初始化vm方法 + */ + public static void initVelocity() + { + Properties p = new Properties(); + try + { + // 加载classpath目录下的vm文件 + p.setProperty("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + // 定义字符集 + p.setProperty(Velocity.INPUT_ENCODING, Constants.UTF8); + // 初始化Velocity引擎,指定配置Properties + Velocity.init(p); + } + catch (Exception e) + { + throw new RuntimeException(e); + } + } +} diff --git a/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityUtils.java b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityUtils.java new file mode 100644 index 0000000..dda0489 --- /dev/null +++ b/ai-bird-generator/src/main/java/net/hzvtc/generator/util/VelocityUtils.java @@ -0,0 +1,334 @@ +package net.hzvtc.generator.util; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.constant.GenConstants; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.generator.domain.GenTable; +import net.hzvtc.generator.domain.GenTableColumn; +import org.apache.velocity.VelocityContext; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * 模板处理工具类 + * + * @author admin + */ +public class VelocityUtils { + /** + * 项目空间路径 + */ + private static final String PROJECT_PATH = "main/java"; + + /** + * mybatis空间路径 + */ + private static final String MYBATIS_PATH = "main/resources/mapper"; + + /** + * 默认上级菜单,系统工具 + */ + private static final String DEFAULT_PARENT_MENU_ID = "3"; + + /** + * 设置模板变量信息 + * + * @return 模板列表 + */ + public static VelocityContext prepareContext(GenTable genTable) { + String moduleName = genTable.getModuleName(); + String businessName = genTable.getBusinessName(); + String packageName = genTable.getPackageName(); + String tplCategory = genTable.getTplCategory(); + String functionName = genTable.getFunctionName(); + + VelocityContext velocityContext = new VelocityContext(); + velocityContext.put("tplCategory", genTable.getTplCategory()); + velocityContext.put("tableName", genTable.getTableName()); + velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); + velocityContext.put("ClassName", genTable.getClassName()); + velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); + velocityContext.put("moduleName", genTable.getModuleName()); + velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName())); + velocityContext.put("businessName", genTable.getBusinessName()); + velocityContext.put("basePackage", getPackagePrefix(packageName)); + velocityContext.put("packageName", packageName); + velocityContext.put("author", genTable.getFunctionAuthor()); + velocityContext.put("datetime", DateUtils.getDate()); + velocityContext.put("pkColumn", genTable.getPkColumn()); + velocityContext.put("importList", getImportList(genTable)); + velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); + velocityContext.put("columns", genTable.getColumns()); + velocityContext.put("table", genTable); + velocityContext.put("dicts", getDicts(genTable)); + setMenuVelocityContext(velocityContext, genTable); + if (GenConstants.TPL_TREE.equals(tplCategory)) { + setTreeVelocityContext(velocityContext, genTable); + } + if (GenConstants.TPL_SUB.equals(tplCategory)) { + setSubVelocityContext(velocityContext, genTable); + } + return velocityContext; + } + + public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { + String options = genTable.getOptions(); + JSONObject paramsObj = JSONObject.parseObject(options); + String parentMenuId = getParentMenuId(paramsObj); + context.put("parentMenuId", parentMenuId); + } + + public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) { + String options = genTable.getOptions(); + JSONObject paramsObj = JSONObject.parseObject(options); + String treeCode = getTreecode(paramsObj); + String treeParentCode = getTreeParentCode(paramsObj); + String treeName = getTreeName(paramsObj); + + context.put("treeCode", treeCode); + context.put("treeParentCode", treeParentCode); + context.put("treeName", treeName); + context.put("expandColumn", getExpandColumn(genTable)); + if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { + context.put("tree_parent_code", paramsObj.getString(GenConstants.TREE_PARENT_CODE)); + } + if (paramsObj.containsKey(GenConstants.TREE_NAME)) { + context.put("tree_name", paramsObj.getString(GenConstants.TREE_NAME)); + } + } + + public static void setSubVelocityContext(VelocityContext context, GenTable genTable) { + GenTable subTable = genTable.getSubTable(); + String subTableName = genTable.getSubTableName(); + String subTableFkName = genTable.getSubTableFkName(); + String subClassName = genTable.getSubTable().getClassName(); + String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName); + + context.put("subTable", subTable); + context.put("subTableName", subTableName); + context.put("subTableFkName", subTableFkName); + context.put("subTableFkClassName", subTableFkClassName); + context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName)); + context.put("subClassName", subClassName); + context.put("subclassName", StringUtils.uncapitalize(subClassName)); + context.put("subImportList", getImportList(genTable.getSubTable())); + } + + /** + * 获取模板信息 + * + * @return 模板列表 + */ + public static List getTemplateList(String tplCategory) { + List templates = new ArrayList(); + templates.add("vm/java/domain.java.vm"); + templates.add("vm/java/mapper.java.vm"); + templates.add("vm/java/service.java.vm"); + templates.add("vm/java/serviceImpl.java.vm"); + templates.add("vm/java/controller.java.vm"); + templates.add("vm/xml/mapper.xml.vm"); + templates.add("vm/sql/sql.vm"); + templates.add("vm/js/api.js.vm"); + if (GenConstants.TPL_CRUD.equals(tplCategory)) { + templates.add("vm/vue/index.vue.vm"); + } else if (GenConstants.TPL_TREE.equals(tplCategory)) { + templates.add("vm/vue/index-tree.vue.vm"); + } else if (GenConstants.TPL_SUB.equals(tplCategory)) { + templates.add("vm/vue/index.vue.vm"); + templates.add("vm/java/sub-domain.java.vm"); + } + return templates; + } + + /** + * 获取文件名 + */ + public static String getFileName(String template, GenTable genTable) { + // 文件名称 + String fileName = ""; + // 包路径 + String packageName = genTable.getPackageName(); + // 模块名 + String moduleName = genTable.getModuleName(); + // 大写类名 + String className = genTable.getClassName(); + // 业务名称 + String businessName = genTable.getBusinessName(); + + String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); + String mybatisPath = MYBATIS_PATH + "/" + moduleName; + String vuePath = "vue"; + + if (template.contains("domain.java.vm")) { + fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); + } + if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { + fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName()); + } else if (template.contains("mapper.java.vm")) { + fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); + } else if (template.contains("service.java.vm")) { + fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className); + } else if (template.contains("serviceImpl.java.vm")) { + fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); + } else if (template.contains("controller.java.vm")) { + fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); + } else if (template.contains("mapper.xml.vm")) { + fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); + } else if (template.contains("sql.vm")) { + fileName = businessName + "Menu.sql"; + } else if (template.contains("api.js.vm")) { + fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); + } else if (template.contains("index.vue.vm")) { + fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + } else if (template.contains("index-tree.vue.vm")) { + fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + } + return fileName; + } + + /** + * 获取包前缀 + * + * @param packageName 包名称 + * @return 包前缀名称 + */ + public static String getPackagePrefix(String packageName) { + int lastIndex = packageName.lastIndexOf("."); + String basePackage = StringUtils.substring(packageName, 0, lastIndex); + return basePackage; + } + + /** + * 根据列类型获取导入包 + * + * @param genTable 业务表对象 + * @return 返回需要导入的包列表 + */ + public static HashSet getImportList(GenTable genTable) { + List columns = genTable.getColumns(); + GenTable subGenTable = genTable.getSubTable(); + HashSet importList = new HashSet(); + if (StringUtils.isNotNull(subGenTable)) { + importList.add("java.util.List"); + } + for (GenTableColumn column : columns) { + if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) { + importList.add("java.util.Date"); + importList.add("com.fasterxml.jackson.annotation.JsonFormat"); + } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) { + importList.add("java.math.BigDecimal"); + } + } + return importList; + } + + /** + * 根据列类型获取字典组 + * + * @param genTable 业务表对象 + * @return 返回字典组 + */ + public static String getDicts(GenTable genTable) { + List columns = genTable.getColumns(); + Set dicts = new HashSet(); + for (GenTableColumn column : columns) { + if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny( + column.getHtmlType(), + new String[]{GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX})) { + dicts.add("'" + column.getDictType() + "'"); + } + } + return StringUtils.join(dicts, ", "); + } + + /** + * 获取权限前缀 + * + * @param moduleName 模块名称 + * @param businessName 业务名称 + * @return 返回权限前缀 + */ + public static String getPermissionPrefix(String moduleName, String businessName) { + return StringUtils.format("{}:{}", moduleName, businessName); + } + + /** + * 获取上级菜单ID字段 + * + * @param paramsObj 生成其他选项 + * @return 上级菜单ID字段 + */ + public static String getParentMenuId(JSONObject paramsObj) { + if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID) + && StringUtils.isNotEmpty(paramsObj.getString(GenConstants.PARENT_MENU_ID))) { + return paramsObj.getString(GenConstants.PARENT_MENU_ID); + } + return DEFAULT_PARENT_MENU_ID; + } + + /** + * 获取树编码 + * + * @param paramsObj 生成其他选项 + * @return 树编码 + */ + public static String getTreecode(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_CODE)) { + return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); + } + return StringUtils.EMPTY; + } + + /** + * 获取树父编码 + * + * @param paramsObj 生成其他选项 + * @return 树父编码 + */ + public static String getTreeParentCode(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { + return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); + } + return StringUtils.EMPTY; + } + + /** + * 获取树名称 + * + * @param paramsObj 生成其他选项 + * @return 树名称 + */ + public static String getTreeName(JSONObject paramsObj) { + if (paramsObj.containsKey(GenConstants.TREE_NAME)) { + return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); + } + return StringUtils.EMPTY; + } + + /** + * 获取需要在哪一列上面显示展开按钮 + * + * @param genTable 业务表对象 + * @return 展开按钮列序号 + */ + public static int getExpandColumn(GenTable genTable) { + String options = genTable.getOptions(); + JSONObject paramsObj = JSONObject.parseObject(options); + String treeName = paramsObj.getString(GenConstants.TREE_NAME); + int num = 0; + for (GenTableColumn column : genTable.getColumns()) { + if (column.isList()) { + num++; + String columnName = column.getColumnName(); + if (columnName.equals(treeName)) { + break; + } + } + } + return num; + } +} diff --git a/ai-bird-generator/src/main/resources/generator.yml b/ai-bird-generator/src/main/resources/generator.yml new file mode 100644 index 0000000..d9af4bb --- /dev/null +++ b/ai-bird-generator/src/main/resources/generator.yml @@ -0,0 +1,10 @@ +# 代码生成 +gen: + # 作者 + author: admin + # 默认生成包路径 system 需改成自己的模块名称 如 system monitor tool + packageName: net.hzvtc.system + # 自动去除表前缀,默认是false + autoRemovePre: false + # 表前缀(生成类名不会包含表前缀,多个用逗号分隔) + tablePrefix: sys_ \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml b/ai-bird-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml new file mode 100644 index 0000000..fe99aa6 --- /dev/null +++ b/ai-bird-generator/src/main/resources/mapper/generator/GenTableColumnMapper.xml @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select * + from gen_table_column + + + + + + + + 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() + ) + + + + update gen_table_column + + column_comment = #{columnComment}, + java_type = #{javaType}, + java_field = #{javaField}, + is_insert = #{isInsert}, + is_edit = #{isEdit}, + is_list = #{isList}, + is_query = #{isQuery}, + is_required = #{isRequired}, + query_type = #{queryType}, + html_type = #{htmlType}, + dict_type = #{dictType}, + sort = #{sort}, + update_by = #{updateBy}, + update_time = sysdate() + + where column_id = #{columnId} + + + + delete from gen_table_column where table_id in + + #{tableId} + + + + + delete from gen_table_column where column_id in + + #{item.columnId} + + + + \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/mapper/generator/GenTableMapper.xml b/ai-bird-generator/src/main/resources/mapper/generator/GenTableMapper.xml new file mode 100644 index 0000000..fb098b5 --- /dev/null +++ b/ai-bird-generator/src/main/resources/mapper/generator/GenTableMapper.xml @@ -0,0 +1,318 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + + + + + + + + + + + + + + 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() + ) + + + + update gen_table + + table_name = #{tableName}, + table_comment = #{tableComment}, + sub_table_name = #{subTableName}, + sub_table_fk_name = #{subTableFkName}, + class_name = #{className}, + function_author = #{functionAuthor}, + gen_type = #{genType}, + gen_path = #{genPath}, + tpl_category = #{tplCategory}, + package_name = #{packageName}, + module_name = #{moduleName}, + business_name = #{businessName}, + function_name = #{functionName}, + options = #{options}, + update_by = #{updateBy}, + remark = #{remark}, + update_time = sysdate() + + where table_id = #{tableId} + + + + delete from gen_table where table_id in + + #{tableId} + + + + \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/vm/java/controller.java.vm b/ai-bird-generator/src/main/resources/vm/java/controller.java.vm new file mode 100644 index 0000000..19e1cd8 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/controller.java.vm @@ -0,0 +1,108 @@ +package ${packageName}.controller; + +import java.util.List; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.enums.BusinessType; +import ${packageName}.domain.${ClassName}; +import ${packageName}.service.${ClassName}Service; +import net.hzvtc.common.utils.poi.ExcelUtil; +#if($table.crud || $table.sub) +import net.hzvtc.common.core.page.TableDataInfo; +#elseif($table.tree) +#end + +/** + * ${functionName}Controller + * + * @author ${author} + * @date ${datetime} + */ +@RestController +@RequestMapping("/${moduleName}/${businessName}") +public class ${ClassName}Controller extends BaseController { + @Autowired + private ${ClassName}Service ${className}Service; + +/** + * 查询${functionName}列表 + */ +@PreAuthorize("@ss.hasPermi('${permissionPrefix}:list')") +@GetMapping("/list") + #if($table.crud || $table.sub) + public TableDataInfo list(${ClassName} ${className}) { + startPage(); + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + return getDataTable(list); + } + #elseif($table.tree) + public AjaxResult list(${ClassName} ${className}) { + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + return AjaxResult.success(list); + } + #end + + /** + * 导出${functionName}列表 + */ + @PreAuthorize("@ss.hasPermi('${permissionPrefix}:export')") + @Log(title = "${functionName}", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, ${ClassName} ${className}) { + List<${ClassName}> list = ${className}Service.select${ClassName}List(${className}); + ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}. class); + util.exportExcel(response, list, "${functionName}数据"); + } + + /** + * 获取${functionName}详细信息 + */ + @PreAuthorize("@ss.hasPermi('${permissionPrefix}:query')") + @GetMapping(value = "/{${pkColumn.javaField}}") + public AjaxResult getInfo(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) { + return AjaxResult.success(${className}Service.select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField})); + } + + /** + * 新增${functionName} + */ + @PreAuthorize("@ss.hasPermi('${permissionPrefix}:add')") + @Log(title = "${functionName}", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ${ClassName} ${className}) { + return toAjax(${className}Service.insert${ClassName}(${className})); + } + + /** + * 修改${functionName} + */ + @PreAuthorize("@ss.hasPermi('${permissionPrefix}:edit')") + @Log(title = "${functionName}", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ${ClassName} ${className}) { + return toAjax(${className}Service.update${ClassName}(${className})); + } + + /** + * 删除${functionName} + */ + @PreAuthorize("@ss.hasPermi('${permissionPrefix}:remove')") + @Log(title = "${functionName}", businessType = BusinessType.DELETE) + @DeleteMapping("/{${pkColumn.javaField}s}") + public AjaxResult remove(@PathVariable ${pkColumn.javaType}[] ${pkColumn.javaField}s) { + return toAjax(${className}Service.delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaField}s)); + } +} diff --git a/ai-bird-generator/src/main/resources/vm/java/domain.java.vm b/ai-bird-generator/src/main/resources/vm/java/domain.java.vm new file mode 100644 index 0000000..1002752 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/domain.java.vm @@ -0,0 +1,89 @@ +package ${packageName}.domain; + +import lombok.Data; + #foreach ($import in $importList) + import ${import}; + #end +import net.hzvtc.common.annotation.Excel; + #if($table.crud || $table.sub) + #elseif($table.tree) + #end +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; +/** + * ${functionName}对象 ${tableName} + * + * @author ${author} + * @date ${datetime} + */ +#if($table.crud || $table.sub) + #set($Entity="BaseEntity") +#elseif($table.tree) + #set($Entity="TreeEntity") +#end +@Data +@Alias("${ClassName}") +public class ${ClassName} extends ${Entity} + { +private static final long serialVersionUID=1L; + +#foreach ($column in $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; + + #end +#end +#if($table.sub) +/** $table.subTable.functionName信息 */ +private List<${subClassName}> ${subclassName}List; + +#end +#foreach ($column in $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 + #end +#end + +#if($table.sub) + +#end +@Override +public String toString(){ + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + #foreach ($column in $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 + #if($table.sub) + .append("${subclassName}List",get${subClassName}List()) + #end + .toString(); + } + } diff --git a/ai-bird-generator/src/main/resources/vm/java/mapper.java.vm b/ai-bird-generator/src/main/resources/vm/java/mapper.java.vm new file mode 100644 index 0000000..7e7d7c2 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/mapper.java.vm @@ -0,0 +1,91 @@ +package ${packageName}.mapper; + +import java.util.List; +import ${packageName}.domain.${ClassName}; +#if($table.sub) +import ${packageName}.domain.${subClassName}; +#end + +/** + * ${functionName}Mapper接口 + * + * @author ${author} + * @date ${datetime} + */ +public interface ${ClassName}Mapper +{ + /** + * 查询${functionName} + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return ${functionName} + */ + public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}); + + /** + * 查询${functionName}列表 + * + * @param ${className} ${functionName} + * @return ${functionName}集合 + */ + public List<${ClassName}> select${ClassName}List(${ClassName} ${className}); + + /** + * 新增${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + public int insert${ClassName}(${ClassName} ${className}); + + /** + * 修改${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + public int update${ClassName}(${ClassName} ${className}); + + /** + * 删除${functionName} + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return 结果 + */ + public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}); + + /** + * 批量删除${functionName} + * + * @param ${pkColumn.javaField}s 需要删除的数据主键集合 + * @return 结果 + */ + public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s); +#if($table.sub) + + /** + * 批量删除${subTable.functionName} + * + * @param ${pkColumn.javaField}s 需要删除的数据主键集合 + * @return 结果 + */ + public int delete${subClassName}By${subTableFkClassName}s(${pkColumn.javaType}[] ${pkColumn.javaField}s); + + /** + * 批量新增${subTable.functionName} + * + * @param ${subclassName}List ${subTable.functionName}列表 + * @return 结果 + */ + public int batch${subClassName}(List<${subClassName}> ${subclassName}List); + + + /** + * 通过${functionName}主键删除${subTable.functionName}信息 + * + * @param ${pkColumn.javaField} ${functionName}ID + * @return 结果 + */ + public int delete${subClassName}By${subTableFkClassName}(${pkColumn.javaType} ${pkColumn.javaField}); +#end +} diff --git a/ai-bird-generator/src/main/resources/vm/java/service.java.vm b/ai-bird-generator/src/main/resources/vm/java/service.java.vm new file mode 100644 index 0000000..b29a128 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/service.java.vm @@ -0,0 +1,61 @@ +package ${packageName}.service; + +import java.util.List; + +import ${packageName}.domain.${ClassName}; + +/** + * ${functionName}Service接口 + * + * @author ${author} + * @date ${datetime} + */ +public interface ${ClassName}Service { + /** + * 查询${functionName} + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return ${functionName} + */ + public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}); + + /** + * 查询${functionName}列表 + * + * @param ${className} ${functionName} + * @return ${functionName}集合 + */ + public List<${ClassName}> select${ClassName}List(${ClassName} ${className}); + + /** + * 新增${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + public int insert${ClassName}(${ClassName} ${className}); + + /** + * 修改${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + public int update${ClassName}(${ClassName} ${className}); + + /** + * 批量删除${functionName} + * + * @param ${pkColumn.javaField}s 需要删除的${functionName}主键集合 + * @return 结果 + */ + public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s); + + /** + * 删除${functionName}信息 + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return 结果 + */ + public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}); +} diff --git a/ai-bird-generator/src/main/resources/vm/java/serviceImpl.java.vm b/ai-bird-generator/src/main/resources/vm/java/serviceImpl.java.vm new file mode 100644 index 0000000..8872184 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/serviceImpl.java.vm @@ -0,0 +1,162 @@ +package ${packageName}.service.impl; + +import java.util.List; + #foreach ($column in $columns) + #if($column.javaField == 'createTime' || $column.javaField == 'updateTime') + import net.hzvtc.common.utils.DateUtils; + #break + #end + #end +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; + #if($table.sub) + import java.util.ArrayList; + + import net.hzvtc.common.utils.StringUtils; + import org.springframework.transaction.annotation.Transactional; + import ${packageName}.domain.${subClassName}; + #end +import ${packageName}.mapper.${ClassName}Mapper; +import ${packageName}.domain.${ClassName}; +import ${packageName}.service.${ClassName}Service; + +/** + * ${functionName}Service业务层处理 + * + * @author ${author} + * @date ${datetime} + */ +@Service +public class ${ClassName}ServiceImpl implements ${ClassName}Service { + @Resource + private ${ClassName}Mapper ${className}Mapper; + + /** + * 查询${functionName} + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return ${functionName} + */ + @Override + public ${ClassName} select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}) { + return ${className}Mapper.select${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField}); + } + + /** + * 查询${functionName}列表 + * + * @param ${className} ${functionName} + * @return ${functionName} + */ + @Override + public List<${ClassName}> select${ClassName}List(${ClassName} ${className}) { + return ${className}Mapper.select${ClassName}List(${className}); + } + + /** + * 新增${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + #if($table.sub) + @Transactional + #end + @Override + public int insert${ClassName}(${ClassName} ${className}) { + #foreach ($column in $columns) + #if($column.javaField == 'createTime') + ${className}.setCreateTime(DateUtils.getNowDate()); + #end + #end + #if($table.sub) + int rows = ${className}Mapper.insert${ClassName}(${className}); + insert${subClassName}(${className}); + return rows; + #else + return ${className}Mapper.insert${ClassName}(${className}); + #end + } + + /** + * 修改${functionName} + * + * @param ${className} ${functionName} + * @return 结果 + */ + #if($table.sub) + @Transactional + #end + @Override + public int update${ClassName}(${ClassName} ${className}) { + #foreach ($column in $columns) + #if($column.javaField == 'updateTime') + ${className}.setUpdateTime(DateUtils.getNowDate()); + #end + #end + #if($table.sub) + ${className}Mapper.delete${subClassName}By${subTableFkClassName}(${className}.get${pkColumn.capJavaField}()) + ; + insert${subClassName}(${className}); + #end + return ${className}Mapper.update${ClassName}(${className}); + } + + /** + * 批量删除${functionName} + * + * @param ${pkColumn.javaField}s 需要删除的${functionName}主键 + * @return 结果 + */ + #if($table.sub) + @Transactional + #end + @Override + public int delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaType}[] ${pkColumn.javaField}s) { + #if($table.sub) + ${className}Mapper.delete${subClassName}By${subTableFkClassName}s(${pkColumn.javaField}s); + #end + return ${className}Mapper.delete${ClassName}By${pkColumn.capJavaField}s(${pkColumn.javaField}s); + } + + /** + * 删除${functionName}信息 + * + * @param ${pkColumn.javaField} ${functionName}主键 + * @return 结果 + */ + #if($table.sub) + @Transactional + #end + @Override + public int delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaType} ${pkColumn.javaField}) { + #if($table.sub) + ${className}Mapper.delete${subClassName}By${subTableFkClassName}(${pkColumn.javaField}); + #end + return ${className}Mapper.delete${ClassName}By${pkColumn.capJavaField}(${pkColumn.javaField}); + } + #if($table.sub) + + /** + * 新增${subTable.functionName}信息 + * + * @param ${className} ${functionName}对象 + */ + public void insert${subClassName}(${ClassName} ${className}) { + List<${subClassName}> ${subclassName}List = ${className}.get${subClassName}List(); + ${pkColumn.javaType} ${pkColumn.javaField} = ${className}.get${pkColumn.capJavaField}(); + if (StringUtils.isNotNull(${subclassName}List)) { + List<${subClassName}> list = new ArrayList<${subClassName}>(); + for (${subClassName} ${subclassName} :${subclassName}List) + { + ${subclassName}.set${subTableFkClassName}(${pkColumn.javaField}); + list.add(${subclassName}); + } + if (list.size() > 0) { + ${className}Mapper.batch${subClassName}(list); + } + } + } + #end +} diff --git a/ai-bird-generator/src/main/resources/vm/java/sub-domain.java.vm b/ai-bird-generator/src/main/resources/vm/java/sub-domain.java.vm new file mode 100644 index 0000000..bac332d --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/java/sub-domain.java.vm @@ -0,0 +1,73 @@ +package ${packageName}.domain; + +#foreach ($import in $subImportList) +import ${import}; +#end +import net.hzvtc.common.annotation.Excel; + +/** + * ${subTable.functionName}对象 ${subTableName} + * + * @author ${author} + * @date ${datetime} + */ +public class ${subClassName} extends BaseEntity +{ + private static final long serialVersionUID = 1L; + +#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; + +#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; + } + + 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/ai-bird-generator/src/main/resources/vm/js/api.js.vm b/ai-bird-generator/src/main/resources/vm/js/api.js.vm new file mode 100644 index 0000000..9295524 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/js/api.js.vm @@ -0,0 +1,44 @@ +import request from '@/utils/request' + +// 查询${functionName}列表 +export function list${BusinessName}(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' + }) +} + +// 新增${functionName} +export function add${BusinessName}(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 + }) +} + +// 删除${functionName} +export function del${BusinessName}(${pkColumn.javaField}) { + return request({ + url: '/${moduleName}/${businessName}/' + ${pkColumn.javaField}, + method: 'delete' + }) +} diff --git a/ai-bird-generator/src/main/resources/vm/sql/sql.vm b/ai-bird-generator/src/main/resources/vm/sql/sql.vm new file mode 100644 index 0000000..1da1f1b --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/sql/sql.vm @@ -0,0 +1,22 @@ +-- 菜单 SQL +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('${functionName}', '${parentMenuId}', '1', '${businessName}', '${moduleName}/${businessName}/index', 1, 0, 'C', '0', '0', '${permissionPrefix}:list', '#', 'admin', sysdate(), '', null, '${functionName}菜单'); + +-- 按钮父菜单ID +SELECT @parentId := LAST_INSERT_ID(); + +-- 按钮 SQL +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('查询', @parentId, '1', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:query', '#', 'admin', sysdate(), '', null, ''); + +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('新增', @parentId, '2', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:add', '#', 'admin', sysdate(), '', null, ''); + +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('修改', @parentId, '3', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:edit', '#', 'admin', sysdate(), '', null, ''); + +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('删除', @parentId, '4', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:remove', '#', 'admin', sysdate(), '', null, ''); + +insert into sys_menu (menu_name, parent_id, order_num, path, component, is_frame, is_cache, menu_type, visible, status, perms, icon, create_by, create_time, update_by, update_time, remark) +values('导出', @parentId, '5', '#', '', 1, 0, 'F', '0', '0', '${permissionPrefix}:export', '#', 'admin', sysdate(), '', null, ''); \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/vm/vue/index-tree.vue.vm b/ai-bird-generator/src/main/resources/vm/vue/index-tree.vue.vm new file mode 100644 index 0000000..385be92 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/vue/index-tree.vue.vm @@ -0,0 +1,482 @@ + + + diff --git a/ai-bird-generator/src/main/resources/vm/vue/index.vue.vm b/ai-bird-generator/src/main/resources/vm/vue/index.vue.vm new file mode 100644 index 0000000..6da537b --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/vue/index.vue.vm @@ -0,0 +1,573 @@ + + + diff --git a/ai-bird-generator/src/main/resources/vm/vue/v3/index-tree.vue.vm b/ai-bird-generator/src/main/resources/vm/vue/v3/index-tree.vue.vm new file mode 100644 index 0000000..d57bbdf --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/vue/v3/index-tree.vue.vm @@ -0,0 +1,464 @@ + + + diff --git a/ai-bird-generator/src/main/resources/vm/vue/v3/index.vue.vm b/ai-bird-generator/src/main/resources/vm/vue/v3/index.vue.vm new file mode 100644 index 0000000..3b4929f --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/vue/v3/index.vue.vm @@ -0,0 +1,670 @@ + + + diff --git a/ai-bird-generator/src/main/resources/vm/vue/v3/readme.txt b/ai-bird-generator/src/main/resources/vm/vue/v3/readme.txt new file mode 100644 index 0000000..b2d1d6e --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/vue/v3/readme.txt @@ -0,0 +1 @@ +���ʹ�õ���trainning-kpi-Vue3ǰ�ˣ���ô��Ҫ����һ�´�Ŀ¼��ģ��index.vue.vm��index-tree.vue.vm�ļ����ϼ�vueĿ¼�� \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.old.vm b/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.old.vm new file mode 100644 index 0000000..6364a9d --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.old.vm @@ -0,0 +1,136 @@ + + + + + +#foreach ($column in $columns) + +#end + +#if($table.sub) + + + + + + +#foreach ($column in $subTable.columns) + +#end + +#end + + + select#foreach($column in $columns) $column.columnName#if($foreach.count != $columns.size()),#end#end from ${tableName} + + + + + + + + insert into ${tableName} + + +#foreach($column in $columns) +#if($column.columnName != $pkColumn.columnName || !$pkColumn.increment) + $column.columnName, +#end +#end + + +#foreach($column in $columns) +#if($column.columnName != $pkColumn.columnName || !$pkColumn.increment) + #{$column.javaField}, +#end +#end + + + + + update ${tableName} + +#foreach($column in $columns) +#if($column.columnName != $pkColumn.columnName) + $column.columnName = #{$column.javaField}, +#end +#end + + where ${pkColumn.columnName} = #{${pkColumn.javaField}} + + + + delete from ${tableName} where ${pkColumn.columnName} = #{${pkColumn.javaField}} + + + + delete from ${tableName} where ${pkColumn.columnName} in + + #{${pkColumn.javaField}} + + +#if($table.sub) + + + delete from ${subTableName} where ${subTableFkName} in + + #{${subTableFkclassName}} + + + + + delete from ${subTableName} where ${subTableFkName} = #{${subTableFkclassName}} + + + + insert into ${subTableName}(#foreach($column in $subTable.columns) $column.columnName#if($foreach.count != $subTable.columns.size()),#end#end) values + + (#foreach($column in $subTable.columns) #{item.$column.javaField}#if($foreach.count != $subTable.columns.size()),#end#end) + + +#end + \ No newline at end of file diff --git a/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.vm b/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.vm new file mode 100644 index 0000000..2440833 --- /dev/null +++ b/ai-bird-generator/src/main/resources/vm/xml/mapper.xml.vm @@ -0,0 +1,159 @@ + + + + + + #foreach ($column in $columns) + + #end + + #if($table.sub) + + + + + + + #foreach ($column in $subTable.columns) + + #end + + #end + + + select * + from ${tableName} + + + + + + + + insert into ${tableName} + ( + #foreach($column in $columns) + #if($column.columnName != $pkColumn.columnName || !$pkColumn.increment) + $column.columnName, + #end + #end + ) values ( + #foreach($column in $columns) + #if($column.columnName != $pkColumn.columnName || !$pkColumn.increment) + #{$column.javaField}, + #end + #end + ) + + + + update ${tableName} + set + #foreach($column in $columns) + #if($column.columnName != $pkColumn.columnName) + $column.columnName = #{$column.javaField}, + #end + #end + where ${pkColumn.columnName} = #{${pkColumn.javaField}} + + + + delete + from ${tableName} where ${pkColumn.columnName} = #{${pkColumn.javaField}} + + + + delete from ${tableName} where ${pkColumn.columnName} in + + #{${pkColumn.javaField}} + + + #if($table.sub) + + + delete from ${subTableName} where ${subTableFkName} in + + #{${subTableFkclassName}} + + + + + delete + from ${subTableName} where ${subTableFkName} = #{${subTableFkclassName}} + + + + insert into ${subTableName} + (#foreach($column in $subTable.columns) $column.columnName#if($foreach.count != $subTable.columns.size()) + ,#end#end) values + + (#foreach($column in $subTable.columns) #{item.$column.javaField + }#if($foreach.count != $subTable.columns.size()),#end#end) + + + #end + \ No newline at end of file diff --git a/ai-bird-quartz/pom.xml b/ai-bird-quartz/pom.xml new file mode 100644 index 0000000..94d2406 --- /dev/null +++ b/ai-bird-quartz/pom.xml @@ -0,0 +1,48 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + + ai-bird-quartz + + + quartz定时任务 + + + + + + + org.quartz-scheduler + quartz + + + com.mchange + c3p0 + + + + + + + net.hzvtc + ai-bird-common + + + net.hzvtc + ai-bird-system + + + net.hzvtc + ai-bird-es + + + + + \ No newline at end of file diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/config/ScheduleConfig.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/config/ScheduleConfig.java new file mode 100644 index 0000000..a494c13 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/config/ScheduleConfig.java @@ -0,0 +1,57 @@ +package net.hzvtc.quartz.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import javax.sql.DataSource; +import java.util.Properties; + +/** + * 定时任务配置(单机部署建议删除此类和qrtz数据库表,默认走内存会最高效) + * + * @author admin + */ +@Configuration +public class ScheduleConfig +{ + @Bean + public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) + { + SchedulerFactoryBean factory = new SchedulerFactoryBean(); + factory.setDataSource(dataSource); + + // quartz参数 + Properties prop = new Properties(); + prop.put("org.quartz.scheduler.instanceName", "AiBirdSysScheduler"); + prop.put("org.quartz.scheduler.instanceId", "AUTO"); + // 线程池配置 + prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool"); + prop.put("org.quartz.threadPool.threadCount", "20"); + prop.put("org.quartz.threadPool.threadPriority", "5"); + // JobStore配置 + prop.put("org.quartz.jobStore.class", "org.springframework.scheduling.quartz.LocalDataSourceJobStore"); + // 集群配置 + prop.put("org.quartz.jobStore.isClustered", "true"); + prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000"); + prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1"); + prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true"); + + // sqlserver 启用 + // prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?"); + prop.put("org.quartz.jobStore.misfireThreshold", "12000"); + prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_"); + factory.setQuartzProperties(prop); + + factory.setSchedulerName("AiBirdSysScheduler"); + // 延时启动 + factory.setStartupDelay(1); + factory.setApplicationContextSchedulerContextKey("applicationContextKey"); + // 可选,QuartzScheduler + // 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 + factory.setOverwriteExistingJobs(true); + // 设置自动启动,默认为true + factory.setAutoStartup(true); + + return factory; + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/QuartzController.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/QuartzController.java new file mode 100644 index 0000000..9a05336 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/QuartzController.java @@ -0,0 +1,24 @@ +package net.hzvtc.quartz.controller; + +import net.hzvtc.quartz.service.impl.QuartzJobUtils; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +@RestController +@RequestMapping("/quartz") +public class QuartzController { + + @Resource + private QuartzJobUtils quartzJobUtils; + + @DeleteMapping("/stopJob") + public String stopJob(@RequestParam String jobName, + @RequestParam(defaultValue = "DEFAULT") String jobGroup) { + quartzJobUtils.stopJob(jobName, jobGroup); + return "任务已停止并删除"; + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobController.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobController.java new file mode 100644 index 0000000..003afd4 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobController.java @@ -0,0 +1,158 @@ +package net.hzvtc.quartz.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.exception.job.TaskException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.quartz.domain.SysJob; +import net.hzvtc.quartz.service.SysJobService; +import net.hzvtc.quartz.util.CronUtils; +import net.hzvtc.quartz.util.ScheduleUtils; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 调度任务信息操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/job") +public class SysJobController extends BaseController { + @Autowired + private SysJobService jobService; + + @Autowired + private SpeciesDailyStatService speciesDailyStatService; + + /** + * 查询定时任务列表 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:list')") + @GetMapping("/list") + public TableDataInfo list(SysJob sysJob) { + startPage(); + List list = jobService.selectJobList(sysJob); + return getDataTable(list); + } + + /** + * 导出定时任务列表 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:export')") + @Log(title = "定时任务", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SysJob sysJob) { + List list = jobService.selectJobList(sysJob); + ExcelUtil util = new ExcelUtil(SysJob.class); + util.exportExcel(response, list, "定时任务"); + } + + /** + * 获取定时任务详细信息 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:query')") + @GetMapping(value = "/{jobId}") + public AjaxResult getInfo(@PathVariable("jobId") Long jobId) { + return AjaxResult.success(jobService.selectJobById(jobId)); + } + + /** + * 新增定时任务 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:add')") + @Log(title = "定时任务", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SysJob job) throws SchedulerException, TaskException { + if (!CronUtils.isValid(job.getCronExpression())) { + return error("新增任务'" + job.getJobName() + "'失败,Cron表达式不正确"); + } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串存在违规"); + } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) { + return error("新增任务'" + job.getJobName() + "'失败,目标字符串不在白名单内"); + } + job.setCreateBy(getUsername()); + return toAjax(jobService.insertJob(job)); + } + + /** + * 修改定时任务 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:edit')") + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException { + if (!CronUtils.isValid(job.getCronExpression())) { + return error("修改任务'" + job.getJobName() + "'失败,Cron表达式不正确"); + } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'rmi'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'ldap(s)'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不允许'http(s)'调用"); + } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串存在违规"); + } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) { + return error("修改任务'" + job.getJobName() + "'失败,目标字符串不在白名单内"); + } + job.setUpdateBy(getUsername()); + return toAjax(jobService.updateJob(job)); + } + + /** + * 定时任务状态修改 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')") + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @PutMapping("/changeStatus") + public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException { + SysJob newJob = jobService.selectJobById(job.getJobId()); + newJob.setStatus(job.getStatus()); + return toAjax(jobService.changeStatus(newJob)); + } + + /** + * 定时任务立即执行一次 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:changeStatus')") + @Log(title = "定时任务", businessType = BusinessType.UPDATE) + @PutMapping("/run") + public AjaxResult run(@RequestBody SysJob job) throws SchedulerException { + jobService.run(job); + return AjaxResult.success(); + } + + /** + * 删除定时任务 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:remove')") + @Log(title = "定时任务", businessType = BusinessType.DELETE) + @DeleteMapping("/{jobIds}") + public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException { + jobService.deleteJobByIds(jobIds); + return AjaxResult.success(); + } + + @GetMapping("/doAllStatTask") + public AjaxResult doAllStatTask() { + speciesDailyStatService.calculateAllResultRecord(); + return AjaxResult.success(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobLogController.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobLogController.java new file mode 100644 index 0000000..edff2ae --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/controller/SysJobLogController.java @@ -0,0 +1,82 @@ +package net.hzvtc.quartz.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.quartz.domain.SysJobLog; +import net.hzvtc.quartz.service.SysJobLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 调度日志操作处理 + * + * @author admin + */ +@RestController +@RequestMapping("/monitor/jobLog") +public class SysJobLogController extends BaseController { + @Autowired + private SysJobLogService jobLogService; + + /** + * 查询定时任务调度日志列表 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:list')") + @GetMapping("/list") + public TableDataInfo list(SysJobLog sysJobLog) { + startPage(); + List list = jobLogService.selectJobLogList(sysJobLog); + return getDataTable(list); + } + + /** + * 导出定时任务调度日志列表 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:export')") + @Log(title = "任务调度日志", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SysJobLog sysJobLog) { + List list = jobLogService.selectJobLogList(sysJobLog); + ExcelUtil util = new ExcelUtil(SysJobLog.class); + util.exportExcel(response, list, "调度日志"); + } + + /** + * 根据调度编号获取详细信息 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:query')") + @GetMapping(value = "/{configId}") + public AjaxResult getInfo(@PathVariable Long jobLogId) { + return AjaxResult.success(jobLogService.selectJobLogById(jobLogId)); + } + + + /** + * 删除定时任务调度日志 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:remove')") + @Log(title = "定时任务调度日志", businessType = BusinessType.DELETE) + @DeleteMapping("/{jobLogIds}") + public AjaxResult remove(@PathVariable Long[] jobLogIds) { + return toAjax(jobLogService.deleteJobLogByIds(jobLogIds)); + } + + /** + * 清空定时任务调度日志 + */ + @PreAuthorize("@ss.hasPermi('monitor:job:remove')") + @Log(title = "调度日志", businessType = BusinessType.CLEAN) + @DeleteMapping("/clean") + public AjaxResult clean() { + jobLogService.cleanJobLog(); + return AjaxResult.success(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJob.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJob.java new file mode 100644 index 0000000..a04995c --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJob.java @@ -0,0 +1,117 @@ +package net.hzvtc.quartz.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.quartz.util.CronUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class SysJob +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u4efb\u52a1\u5e8f\u53f7", cellType=Excel.ColumnType.NUMERIC) + private Long jobId; + @Excel(name="\u4efb\u52a1\u540d\u79f0") + private String jobName; + @Excel(name="\u4efb\u52a1\u7ec4\u540d") + private String jobGroup; + @Excel(name="\u8c03\u7528\u76ee\u6807\u5b57\u7b26\u4e32") + private String invokeTarget; + @Excel(name="\u6267\u884c\u8868\u8fbe\u5f0f ") + private String cronExpression; + @Excel(name="\u8ba1\u5212\u7b56\u7565 ", readConverterExp="0=\u9ed8\u8ba4,1=\u7acb\u5373\u89e6\u53d1\u6267\u884c,2=\u89e6\u53d1\u4e00\u6b21\u6267\u884c,3=\u4e0d\u89e6\u53d1\u7acb\u5373\u6267\u884c") + private String misfirePolicy = "0"; + @Excel(name="\u5e76\u53d1\u6267\u884c", readConverterExp="0=\u5141\u8bb8,1=\u7981\u6b62") + private String concurrent; + @Excel(name="\u4efb\u52a1\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u6682\u505c") + private String status; + + public Long getJobId() { + return this.jobId; + } + + public void setJobId(Long jobId) { + this.jobId = jobId; + } + + @NotBlank(message="\u4efb\u52a1\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=64, message="\u4efb\u52a1\u540d\u79f0\u4e0d\u80fd\u8d85\u8fc764\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u4efb\u52a1\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=64, message="\u4efb\u52a1\u540d\u79f0\u4e0d\u80fd\u8d85\u8fc764\u4e2a\u5b57\u7b26") String getJobName() { + return this.jobName; + } + + public void setJobName(String jobName) { + this.jobName = jobName; + } + + public String getJobGroup() { + return this.jobGroup; + } + + public void setJobGroup(String jobGroup) { + this.jobGroup = jobGroup; + } + + @NotBlank(message="\u8c03\u7528\u76ee\u6807\u5b57\u7b26\u4e32\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=500, message="\u8c03\u7528\u76ee\u6807\u5b57\u7b26\u4e32\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7500\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u8c03\u7528\u76ee\u6807\u5b57\u7b26\u4e32\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=500, message="\u8c03\u7528\u76ee\u6807\u5b57\u7b26\u4e32\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7500\u4e2a\u5b57\u7b26") String getInvokeTarget() { + return this.invokeTarget; + } + + public void setInvokeTarget(String invokeTarget) { + this.invokeTarget = invokeTarget; + } + + @NotBlank(message="Cron\u6267\u884c\u8868\u8fbe\u5f0f\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=255, message="Cron\u6267\u884c\u8868\u8fbe\u5f0f\u4e0d\u80fd\u8d85\u8fc7255\u4e2a\u5b57\u7b26") + public @NotBlank(message="Cron\u6267\u884c\u8868\u8fbe\u5f0f\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=255, message="Cron\u6267\u884c\u8868\u8fbe\u5f0f\u4e0d\u80fd\u8d85\u8fc7255\u4e2a\u5b57\u7b26") String getCronExpression() { + return this.cronExpression; + } + + public void setCronExpression(String cronExpression) { + this.cronExpression = cronExpression; + } + + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") + public Date getNextValidTime() { + if (StringUtils.isNotEmpty((String)this.cronExpression)) { + return CronUtils.getNextExecution(this.cronExpression); + } + return null; + } + + public String getMisfirePolicy() { + return this.misfirePolicy; + } + + public void setMisfirePolicy(String misfirePolicy) { + this.misfirePolicy = misfirePolicy; + } + + public String getConcurrent() { + return this.concurrent; + } + + public void setConcurrent(String concurrent) { + this.concurrent = concurrent; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("jobId", (Object)this.getJobId()).append("jobName", (Object)this.getJobName()).append("jobGroup", (Object)this.getJobGroup()).append("cronExpression", (Object)this.getCronExpression()).append("nextValidTime", (Object)this.getNextValidTime()).append("misfirePolicy", (Object)this.getMisfirePolicy()).append("concurrent", (Object)this.getConcurrent()).append("status", (Object)this.getStatus()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJobLog.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJobLog.java new file mode 100644 index 0000000..dc8857c --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/domain/SysJobLog.java @@ -0,0 +1,156 @@ +package net.hzvtc.quartz.domain; + +import java.util.Date; + +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import net.hzvtc.common.annotation.Excel; + +/** + * 定时任务调度日志表 sys_job_log + * + * @author admin + */ +public class SysJobLog extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** ID */ + @Excel(name = "日志序号") + private Long jobLogId; + + /** 任务名称 */ + @Excel(name = "任务名称") + private String jobName; + + /** 任务组名 */ + @Excel(name = "任务组名") + private String jobGroup; + + /** 调用目标字符串 */ + @Excel(name = "调用目标字符串") + private String invokeTarget; + + /** 日志信息 */ + @Excel(name = "日志信息") + private String jobMessage; + + /** 执行状态(0正常 1失败) */ + @Excel(name = "执行状态", readConverterExp = "0=正常,1=失败") + private String status; + + /** 异常信息 */ + @Excel(name = "异常信息") + private String exceptionInfo; + + /** 开始时间 */ + private Date startTime; + + /** 停止时间 */ + private Date stopTime; + + public Long getJobLogId() + { + return jobLogId; + } + + public void setJobLogId(Long jobLogId) + { + this.jobLogId = jobLogId; + } + + public String getJobName() + { + return jobName; + } + + public void setJobName(String jobName) + { + this.jobName = jobName; + } + + public String getJobGroup() + { + return jobGroup; + } + + public void setJobGroup(String jobGroup) + { + this.jobGroup = jobGroup; + } + + public String getInvokeTarget() + { + return invokeTarget; + } + + public void setInvokeTarget(String invokeTarget) + { + this.invokeTarget = invokeTarget; + } + + public String getJobMessage() + { + return jobMessage; + } + + public void setJobMessage(String jobMessage) + { + this.jobMessage = jobMessage; + } + + public String getStatus() + { + return status; + } + + public void setStatus(String status) + { + this.status = status; + } + + public String getExceptionInfo() + { + return exceptionInfo; + } + + public void setExceptionInfo(String exceptionInfo) + { + this.exceptionInfo = exceptionInfo; + } + + public Date getStartTime() + { + return startTime; + } + + public void setStartTime(Date startTime) + { + this.startTime = startTime; + } + + public Date getStopTime() + { + return stopTime; + } + + public void setStopTime(Date stopTime) + { + this.stopTime = stopTime; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("jobLogId", getJobLogId()) + .append("jobName", getJobName()) + .append("jobGroup", getJobGroup()) + .append("jobMessage", getJobMessage()) + .append("status", getStatus()) + .append("exceptionInfo", getExceptionInfo()) + .append("startTime", getStartTime()) + .append("stopTime", getStopTime()) + .toString(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobLogMapper.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobLogMapper.java new file mode 100644 index 0000000..2393d56 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobLogMapper.java @@ -0,0 +1,64 @@ +package net.hzvtc.quartz.mapper; + +import java.util.List; +import net.hzvtc.quartz.domain.SysJobLog; + +/** + * 调度任务日志信息 数据层 + * + * @author admin + */ +public interface SysJobLogMapper +{ + /** + * 获取quartz调度器日志的计划任务 + * + * @param jobLog 调度日志信息 + * @return 调度任务日志集合 + */ + public List selectJobLogList(SysJobLog jobLog); + + /** + * 查询所有调度任务日志 + * + * @return 调度任务日志列表 + */ + public List selectJobLogAll(); + + /** + * 通过调度任务日志ID查询调度信息 + * + * @param jobLogId 调度任务日志ID + * @return 调度任务日志对象信息 + */ + public SysJobLog selectJobLogById(Long jobLogId); + + /** + * 新增任务日志 + * + * @param jobLog 调度日志信息 + * @return 结果 + */ + public int insertJobLog(SysJobLog jobLog); + + /** + * 批量删除调度日志信息 + * + * @param logIds 需要删除的数据ID + * @return 结果 + */ + public int deleteJobLogByIds(Long[] logIds); + + /** + * 删除任务日志 + * + * @param jobId 调度日志ID + * @return 结果 + */ + public int deleteJobLogById(Long jobId); + + /** + * 清空任务日志 + */ + public void cleanJobLog(); +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobMapper.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobMapper.java new file mode 100644 index 0000000..1195c63 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/mapper/SysJobMapper.java @@ -0,0 +1,67 @@ +package net.hzvtc.quartz.mapper; + +import java.util.List; +import net.hzvtc.quartz.domain.SysJob; + +/** + * 调度任务信息 数据层 + * + * @author admin + */ +public interface SysJobMapper +{ + /** + * 查询调度任务日志集合 + * + * @param job 调度信息 + * @return 操作日志集合 + */ + public List selectJobList(SysJob job); + + /** + * 查询所有调度任务 + * + * @return 调度任务列表 + */ + public List selectJobAll(); + + /** + * 通过调度ID查询调度任务信息 + * + * @param jobId 调度ID + * @return 角色对象信息 + */ + public SysJob selectJobById(Long jobId); + + /** + * 通过调度ID删除调度任务信息 + * + * @param jobId 调度ID + * @return 结果 + */ + public int deleteJobById(Long jobId); + + /** + * 批量删除调度任务信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteJobByIds(Long[] ids); + + /** + * 修改调度任务信息 + * + * @param job 调度任务信息 + * @return 结果 + */ + public int updateJob(SysJob job); + + /** + * 新增调度任务信息 + * + * @param job 调度任务信息 + * @return 结果 + */ + public int insertJob(SysJob job); +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobLogService.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobLogService.java new file mode 100644 index 0000000..78f305f --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobLogService.java @@ -0,0 +1,56 @@ +package net.hzvtc.quartz.service; + +import net.hzvtc.quartz.domain.SysJobLog; + +import java.util.List; + +/** + * 定时任务调度日志信息信息 服务层 + * + * @author admin + */ +public interface SysJobLogService { + /** + * 获取quartz调度器日志的计划任务 + * + * @param jobLog 调度日志信息 + * @return 调度任务日志集合 + */ + public List selectJobLogList(SysJobLog jobLog); + + /** + * 通过调度任务日志ID查询调度信息 + * + * @param jobLogId 调度任务日志ID + * @return 调度任务日志对象信息 + */ + public SysJobLog selectJobLogById(Long jobLogId); + + /** + * 新增任务日志 + * + * @param jobLog 调度日志信息 + */ + public void addJobLog(SysJobLog jobLog); + + /** + * 批量删除调度日志信息 + * + * @param logIds 需要删除的日志ID + * @return 结果 + */ + public int deleteJobLogByIds(Long[] logIds); + + /** + * 删除任务日志 + * + * @param jobId 调度日志ID + * @return 结果 + */ + public int deleteJobLogById(Long jobId); + + /** + * 清空任务日志 + */ + public void cleanJobLog(); +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobService.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobService.java new file mode 100644 index 0000000..ded3ae7 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/SysJobService.java @@ -0,0 +1,102 @@ +package net.hzvtc.quartz.service; + +import net.hzvtc.common.exception.job.TaskException; +import net.hzvtc.quartz.domain.SysJob; +import org.quartz.SchedulerException; + +import java.util.List; + +/** + * 定时任务调度信息信息 服务层 + * + * @author admin + */ +public interface SysJobService { + /** + * 获取quartz调度器的计划任务 + * + * @param job 调度信息 + * @return 调度任务集合 + */ + public List selectJobList(SysJob job); + + /** + * 通过调度任务ID查询调度信息 + * + * @param jobId 调度任务ID + * @return 调度任务对象信息 + */ + public SysJob selectJobById(Long jobId); + + /** + * 暂停任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int pauseJob(SysJob job) throws SchedulerException; + + /** + * 恢复任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int resumeJob(SysJob job) throws SchedulerException; + + /** + * 删除任务后,所对应的trigger也将被删除 + * + * @param job 调度信息 + * @return 结果 + */ + public int deleteJob(SysJob job) throws SchedulerException; + + /** + * 批量删除调度信息 + * + * @param jobIds 需要删除的任务ID + * @return 结果 + */ + public void deleteJobByIds(Long[] jobIds) throws SchedulerException; + + /** + * 任务调度状态修改 + * + * @param job 调度信息 + * @return 结果 + */ + public int changeStatus(SysJob job) throws SchedulerException; + + /** + * 立即运行任务 + * + * @param job 调度信息 + * @return 结果 + */ + public void run(SysJob job) throws SchedulerException; + + /** + * 新增任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int insertJob(SysJob job) throws SchedulerException, TaskException; + + /** + * 更新任务 + * + * @param job 调度信息 + * @return 结果 + */ + public int updateJob(SysJob job) throws SchedulerException, TaskException; + + /** + * 校验cron表达式是否有效 + * + * @param cronExpression 表达式 + * @return 结果 + */ + public boolean checkCronExpressionIsValid(String cronExpression); +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/QuartzJobUtils.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/QuartzJobUtils.java new file mode 100644 index 0000000..8fcbde9 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/QuartzJobUtils.java @@ -0,0 +1,44 @@ +package net.hzvtc.quartz.service.impl; + +import org.quartz.*; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +@Component +public class QuartzJobUtils { + + @Resource + private Scheduler scheduler; + + /** + * 停止并删除任务(先删 Trigger,再删 Job) + * + * @param jobName Job 名称 + * @param jobGroup Job 组名(默认 DEFAULT) + */ + public void stopJob(String jobName, String jobGroup) { + try { + JobKey jobKey = JobKey.jobKey(jobName, jobGroup); + + if (!scheduler.checkExists(jobKey)) { + System.out.println("⚠️ Job 不存在: " + jobKey); + return; + } + + // 获取所有 TriggerKey + for (Trigger trigger : scheduler.getTriggersOfJob(jobKey)) { + TriggerKey triggerKey = trigger.getKey(); + scheduler.unscheduleJob(triggerKey); // 停止并删除触发器 + System.out.println("✅ 成功删除 Trigger: " + triggerKey); + } + + // 删除 Job + scheduler.deleteJob(jobKey); + System.out.println("✅ 成功删除 Job: " + jobKey); + + } catch (SchedulerException e) { + throw new RuntimeException("停止 Job 失败: " + e.getMessage(), e); + } + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobLogServiceImpl.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobLogServiceImpl.java new file mode 100644 index 0000000..fbbacaa --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobLogServiceImpl.java @@ -0,0 +1,81 @@ +package net.hzvtc.quartz.service.impl; + +import net.hzvtc.quartz.domain.SysJobLog; +import net.hzvtc.quartz.mapper.SysJobLogMapper; +import net.hzvtc.quartz.service.SysJobLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 定时任务调度日志信息 服务层 + * + * @author admin + */ +@Service +public class SysJobLogServiceImpl implements SysJobLogService { + @Autowired + private SysJobLogMapper jobLogMapper; + + /** + * 获取quartz调度器日志的计划任务 + * + * @param jobLog 调度日志信息 + * @return 调度任务日志集合 + */ + @Override + public List selectJobLogList(SysJobLog jobLog) { + return jobLogMapper.selectJobLogList(jobLog); + } + + /** + * 通过调度任务日志ID查询调度信息 + * + * @param jobLogId 调度任务日志ID + * @return 调度任务日志对象信息 + */ + @Override + public SysJobLog selectJobLogById(Long jobLogId) { + return jobLogMapper.selectJobLogById(jobLogId); + } + + /** + * 新增任务日志 + * + * @param jobLog 调度日志信息 + */ + @Override + public void addJobLog(SysJobLog jobLog) { + jobLogMapper.insertJobLog(jobLog); + } + + /** + * 批量删除调度日志信息 + * + * @param logIds 需要删除的数据ID + * @return 结果 + */ + @Override + public int deleteJobLogByIds(Long[] logIds) { + return jobLogMapper.deleteJobLogByIds(logIds); + } + + /** + * 删除任务日志 + * + * @param jobId 调度日志ID + */ + @Override + public int deleteJobLogById(Long jobId) { + return jobLogMapper.deleteJobLogById(jobId); + } + + /** + * 清空任务日志 + */ + @Override + public void cleanJobLog() { + jobLogMapper.cleanJobLog(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobServiceImpl.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobServiceImpl.java new file mode 100644 index 0000000..3e19921 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/service/impl/SysJobServiceImpl.java @@ -0,0 +1,230 @@ +package net.hzvtc.quartz.service.impl; + +import net.hzvtc.common.constant.ScheduleConstants; +import net.hzvtc.common.exception.job.TaskException; +import net.hzvtc.quartz.domain.SysJob; +import net.hzvtc.quartz.mapper.SysJobMapper; +import net.hzvtc.quartz.service.SysJobService; +import net.hzvtc.quartz.util.CronUtils; +import net.hzvtc.quartz.util.ScheduleUtils; +import org.quartz.JobDataMap; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import java.util.List; + +/** + * 定时任务调度信息 服务层 + * + * @author admin + */ +@Service +public class SysJobServiceImpl implements SysJobService { + @Autowired + private Scheduler scheduler; + + @Autowired + private SysJobMapper jobMapper; + + /** + * 项目启动时,初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理(注:不能手动修改数据库ID和任务组名,否则会导致脏数据) + */ + @PostConstruct + public void init() throws SchedulerException, TaskException { + scheduler.clear(); + List jobList = jobMapper.selectJobAll(); + for (SysJob job : jobList) { + ScheduleUtils.createScheduleJob(scheduler, job); + } + } + + /** + * 获取quartz调度器的计划任务列表 + * + * @param job 调度信息 + * @return + */ + @Override + public List selectJobList(SysJob job) { + return jobMapper.selectJobList(job); + } + + /** + * 通过调度任务ID查询调度信息 + * + * @param jobId 调度任务ID + * @return 调度任务对象信息 + */ + @Override + public SysJob selectJobById(Long jobId) { + return jobMapper.selectJobById(jobId); + } + + /** + * 暂停任务 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int pauseJob(SysJob 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) { + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 恢复任务 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int resumeJob(SysJob 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) { + scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 删除任务后,所对应的trigger也将被删除 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int deleteJob(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + int rows = jobMapper.deleteJobById(jobId); + if (rows > 0) { + scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + return rows; + } + + /** + * 批量删除调度信息 + * + * @param jobIds 需要删除的任务ID + * @return 结果 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteJobByIds(Long[] jobIds) throws SchedulerException { + for (Long jobId : jobIds) { + SysJob job = jobMapper.selectJobById(jobId); + deleteJob(job); + } + } + + /** + * 任务调度状态修改 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int changeStatus(SysJob job) throws SchedulerException { + int rows = 0; + String status = job.getStatus(); + if (ScheduleConstants.Status.NORMAL.getValue().equals(status)) { + rows = resumeJob(job); + } else if (ScheduleConstants.Status.PAUSE.getValue().equals(status)) { + rows = pauseJob(job); + } + return rows; + } + + /** + * 立即运行任务 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void run(SysJob job) throws SchedulerException { + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + SysJob properties = selectJobById(job.getJobId()); + // 参数 + JobDataMap dataMap = new JobDataMap(); + dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties); + scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap); + } + + /** + * 新增任务 + * + * @param job 调度信息 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int insertJob(SysJob job) throws SchedulerException, TaskException { + job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); + int rows = jobMapper.insertJob(job); + if (rows > 0) { + ScheduleUtils.createScheduleJob(scheduler, job); + } + return rows; + } + + /** + * 更新任务的时间表达式 + * + * @param job 调度信息 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public int updateJob(SysJob job) throws SchedulerException, TaskException { + SysJob properties = selectJobById(job.getJobId()); + int rows = jobMapper.updateJob(job); + if (rows > 0) { + updateSchedulerJob(job, properties.getJobGroup()); + } + return rows; + } + + /** + * 更新任务 + * + * @param job 任务对象 + * @param jobGroup 任务组名 + */ + public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException { + Long jobId = job.getJobId(); + // 判断是否存在 + JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup); + if (scheduler.checkExists(jobKey)) { + // 防止创建时存在数据问题 先移除,然后在执行创建操作 + scheduler.deleteJob(jobKey); + } + ScheduleUtils.createScheduleJob(scheduler, job); + } + + /** + * 校验cron表达式是否有效 + * + * @param cronExpression 表达式 + * @return 结果 + */ + @Override + public boolean checkCronExpressionIsValid(String cronExpression) { + return CronUtils.isValid(cronExpression); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/BirdLeaveArriveCalcYearTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/BirdLeaveArriveCalcYearTask.java new file mode 100644 index 0000000..743872c --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/BirdLeaveArriveCalcYearTask.java @@ -0,0 +1,16 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.bird.service.BirdLeaveArriveInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("birdLeaveArriveCalcYearTask") +public class BirdLeaveArriveCalcYearTask { + @Autowired + private BirdLeaveArriveInfoService birdLeaveArriveInfoService; + + public void calc() { + birdLeaveArriveInfoService.calcBirdLeaveArriveInfoByParam(); + } + +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DemoTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DemoTask.java new file mode 100644 index 0000000..4f993da --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DemoTask.java @@ -0,0 +1,24 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.common.utils.StringUtils; +import org.springframework.stereotype.Component; + +/** + * 定时任务调度测试 + * + * @author admin + */ +@Component("demoTask") +public class DemoTask { + public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i) { + System.out.println(StringUtils.format("执行多参方法: 字符串类型{},布尔类型{},长整型{},浮点型{},整形{}", s, b, l, d, i)); + } + + public void ryParams(String params) { + System.out.println("执行有参方法:" + params); + } + + public void ryNoParams() { + System.out.println("执行无参方法"); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceConnectionTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceConnectionTask.java new file mode 100644 index 0000000..9c1dc90 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceConnectionTask.java @@ -0,0 +1,15 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.device.service.DeviceInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("DeviceConnectionTask") +public class DeviceConnectionTask { + @Autowired + private DeviceInfoService deviceInfoService; + + public void checkDeviceConnection() { + deviceInfoService.updateDeviceConnectState(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceOfflineCheckTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceOfflineCheckTask.java new file mode 100644 index 0000000..f1cc98f --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/DeviceOfflineCheckTask.java @@ -0,0 +1,15 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.device.service.DeviceInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("deviceOfflineCheckTask") +public class DeviceOfflineCheckTask { + @Autowired + private DeviceInfoService deviceInfoService; + + public void doTask() { + deviceInfoService.sendDeviceConnectStateEmail(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/EmailTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/EmailTask.java new file mode 100644 index 0000000..cc47cc8 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/EmailTask.java @@ -0,0 +1,20 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.data.check.service.ResultRecordService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("emailTask") +public class EmailTask { + @Autowired + private ResultRecordService resultRecordService; + + public void sendDailyStatReportEmail() { + resultRecordService.sendBirdDataStatEmail(); + } + + public void sendWeeklyStatReportEmail() { + resultRecordService.sendBirdDataWeeklyStatEmail(); + } + +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtraAudioListTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtraAudioListTask.java new file mode 100644 index 0000000..320145b --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtraAudioListTask.java @@ -0,0 +1,16 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.data.check.service.ResultRecordExtractService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("ExtraAudioListTask") +public class ExtraAudioListTask { + @Autowired + private ResultRecordExtractService resultRecordExtractService; + + public void doTask() { + resultRecordExtractService.extraAudioRecordDataList(); + } + +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtractResultDataListTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtractResultDataListTask.java new file mode 100644 index 0000000..b785938 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ExtractResultDataListTask.java @@ -0,0 +1,20 @@ +package net.hzvtc.quartz.task; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.data.check.service.ResultRecordExtractService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("ExtractResultDataListTask") +public class ExtractResultDataListTask { + @Autowired + private ResultRecordExtractService resultRecordExtractService; + + public void extractRecordData() { + JSONObject object = new JSONObject(); + object.put("areaId", 19); + resultRecordExtractService.getResultRecordListToPush(object); + object.put("areaId", 60); + resultRecordExtractService.getResultRecordListToPush(object); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/LevelOneSpeciesDailyTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/LevelOneSpeciesDailyTask.java new file mode 100644 index 0000000..af11116 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/LevelOneSpeciesDailyTask.java @@ -0,0 +1,21 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.area.service.SpeciesAbnormalInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +//国家1类保护动物 +@Component("levelOneSpeciesDailyTask") +public class LevelOneSpeciesDailyTask { + @Autowired + private SpeciesAbnormalInfoService speciesAbnormalInfoService; + + public void getAllLevelOneSpeciesResult() { + speciesAbnormalInfoService.getAllLevelOneSpecieResult(); + } + + public void getDailyLevelOneSpeciesResult() { +// speciesAbnormalInfoService.getDailyLevelOneSpecieResult(); + speciesAbnormalInfoService.getSpeciesAbnormalInfoListForJob(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultMediaDataPostTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultMediaDataPostTask.java new file mode 100644 index 0000000..f9e5e62 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultMediaDataPostTask.java @@ -0,0 +1,27 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("ResultMediaDataPostTask") +public class ResultMediaDataPostTask { + @Autowired + private ResultMediaService resultMediaService; + + @Autowired + private SpeciesDailyStatService speciesDailyStatService; + + public void doYuyuanTanDataTask() { + resultMediaService.getVideoListForPush(57L); + } + + public void postStatDataToYYT() { + speciesDailyStatService.postTodaySpeciesData(57L); + } + + public void doHuixianDataTask() { + resultMediaService.getVideoListForHuiXianPost(); + } +} \ No newline at end of file diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordDailyStatTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordDailyStatTask.java new file mode 100644 index 0000000..b61b760 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordDailyStatTask.java @@ -0,0 +1,19 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("resultRecordDailyStatTask") +public class ResultRecordDailyStatTask { + @Autowired + private SpeciesDailyStatService speciesDailyStatService; + + public void doDailyStatTask() { + speciesDailyStatService.calculateDailyResultRecord(null); + } + + public void doAllStatTask() { + speciesDailyStatService.calculateAllResultRecord(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordToEsTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordToEsTask.java new file mode 100644 index 0000000..0269ea1 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/ResultRecordToEsTask.java @@ -0,0 +1,15 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.es.service.EsResultRecordDetailsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("resultRecordToEsTask") +public class ResultRecordToEsTask { + @Autowired + private EsResultRecordDetailsService esResultRecordDetailsService; + + public void doDailyTask() { + esResultRecordDetailsService.bulkAddResultRecordDocument(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/SpeciesWinterPeriodStatTask.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/SpeciesWinterPeriodStatTask.java new file mode 100644 index 0000000..e88a72b --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/task/SpeciesWinterPeriodStatTask.java @@ -0,0 +1,15 @@ +package net.hzvtc.quartz.task; + +import net.hzvtc.web.stat.service.SpeciesWinterPeriodService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("speciesWinterPeriodStatTask") +public class SpeciesWinterPeriodStatTask { + @Autowired + private SpeciesWinterPeriodService speciesWinterPeriodService; + + public void doTask() { + speciesWinterPeriodService.calcSpeciesWinterPeriodByParam(); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/AbstractQuartzJob.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/AbstractQuartzJob.java new file mode 100644 index 0000000..56bdae6 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/AbstractQuartzJob.java @@ -0,0 +1,97 @@ +package net.hzvtc.quartz.util; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.ScheduleConstants; +import net.hzvtc.common.utils.ExceptionUtil; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanUtils; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.quartz.domain.SysJob; +import net.hzvtc.quartz.domain.SysJobLog; +import net.hzvtc.quartz.service.SysJobLogService; +import org.quartz.Job; +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +/** + * 抽象quartz调用 + * + * @author admin + */ +public abstract class AbstractQuartzJob implements Job { + private static final Logger log = LoggerFactory.getLogger(AbstractQuartzJob.class); + + /** + * 线程本地变量 + */ + private static ThreadLocal threadLocal = new ThreadLocal<>(); + + @Override + public void execute(JobExecutionContext context) throws JobExecutionException { + SysJob sysJob = new SysJob(); + BeanUtils.copyBeanProp(sysJob, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES)); + try { + before(context, sysJob); + if (sysJob != null) { + doExecute(context, sysJob); + } + after(context, sysJob, null); + } catch (Exception e) { + log.error("任务执行异常 - :", e); + after(context, sysJob, e); + } + } + + /** + * 执行前 + * + * @param context 工作执行上下文对象 + * @param sysJob 系统计划任务 + */ + protected void before(JobExecutionContext context, SysJob sysJob) { + threadLocal.set(new Date()); + } + + /** + * 执行后 + * + * @param context 工作执行上下文对象 + * @param sysJob 系统计划任务 + */ + protected void after(JobExecutionContext context, SysJob sysJob, Exception e) { + Date startTime = threadLocal.get(); + threadLocal.remove(); + + SysJobLog sysJobLog = new SysJobLog(); + sysJobLog.setJobName(sysJob.getJobName()); + sysJobLog.setJobGroup(sysJob.getJobGroup()); + sysJobLog.setInvokeTarget(sysJob.getInvokeTarget()); + sysJobLog.setStartTime(startTime); + sysJobLog.setStopTime(new Date()); + long runMs = sysJobLog.getStopTime().getTime() - sysJobLog.getStartTime().getTime(); + sysJobLog.setJobMessage(sysJobLog.getJobName() + " 总共耗时:" + runMs + "毫秒"); + if (e != null) { + sysJobLog.setStatus(Constants.FAIL); + String errorMsg = StringUtils.substring(ExceptionUtil.getExceptionMessage(e), 0, 2000); + sysJobLog.setExceptionInfo(errorMsg); + } else { + sysJobLog.setStatus(Constants.SUCCESS); + } + + // 写入数据库当中 + SpringUtils.getBean(SysJobLogService.class).addJobLog(sysJobLog); + } + + /** + * 执行方法,由子类重载 + * + * @param context 工作执行上下文对象 + * @param sysJob 系统计划任务 + * @throws Exception 执行过程中的异常 + */ + protected abstract void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception; +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/CronUtils.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/CronUtils.java new file mode 100644 index 0000000..2c98ddc --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/CronUtils.java @@ -0,0 +1,63 @@ +package net.hzvtc.quartz.util; + +import java.text.ParseException; +import java.util.Date; +import org.quartz.CronExpression; + +/** + * cron表达式工具类 + * + * @author admin + * + */ +public class CronUtils +{ + /** + * 返回一个布尔值代表一个给定的Cron表达式的有效性 + * + * @param cronExpression Cron表达式 + * @return boolean 表达式是否有效 + */ + public static boolean isValid(String cronExpression) + { + return CronExpression.isValidExpression(cronExpression); + } + + /** + * 返回一个字符串值,表示该消息无效Cron表达式给出有效性 + * + * @param cronExpression Cron表达式 + * @return String 无效时返回表达式错误描述,如果有效返回null + */ + public static String getInvalidMessage(String cronExpression) + { + try + { + new CronExpression(cronExpression); + return null; + } + catch (ParseException pe) + { + return pe.getMessage(); + } + } + + /** + * 返回下一个执行时间根据给定的Cron表达式 + * + * @param cronExpression Cron表达式 + * @return Date 下次Cron表达式执行时间 + */ + public static Date getNextExecution(String cronExpression) + { + try + { + CronExpression cron = new CronExpression(cronExpression); + return cron.getNextValidTimeAfter(new Date(System.currentTimeMillis())); + } + catch (ParseException e) + { + throw new IllegalArgumentException(e.getMessage()); + } + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/JobInvokeUtil.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/JobInvokeUtil.java new file mode 100644 index 0000000..c949bdc --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/JobInvokeUtil.java @@ -0,0 +1,182 @@ +package net.hzvtc.quartz.util; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.LinkedList; +import java.util.List; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.quartz.domain.SysJob; + +/** + * 任务执行工具 + * + * @author admin + */ +public class JobInvokeUtil +{ + /** + * 执行方法 + * + * @param sysJob 系统任务 + */ + public static void invokeMethod(SysJob sysJob) throws Exception + { + String invokeTarget = sysJob.getInvokeTarget(); + String beanName = getBeanName(invokeTarget); + String methodName = getMethodName(invokeTarget); + List methodParams = getMethodParams(invokeTarget); + + if (!isValidClassName(beanName)) + { + Object bean = SpringUtils.getBean(beanName); + invokeMethod(bean, methodName, methodParams); + } + else + { + Object bean = Class.forName(beanName).newInstance(); + invokeMethod(bean, methodName, methodParams); + } + } + + /** + * 调用任务方法 + * + * @param bean 目标对象 + * @param methodName 方法名称 + * @param methodParams 方法参数 + */ + private static void invokeMethod(Object bean, String methodName, List methodParams) + throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException + { + if (StringUtils.isNotNull(methodParams) && methodParams.size() > 0) + { + Method method = bean.getClass().getDeclaredMethod(methodName, getMethodParamsType(methodParams)); + method.invoke(bean, getMethodParamsValue(methodParams)); + } + else + { + Method method = bean.getClass().getDeclaredMethod(methodName); + method.invoke(bean); + } + } + + /** + * 校验是否为为class包名 + * + * @param invokeTarget 名称 + * @return true是 false否 + */ + public static boolean isValidClassName(String invokeTarget) + { + return StringUtils.countMatches(invokeTarget, ".") > 1; + } + + /** + * 获取bean名称 + * + * @param invokeTarget 目标字符串 + * @return bean名称 + */ + public static String getBeanName(String invokeTarget) + { + String beanName = StringUtils.substringBefore(invokeTarget, "("); + return StringUtils.substringBeforeLast(beanName, "."); + } + + /** + * 获取bean方法 + * + * @param invokeTarget 目标字符串 + * @return method方法 + */ + public static String getMethodName(String invokeTarget) + { + String methodName = StringUtils.substringBefore(invokeTarget, "("); + return StringUtils.substringAfterLast(methodName, "."); + } + + /** + * 获取method方法参数相关列表 + * + * @param invokeTarget 目标字符串 + * @return method方法相关参数列表 + */ + public static List getMethodParams(String invokeTarget) + { + String methodStr = StringUtils.substringBetween(invokeTarget, "(", ")"); + if (StringUtils.isEmpty(methodStr)) + { + return null; + } + String[] methodParams = methodStr.split(",(?=([^\"']*[\"'][^\"']*[\"'])*[^\"']*$)"); + List classs = new LinkedList<>(); + for (int i = 0; i < methodParams.length; i++) + { + String str = StringUtils.trimToEmpty(methodParams[i]); + // String字符串类型,以'或"开头 + if (StringUtils.startsWithAny(str, "'", "\"")) + { + classs.add(new Object[] { StringUtils.substring(str, 1, str.length() - 1), String.class }); + } + // boolean布尔类型,等于true或者false + else if ("true".equalsIgnoreCase(str) || "false".equalsIgnoreCase(str)) + { + classs.add(new Object[] { Boolean.valueOf(str), Boolean.class }); + } + // long长整形,以L结尾 + else if (StringUtils.endsWith(str, "L")) + { + classs.add(new Object[] { Long.valueOf(StringUtils.substring(str, 0, str.length() - 1)), Long.class }); + } + // double浮点类型,以D结尾 + else if (StringUtils.endsWith(str, "D")) + { + classs.add(new Object[] { Double.valueOf(StringUtils.substring(str, 0, str.length() - 1)), Double.class }); + } + // 其他类型归类为整形 + else + { + classs.add(new Object[] { Integer.valueOf(str), Integer.class }); + } + } + return classs; + } + + /** + * 获取参数类型 + * + * @param methodParams 参数相关列表 + * @return 参数类型列表 + */ + public static Class[] getMethodParamsType(List methodParams) + { + Class[] classs = new Class[methodParams.size()]; + int index = 0; + for (Object[] os : methodParams) + { + classs[index] = (Class) os[1]; + index++; + } + return classs; + } + + /** + * 获取参数值 + * + * @param methodParams 参数相关列表 + * @return 参数值列表 + */ + public static Object[] getMethodParamsValue(List methodParams) + { + Object[] classs = new Object[methodParams.size()]; + int index = 0; + for (Object[] os : methodParams) + { + classs[index] = (Object) os[0]; + index++; + } + return classs; + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzDisallowConcurrentExecution.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzDisallowConcurrentExecution.java new file mode 100644 index 0000000..fe748e3 --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzDisallowConcurrentExecution.java @@ -0,0 +1,21 @@ +package net.hzvtc.quartz.util; + +import net.hzvtc.quartz.domain.SysJob; +import org.quartz.DisallowConcurrentExecution; +import org.quartz.JobExecutionContext; + +/** + * 定时任务处理(禁止并发执行) + * + * @author admin + * + */ +@DisallowConcurrentExecution +public class QuartzDisallowConcurrentExecution extends AbstractQuartzJob +{ + @Override + protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception + { + JobInvokeUtil.invokeMethod(sysJob); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzJobExecution.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzJobExecution.java new file mode 100644 index 0000000..07b922d --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/QuartzJobExecution.java @@ -0,0 +1,19 @@ +package net.hzvtc.quartz.util; + +import net.hzvtc.quartz.domain.SysJob; +import org.quartz.JobExecutionContext; + +/** + * 定时任务处理(允许并发执行) + * + * @author admin + * + */ +public class QuartzJobExecution extends AbstractQuartzJob +{ + @Override + protected void doExecute(JobExecutionContext context, SysJob sysJob) throws Exception + { + JobInvokeUtil.invokeMethod(sysJob); + } +} diff --git a/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/ScheduleUtils.java b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/ScheduleUtils.java new file mode 100644 index 0000000..590204c --- /dev/null +++ b/ai-bird-quartz/src/main/java/net/hzvtc/quartz/util/ScheduleUtils.java @@ -0,0 +1,134 @@ +package net.hzvtc.quartz.util; + +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.ScheduleConstants; +import net.hzvtc.common.exception.job.TaskException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.quartz.domain.SysJob; +import org.quartz.CronScheduleBuilder; +import org.quartz.CronTrigger; +import org.quartz.Job; +import org.quartz.JobBuilder; +import org.quartz.JobDetail; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.TriggerBuilder; +import org.quartz.TriggerKey; + +/** + * 定时任务工具类 + * + * @author admin + * + */ +public class ScheduleUtils +{ + /** + * 得到quartz任务类 + * + * @param sysJob 执行计划 + * @return 具体执行任务类 + */ + private static Class getQuartzJobClass(SysJob sysJob) + { + boolean isConcurrent = "0".equals(sysJob.getConcurrent()); + return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class; + } + + /** + * 构建任务触发对象 + */ + 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) + { + return JobKey.jobKey(ScheduleConstants.TASK_CLASS_NAME + jobId, jobGroup); + } + + /** + * 创建定时任务 + */ + public static void createScheduleJob(Scheduler scheduler, SysJob job) throws SchedulerException, TaskException + { + Class jobClass = getQuartzJobClass(job); + // 构建job信息 + Long jobId = job.getJobId(); + String jobGroup = job.getJobGroup(); + JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build(); + + // 表达式调度构建器 + CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression()); + cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder); + + // 按新的cronExpression表达式构建一个新的trigger + CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup)) + .withSchedule(cronScheduleBuilder).build(); + + // 放入参数,运行时的方法可以获取 + jobDetail.getJobDataMap().put(ScheduleConstants.TASK_PROPERTIES, job); + + // 判断是否存在 + if (scheduler.checkExists(getJobKey(jobId, jobGroup))) + { + // 防止创建时存在数据问题 先移除,然后在执行创建操作 + scheduler.deleteJob(getJobKey(jobId, jobGroup)); + } + + scheduler.scheduleJob(jobDetail, trigger); + + // 暂停任务 + if (job.getStatus().equals(ScheduleConstants.Status.PAUSE.getValue())) + { + scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup)); + } + } + + /** + * 设置定时任务策略 + */ + public static CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb) + throws TaskException + { + switch (job.getMisfirePolicy()) + { + case ScheduleConstants.MISFIRE_DEFAULT: + return cb; + case ScheduleConstants.MISFIRE_IGNORE_MISFIRES: + return cb.withMisfireHandlingInstructionIgnoreMisfires(); + case ScheduleConstants.MISFIRE_FIRE_AND_PROCEED: + return cb.withMisfireHandlingInstructionFireAndProceed(); + case ScheduleConstants.MISFIRE_DO_NOTHING: + return cb.withMisfireHandlingInstructionDoNothing(); + default: + throw new TaskException("The task misfire policy '" + job.getMisfirePolicy() + + "' cannot be used in cron schedule tasks", TaskException.Code.CONFIG_ERROR); + } + } + + /** + * 检查包名是否为白名单配置 + * + * @param invokeTarget 目标字符串 + * @return 结果 + */ + public static boolean whiteList(String invokeTarget) + { + String packageName = StringUtils.substringBefore(invokeTarget, "("); + int count = StringUtils.countMatches(packageName, "."); + if (count > 1) + { + if (!StringUtils.containsAnyIgnoreCase(invokeTarget, Constants.JOB_WHITELIST_STR)) + { + return false; + } + } + return true; + } +} diff --git a/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml b/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml new file mode 100644 index 0000000..9c62072 --- /dev/null +++ b/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobLogMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + + select job_log_id, + job_name, + job_group, + invoke_target, + job_message, + status, + exception_info, + create_time + from sys_job_log + + + + + + + + + + delete + from sys_job_log + where job_log_id = #{jobLogId} + + + + delete from sys_job_log where job_log_id in + + #{jobLogId} + + + + + truncate table sys_job_log + + + + insert into sys_job_log( + job_log_id, + job_name, + job_group, + invoke_target, + job_message, + status, + exception_info, + create_time + )values( + #{jobLogId}, + #{jobName}, + #{jobGroup}, + #{invokeTarget}, + #{jobMessage}, + #{status}, + #{exceptionInfo}, + sysdate() + ) + + + \ No newline at end of file diff --git a/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml b/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml new file mode 100644 index 0000000..ac03dd7 --- /dev/null +++ b/ai-bird-quartz/src/main/resources/mapper/quartz/SysJobMapper.xml @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + select job_id, job_name, job_group, invoke_target, cron_expression, misfire_policy, concurrent, status, create_by, create_time, remark + from sys_job + + + + + + + + + + delete from sys_job where job_id = #{jobId} + + + + delete from sys_job where job_id in + + #{jobId} + + + + + update sys_job + + job_name = #{jobName}, + job_group = #{jobGroup}, + invoke_target = #{invokeTarget}, + cron_expression = #{cronExpression}, + misfire_policy = #{misfirePolicy}, + concurrent = #{concurrent}, + status = #{status}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where job_id = #{jobId} + + + + insert into sys_job( + job_id, + job_name, + job_group, + invoke_target, + cron_expression, + misfire_policy, + concurrent, + status, + remark, + create_by, + create_time + )values( + #{jobId}, + #{jobName}, + #{jobGroup}, + #{invokeTarget}, + #{cronExpression}, + #{misfirePolicy}, + #{concurrent}, + #{status}, + #{remark}, + #{createBy}, + sysdate() + ) + + + \ No newline at end of file diff --git a/ai-bird-system/pom.xml b/ai-bird-system/pom.xml new file mode 100644 index 0000000..9cebee0 --- /dev/null +++ b/ai-bird-system/pom.xml @@ -0,0 +1,73 @@ + + + + aibird + net.hzvtc + 1.2.0 + + 4.0.0 + + ai-bird-system + + + system系统模块 + + + + + net.hzvtc + ai-bird-common + + + org.projectlombok + lombok + 1.18.20 + provided + + + com.sun.mail + javax.mail + 1.6.2 + + + + io.swagger + swagger-annotations + 1.6.2 + compile + + + org.apache.poi + poi-ooxml + 5.2.3 + + + org.apache.poi + ooxml-schemas + 1.4 + + + org.onvif + onvif-java-lib + 0.0.1-SNAPSHOT + + + org.apache.httpcomponents + httpclient + 4.5.14 + + + org.apache.httpcomponents + httpmime + 4.5.14 + + + xuggle + xuggle-xuggler + 5.4 + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/java/net/hzvtc/app/domain/AppUpgrade.java b/ai-bird-system/src/main/java/net/hzvtc/app/domain/AppUpgrade.java new file mode 100644 index 0000000..f99e1fb --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/app/domain/AppUpgrade.java @@ -0,0 +1,25 @@ +package net.hzvtc.app.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="AppUpgrade") +@Data +public class AppUpgrade { + private static final long serialVersionUID = 1L; + private Long id; + private int code; + private int updateStatus; + private int versionCode; + private String versionName; + private Date uploadTime; + private String modifyContent; + private String downloadUrl; + private int apkSize; + private String apkMd5; + private String msg; + private int isDeleted; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/app/mapper/AppUpgradeMapper.java b/ai-bird-system/src/main/java/net/hzvtc/app/mapper/AppUpgradeMapper.java new file mode 100644 index 0000000..9caa62e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/app/mapper/AppUpgradeMapper.java @@ -0,0 +1,9 @@ +package net.hzvtc.app.mapper; + +import net.hzvtc.app.domain.AppUpgrade; + +public interface AppUpgradeMapper { + public AppUpgrade getLastAppUpgradeInfo(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/app/service/AppUpgradeService.java b/ai-bird-system/src/main/java/net/hzvtc/app/service/AppUpgradeService.java new file mode 100644 index 0000000..71b51ce --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/app/service/AppUpgradeService.java @@ -0,0 +1,9 @@ +package net.hzvtc.app.service; + +import net.hzvtc.app.domain.AppUpgrade; + +public interface AppUpgradeService { + public AppUpgrade getLastAppUpgradeInfo(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/app/service/impl/AppUpgradeServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/app/service/impl/AppUpgradeServiceImpl.java new file mode 100644 index 0000000..51a895f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/app/service/impl/AppUpgradeServiceImpl.java @@ -0,0 +1,32 @@ +package net.hzvtc.app.service.impl; + +import net.hzvtc.app.domain.AppUpgrade; +import net.hzvtc.app.mapper.AppUpgradeMapper; +import net.hzvtc.app.service.AppUpgradeService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; + +@Service +public class AppUpgradeServiceImpl implements AppUpgradeService { + @Resource + private AppUpgradeMapper appUpgradeMapper; + + @Override + public AppUpgrade getLastAppUpgradeInfo() { + AppUpgrade data = appUpgradeMapper.getLastAppUpgradeInfo(); +// JSONObject obj = new JSONObject(); +// obj.put("Code", data.getCode()); +// obj.put("Msg", data.getMsg()); +// obj.put("UpdateStatus", data.getUpdateStatus()); +// obj.put("VersionCode", data.getVersionCode()); +// obj.put("VersionName", data.getVersionName()); +// obj.put("UploadTime", data.getUploadTime()); +// obj.put("ModifyContent", data.getModifyContent()); +// obj.put("DownloadUrl", data.getDownloadUrl()); +// obj.put("ApkSize", data.getApkSize()); +// obj.put("ApkMd5", data.getApkMd5()); +// System.out.println(obj.get("ModifyContent")); + return data; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaController.java b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaController.java new file mode 100644 index 0000000..8171230 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaController.java @@ -0,0 +1,151 @@ +package net.hzvtc.area.controller; + +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Set; + +/** + * 保护区Controller + * + * @author admin + * @date 2022-07-20 + */ +@RestController +@RequestMapping("/area/protectedArea") +public class ProtectedAreaController extends BaseController { + @Autowired + private ProtectedAreaService protectedAreaService; + + @GetMapping("/listForPortal") + public AjaxResult getProtectedAreaListForPortal() { + return AjaxResult.success(protectedAreaService.getProtectedAreaListForPortal()); + } + + /** + * 查询保护区列表 + */ +// @PreAuthorize("@ss.hasPermi('area:protectedArea:list')") + @GetMapping("/list") + public TableDataInfo list(ProtectedArea protectedArea) { + startPage(); + List list = protectedAreaService.selectProtectedAreaList(protectedArea); + return getDataTable(list); + } + + /** + * 导出保护区列表 + */ + @PreAuthorize("@ss.hasPermi('area:protectedArea:export')") + @Log(title = "保护区", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, ProtectedArea protectedArea) { + List list = protectedAreaService.selectProtectedAreaList(protectedArea); + ExcelUtil util = new ExcelUtil(ProtectedArea.class); + util.exportExcel(response, list, "保护区数据"); + } + + @GetMapping("/treeList") + public AjaxResult getTreeList() { + return AjaxResult.success(protectedAreaService.getProtectedAreaTreeList()); + } + + /** + * 获取保护区详细信息 + */ + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + if (checkAreaIsLegal(id)) { + return AjaxResult.success(protectedAreaService.selectProtectedAreaById(id)); + } else { + return AjaxResult.error(403, "非法访问未授权的保护区数据,请联系管理员开通权限!"); + } + } + + @GetMapping(value = "/areaLogo/{id}") + public AjaxResult getAreaLogoInfo(@PathVariable("id") Long id) { + return AjaxResult.success(protectedAreaService.getAreaLogoInfoById(id)); + } + + private boolean checkAreaIsLegal(Long areaId) { + if (SecurityUtils.getLoginUser().getUser().isAdmin()) { + return true; + } + Set ids = SecurityUtils.getLoginUser().getAreaIds(); + if (ids == null || ids.isEmpty()) { + return false; + } else { + return ids.contains(areaId); + } + } + + /** + * 新增保护区 + */ + @PreAuthorize("@ss.hasPermi('area:protectedArea:add')") + @Log(title = "保护区", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ProtectedArea protectedArea) { + return toAjax(protectedAreaService.insertProtectedArea(protectedArea)); + } + + /** + * 修改保护区 + */ + @PreAuthorize("@ss.hasPermi('area:protectedArea:edit')") + @Log(title = "保护区", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ProtectedArea protectedArea) { + return toAjax(protectedAreaService.updateProtectedArea(protectedArea)); + } + + /** + * 删除保护区 + */ + @PreAuthorize("@ss.hasPermi('area:protectedArea:remove')") + @Log(title = "保护区", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(protectedAreaService.deleteProtectedAreaByIds(ids)); + } + + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil<>(ProtectedArea.class); + List list = util.importExcel(file.getInputStream()); + String message = protectedAreaService.importData(list, updateSupport); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil<>(ProtectedArea.class); + util.importTemplateExcel(response, "保护区信息"); + } + + @PostMapping("/upload") + public AjaxResult uploadFile(MultipartFile file) { + String baseDir = FileUploadUtils.getDefaultBaseDir() + "/" + "bgimg" + "/" + SecurityUtils.getDeptId(); + try { + String filePath = FileUploadUtils.upload(baseDir, file); + return AjaxResult.success(filePath); + } catch (Exception ex) { +// ex.printStackTrace(); + return AjaxResult.error(ex.getMessage()); + } + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaSpeciesController.java b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaSpeciesController.java new file mode 100644 index 0000000..df86cfc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedAreaSpeciesController.java @@ -0,0 +1,137 @@ +package net.hzvtc.area.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.area.domain.ProtectedAreaSpecies; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping(value={"/area/areaSpecies"}) +public class ProtectedAreaSpeciesController +extends BaseController { + private static final Logger log = LoggerFactory.getLogger(ProtectedAreaSpeciesController.class); + @Autowired + private ProtectedAreaSpeciesService protectedAreaSpeciesService; + @Autowired + private ResultRecordDetailsService resultRecordDetailsService; + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:list')") + @GetMapping(value={"/list"}) + public TableDataInfo list(ProtectedAreaSpecies protectedAreaSpecies) { + this.startPage(); + List list = this.protectedAreaSpeciesService.selectProtectedAreaSpeciesList(protectedAreaSpecies); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:export')") + @Log(title="\u4fdd\u62a4\u533a\u7269\u79cd", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, ProtectedAreaSpecies protectedAreaSpecies) { + List list = this.protectedAreaSpeciesService.selectProtectedAreaSpeciesList(protectedAreaSpecies); + ExcelUtil util = new ExcelUtil(ProtectedAreaSpecies.class); + util.exportExcel(response, list, "\u4fdd\u62a4\u533a\u7269\u79cd\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:query')") + @GetMapping(value={"/{id}"}) + public AjaxResult getInfo(@PathVariable(value="id") Long id) { + return AjaxResult.success((Object)((Object)this.protectedAreaSpeciesService.selectProtectedAreaSpeciesById(id))); + } + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:add')") + @Log(title="\u4fdd\u62a4\u533a\u7269\u79cd", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ProtectedAreaSpecies protectedAreaSpecies) { + return this.toAjax(this.protectedAreaSpeciesService.batchInsertProtectedAreaSpecies(protectedAreaSpecies)); + } + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:edit')") + @Log(title="\u4fdd\u62a4\u533a\u7269\u79cd", businessType=BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ProtectedAreaSpecies protectedAreaSpecies) { + return this.toAjax(this.protectedAreaSpeciesService.updateProtectedAreaSpecies(protectedAreaSpecies)); + } + + @PreAuthorize(value="@ss.hasPermi('area:areaSpecies:remove')") + @Log(title="\u4fdd\u62a4\u533a\u7269\u79cd", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{ids}"}) + public AjaxResult remove(@PathVariable Long[] ids) { + return this.toAjax(this.protectedAreaSpeciesService.deleteProtectedAreaSpeciesByIds(ids)); + } + + @PostMapping(value={"/importData"}) + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(ProtectedAreaSpecies.class); + List list = util.importExcel(file.getInputStream()); + String message = this.protectedAreaSpeciesService.importData(list, updateSupport); + return AjaxResult.success((String)message); + } + + @PostMapping(value={"/importTemplate"}) + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil(ProtectedAreaSpecies.class); + util.importTemplateExcel(response, "\u4fdd\u62a4\u533a\u9e1f\u7c7b\u4fe1\u606f"); + } + + @PostMapping(value={"/listSpeciesByParam"}) + public AjaxResult getSpeciesListByAreacode(@RequestBody JSONObject obj) { + return AjaxResult.success(this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByParam(obj)); + } + + @PostMapping(value={"/querySpeciesByQuery"}) + public TableDataInfo querySpeciesListByQuery(@RequestBody JSONObject obj) { + return this.protectedAreaSpeciesService.getProtectedAreaSpeciesByQuery(obj); + } + + @PostMapping(value={"/querySpeciesByParam"}) + public TableDataInfo getBirdResultMediasByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + this.startPage(pageNum, pageSize); + List list = this.resultRecordDetailsService.querySpeciesRecordListByParam(params); + return this.getDataTable(list); + } + + @PostMapping(value={"/queryVideoListByParam"}) + public TableDataInfo getBirdVidelByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + this.startPage(pageNum, pageSize); + List list = this.resultRecordDetailsService.getResultMediaVideoListByParam(params); + return this.getDataTable(list); + } + + @PostMapping(value={"/areaSpeciesByParam"}) + public AjaxResult getProtectedAreaSpeciesByParam(@RequestBody JSONObject params) { + return AjaxResult.success(this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByParams(params)); + } + + @PostMapping(value={"/changeSpeciesInArea"}) + public AjaxResult changeProtectedAreaSpeciesByParam(@RequestBody JSONObject params) { + return AjaxResult.success((Object)this.protectedAreaSpeciesService.changeProtectedAreaSpeciesByParam(params)); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedCareSpeciesController.java b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedCareSpeciesController.java new file mode 100644 index 0000000..85e3c05 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/controller/ProtectedCareSpeciesController.java @@ -0,0 +1,58 @@ +package net.hzvtc.area.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.area.domain.ProtectedCareSpecies; +import net.hzvtc.area.service.ProtectedCareSpeciesService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.enums.BusinessType; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +/** + * 保护区关注鸟类Controller + * + * @author admin + * @date 2023-08-16 + */ +@RestController +@RequestMapping("/area/care") +public class ProtectedCareSpeciesController extends BaseController { + @Autowired + private ProtectedCareSpeciesService protectedCareSpeciesService; + + /** + * 查询保护区关注鸟类列表 + */ + @PostMapping("/list") + public AjaxResult list(@RequestBody JSONObject params) { + return AjaxResult.success(protectedCareSpeciesService.selectProtectedCareSpeciesList(params)); + } + + /** + * 获取保护区关注鸟类详细信息 + */ + @PreAuthorize("@ss.hasPermi('area:care:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(protectedCareSpeciesService.selectProtectedCareSpeciesById(id)); + } + + /** + * 新增保护区关注鸟类 + */ + @PreAuthorize("@ss.hasPermi('area:care:add')") + @Log(title = "保护区关注鸟类", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ProtectedCareSpecies protectedCareSpecies) { + return toAjax(protectedCareSpeciesService.insertProtectedCareSpecies(protectedCareSpecies)); + } + + @PostMapping("/changeCareSpeciesInArea") + public AjaxResult changeProtectedAreaCareSpeciesByParam(@RequestBody JSONObject params) { + return AjaxResult.success(protectedCareSpeciesService.changeProtectedAreaCareSpeciesByParam(params)); + } + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/controller/SpeciesAbnormalInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/area/controller/SpeciesAbnormalInfoController.java new file mode 100644 index 0000000..45ae8d7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/controller/SpeciesAbnormalInfoController.java @@ -0,0 +1,80 @@ +package net.hzvtc.area.controller; + +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.area.service.SpeciesAbnormalInfoService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 关键物种与异常事件报警Controller + * + * @author admin + * @date 2023-03-10 + */ +@RestController +@RequestMapping("/area/abnormalInfo") +public class SpeciesAbnormalInfoController extends BaseController { + @Autowired + private SpeciesAbnormalInfoService speciesAbnormalInfoService; + + /** + * 查询关键物种与异常事件报警列表 + */ + + @GetMapping("/list") + public TableDataInfo list(SpeciesAbnormalInfo speciesAbnormalInfo) { + startPage(); + List list = speciesAbnormalInfoService.selectSpeciesAbnormalInfoList(speciesAbnormalInfo); + return getDataTable(list); + } + + /** + * 导出关键物种与异常事件报警列表 + */ + @Log(title = "关键物种与异常事件报警", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SpeciesAbnormalInfo speciesAbnormalInfo) { + List list = speciesAbnormalInfoService.selectSpeciesAbnormalInfoList(speciesAbnormalInfo); + ExcelUtil util = new ExcelUtil(SpeciesAbnormalInfo.class); + util.exportExcel(response, list, "关键物种与异常事件报警数据"); + } + + /** + * 获取关键物种与异常事件报警详细信息 + */ + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(speciesAbnormalInfoService.selectSpeciesAbnormalInfoById(id)); + } + + /** + * 新增关键物种与异常事件报警 + */ + @PreAuthorize("@ss.hasPermi('area:abnormalInfo:add')") + @Log(title = "关键物种与异常事件报警", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesAbnormalInfo speciesAbnormalInfo) { + return toAjax(speciesAbnormalInfoService.insertSpeciesAbnormalInfo(speciesAbnormalInfo)); + } + + + /** + * 删除关键物种与异常事件报警 + */ + @PreAuthorize("@ss.hasPermi('area:abnormalInfo:remove')") + @Log(title = "关键物种与异常事件报警", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(speciesAbnormalInfoService.deleteSpeciesAbnormalInfoByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/controller/WinteringPeriodController.java b/ai-bird-system/src/main/java/net/hzvtc/area/controller/WinteringPeriodController.java new file mode 100644 index 0000000..8629437 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/controller/WinteringPeriodController.java @@ -0,0 +1,97 @@ +package net.hzvtc.area.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.area.domain.WinteringPeriod; +import net.hzvtc.area.service.WinteringPeriodService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 越冬期Controller + * + * @author admin + * @date 2022-09-13 + */ +@RestController +@RequestMapping("/area/winterperiod") +public class WinteringPeriodController extends BaseController { + @Autowired + private WinteringPeriodService winteringPeriodService; + + /** + * 查询越冬期列表 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:list')") + @GetMapping("/list") + public TableDataInfo list(WinteringPeriod winteringPeriod) { + startPage(); + List list = winteringPeriodService.selectWinteringPeriodList(winteringPeriod); + return getDataTable(list); + } + + /** + * 导出越冬期列表 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:export')") + @Log(title = "越冬期", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, WinteringPeriod winteringPeriod) { + List list = winteringPeriodService.selectWinteringPeriodList(winteringPeriod); + ExcelUtil util = new ExcelUtil(WinteringPeriod.class); + util.exportExcel(response, list, "越冬期数据"); + } + + /** + * 获取越冬期详细信息 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(winteringPeriodService.selectWinteringPeriodById(id)); + } + + /** + * 新增越冬期 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:add')") + @Log(title = "越冬期", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody WinteringPeriod winteringPeriod) { + return toAjax(winteringPeriodService.insertWinteringPeriod(winteringPeriod)); + } + + /** + * 修改越冬期 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:edit')") + @Log(title = "越冬期", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody WinteringPeriod winteringPeriod) { + return toAjax(winteringPeriodService.updateWinteringPeriod(winteringPeriod)); + } + + /** + * 删除越冬期 + */ + @PreAuthorize("@ss.hasPermi('area:winterperiod:remove')") + @Log(title = "越冬期", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(winteringPeriodService.deleteWinteringPeriodByIds(ids)); + } + + @PostMapping("/chartList") + public AjaxResult getWinterPeriodChartData(@RequestBody JSONObject obj) { + return AjaxResult.success(winteringPeriodService.getWinteringPeriodDataList(obj)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedArea.java b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedArea.java new file mode 100644 index 0000000..9452450 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedArea.java @@ -0,0 +1,39 @@ +package net.hzvtc.area.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="ProtectedArea") +@Data +public class ProtectedArea extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String code; + private String name; + private String shortName; + private String url; + private String province; + private String provinceName; + private String areaLevel; + private String lon; + private String lat; + private String manager; + private String telephone; + private int sendEmail = 0; + private String email; + private int picWidth; + private int picHeight; + private int picNum; + private String bannerFile; + private String gisFile; + private int zoom; + private String introduction; + private String logoPath; + private String title; + private String enTitle; + private List deviceList; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedAreaSpecies.java b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedAreaSpecies.java new file mode 100644 index 0000000..fc18072 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedAreaSpecies.java @@ -0,0 +1,24 @@ +package net.hzvtc.area.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="ProtectedAreaSpecies") +@Data +public class ProtectedAreaSpecies extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private String speciesName; + private Long areaId; + private String areaName; + private int position = 0; + private BirdSpecies birdSpecies; + private int isCommon; + private int isSpecial; + private List ids; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedCareSpecies.java b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedCareSpecies.java new file mode 100644 index 0000000..aa791be --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/domain/ProtectedCareSpecies.java @@ -0,0 +1,17 @@ +package net.hzvtc.area.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="ProtectedCareSpecies") +@Data +public class ProtectedCareSpecies { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private Long areaId; + private Date createTime; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/domain/SpeciesAbnormalInfo.java b/ai-bird-system/src/main/java/net/hzvtc/area/domain/SpeciesAbnormalInfo.java new file mode 100644 index 0000000..85daf29 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/domain/SpeciesAbnormalInfo.java @@ -0,0 +1,29 @@ +package net.hzvtc.area.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesAbnormalInfo") +@Data +public class SpeciesAbnormalInfo { + private static final long serialVersionUID = 1L; + private Long id; + private Long deviceId; + private String deviceName; + private Long areaId; + private String areaName; + private Date happenTime; + private Long speciesId; + private String speciesName; + private String speciesImageUrl; + private int count; + private int type; + private Long mediaId; + private Long recordId; + private String mediaUrl; + private ResultMedia resultMedia; + private int isDeleted; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/domain/WinteringPeriod.java b/ai-bird-system/src/main/java/net/hzvtc/area/domain/WinteringPeriod.java new file mode 100644 index 0000000..0ded4b1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/domain/WinteringPeriod.java @@ -0,0 +1,20 @@ +package net.hzvtc.area.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="WinteringPeriod") +@Data +public class WinteringPeriod { + private static final long serialVersionUID = 1L; + private Long id; + private Long protectedAreaId; + private String protectedAreaName; + private String year; + private Date startTime; + private Date endTime; + private int amount; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaMapper.java b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaMapper.java new file mode 100644 index 0000000..e4ad145 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaMapper.java @@ -0,0 +1,41 @@ +package net.hzvtc.area.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.ProtectedArea; + +public interface ProtectedAreaMapper { + public ProtectedArea selectProtectedAreaById(Long var1); + + public ProtectedArea selectProtectedAreaByCode(String var1); + + public ProtectedArea selectProtectedAreaByName(String var1); + + public List selectProtectedAreaList(ProtectedArea var1); + + public List getProtectedAreaTreeList(Map var1); + + public List getAllProtectedAreaList(); + + public List getProtectedAreaListByUserId(Map var1); + + public List getProtectedAreaEmailList(); + + public List getAreaIdsByUserId(Long var1); + + public List getAreaListForSelect(); + + public List getAreaListByUserId(Long var1); + + public ProtectedArea getAreaLogoInfoById(Long var1); + + public int insertProtectedArea(ProtectedArea var1); + + public int updateProtectedArea(ProtectedArea var1); + + public int deleteProtectedAreaById(Long var1); + + public int deleteProtectedAreaByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaSpeciesMapper.java b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaSpeciesMapper.java new file mode 100644 index 0000000..b332906 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedAreaSpeciesMapper.java @@ -0,0 +1,40 @@ +package net.hzvtc.area.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.ProtectedAreaSpecies; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface ProtectedAreaSpeciesMapper { + public ProtectedAreaSpecies selectProtectedAreaSpeciesById(Long var1); + + public ProtectedAreaSpecies selectProtectedAreaSpeciesByParam(ProtectedAreaSpecies var1); + + public List selectProtectedAreaSpeciesList(ProtectedAreaSpecies var1); + + public List getProtectedAreaSpeciesListByParams(Map var1); + + public List getProtectedAreaSpeciesListByParam(Map var1); + + public List getProtectedAreaSpeciesByQuery(Map var1); + + public List getProtectedAreaSpeciesIdsByParam(Map var1); + + public List getProtectedAreaSpeciesListByAreaId(Map var1); + + public int insertProtectedAreaSpecies(ProtectedAreaSpecies var1); + + public int batchInsertProtectedAreaSpecies(List var1); + + public int updateProtectedAreaSpecies(ProtectedAreaSpecies var1); + + public void batchUpdateProtectedAreaSpecies(Map var1); + + public int deleteProtectedAreaSpeciesById(Long var1); + + public int deleteProtectedAreaSpeciesByIds(Long[] var1); + + public int deleteProtectedAreaSpeciesByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedCareSpeciesMapper.java b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedCareSpeciesMapper.java new file mode 100644 index 0000000..7491d85 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/ProtectedCareSpeciesMapper.java @@ -0,0 +1,19 @@ +package net.hzvtc.area.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.ProtectedCareSpecies; + +public interface ProtectedCareSpeciesMapper { + public ProtectedCareSpecies selectProtectedCareSpeciesById(Long var1); + + public List selectProtectedCareSpeciesList(Map var1); + + public List getProtectedCareSpeciesByParam(Map var1); + + public int insertProtectedCareSpecies(ProtectedCareSpecies var1); + + public int deleteProtectedCareSpeciesById(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/mapper/SpeciesAbnormalInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/SpeciesAbnormalInfoMapper.java new file mode 100644 index 0000000..2343b70 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/SpeciesAbnormalInfoMapper.java @@ -0,0 +1,30 @@ +package net.hzvtc.area.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.system.domain.vo.MessageVo; + +public interface SpeciesAbnormalInfoMapper { + public SpeciesAbnormalInfo selectSpeciesAbnormalInfoById(Long var1); + + public List selectSpeciesAbnormalInfoList(SpeciesAbnormalInfo var1); + + public SpeciesAbnormalInfo getLatestSpeciesAbnormalInfo(Long var1); + + public int getSpeciesAbnormalInfoCountByUserId(Map var1); + + public int insertSpeciesAbnormalInfo(SpeciesAbnormalInfo var1); + + public int batchInsertSpeciesAbnormalInfo(List var1); + + public int deleteSpeciesAbnormalInfoById(Long var1); + + public int deleteSpeciesAbnormalInfoByMediaId(Long var1); + + public int deleteSpeciesAbnormalInfoByIds(Long[] var1); + + public List getSpeciesAbnormalInfoListByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/mapper/WinteringPeriodMapper.java b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/WinteringPeriodMapper.java new file mode 100644 index 0000000..1cfbcb0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/mapper/WinteringPeriodMapper.java @@ -0,0 +1,22 @@ +package net.hzvtc.area.mapper; + +import java.util.List; +import net.hzvtc.area.domain.WinteringPeriod; + +public interface WinteringPeriodMapper { + public WinteringPeriod selectWinteringPeriodById(Long var1); + + public List selectWinteringPeriodList(WinteringPeriod var1); + + public List getWinteringPeriodDataList(WinteringPeriod var1); + + public int insertWinteringPeriod(WinteringPeriod var1); + + public int updateWinteringPeriod(WinteringPeriod var1); + + public int deleteWinteringPeriodById(Long var1); + + public int deleteWinteringPeriodByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaService.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaService.java new file mode 100644 index 0000000..a69c64a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaService.java @@ -0,0 +1,41 @@ +package net.hzvtc.area.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.area.domain.ProtectedArea; + +public interface ProtectedAreaService { + public ProtectedArea selectProtectedAreaById(Long var1); + + public ProtectedArea selectProtectedAreaByName(String var1); + + public List getProtectedAreaListForPortal(); + + public List selectProtectedAreaList(ProtectedArea var1); + + public List getProtectedAreaTreeList(); + + public int insertProtectedArea(ProtectedArea var1); + + public int updateProtectedArea(ProtectedArea var1); + + public int deleteProtectedAreaByIds(Long[] var1); + + public int deleteProtectedAreaById(Long var1); + + public String importData(List var1, boolean var2); + + public List getProtectedAreaEmailList(); + + public ProtectedArea selectProtectedAreaByCode(String var1); + + public List getAreaListForSelect(); + + public List getAreaIdsByUserId(Long var1); + + public List getAreaListByUserId(Long var1); + + public ProtectedArea getAreaLogoInfoById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaSpeciesService.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaSpeciesService.java new file mode 100644 index 0000000..ea6e108 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedAreaSpeciesService.java @@ -0,0 +1,38 @@ +package net.hzvtc.area.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.ProtectedAreaSpecies; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface ProtectedAreaSpeciesService { + public ProtectedAreaSpecies selectProtectedAreaSpeciesById(Long var1); + + public List selectProtectedAreaSpeciesList(ProtectedAreaSpecies var1); + + public int batchInsertProtectedAreaSpecies(ProtectedAreaSpecies var1); + + public int insertProtectedAreaSpecies(ProtectedAreaSpecies var1); + + public int updateProtectedAreaSpecies(ProtectedAreaSpecies var1); + + public int deleteProtectedAreaSpeciesByIds(Long[] var1); + + public List getProtectedAreaSpeciesListByParam(JSONObject var1); + + public int deleteProtectedAreaSpeciesById(Long var1); + + public String importData(List var1, boolean var2); + + public TableDataInfo getProtectedAreaSpeciesByQuery(JSONObject var1); + + public List getProtectedAreaSpeciesListByParams(JSONObject var1); + + public int changeProtectedAreaSpeciesByParam(JSONObject var1); + + public List getProtectedAreaSpeciesListByAreaId(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedCareSpeciesService.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedCareSpeciesService.java new file mode 100644 index 0000000..8339940 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/ProtectedCareSpeciesService.java @@ -0,0 +1,20 @@ +package net.hzvtc.area.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.ProtectedCareSpecies; + +public interface ProtectedCareSpeciesService { + public ProtectedCareSpecies selectProtectedCareSpeciesById(Long var1); + + public List selectProtectedCareSpeciesList(JSONObject var1); + + public int insertProtectedCareSpecies(ProtectedCareSpecies var1); + + public int changeProtectedAreaCareSpeciesByParam(JSONObject var1); + + public List getProtectedCareSpeciesByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/SpeciesAbnormalInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/SpeciesAbnormalInfoService.java new file mode 100644 index 0000000..747ad6c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/SpeciesAbnormalInfoService.java @@ -0,0 +1,34 @@ +package net.hzvtc.area.service; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.system.domain.vo.MessageVo; + +public interface SpeciesAbnormalInfoService { + public SpeciesAbnormalInfo selectSpeciesAbnormalInfoById(Long var1); + + public List selectSpeciesAbnormalInfoList(SpeciesAbnormalInfo var1); + + public int insertSpeciesAbnormalInfo(SpeciesAbnormalInfo var1); + + public int deleteSpeciesAbnormalInfoByIds(Long[] var1); + + public int deleteSpeciesAbnormalInfoById(Long var1); + + public void getDailyLevelOneSpecieResult(); + + public void getAllLevelOneSpecieResult(); + + public SpeciesAbnormalInfo getLatestSpeciesAbnormalInfo(Long var1); + + public int getSpeciesAbnormalInfoCountByUserId(Map var1); + + public List getSpeciesAbnormalInfoListByParam(); + + public void getSpeciesAbnormalInfoListForJob(); + + public int deleteSpeciesAbnormalInfoByMediaId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/WinteringPeriodService.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/WinteringPeriodService.java new file mode 100644 index 0000000..705b9b3 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/WinteringPeriodService.java @@ -0,0 +1,24 @@ +package net.hzvtc.area.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.area.domain.WinteringPeriod; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface WinteringPeriodService { + public WinteringPeriod selectWinteringPeriodById(Long var1); + + public List selectWinteringPeriodList(WinteringPeriod var1); + + public int insertWinteringPeriod(WinteringPeriod var1); + + public int updateWinteringPeriod(WinteringPeriod var1); + + public int deleteWinteringPeriodByIds(Long[] var1); + + public int deleteWinteringPeriodById(Long var1); + + public List getWinteringPeriodDataList(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaServiceImpl.java new file mode 100644 index 0000000..a6eee47 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaServiceImpl.java @@ -0,0 +1,191 @@ +package net.hzvtc.area.service.impl; + +import com.alibaba.fastjson.JSONObject; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import javax.validation.Validator; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.mapper.ProtectedAreaMapper; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ProtectedAreaServiceImpl +implements ProtectedAreaService { + private static final Logger log = LoggerFactory.getLogger(ProtectedAreaServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private ProtectedAreaMapper protectedAreaMapper; + + @Override + public ProtectedArea selectProtectedAreaById(Long id) { + return this.protectedAreaMapper.selectProtectedAreaById(id); + } + + @Override + public ProtectedArea selectProtectedAreaByName(String name) { + return this.protectedAreaMapper.selectProtectedAreaByName(name); + } + + @Override + public List getProtectedAreaListForPortal() { + Long userId = SecurityUtils.getUserId(); + if (userId <= 1L) { + return this.protectedAreaMapper.getAllProtectedAreaList(); + } + HashMap map = new HashMap(); + map.put("userId", userId); + return this.protectedAreaMapper.getProtectedAreaListByUserId(map); + } + + @Override + public List selectProtectedAreaList(ProtectedArea protectedArea) { + Long userId = SecurityUtils.getUserId(); + if (userId > 1L) { + protectedArea.setId(userId); + } else { + protectedArea.setId(null); + } + return this.protectedAreaMapper.selectProtectedAreaList(protectedArea); + } + + @Override + public List getProtectedAreaTreeList() { + HashMap map = new HashMap(); + Long userId = SecurityUtils.getUserId(); + if (userId > 1L) { + map.put("userId", userId); + } + return this.protectedAreaMapper.getProtectedAreaTreeList(map); + } + + @Override + public int insertProtectedArea(ProtectedArea protectedArea) { + protectedArea.setCreateTime(DateUtils.getNowDate()); + if (protectedArea.getShortName() == null || protectedArea.getShortName().isEmpty()) { + protectedArea.setShortName(protectedArea.getName()); + } + return this.protectedAreaMapper.insertProtectedArea(protectedArea); + } + + @Override + public int updateProtectedArea(ProtectedArea protectedArea) { + if (protectedArea.getShortName() == null || protectedArea.getShortName().isEmpty()) { + protectedArea.setShortName(protectedArea.getName()); + } + return this.protectedAreaMapper.updateProtectedArea(protectedArea); + } + + @Override + public int deleteProtectedAreaByIds(Long[] ids) { + return this.protectedAreaMapper.deleteProtectedAreaByIds(ids); + } + + @Override + public int deleteProtectedAreaById(Long id) { + return this.protectedAreaMapper.deleteProtectedAreaById(id); + } + + @Override + public String importData(List list, boolean updateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("\u5bfc\u5165\u4fdd\u62a4\u533a\u6570\u636e\u4e0d\u80fd\u4e3a\u7a7a\uff01"); + } + AtomicInteger[] successNum = new AtomicInteger[]{new AtomicInteger()}; + int[] failureNum = new int[]{0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + ProtectedArea protectedArea = this.protectedAreaMapper.selectProtectedAreaByName(data.getName()); + if (Objects.isNull((Object)protectedArea)) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setIsDeleted(0); + this.insertProtectedArea((ProtectedArea)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u4fdd\u62a4\u533a " + data.getName() + " \u5bfc\u5165\u6210\u529f"); + } else if (updateSupport) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setId(protectedArea.getId()); + this.updateProtectedArea((ProtectedArea)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u4fdd\u62a4\u533a " + data.getName() + " \u66f4\u65b0\u6210\u529f"); + } else { + failureNum[0] = failureNum[0] + 1; + failureMsg.append("
" + failureNum[0] + "\u3001\u4fdd\u62a4\u533a " + data.getName() + " \u5df2\u5b58\u5728"); + } + } + catch (Exception e) { + failureNum[0] = failureNum[0] + 1; + String msg = "
" + failureNum + "\u3001\u4fdd\u62a4\u533a " + data.getName() + " \u5bfc\u5165\u5931\u8d25\uff1a"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, (Throwable)e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "\u5f88\u62b1\u6b49\uff0c\u5bfc\u5165\u5931\u8d25\uff01\u5171 " + failureNum[0] + " \u6761\u6570\u636e\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c\u9519\u8bef\u5982\u4e0b\uff1a"); + throw new ServiceException(failureMsg.toString()); + } + successMsg.insert(0, "\u606d\u559c\u60a8\uff0c\u6570\u636e\u5df2\u5168\u90e8\u5bfc\u5165\u6210\u529f\uff01\u5171 " + successNum + " \u6761\uff0c\u6570\u636e\u5982\u4e0b\uff1a"); + return successMsg.toString(); + } + + @Override + public List getProtectedAreaEmailList() { + return this.protectedAreaMapper.getProtectedAreaEmailList(); + } + + @Override + public ProtectedArea selectProtectedAreaByCode(String code) { + return this.protectedAreaMapper.selectProtectedAreaByCode(code); + } + + @Override + public List getAreaListForSelect() { + return this.protectedAreaMapper.getAreaListForSelect(); + } + + @Override + public List getAreaIdsByUserId(Long userId) { + return this.protectedAreaMapper.getAreaIdsByUserId(userId); + } + + @Override + public List getAreaListByUserId(Long userId) { + if (userId <= 1L) { + userId = null; + } + List list = this.protectedAreaMapper.getAreaListByUserId(userId); + List objectList = list.stream().map(item -> { + JSONObject obj = new JSONObject(); + obj.put("id", (Object)item.getId()); + obj.put("name", (Object)item.getName()); + obj.put("provinceName", (Object)item.getProvinceName()); + obj.put("code", (Object)item.getProvince()); + obj.put("lat", (Object)item.getLat()); + obj.put("lon", (Object)item.getLon()); + return obj; + }).collect(Collectors.toList()); + return objectList; + } + + @Override + public ProtectedArea getAreaLogoInfoById(Long id) { + return this.protectedAreaMapper.getAreaLogoInfoById(id); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaSpeciesServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaSpeciesServiceImpl.java new file mode 100644 index 0000000..0d4387b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedAreaSpeciesServiceImpl.java @@ -0,0 +1,330 @@ +package net.hzvtc.area.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import lombok.RequiredArgsConstructor; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.domain.ProtectedAreaSpecies; +import net.hzvtc.area.mapper.ProtectedAreaSpeciesMapper; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.common.constant.HttpStatus; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.PageUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import javax.validation.Validator; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 保护区物种Service业务层处理 + * + * @author admin + * @date 2022-07-20 + */ +@Service +@RequiredArgsConstructor +public class ProtectedAreaSpeciesServiceImpl implements ProtectedAreaSpeciesService { + private static final Logger log = LoggerFactory.getLogger(ProtectedAreaServiceImpl.class); + @Resource + protected Validator validator; + @Resource + private ProtectedAreaSpeciesMapper protectedAreaSpeciesMapper; + + + private final ProtectedAreaService protectedAreaService; + + private final BirdSpeciesService birdSpeciesService; + + private final ResultRecordService resultRecordService; + + + /** + * 查询保护区物种 + * + * @param id 保护区物种主键 + * @return 保护区物种 + */ + @Override + public ProtectedAreaSpecies selectProtectedAreaSpeciesById(Long id) { + return protectedAreaSpeciesMapper.selectProtectedAreaSpeciesById(id); + } + + /** + * 查询保护区物种列表 + * + * @param protectedAreaSpecies 保护区物种 + * @return 保护区物种 + */ + @Override + public List selectProtectedAreaSpeciesList(ProtectedAreaSpecies protectedAreaSpecies) { + return protectedAreaSpeciesMapper.selectProtectedAreaSpeciesList(protectedAreaSpecies); + } + + /** + * 新增保护区物种 + * + * @param species 保护区物种 + * @return 结果 + */ + @Override + @Transactional + public int batchInsertProtectedAreaSpecies(ProtectedAreaSpecies species) { + species.setCreateTime(DateUtils.getNowDate()); + Map map = new HashMap<>(); + map.put("areaId", species.getAreaId()); + map.put("list", species.getIds()); + List birdIds = protectedAreaSpeciesMapper.getProtectedAreaSpeciesListByParams(map); + if (birdIds != null && birdIds.size() > 0) { + map.clear(); + map.put("isCommon", species.getIsCommon()); + map.put("list", birdIds); + map.put("areaId", species.getAreaId()); + protectedAreaSpeciesMapper.batchUpdateProtectedAreaSpecies(map); + } + List newIds = listRemove(species.getIds(), birdIds); + if (newIds != null && newIds.size() > 0) { + List list = new ArrayList<>(); + newIds.stream().forEach(id -> { + ProtectedAreaSpecies data = new ProtectedAreaSpecies(); + data.setAreaId(species.getAreaId()); + data.setIsCommon(species.getIsCommon()); + data.setIsDeleted(0); + data.setCreateTime(species.getCreateTime()); + data.setSpeciesId(id); + list.add(data); + }); + return protectedAreaSpeciesMapper.batchInsertProtectedAreaSpecies(list); + } else { + return 1; + } + + } + + @Override + public int insertProtectedAreaSpecies(ProtectedAreaSpecies protectedAreaSpecies) { + return protectedAreaSpeciesMapper.insertProtectedAreaSpecies(protectedAreaSpecies); + } + + private List listRemove(List fromList, List toList) { + HashSet hs1 = new HashSet(fromList); + HashSet hs2 = new HashSet(toList); + hs1.removeAll(hs2); + List list = new ArrayList(); + list.addAll(hs1); + return list; + } + + /** + * 修改保护区物种 + * + * @param protectedAreaSpecies 保护区物种 + * @return 结果 + */ + @Override + public int updateProtectedAreaSpecies(ProtectedAreaSpecies protectedAreaSpecies) { + return protectedAreaSpeciesMapper.updateProtectedAreaSpecies(protectedAreaSpecies); + } + + /** + * 批量删除保护区物种 + * + * @param ids 需要删除的保护区物种主键 + * @return 结果 + */ + @Override + public int deleteProtectedAreaSpeciesByIds(Long[] ids) { + return protectedAreaSpeciesMapper.deleteProtectedAreaSpeciesByIds(ids); + } + + @Override + public List getProtectedAreaSpeciesListByParam(JSONObject obj) { + Map map = new HashMap<>(); + Integer isCommon = obj.getInteger("isCommon"); + if (isCommon != null) { + map.put("isCommon", isCommon); + } + String code = obj.getString("code"); + if (code != null && !code.isEmpty()) { + map.put("code", code); + } + Long areaId = obj.getLong("areaId"); + map.put("areaId", areaId); + return protectedAreaSpeciesMapper.getProtectedAreaSpeciesListByParam(map); + } + + /** + * 删除保护区物种信息 + * + * @param id 保护区物种主键 + * @return 结果 + */ + @Override + public int deleteProtectedAreaSpeciesById(Long id) { + return protectedAreaSpeciesMapper.deleteProtectedAreaSpeciesById(id); + } + + @Override + public String importData(List list, boolean updateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("导入保护区鸟类不能为空!"); + } + AtomicInteger[] successNum = {new AtomicInteger()}; + int[] failureNum = {0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + ProtectedArea protectedArea = protectedAreaService.selectProtectedAreaByName(data.getAreaName()); + BirdSpecies birdSpecies = birdSpeciesService.selectBirdSpeciesByName(data.getSpeciesName()); + if (Objects.isNull(protectedArea)) { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、保护区 " + data.getAreaName() + " 不存在"); + } else if (Objects.isNull(birdSpecies)) { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟类 " + data.getSpeciesName() + " 不存在"); + } else { + ProtectedAreaSpecies param = new ProtectedAreaSpecies(); + param.setAreaId(protectedArea.getId()); + param.setSpeciesId(birdSpecies.getId()); + ProtectedAreaSpecies areaSpecies = protectedAreaSpeciesMapper.selectProtectedAreaSpeciesByParam(param); + if (Objects.isNull(areaSpecies)) { + BeanValidators.validateWithException(validator, data); + data.setIsDeleted(0); + data.setAreaId(protectedArea.getId()); + data.setSpeciesId(birdSpecies.getId()); + data.setCreateTime(new Date()); + insertProtectedAreaSpecies(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟类 " + data.getSpeciesName() + " 导入成功"); + } else if (updateSupport) { + BeanValidators.validateWithException(validator, data); + data.setId(areaSpecies.getId()); + data.setIsDeleted(0); + data.setAreaId(protectedArea.getId()); + data.setSpeciesId(birdSpecies.getId()); + updateProtectedAreaSpecies(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟类 " + data.getSpeciesName() + " 更新成功"); + } else { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟类 " + data.getSpeciesName() + " 已存在"); + } + } + + + } catch (Exception e) { + failureNum[0]++; + String msg = "
" + failureNum + "、鸟类 " + data.getSpeciesName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum[0] + " 条数据格式不正确,错误如下:"); + throw new ServiceException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } + + @Override + public TableDataInfo getProtectedAreaSpeciesByQuery(JSONObject param) { + Map map = new HashMap<>(); + String areaName = ""; + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + if (areaId != null) { + areaName = protectedAreaService.selectProtectedAreaById(areaId).getName(); + } + String name = param.getString("name"); + map.put("name", name); + Integer pageNum = param.getInteger("pageNum"); + Integer pageSize = param.getInteger("pageSize"); + PageUtils.startPage(pageNum, pageSize); + List birdSpecies = birdSpeciesService.getBirdSpeciesListByQuery(map); + TableDataInfo rspData = new TableDataInfo(); + rspData.setCode(HttpStatus.SUCCESS); + rspData.setMsg("查询成功"); + rspData.setTotal(new PageInfo(birdSpecies).getTotal()); + + // List ids = protectedAreaSpeciesMapper.getProtectedAreaSpeciesIdsByParam(map); + List list = new ArrayList<>(); + for (BirdSpecies item : birdSpecies) { + ProtectedAreaSpecies data = new ProtectedAreaSpecies(); + data.setSpeciesId(item.getId()); + data.setBirdSpecies(item); + map.put("speciesId", item.getId()); + ResultRecord resultRecord = resultRecordService.getResultRecordInfoBySpeciesId(map); + if (resultRecord != null) { + data.setAreaName(areaName); + data.setUpdateTime(resultRecord.getRecordTime()); + } else { + data.setAreaName("当前未监测到"); + } + list.add(data); + } + rspData.setRows(list); + return rspData; + } + + @Override + public List getProtectedAreaSpeciesListByParams(JSONObject param) { + Map map = new HashMap<>(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + String str = param.getString("list"); + if (str != null && !str.isEmpty()) { + List list = JSON.parseArray(str, Long.class); + if (list != null && !list.isEmpty()) { + map.put("list", list); + } + } + return protectedAreaSpeciesMapper.getProtectedAreaSpeciesListByParams(map); + } + + @Override + public int changeProtectedAreaSpeciesByParam(JSONObject param) { + Long id = param.getLong("id"); + int val = param.getInteger("val"); + Long areaId = param.getLong("areaId"); + if (val == 0) { + Map map = new HashMap<>(); + map.put("areaId", areaId); + map.put("speciesId", id); + return protectedAreaSpeciesMapper.deleteProtectedAreaSpeciesByParam(map); + } else { + ProtectedAreaSpecies data = new ProtectedAreaSpecies(); + data.setIsCommon(1); + data.setSpeciesId(id); + data.setAreaId(areaId); + data.setCreateTime(new Date()); + data.setPosition(99); + data.setIsDeleted(0); + return protectedAreaSpeciesMapper.insertProtectedAreaSpecies(data); + } + } + + @Override + public List getProtectedAreaSpeciesListByAreaId(Map map) { + return protectedAreaSpeciesMapper.getProtectedAreaSpeciesListByAreaId(map); + } + + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedCareSpeciesServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedCareSpeciesServiceImpl.java new file mode 100644 index 0000000..dbf3921 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/ProtectedCareSpeciesServiceImpl.java @@ -0,0 +1,73 @@ +package net.hzvtc.area.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedCareSpecies; +import net.hzvtc.area.mapper.ProtectedCareSpeciesMapper; +import net.hzvtc.area.service.ProtectedCareSpeciesService; +import net.hzvtc.common.utils.DateUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class ProtectedCareSpeciesServiceImpl +implements ProtectedCareSpeciesService { + private static final Logger log = LoggerFactory.getLogger(ProtectedCareSpeciesServiceImpl.class); + @Resource + private ProtectedCareSpeciesMapper protectedCareSpeciesMapper; + + @Override + public ProtectedCareSpecies selectProtectedCareSpeciesById(Long id) { + return this.protectedCareSpeciesMapper.selectProtectedCareSpeciesById(id); + } + + @Override + public List selectProtectedCareSpeciesList(JSONObject param) { + List list; + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + String str = param.getString("list"); + if (str != null && !str.isEmpty() && (list = JSON.parseArray((String)str, Long.class)) != null && !list.isEmpty()) { + map.put("list", list); + } + return this.protectedCareSpeciesMapper.selectProtectedCareSpeciesList(map); + } + + @Override + public int insertProtectedCareSpecies(ProtectedCareSpecies protectedCareSpecies) { + protectedCareSpecies.setCreateTime(DateUtils.getNowDate()); + return this.protectedCareSpeciesMapper.insertProtectedCareSpecies(protectedCareSpecies); + } + + @Override + public int changeProtectedAreaCareSpeciesByParam(JSONObject param) { + Long id = param.getLong("id"); + int val = param.getInteger("val"); + Long areaId = param.getLong("areaId"); + if (val == 0) { + HashMap map = new HashMap(); + map.put("areaId", areaId); + map.put("speciesId", id); + return this.protectedCareSpeciesMapper.deleteProtectedCareSpeciesById(map); + } + ProtectedCareSpecies data = new ProtectedCareSpecies(); + data.setSpeciesId(id); + data.setAreaId(areaId); + data.setCreateTime(new Date()); + return this.protectedCareSpeciesMapper.insertProtectedCareSpecies(data); + } + + @Override + public List getProtectedCareSpeciesByParam(Map map) { + return this.protectedCareSpeciesMapper.getProtectedCareSpeciesByParam(map); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/SpeciesAbnormalInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/SpeciesAbnormalInfoServiceImpl.java new file mode 100644 index 0000000..d9aaa2d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/SpeciesAbnormalInfoServiceImpl.java @@ -0,0 +1,214 @@ +package net.hzvtc.area.service.impl; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.area.mapper.SpeciesAbnormalInfoMapper; +import net.hzvtc.area.service.ProtectedCareSpeciesService; +import net.hzvtc.area.service.SpeciesAbnormalInfoService; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.data.job.domain.TableStatInfo; +import net.hzvtc.data.job.service.TableStatInfoService; +import net.hzvtc.system.domain.vo.MessageVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SpeciesAbnormalInfoServiceImpl +implements SpeciesAbnormalInfoService { + private static final Logger log = LoggerFactory.getLogger(SpeciesAbnormalInfoServiceImpl.class); + @Resource + private SpeciesAbnormalInfoMapper speciesAbnormalInfoMapper; + @Autowired + private ResultRecordDetailsService resultRecordDetailsService; + @Autowired + private TableStatInfoService tableStatInfoService; + @Autowired + private ResultRecordService resultRecordService; + @Autowired + private ProtectedCareSpeciesService careSpeciesService; + + @Override + public SpeciesAbnormalInfo selectSpeciesAbnormalInfoById(Long id) { + return this.speciesAbnormalInfoMapper.selectSpeciesAbnormalInfoById(id); + } + + @Override + public List selectSpeciesAbnormalInfoList(SpeciesAbnormalInfo speciesAbnormalInfo) { + return this.speciesAbnormalInfoMapper.selectSpeciesAbnormalInfoList(speciesAbnormalInfo); + } + + @Override + public int insertSpeciesAbnormalInfo(SpeciesAbnormalInfo speciesAbnormalInfo) { + return this.speciesAbnormalInfoMapper.insertSpeciesAbnormalInfo(speciesAbnormalInfo); + } + + @Override + public int deleteSpeciesAbnormalInfoByIds(Long[] ids) { + return this.speciesAbnormalInfoMapper.deleteSpeciesAbnormalInfoByIds(ids); + } + + @Override + public int deleteSpeciesAbnormalInfoById(Long id) { + return this.speciesAbnormalInfoMapper.deleteSpeciesAbnormalInfoById(id); + } + + @Override + public void getDailyLevelOneSpecieResult() { + HashMap map = new HashMap(); + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + map.put("happenTime", fmDate.format(LocalDate.now())); + List list = this.resultRecordDetailsService.getLevelOneSpeciesLitByParam(map); + if (list != null && !list.isEmpty()) { + list.forEach(item -> item.setType(1)); + this.speciesAbnormalInfoMapper.batchInsertSpeciesAbnormalInfo(list); + } + if ((list = this.resultRecordDetailsService.getCrOrEnSpeciesLitByParam(map)) != null && !list.isEmpty()) { + list.forEach(item -> item.setType(2)); + this.speciesAbnormalInfoMapper.batchInsertSpeciesAbnormalInfo(list); + } + } + + @Override + public void getAllLevelOneSpecieResult() { + HashMap map = new HashMap(); + List list = this.resultRecordDetailsService.getLevelOneSpeciesLitByParam(map); + if (list != null && !list.isEmpty()) { + this.speciesAbnormalInfoMapper.batchInsertSpeciesAbnormalInfo(list); + } + } + + @Override + public SpeciesAbnormalInfo getLatestSpeciesAbnormalInfo(Long userId) { + return this.speciesAbnormalInfoMapper.getLatestSpeciesAbnormalInfo(userId); + } + + @Override + public int getSpeciesAbnormalInfoCountByUserId(Map map) { + return this.speciesAbnormalInfoMapper.getSpeciesAbnormalInfoCountByUserId(map); + } + + @Override + public List getSpeciesAbnormalInfoListByParam() { + HashMap map = new HashMap(); + Long userId = SecurityUtils.getUserId(); + map.put("readerId", userId); + if (userId <= 1L) { + userId = null; + } + map.put("userId", userId); + return this.speciesAbnormalInfoMapper.getSpeciesAbnormalInfoListByParam(map); + } + + @Override + @Transactional + public void getSpeciesAbnormalInfoListForJob() { + TableStatInfo data; + TableStatInfo param = new TableStatInfo(); + param.setType(0); + Long miniId = null; + List list = this.tableStatInfoService.selectTableStatInfoList(param); + HashMap map = new HashMap(); + if (list == null || list.isEmpty()) { + map.put("recordTime", new Date()); + } else { + Long id = list.get(0).getTableId(); + map.put("recordId", id); + } + List ids = this.resultRecordService.getResultRecordIdsByParam(map); + if (ids == null || ids.isEmpty()) { + return; + } + if (list == null || list.isEmpty()) { + data = new TableStatInfo(); + data.setType(0); + data.setTableId(ids.get(0)); + this.tableStatInfoService.insertTableStatInfo(data); + } else { + data = list.get(0); + data.setTableId(ids.get(0)); + this.tableStatInfoService.updateTableStatInfo(data); + } + miniId = ids.get(ids.size() - 1); + map.clear(); + map.put("list", ids); + ArrayList speciesList = new ArrayList(); + List nlist = this.resultRecordDetailsService.getCrOrEnSpeciesLitByParam(map); + if (nlist != null && nlist.size() > 0) { + nlist.forEach(item -> { + if (!this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + item.setType(2); + speciesList.add((SpeciesAbnormalInfo)item); + } + }); + } + nlist = this.resultRecordDetailsService.getSpeciesDateListByParam(map); + map.clear(); + map.put("recordId", miniId); + nlist.forEach(item -> { + if (!this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + map.put("speciesId", item.getSpeciesId()); + map.put("areaId", item.getAreaId()); + List subIds = this.resultRecordDetailsService.checkIsNewSpeciesByParam(map); + if ((subIds == null || subIds.isEmpty()) && !this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + item.setType(3); + speciesList.add((SpeciesAbnormalInfo)item); + } + } + }); + map.clear(); + map.put("list", ids); + nlist.forEach(item -> { + if (!this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + map.put("speciesId", item.getSpeciesId()); + map.put("areaId", item.getAreaId()); + List subIds = this.careSpeciesService.getProtectedCareSpeciesByParam(map); + if (subIds != null && !subIds.isEmpty() && !this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + item.setType(4); + speciesList.add((SpeciesAbnormalInfo)item); + } + } + }); + map.clear(); + map.put("list", ids); + nlist = this.resultRecordDetailsService.getLevelOneSpeciesLitByParam(map); + if (nlist != null && !nlist.isEmpty()) { + nlist.forEach(item -> { + if (!this.containsItem((List)speciesList, (SpeciesAbnormalInfo)item)) { + item.setType(1); + speciesList.add((SpeciesAbnormalInfo)item); + } + }); + } + if (!speciesList.isEmpty()) { + this.speciesAbnormalInfoMapper.batchInsertSpeciesAbnormalInfo(speciesList); + } + } + + @Override + public int deleteSpeciesAbnormalInfoByMediaId(Long id) { + return this.speciesAbnormalInfoMapper.deleteSpeciesAbnormalInfoByMediaId(id); + } + + private boolean containsItem(List list, SpeciesAbnormalInfo item) { + if (list == null || list.size() == 0) { + return false; + } + List slist = list.stream().filter(sitem -> sitem.getRecordId().longValue() == item.getRecordId().longValue() && sitem.getSpeciesId().longValue() == item.getSpeciesId().longValue()).collect(Collectors.toList()); + return slist != null && slist.size() != 0; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/WinteringPeriodServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/WinteringPeriodServiceImpl.java new file mode 100644 index 0000000..869acf9 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/area/service/impl/WinteringPeriodServiceImpl.java @@ -0,0 +1,120 @@ +package net.hzvtc.area.service.impl; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.domain.WinteringPeriod; +import net.hzvtc.area.mapper.WinteringPeriodMapper; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.WinteringPeriodService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 越冬期Service业务层处理 + * + * @author admin + * @date 2022-09-13 + */ +@Service +public class WinteringPeriodServiceImpl implements WinteringPeriodService { + @Resource + private WinteringPeriodMapper winteringPeriodMapper; + + @Autowired + private ProtectedAreaService protectedAreaService; + + /** + * 查询越冬期 + * + * @param id 越冬期主键 + * @return 越冬期 + */ + @Override + public WinteringPeriod selectWinteringPeriodById(Long id) { + return winteringPeriodMapper.selectWinteringPeriodById(id); + } + + /** + * 查询越冬期列表 + * + * @param winteringPeriod 越冬期 + * @return 越冬期 + */ + @Override + public List selectWinteringPeriodList(WinteringPeriod winteringPeriod) { + return winteringPeriodMapper.selectWinteringPeriodList(winteringPeriod); + } + + /** + * 新增越冬期 + * + * @param winteringPeriod 越冬期 + * @return 结果 + */ + @Override + public int insertWinteringPeriod(WinteringPeriod winteringPeriod) { + return winteringPeriodMapper.insertWinteringPeriod(winteringPeriod); + } + + /** + * 修改越冬期 + * + * @param winteringPeriod 越冬期 + * @return 结果 + */ + @Override + public int updateWinteringPeriod(WinteringPeriod winteringPeriod) { + return winteringPeriodMapper.updateWinteringPeriod(winteringPeriod); + } + + /** + * 批量删除越冬期 + * + * @param ids 需要删除的越冬期主键 + * @return 结果 + */ + @Override + public int deleteWinteringPeriodByIds(Long[] ids) { + return winteringPeriodMapper.deleteWinteringPeriodByIds(ids); + } + + /** + * 删除越冬期信息 + * + * @param id 越冬期主键 + * @return 结果 + */ + @Override + public int deleteWinteringPeriodById(Long id) { + return winteringPeriodMapper.deleteWinteringPeriodById(id); + } + + @Override + public List getWinteringPeriodDataList(JSONObject param) { + String areaCode = param.getString("areaCode"); + if (areaCode != null) { + ProtectedArea data = protectedAreaService.selectProtectedAreaByCode(areaCode); + WinteringPeriod winteringPeriod = new WinteringPeriod(); + winteringPeriod.setProtectedAreaId(data.getId()); + List list = winteringPeriodMapper.getWinteringPeriodDataList(winteringPeriod); + Collections.reverse(list); + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + List datalist = list.stream().map(item -> { + BirdStatDataVo statDataVo = new BirdStatDataVo(); + statDataVo.setValue(item.getAmount()); + String code = df.format(item.getStartTime()) + "-" + df.format(item.getEndTime()); + statDataVo.setCode(code); + return statDataVo; + }).collect(Collectors.toList()); + return datalist; + } + return null; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdCatalogueController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdCatalogueController.java new file mode 100644 index 0000000..041515c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdCatalogueController.java @@ -0,0 +1,112 @@ +package net.hzvtc.bird.controller; + +import net.hzvtc.bird.domain.BirdCatalogue; +import net.hzvtc.bird.service.BirdCatalogueService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 鸟类目Controller + * + * @author admin + * @date 2022-07-16 + */ +@RestController +@RequestMapping("/birdInfo/catalogue") +public class BirdCatalogueController extends BaseController { + @Autowired + private BirdCatalogueService birdCatalogueService; + + /** + * 查询鸟类目列表 + */ +// @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:list')") + @GetMapping("/list") + public TableDataInfo list(BirdCatalogue birdCatalogue) { + startPage(); + List list = birdCatalogueService.selectBirdCatalogueList(birdCatalogue); + return getDataTable(list); + } + + @GetMapping("/selectList") + public AjaxResult getBirdCatalogueSelectList() { + return AjaxResult.success(birdCatalogueService.getBirdCatalogueSelectList()); + } + + /** + * 导出鸟类目列表 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:export')") + @Log(title = "鸟类目", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdCatalogue birdCatalogue) { + List list = birdCatalogueService.selectBirdCatalogueList(birdCatalogue); + ExcelUtil util = new ExcelUtil(BirdCatalogue.class); + util.exportExcel(response, list, "鸟类目数据"); + } + + @Log(title = "鸟类目", businessType = BusinessType.IMPORT) + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(BirdCatalogue.class); + List list = util.importExcel(file.getInputStream()); + String message = birdCatalogueService.importData(list, updateSupport); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil<>(BirdCatalogue.class); + util.importTemplateExcel(response, "鸟类目数据"); + } + + /** + * 获取鸟类目详细信息 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdCatalogueService.selectBirdCatalogueById(id)); + } + + /** + * 新增鸟类目 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:add')") + @Log(title = "鸟类目", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdCatalogue birdCatalogue) { + return toAjax(birdCatalogueService.insertBirdCatalogue(birdCatalogue)); + } + + /** + * 修改鸟类目 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:edit')") + @Log(title = "鸟类目", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdCatalogue birdCatalogue) { + return toAjax(birdCatalogueService.updateBirdCatalogue(birdCatalogue)); + } + + /** + * 删除鸟类目 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:catalogue:remove')") + @Log(title = "鸟类目", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdCatalogueService.deleteBirdCatalogueByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFamilyController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFamilyController.java new file mode 100644 index 0000000..3256cf9 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFamilyController.java @@ -0,0 +1,111 @@ +package net.hzvtc.bird.controller; + +import net.hzvtc.bird.domain.BirdFamily; +import net.hzvtc.bird.service.BirdFamilyService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 鸟类科Controller + * + * @author admin + * @date 2022-07-16 + */ +@RestController +@RequestMapping("/birdInfo/family") +public class BirdFamilyController extends BaseController { + @Autowired + private BirdFamilyService birdFamilyService; + + /** + * 查询鸟类科列表 + */ +// @PreAuthorize("@ss.hasPermi('birdInfo:family:list')") + @GetMapping("/list") + public TableDataInfo list(BirdFamily birdFamily) { + startPage(); + List list = birdFamilyService.selectBirdFamilyList(birdFamily); + return getDataTable(list); + } + + @GetMapping("/listByCataId") + public AjaxResult getBirdFamilyListByCatalogueId(@RequestParam(name = "id") Long id) { + return AjaxResult.success(birdFamilyService.getBirdFamilyListByCataId(id)); + } + + /** + * 导出鸟类科列表 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:family:export')") + @Log(title = "鸟类科", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdFamily birdFamily) { + List list = birdFamilyService.selectBirdFamilyList(birdFamily); + ExcelUtil util = new ExcelUtil(BirdFamily.class); + util.exportExcel(response, list, "鸟类科数据"); + } + + /** + * 获取鸟类科详细信息 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:family:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdFamilyService.selectBirdFamilyById(id)); + } + + /** + * 新增鸟类科 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:family:add')") + @Log(title = "鸟类科", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdFamily birdFamily) { + return toAjax(birdFamilyService.insertBirdFamily(birdFamily)); + } + + /** + * 修改鸟类科 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:family:edit')") + @Log(title = "鸟类科", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdFamily birdFamily) { + return toAjax(birdFamilyService.updateBirdFamily(birdFamily)); + } + + /** + * 删除鸟类科 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:family:remove')") + @Log(title = "鸟类科", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdFamilyService.deleteBirdFamilyByIds(ids)); + } + + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(BirdFamily.class); + List list = util.importExcel(file.getInputStream()); + String message = birdFamilyService.importData(list, updateSupport); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil<>(BirdFamily.class); + util.importTemplateExcel(response, "鸟类科数据"); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFlyingInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFlyingInfoController.java new file mode 100644 index 0000000..777f8cd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdFlyingInfoController.java @@ -0,0 +1,96 @@ +package net.hzvtc.bird.controller; + +import net.hzvtc.bird.domain.BirdFlyingInfo; +import net.hzvtc.bird.service.BirdFlyingInfoService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 鸟类越冬飞行路线图Controller + * + * @author admin + * @date 2022-07-30 + */ +@RestController +@RequestMapping("/birdInfo/flyingInfo") +public class BirdFlyingInfoController extends BaseController { + @Autowired + private BirdFlyingInfoService birdFlyingInfoService; + + @GetMapping("/allList") + public AjaxResult getAll() { + return AjaxResult.success(birdFlyingInfoService.getAllBirdFlyingInfoList()); + } + + /** + * 查询鸟类越冬飞行路线图列表 + */ +// @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:list')") + @GetMapping("/list") + public TableDataInfo list(BirdFlyingInfo birdFlyingInfo) { + startPage(); + List list = birdFlyingInfoService.selectBirdFlyingInfoList(birdFlyingInfo); + return getDataTable(list); + } + + /** + * 导出鸟类越冬飞行路线图列表 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:export')") + @Log(title = "鸟类越冬飞行路线图", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdFlyingInfo birdFlyingInfo) { + List list = birdFlyingInfoService.selectBirdFlyingInfoList(birdFlyingInfo); + ExcelUtil util = new ExcelUtil(BirdFlyingInfo.class); + util.exportExcel(response, list, "鸟类越冬飞行路线图数据"); + } + + /** + * 获取鸟类越冬飞行路线图详细信息 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdFlyingInfoService.selectBirdFlyingInfoById(id)); + } + + /** + * 新增鸟类越冬飞行路线图 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:add')") + @Log(title = "鸟类越冬飞行路线图", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdFlyingInfo birdFlyingInfo) { + return toAjax(birdFlyingInfoService.insertBirdFlyingInfo(birdFlyingInfo)); + } + + /** + * 修改鸟类越冬飞行路线图 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:edit')") + @Log(title = "鸟类越冬飞行路线图", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdFlyingInfo birdFlyingInfo) { + return toAjax(birdFlyingInfoService.updateBirdFlyingInfo(birdFlyingInfo)); + } + + /** + * 删除鸟类越冬飞行路线图 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:flyingInfo:remove')") + @Log(title = "鸟类越冬飞行路线图", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdFlyingInfoService.deleteBirdFlyingInfoByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdGenusController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdGenusController.java new file mode 100644 index 0000000..3d8fea2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdGenusController.java @@ -0,0 +1,113 @@ +package net.hzvtc.bird.controller; + +import net.hzvtc.bird.domain.BirdGenus; +import net.hzvtc.bird.service.BirdGenusService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 鸟类属Controller + * + * @author admin + * @date 2022-07-18 + */ +@RestController +@RequestMapping("/birdInfo/genus") +public class BirdGenusController extends BaseController { + @Autowired + private BirdGenusService birdGenusService; + + /** + * 查询鸟类属列表 + */ +// @PreAuthorize("@ss.hasPermi('birdInfo:genus:list')") + @GetMapping("/list") + public TableDataInfo list(BirdGenus birdGenus) { + startPage(); + List list = birdGenusService.selectBirdGenusList(birdGenus); + return getDataTable(list); + } + + + @GetMapping("/listByFamilyId") + public AjaxResult getBirdFamilyListByCatalogueId(@RequestParam(name = "id") Long id) { + return AjaxResult.success(birdGenusService.getBirdGenusListByFamilyId(id)); + } + + + /** + * 导出鸟类属列表 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:genus:export')") + @Log(title = "鸟类属", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdGenus birdGenus) { + List list = birdGenusService.selectBirdGenusList(birdGenus); + ExcelUtil util = new ExcelUtil(BirdGenus.class); + util.exportExcel(response, list, "鸟类属数据"); + } + + /** + * 获取鸟类属详细信息 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:genus:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdGenusService.selectBirdGenusById(id)); + } + + /** + * 新增鸟类属 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:genus:add')") + @Log(title = "鸟类属", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdGenus birdGenus) { + return toAjax(birdGenusService.insertBirdGenus(birdGenus)); + } + + /** + * 修改鸟类属 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:genus:edit')") + @Log(title = "鸟类属", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdGenus birdGenus) { + return toAjax(birdGenusService.updateBirdGenus(birdGenus)); + } + + /** + * 删除鸟类属 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:genus:remove')") + @Log(title = "鸟类属", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdGenusService.deleteBirdGenusByIds(ids)); + } + + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(BirdGenus.class); + List list = util.importExcel(file.getInputStream()); + String message = birdGenusService.importData(list, updateSupport); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil<>(BirdGenus.class); + util.importTemplateExcel(response, "鸟类科数据"); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdLeaveArriveInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdLeaveArriveInfoController.java new file mode 100644 index 0000000..ac30f47 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdLeaveArriveInfoController.java @@ -0,0 +1,98 @@ +package net.hzvtc.bird.controller; + +import java.util.List; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.bird.domain.BirdLeaveArriveInfo; +import net.hzvtc.bird.service.BirdLeaveArriveInfoService; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.common.core.page.TableDataInfo; + +/** + * 候鸟飞离和抵达时间Controller + * + * @author admin + * @date 2023-03-27 + */ +@RestController +@RequestMapping("/bird/leaveArrive") +public class BirdLeaveArriveInfoController extends BaseController { + @Autowired + private BirdLeaveArriveInfoService birdLeaveArriveInfoService; + +/** + * 查询候鸟飞离和抵达时间列表 + */ +@PreAuthorize("@ss.hasPermi('bird:leaveArrive:list')") +@GetMapping("/list") + public TableDataInfo list(BirdLeaveArriveInfo birdLeaveArriveInfo) { + startPage(); + List list = birdLeaveArriveInfoService.selectBirdLeaveArriveInfoList(birdLeaveArriveInfo); + return getDataTable(list); + } + + /** + * 导出候鸟飞离和抵达时间列表 + */ + @PreAuthorize("@ss.hasPermi('bird:leaveArrive:export')") + @Log(title = "候鸟飞离和抵达时间", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdLeaveArriveInfo birdLeaveArriveInfo) { + List list = birdLeaveArriveInfoService.selectBirdLeaveArriveInfoList(birdLeaveArriveInfo); + ExcelUtil util = new ExcelUtil(BirdLeaveArriveInfo. class); + util.exportExcel(response, list, "候鸟飞离和抵达时间数据"); + } + + /** + * 获取候鸟飞离和抵达时间详细信息 + */ + @PreAuthorize("@ss.hasPermi('bird:leaveArrive:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdLeaveArriveInfoService.selectBirdLeaveArriveInfoById(id)); + } + + /** + * 新增候鸟飞离和抵达时间 + */ + @PreAuthorize("@ss.hasPermi('bird:leaveArrive:add')") + @Log(title = "候鸟飞离和抵达时间", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdLeaveArriveInfo birdLeaveArriveInfo) { + return toAjax(birdLeaveArriveInfoService.insertBirdLeaveArriveInfo(birdLeaveArriveInfo)); + } + + /** + * 修改候鸟飞离和抵达时间 + */ + @PreAuthorize("@ss.hasPermi('bird:leaveArrive:edit')") + @Log(title = "候鸟飞离和抵达时间", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdLeaveArriveInfo birdLeaveArriveInfo) { + return toAjax(birdLeaveArriveInfoService.updateBirdLeaveArriveInfo(birdLeaveArriveInfo)); + } + + /** + * 删除候鸟飞离和抵达时间 + */ + @PreAuthorize("@ss.hasPermi('bird:leaveArrive:remove')") + @Log(title = "候鸟飞离和抵达时间", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdLeaveArriveInfoService.deleteBirdLeaveArriveInfoByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdMediaController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdMediaController.java new file mode 100644 index 0000000..5c689d8 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdMediaController.java @@ -0,0 +1,103 @@ +package net.hzvtc.bird.controller; + +import net.hzvtc.bird.domain.BirdMedia; +import net.hzvtc.bird.service.BirdMediaService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 鸟类媒体Controller + * + * @author admin + * @date 2022-07-19 + */ +@RestController +@RequestMapping("/birdInfo/media") +public class BirdMediaController extends BaseController { + @Autowired + private BirdMediaService birdMediaService; + + /** + * 查询鸟类媒体列表 + */ +// @PreAuthorize("@ss.hasPermi('birdInfo:media:list')") + @GetMapping("/list") + public TableDataInfo list(BirdMedia birdMedia) { + startPage(); + List list = birdMediaService.selectBirdMediaList(birdMedia); + return getDataTable(list); + } + + /** + * 导出鸟类媒体列表 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:media:export')") + @Log(title = "鸟类媒体", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, BirdMedia birdMedia) { + List list = birdMediaService.selectBirdMediaList(birdMedia); + ExcelUtil util = new ExcelUtil(BirdMedia.class); + util.exportExcel(response, list, "鸟类媒体数据"); + } + + /** + * 获取鸟类媒体详细信息 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:media:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(birdMediaService.selectBirdMediaById(id)); + } + + /** + * 新增鸟类媒体 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:media:add')") + @Log(title = "鸟类媒体", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdMedia birdMedia) { + return toAjax(birdMediaService.insertBirdMedia(birdMedia)); + } + + /** + * 修改鸟类媒体 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:media:edit')") + @Log(title = "鸟类媒体", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdMedia birdMedia) { + return toAjax(birdMediaService.updateBirdMedia(birdMedia)); + } + + /** + * 删除鸟类媒体 + */ + @PreAuthorize("@ss.hasPermi('birdInfo:media:remove')") + @Log(title = "鸟类媒体", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(birdMediaService.deleteBirdMediaByIds(ids)); + } + + @PostMapping("/upload") + public AjaxResult upload(MultipartFile file) { + return birdMediaService.uploadFile(file); + } + + @GetMapping("/listForPage") + public AjaxResult listByParam(BirdMedia birdMedia) { + return AjaxResult.success(birdMediaService.selectBirdMediaList(birdMedia)); + } + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdSpeciesController.java b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdSpeciesController.java new file mode 100644 index 0000000..ffd177b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/controller/BirdSpeciesController.java @@ -0,0 +1,183 @@ +package net.hzvtc.bird.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.domain.SpeciesAnswer; +import net.hzvtc.bird.domain.SpeciesIntro; +import net.hzvtc.bird.domain.SpeciesList; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.bird.service.SpeciesAnswerService; +import net.hzvtc.bird.service.SpeciesIntroService; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.domain.ResultMedia; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping(value={"/birdInfo/species"}) +public class BirdSpeciesController +extends BaseController { + private static final Logger log = LoggerFactory.getLogger(BirdSpeciesController.class); + @Autowired + private BirdSpeciesService birdSpeciesService; + @Autowired + private SpeciesIntroService speciesIntroService; + @Autowired + private SpeciesAnswerService speciesAnswerService; + + @GetMapping(value={"/list"}) + public TableDataInfo list(BirdSpecies birdSpecies) { + this.startPage(); + List list = this.birdSpeciesService.selectBirdSpeciesList(birdSpecies); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('birdInfo:species:export')") + @Log(title="\u9e1f\u7c7b\u79cd\u7c7b", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, BirdSpecies birdSpecies) { + List list = this.birdSpeciesService.selectBirdSpeciesList(birdSpecies); + ExcelUtil util = new ExcelUtil(BirdSpecies.class); + util.exportExcel(response, list, "\u9e1f\u7c7b\u79cd\u7c7b\u6570\u636e"); + } + + @GetMapping(value={"/{id}"}) + public AjaxResult getInfo(@PathVariable(value="id") Long id) { + return AjaxResult.success((Object)((Object)this.birdSpeciesService.selectBirdSpeciesById(id))); + } + + @PreAuthorize(value="@ss.hasPermi('birdInfo:species:add')") + @Log(title="\u9e1f\u7c7b\u79cd\u7c7b", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody BirdSpecies birdSpecies) { + return this.toAjax(this.birdSpeciesService.insertBirdSpecies(birdSpecies)); + } + + @PreAuthorize(value="@ss.hasPermi('birdInfo:species:edit')") + @Log(title="\u9e1f\u7c7b\u79cd\u7c7b", businessType=BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody BirdSpecies birdSpecies) { + return this.toAjax(this.birdSpeciesService.updateBirdSpecies(birdSpecies)); + } + + @PreAuthorize(value="@ss.hasPermi('birdInfo:species:remove')") + @Log(title="\u9e1f\u7c7b\u79cd\u7c7b", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{ids}"}) + public AjaxResult remove(@PathVariable Long[] ids) { + return this.toAjax(this.birdSpeciesService.deleteBirdSpeciesByIds(ids)); + } + + @PostMapping(value={"/importData"}) + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil(BirdSpecies.class); + List list = util.importExcel(file.getInputStream()); + String message = this.birdSpeciesService.importData(list, updateSupport); + return AjaxResult.success((String)message); + } + + @PostMapping(value={"/importTemplate"}) + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil(BirdSpecies.class); + util.importTemplateExcel(response, "\u9e1f\u7c7b\u6570\u636e"); + } + + @PostMapping(value={"/birdResultMedias"}) + public TableDataInfo getBirdResultMediasByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + this.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize); + List list = this.birdSpeciesService.getResultMediaListByParam(params); + return this.getDataTable(list); + } + + @PostMapping(value={"/birdResultAudioMedias"}) + public TableDataInfo getBirdResultAudioMediasByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + this.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize); + List list = this.birdSpeciesService.getResultAudioMediaListByParam(params); + return this.getDataTable(list); + } + + @PostMapping(value={"/birdMediaesByParam"}) + public TableDataInfo getSpeciesResultMediasByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + pageNum = pageNum == null ? 1 : pageNum; + Integer pageSize = params.getInteger("pageSize"); + pageSize = pageSize == null ? 10 : pageSize; + this.startPage(pageNum, pageSize); + return this.getDataTable(this.birdSpeciesService.getBirdMediaListByParam(params)); + } + + @PostMapping(value={"/birdMediaesForPageByParam"}) + public TableDataInfo getSpeciesResultMediasForPageFirstByParam(@RequestBody JSONObject params) { + return this.getDataTable(this.birdSpeciesService.getBirdMediaListByParam(params)); + } + + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u9644\u4ef6\u5bfc\u51fa", businessType=BusinessType.EXPORT) + @PostMapping(value={"/mediaExport"}) + public void export(HttpServletResponse response, @RequestBody JSONObject params) { + List list = this.birdSpeciesService.getResultMediaListByParam(params); + ExcelUtil util = new ExcelUtil(ResultMedia.class); + util.exportExcel(response, list, "\u76d1\u6d4b\u5a92\u4f53\u6570\u636e"); + } + + @Log(title="media\u6570\u636e\u6062\u590d", businessType=BusinessType.UPDATE) + @PostMapping(value={"/media/recovery"}) + public AjaxResult recoverBirdMediaByParam(@RequestBody JSONObject params) { + return AjaxResult.success((Object)this.birdSpeciesService.recoverResultMediaStateByParam(params)); + } + + @PostMapping(value={"/getListForSelect"}) + public AjaxResult getSpeciesSelectListFromDetails(@RequestBody JSONObject params) { + return AjaxResult.success(this.birdSpeciesService.getSpeciesSelectListFromDetails(params)); + } + + @GetMapping(value={"/getSpeciesListPages"}) + public TableDataInfo getSpeciesListPages(SpeciesList speciesList) { + this.startPage(); + List list = this.birdSpeciesService.getSpeciesListPages(); + return this.getDataTable(list); + } + + @GetMapping(value={"/getSpeciesIntroListPages"}) + public TableDataInfo getSpeciesIntroListPages(SpeciesIntro param) { + this.startPage(); + List list = this.speciesIntroService.getSpeciesIntroList(param); + return this.getDataTable(list); + } + + @GetMapping(value={"/getSpeciesIntroOtherListPages"}) + public TableDataInfo getSpeciesIntroOtherListPages(SpeciesIntro param) { + this.startPage(); + List list = this.speciesIntroService.getSpeciesIntroOtherList(param); + return this.getDataTable(list); + } + + @GetMapping(value={"/getSpeciesAnswerListPages"}) + public TableDataInfo getSpeciesAnswerListPages(SpeciesAnswer param) { + this.startPage(); + List list = this.speciesAnswerService.getSpeciesAnswerList(); + return this.getDataTable(list); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdCatalogue.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdCatalogue.java new file mode 100644 index 0000000..22ce74c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdCatalogue.java @@ -0,0 +1,18 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdCatalogue") +@Data +public class BirdCatalogue extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private String scientificName; + private String englishName; + private String description; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFamily.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFamily.java new file mode 100644 index 0000000..21042cc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFamily.java @@ -0,0 +1,20 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdFamily") +@Data +public class BirdFamily extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String familyName; + private String scientificName; + private String englishName; + private String description; + private Long catalogueId; + private String catalogueName; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFlyingInfo.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFlyingInfo.java new file mode 100644 index 0000000..500a80d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdFlyingInfo.java @@ -0,0 +1,21 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdFlyingInfo") +@Data +public class BirdFlyingInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private String source; + private String sourceLongitude; + private String sourceLatitude; + private String target; + private String targetLongitude; + private String targetLatitude; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdGenus.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdGenus.java new file mode 100644 index 0000000..f488927 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdGenus.java @@ -0,0 +1,21 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdGenus") +@Data +public class BirdGenus extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private String scientificName; + private String englishName; + private Long catalogueId; + private Long familyId; + private String description; + private String familyName; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdLeaveArriveInfo.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdLeaveArriveInfo.java new file mode 100644 index 0000000..0cc4e2f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdLeaveArriveInfo.java @@ -0,0 +1,23 @@ +package net.hzvtc.bird.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdLeaveArriveInfo") +@Data +public class BirdLeaveArriveInfo { + private static final long serialVersionUID = 1L; + private Long id; + private Long areaId; + private String name; + private Long speciesId; + private int statYear; + private Date leaveDate; + private String strLeaveDate; + private Date arriveDate; + private String strArriveDate; + private int isDeleted = 0; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdMedia.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdMedia.java new file mode 100644 index 0000000..7768ccd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdMedia.java @@ -0,0 +1,20 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdMedia") +@Data +public class BirdMedia extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private String name; + private String mediaType; + private String url; + private String description; + private Integer pcShow = 0; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdSpecies.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdSpecies.java new file mode 100644 index 0000000..700c3a6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/BirdSpecies.java @@ -0,0 +1,39 @@ +package net.hzvtc.bird.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdSpecies") +@Data +public class BirdSpecies extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String name; + private String scientificName; + private String englishName; + private String morphology; + private String habitat; + private String voice; + private String distribution; + private String overseasDistribution; + private String domesticDistribution; + private String avatar; + private String protectLevel; + private String protectLevelName; + private String iucn; + private String iucnName; + private String residenceType; + private String speciesType; + private String speciesTypeName; + private Long catalogueId; + private String catalogueName; + private Long familyId; + private String familyName; + private Long genusId; + private String genusName; + private List mediaList; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswer.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswer.java new file mode 100644 index 0000000..c616391 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswer.java @@ -0,0 +1,18 @@ +package net.hzvtc.bird.domain; + + + +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.ibatis.type.Alias; +import lombok.Data; + +@Alias(value="SpeciesAnswer") +@Data +public class SpeciesAnswer extends BaseEntity { + private Long id; + private Long speciesId; + private String speciesName; + private String scientificName; +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswerItem.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswerItem.java new file mode 100644 index 0000000..0f4c4b3 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesAnswerItem.java @@ -0,0 +1,16 @@ +package net.hzvtc.bird.domain; + + +import org.apache.ibatis.type.Alias; +import lombok.Data; + +@Alias(value="SpeciesAnswerItem") +@Data +public class SpeciesAnswerItem { + private Long id; + private String cn; + private String en; + private Long pid; +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesIntro.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesIntro.java new file mode 100644 index 0000000..b966877 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesIntro.java @@ -0,0 +1,25 @@ +package net.hzvtc.bird.domain; + + + +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.ibatis.type.Alias; +import lombok.Data; + +@Alias(value="SpeciesIntro") +@Data +public class SpeciesIntro extends BaseEntity { + private Long id; + private Long speciesId; + private String speciesName; + private String scientificName; + private String audio; + private String frame; + private String image; + private String spectrogram; + private String txt; + private String video; + private String videoImg; +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesList.java b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesList.java new file mode 100644 index 0000000..57a8f16 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/domain/SpeciesList.java @@ -0,0 +1,21 @@ +package net.hzvtc.bird.domain; + + + +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.ibatis.type.Alias; +import lombok.Data; + +@Alias(value="SpeciesList") +@Data +public class SpeciesList extends BaseEntity { + private Long id; + private String name; + private String scientificName; + private String mediaUrl; + private String catalogueName; + private String familyName; + private String genusName; +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdCatalogueMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdCatalogueMapper.java new file mode 100644 index 0000000..0271434 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdCatalogueMapper.java @@ -0,0 +1,24 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.BirdCatalogue; + +public interface BirdCatalogueMapper { + public BirdCatalogue selectBirdCatalogueById(Long var1); + + public BirdCatalogue selectBirdCatalogueByName(String var1); + + public List selectBirdCatalogueList(BirdCatalogue var1); + + public List getBirdCatalogueSelectList(); + + public int insertBirdCatalogue(BirdCatalogue var1); + + public int updateBirdCatalogue(BirdCatalogue var1); + + public int deleteBirdCatalogueById(Long var1); + + public int deleteBirdCatalogueByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFamilyMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFamilyMapper.java new file mode 100644 index 0000000..a6f242b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFamilyMapper.java @@ -0,0 +1,24 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.BirdFamily; + +public interface BirdFamilyMapper { + public BirdFamily selectBirdFamilyById(Long var1); + + public BirdFamily selectBirdFamilyByName(String var1); + + public List selectBirdFamilyList(BirdFamily var1); + + public List getBirdFamilyListByCataId(Long var1); + + public int insertBirdFamily(BirdFamily var1); + + public int updateBirdFamily(BirdFamily var1); + + public int deleteBirdFamilyById(Long var1); + + public int deleteBirdFamilyByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFlyingInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFlyingInfoMapper.java new file mode 100644 index 0000000..f9b1191 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdFlyingInfoMapper.java @@ -0,0 +1,63 @@ +package net.hzvtc.bird.mapper; + +import net.hzvtc.bird.domain.BirdFlyingInfo; + +import java.util.List; + +/** + * 鸟类越冬飞行路线图Mapper接口 + * + * @author admin + * @date 2022-07-30 + */ +public interface BirdFlyingInfoMapper { + /** + * 查询鸟类越冬飞行路线图 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 鸟类越冬飞行路线图 + */ + public BirdFlyingInfo selectBirdFlyingInfoById(Long id); + + /** + * 查询鸟类越冬飞行路线图列表 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 鸟类越冬飞行路线图集合 + */ + public List selectBirdFlyingInfoList(BirdFlyingInfo birdFlyingInfo); + + public List getAllBirdFlyingInfoList(); + + /** + * 新增鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + public int insertBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo); + + /** + * 修改鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + public int updateBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo); + + /** + * 删除鸟类越冬飞行路线图 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 结果 + */ + public int deleteBirdFlyingInfoById(Long id); + + /** + * 批量删除鸟类越冬飞行路线图 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteBirdFlyingInfoByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdGenusMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdGenusMapper.java new file mode 100644 index 0000000..cd168e2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdGenusMapper.java @@ -0,0 +1,24 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.BirdGenus; + +public interface BirdGenusMapper { + public BirdGenus selectBirdGenusById(Long var1); + + public BirdGenus selectBirdGenusByName(String var1); + + public List selectBirdGenusList(BirdGenus var1); + + public List getBirdGenusListByFamilyId(Long var1); + + public int insertBirdGenus(BirdGenus var1); + + public int updateBirdGenus(BirdGenus var1); + + public int deleteBirdGenusById(Long var1); + + public int deleteBirdGenusByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdLeaveArriveInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdLeaveArriveInfoMapper.java new file mode 100644 index 0000000..a091e40 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdLeaveArriveInfoMapper.java @@ -0,0 +1,27 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.bird.domain.BirdLeaveArriveInfo; + +public interface BirdLeaveArriveInfoMapper { + public BirdLeaveArriveInfo selectBirdLeaveArriveInfoById(Long var1); + + public List selectBirdLeaveArriveInfoList(BirdLeaveArriveInfo var1); + + public List getBirdArrivalDateByParam(Map var1); + + public List getBirdLeaveDateByParam(Map var1); + + public int insertBirdLeaveArriveInfo(BirdLeaveArriveInfo var1); + + public int batchInsertBirdLeaveArriveInfo(List var1); + + public int updateBirdLeaveArriveInfo(BirdLeaveArriveInfo var1); + + public int deleteBirdLeaveArriveInfoById(Long var1); + + public int deleteBirdLeaveArriveInfoByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdMediaMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdMediaMapper.java new file mode 100644 index 0000000..d7b5345 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdMediaMapper.java @@ -0,0 +1,22 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.BirdMedia; + +public interface BirdMediaMapper { + public BirdMedia selectBirdMediaById(Long var1); + + public List selectBirdMediaList(BirdMedia var1); + + public int insertBirdMedia(BirdMedia var1); + + public int updateBirdMedia(BirdMedia var1); + + public int deleteBirdMediaById(Long var1); + + public int deleteBirdMediaByIds(Long[] var1); + + public String getBirdIconImageBySpeciesId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdSpeciesMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdSpeciesMapper.java new file mode 100644 index 0000000..181b10c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/BirdSpeciesMapper.java @@ -0,0 +1,42 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.domain.SpeciesList; + +public interface BirdSpeciesMapper { + public BirdSpecies selectBirdSpeciesById(Long var1); + + public BirdSpecies selectBirdSpeciesForEsById(Long var1); + + public BirdSpecies selectBirdSpeciesByName(String var1); + + public List selectBirdSpeciesList(BirdSpecies var1); + + public List getBirdSpeciesListByQuery(Map var1); + + public int insertBirdSpecies(BirdSpecies var1); + + public int updateBirdSpecies(BirdSpecies var1); + + public int deleteBirdSpeciesById(Long var1); + + public int deleteBirdSpeciesByIds(Long[] var1); + + public List getBirdSpeciesInfoByName(String var1); + + public Long getBirdSpeciesIdByName(String var1); + + public Long getBirdSpeciesIdByScientificName(String var1); + + public BirdSpecies getBirdSpeciesInfoById(Long var1); + + public List getSpeciesSelectListByParam(Map var1); + + public List getSpeciesSelectListFromDetails(Map var1); + + public List getSpeciesListPages(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesAnswerMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesAnswerMapper.java new file mode 100644 index 0000000..8b6e4f5 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesAnswerMapper.java @@ -0,0 +1,15 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.SpeciesAnswer; +import net.hzvtc.bird.domain.SpeciesAnswerItem; + +public interface SpeciesAnswerMapper { + public int addSpeciesAnswer(SpeciesAnswer var1); + + public int batchAddSpeciesAnswerItem(List var1); + + public List getSpeciesAnswerList(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesIntroMapper.java b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesIntroMapper.java new file mode 100644 index 0000000..a27f05b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/mapper/SpeciesIntroMapper.java @@ -0,0 +1,18 @@ +package net.hzvtc.bird.mapper; + +import java.util.List; +import net.hzvtc.bird.domain.SpeciesIntro; + +public interface SpeciesIntroMapper { + public int addSpeciesIntro(SpeciesIntro var1); + + public int batchAddSpeciesIntro(List var1); + + public List getSpeciesIntroList(SpeciesIntro var1); + + public List getSpeciesIntroOtherList(SpeciesIntro var1); + + public void updateImageUrl(SpeciesIntro var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdCatalogueService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdCatalogueService.java new file mode 100644 index 0000000..be02b26 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdCatalogueService.java @@ -0,0 +1,26 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.BirdCatalogue; + +public interface BirdCatalogueService { + public BirdCatalogue selectBirdCatalogueById(Long var1); + + public BirdCatalogue selectBirdCatalogueByName(String var1); + + public List selectBirdCatalogueList(BirdCatalogue var1); + + public List getBirdCatalogueSelectList(); + + public int insertBirdCatalogue(BirdCatalogue var1); + + public int updateBirdCatalogue(BirdCatalogue var1); + + public int deleteBirdCatalogueByIds(Long[] var1); + + public int deleteBirdCatalogueById(Long var1); + + public String importData(List var1, boolean var2); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFamilyService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFamilyService.java new file mode 100644 index 0000000..526a18f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFamilyService.java @@ -0,0 +1,26 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.BirdFamily; + +public interface BirdFamilyService { + public BirdFamily selectBirdFamilyById(Long var1); + + public List selectBirdFamilyList(BirdFamily var1); + + public List getBirdFamilyListByCataId(Long var1); + + public int insertBirdFamily(BirdFamily var1); + + public int updateBirdFamily(BirdFamily var1); + + public int deleteBirdFamilyByIds(Long[] var1); + + public int deleteBirdFamilyById(Long var1); + + public String importData(List var1, boolean var2); + + public BirdFamily selectBirdFamilyByName(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFlyingInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFlyingInfoService.java new file mode 100644 index 0000000..5cabec7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdFlyingInfoService.java @@ -0,0 +1,63 @@ +package net.hzvtc.bird.service; + +import net.hzvtc.bird.domain.BirdFlyingInfo; + +import java.util.List; + +/** + * 鸟类越冬飞行路线图Service接口 + * + * @author admin + * @date 2022-07-30 + */ +public interface BirdFlyingInfoService { + /** + * 查询鸟类越冬飞行路线图 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 鸟类越冬飞行路线图 + */ + public BirdFlyingInfo selectBirdFlyingInfoById(Long id); + + /** + * 查询鸟类越冬飞行路线图列表 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 鸟类越冬飞行路线图集合 + */ + public List selectBirdFlyingInfoList(BirdFlyingInfo birdFlyingInfo); + + public List getAllBirdFlyingInfoList(); + + /** + * 新增鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + public int insertBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo); + + /** + * 修改鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + public int updateBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo); + + /** + * 批量删除鸟类越冬飞行路线图 + * + * @param ids 需要删除的鸟类越冬飞行路线图主键集合 + * @return 结果 + */ + public int deleteBirdFlyingInfoByIds(Long[] ids); + + /** + * 删除鸟类越冬飞行路线图信息 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 结果 + */ + public int deleteBirdFlyingInfoById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdGenusService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdGenusService.java new file mode 100644 index 0000000..ccfd1ef --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdGenusService.java @@ -0,0 +1,26 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.BirdGenus; + +public interface BirdGenusService { + public BirdGenus selectBirdGenusById(Long var1); + + public List selectBirdGenusList(BirdGenus var1); + + public int insertBirdGenus(BirdGenus var1); + + public int updateBirdGenus(BirdGenus var1); + + public int deleteBirdGenusByIds(Long[] var1); + + public int deleteBirdGenusById(Long var1); + + public List getBirdGenusListByFamilyId(Long var1); + + public String importData(List var1, boolean var2); + + public BirdGenus selectBirdGenusByName(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdLeaveArriveInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdLeaveArriveInfoService.java new file mode 100644 index 0000000..c3e916f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdLeaveArriveInfoService.java @@ -0,0 +1,22 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.BirdLeaveArriveInfo; + +public interface BirdLeaveArriveInfoService { + public BirdLeaveArriveInfo selectBirdLeaveArriveInfoById(Long var1); + + public List selectBirdLeaveArriveInfoList(BirdLeaveArriveInfo var1); + + public int insertBirdLeaveArriveInfo(BirdLeaveArriveInfo var1); + + public int updateBirdLeaveArriveInfo(BirdLeaveArriveInfo var1); + + public int deleteBirdLeaveArriveInfoByIds(Long[] var1); + + public int deleteBirdLeaveArriveInfoById(Long var1); + + public void calcBirdLeaveArriveInfoByParam(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdMediaService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdMediaService.java new file mode 100644 index 0000000..442f54c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdMediaService.java @@ -0,0 +1,26 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.BirdMedia; +import net.hzvtc.common.core.domain.AjaxResult; +import org.springframework.web.multipart.MultipartFile; + +public interface BirdMediaService { + public BirdMedia selectBirdMediaById(Long var1); + + public List selectBirdMediaList(BirdMedia var1); + + public int insertBirdMedia(BirdMedia var1); + + public int updateBirdMedia(BirdMedia var1); + + public int deleteBirdMediaByIds(Long[] var1); + + public int deleteBirdMediaById(Long var1); + + public AjaxResult uploadFile(MultipartFile var1); + + public String getBirdIconImageBySpeciesId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdSpeciesService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdSpeciesService.java new file mode 100644 index 0000000..49fb028 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/BirdSpeciesService.java @@ -0,0 +1,56 @@ +package net.hzvtc.bird.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.domain.SpeciesList; +import net.hzvtc.data.check.domain.ResultMedia; + +public interface BirdSpeciesService { + public BirdSpecies selectBirdSpeciesById(Long var1); + + public BirdSpecies selectBirdSpeciesByName(String var1); + + public List selectBirdSpeciesList(BirdSpecies var1); + + public int insertBirdSpecies(BirdSpecies var1); + + public int updateBirdSpecies(BirdSpecies var1); + + public int deleteBirdSpeciesByIds(Long[] var1); + + public int deleteBirdSpeciesById(Long var1); + + public String importData(List var1, boolean var2); + + public List getResultMediaListByParam(JSONObject var1); + + public int recoverResultMediaStateByParam(JSONObject var1); + + public List getResultAudioMediaListByParam(JSONObject var1); + + public List getBirdMediaListByParam(JSONObject var1); + + public List getBirdSpeciesListByQuery(Map var1); + + public Long getBirdSpeciesInfoIdByName(String var1); + + public Long getBirdSpeciesInfoIdByScientificName(String var1); + + public BirdSpecies selectBirdSpeciesForEsById(Long var1); + + public BirdSpecies getBirdSpeciesInfoById(Long var1); + + public List getSpeciesSelectListByParam(Map var1); + + public Long getBirdSpeciesIdByScientificName(String var1); + + public Long getBirdSpeciesIdByName(String var1); + + public List getSpeciesSelectListFromDetails(JSONObject var1); + + public List getSpeciesListPages(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesAnswerService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesAnswerService.java new file mode 100644 index 0000000..c3e7699 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesAnswerService.java @@ -0,0 +1,15 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.SpeciesAnswer; +import net.hzvtc.bird.domain.SpeciesAnswerItem; + +public interface SpeciesAnswerService { + public void addSpeciesAnswer(SpeciesAnswer var1); + + public void batchAddSpeciesAnswerItem(List var1); + + public List getSpeciesAnswerList(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesIntroService.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesIntroService.java new file mode 100644 index 0000000..708daf5 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/SpeciesIntroService.java @@ -0,0 +1,18 @@ +package net.hzvtc.bird.service; + +import java.util.List; +import net.hzvtc.bird.domain.SpeciesIntro; + +public interface SpeciesIntroService { + public int addSpeciesIntro(SpeciesIntro var1); + + public void batchAddSpeciesIntro(List var1); + + public List getSpeciesIntroList(SpeciesIntro var1); + + public List getSpeciesIntroOtherList(SpeciesIntro var1); + + public void updateImageUrl(SpeciesIntro var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdCatalogueServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdCatalogueServiceImpl.java new file mode 100644 index 0000000..03fd9b9 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdCatalogueServiceImpl.java @@ -0,0 +1,153 @@ +package net.hzvtc.bird.service.impl; + +import net.hzvtc.bird.domain.BirdCatalogue; +import net.hzvtc.bird.mapper.BirdCatalogueMapper; +import net.hzvtc.bird.service.BirdCatalogueService; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.validation.Validator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 鸟类目Service业务层处理 + * + * @author admin + * @date 2022-07-16 + */ +@Service +public class BirdCatalogueServiceImpl implements BirdCatalogueService { + private static final Logger log = LoggerFactory.getLogger(BirdCatalogueServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private BirdCatalogueMapper birdCatalogueMapper; + + /** + * 查询鸟类目 + * + * @param id 鸟类目主键 + * @return 鸟类目 + */ + @Override + public BirdCatalogue selectBirdCatalogueById(Long id) { + return birdCatalogueMapper.selectBirdCatalogueById(id); + } + + @Override + public BirdCatalogue selectBirdCatalogueByName(String name) { + return birdCatalogueMapper.selectBirdCatalogueByName(name); + } + + /** + * 查询鸟类目列表 + * + * @param birdCatalogue 鸟类目 + * @return 鸟类目 + */ + @Override + public List selectBirdCatalogueList(BirdCatalogue birdCatalogue) { + return birdCatalogueMapper.selectBirdCatalogueList(birdCatalogue); + } + + @Override + public List getBirdCatalogueSelectList() { + return birdCatalogueMapper.getBirdCatalogueSelectList(); + } + + /** + * 新增鸟类目 + * + * @param birdCatalogue 鸟类目 + * @return 结果 + */ + @Override + public int insertBirdCatalogue(BirdCatalogue birdCatalogue) { + return birdCatalogueMapper.insertBirdCatalogue(birdCatalogue); + } + + /** + * 修改鸟类目 + * + * @param birdCatalogue 鸟类目 + * @return 结果 + */ + @Override + public int updateBirdCatalogue(BirdCatalogue birdCatalogue) { + return birdCatalogueMapper.updateBirdCatalogue(birdCatalogue); + } + + /** + * 批量删除鸟类目 + * + * @param ids 需要删除的鸟类目主键 + * @return 结果 + */ + @Override + public int deleteBirdCatalogueByIds(Long[] ids) { + return birdCatalogueMapper.deleteBirdCatalogueByIds(ids); + } + + /** + * 删除鸟类目信息 + * + * @param id 鸟类目主键 + * @return 结果 + */ + @Override + public int deleteBirdCatalogueById(Long id) { + return birdCatalogueMapper.deleteBirdCatalogueById(id); + } + + @Override + public String importData(List list, boolean isUpdateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("导入鸟类目数据不能为空!"); + } + AtomicInteger[] successNum = {new AtomicInteger()}; + int[] failureNum = {0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + BirdCatalogue catalogue = birdCatalogueMapper.selectBirdCatalogueByName(data.getName()); + if (Objects.isNull(catalogue)) { + BeanValidators.validateWithException(validator, data); + data.setIsDeleted(0); + insertBirdCatalogue(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟类目 " + data.getName() + " 导入成功"); + } else if (isUpdateSupport) { + BeanValidators.validateWithException(validator, data); + data.setId(catalogue.getId()); + updateBirdCatalogue(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟类目 " + data.getName() + " 更新成功"); + } else { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟类目 " + data.getName() + " 已存在"); + } + } catch (Exception e) { + failureNum[0]++; + String msg = "
" + failureNum + "、鸟类目 " + data.getName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum[0] + " 条数据格式不正确,错误如下:"); + throw new ServiceException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFamilyServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFamilyServiceImpl.java new file mode 100644 index 0000000..54b3120 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFamilyServiceImpl.java @@ -0,0 +1,165 @@ +package net.hzvtc.bird.service.impl; + +import net.hzvtc.bird.domain.BirdCatalogue; +import net.hzvtc.bird.domain.BirdFamily; +import net.hzvtc.bird.mapper.BirdFamilyMapper; +import net.hzvtc.bird.service.BirdCatalogueService; +import net.hzvtc.bird.service.BirdFamilyService; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.validation.Validator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 鸟类科Service业务层处理 + * + * @author admin + * @date 2022-07-16 + */ +@Service +public class BirdFamilyServiceImpl implements BirdFamilyService { + private static final Logger log = LoggerFactory.getLogger(BirdFamilyServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private BirdFamilyMapper birdFamilyMapper; + @Autowired + private BirdCatalogueService catalogueService; + + /** + * 查询鸟类科 + * + * @param id 鸟类科主键 + * @return 鸟类科 + */ + @Override + public BirdFamily selectBirdFamilyById(Long id) { + return birdFamilyMapper.selectBirdFamilyById(id); + } + + /** + * 查询鸟类科列表 + * + * @param birdFamily 鸟类科 + * @return 鸟类科 + */ + @Override + public List selectBirdFamilyList(BirdFamily birdFamily) { + return birdFamilyMapper.selectBirdFamilyList(birdFamily); + } + + @Override + public List getBirdFamilyListByCataId(Long catalogueId) { + return birdFamilyMapper.getBirdFamilyListByCataId(catalogueId); + } + + /** + * 新增鸟类科 + * + * @param birdFamily 鸟类科 + * @return 结果 + */ + @Override + public int insertBirdFamily(BirdFamily birdFamily) { + return birdFamilyMapper.insertBirdFamily(birdFamily); + } + + /** + * 修改鸟类科 + * + * @param birdFamily 鸟类科 + * @return 结果 + */ + @Override + public int updateBirdFamily(BirdFamily birdFamily) { + return birdFamilyMapper.updateBirdFamily(birdFamily); + } + + /** + * 批量删除鸟类科 + * + * @param ids 需要删除的鸟类科主键 + * @return 结果 + */ + @Override + public int deleteBirdFamilyByIds(Long[] ids) { + return birdFamilyMapper.deleteBirdFamilyByIds(ids); + } + + /** + * 删除鸟类科信息 + * + * @param id 鸟类科主键 + * @return 结果 + */ + @Override + public int deleteBirdFamilyById(Long id) { + return birdFamilyMapper.deleteBirdFamilyById(id); + } + + @Override + public String importData(List list, boolean isUpdateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("导入鸟类科数据不能为空!"); + } + AtomicInteger[] successNum = {new AtomicInteger()}; + int[] failureNum = {0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + BirdFamily birdFamily = birdFamilyMapper.selectBirdFamilyByName(data.getFamilyName()); + BirdCatalogue birdCatalogue = catalogueService.selectBirdCatalogueByName(data.getCatalogueName()); + if (Objects.isNull(birdCatalogue)) { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟目 " + data.getFamilyName() + " 不存在"); + } else { + if (Objects.isNull(birdFamily)) { + BeanValidators.validateWithException(validator, data); + data.setIsDeleted(0); + data.setCatalogueId(birdCatalogue.getId()); + insertBirdFamily(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟科 " + data.getFamilyName() + " 导入成功"); + } else if (isUpdateSupport) { + BeanValidators.validateWithException(validator, data); + data.setId(birdFamily.getId()); + data.setCatalogueId(birdCatalogue.getId()); + updateBirdFamily(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟科 " + data.getFamilyName() + " 更新成功"); + } else { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟科 " + data.getFamilyName() + " 已存在"); + } + } + } catch (Exception e) { + failureNum[0]++; + String msg = "
" + failureNum + "、鸟科 " + data.getFamilyName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum[0] + " 条数据格式不正确,错误如下:"); + throw new ServiceException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } + + @Override + public BirdFamily selectBirdFamilyByName(String name) { + return birdFamilyMapper.selectBirdFamilyByName(name); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFlyingInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFlyingInfoServiceImpl.java new file mode 100644 index 0000000..e6c4dd7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdFlyingInfoServiceImpl.java @@ -0,0 +1,92 @@ +package net.hzvtc.bird.service.impl; + +import net.hzvtc.bird.domain.BirdFlyingInfo; +import net.hzvtc.bird.mapper.BirdFlyingInfoMapper; +import net.hzvtc.bird.service.BirdFlyingInfoService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 鸟类越冬飞行路线图Service业务层处理 + * + * @author admin + * @date 2022-07-30 + */ +@Service +public class BirdFlyingInfoServiceImpl implements BirdFlyingInfoService { + @Resource + private BirdFlyingInfoMapper birdFlyingInfoMapper; + + /** + * 查询鸟类越冬飞行路线图 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 鸟类越冬飞行路线图 + */ + @Override + public BirdFlyingInfo selectBirdFlyingInfoById(Long id) { + return birdFlyingInfoMapper.selectBirdFlyingInfoById(id); + } + + /** + * 查询鸟类越冬飞行路线图列表 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 鸟类越冬飞行路线图 + */ + @Override + public List selectBirdFlyingInfoList(BirdFlyingInfo birdFlyingInfo) { + return birdFlyingInfoMapper.selectBirdFlyingInfoList(birdFlyingInfo); + } + + @Override + public List getAllBirdFlyingInfoList() { + return birdFlyingInfoMapper.getAllBirdFlyingInfoList(); + } + + /** + * 新增鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + @Override + public int insertBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo) { + return birdFlyingInfoMapper.insertBirdFlyingInfo(birdFlyingInfo); + } + + /** + * 修改鸟类越冬飞行路线图 + * + * @param birdFlyingInfo 鸟类越冬飞行路线图 + * @return 结果 + */ + @Override + public int updateBirdFlyingInfo(BirdFlyingInfo birdFlyingInfo) { + return birdFlyingInfoMapper.updateBirdFlyingInfo(birdFlyingInfo); + } + + /** + * 批量删除鸟类越冬飞行路线图 + * + * @param ids 需要删除的鸟类越冬飞行路线图主键 + * @return 结果 + */ + @Override + public int deleteBirdFlyingInfoByIds(Long[] ids) { + return birdFlyingInfoMapper.deleteBirdFlyingInfoByIds(ids); + } + + /** + * 删除鸟类越冬飞行路线图信息 + * + * @param id 鸟类越冬飞行路线图主键 + * @return 结果 + */ + @Override + public int deleteBirdFlyingInfoById(Long id) { + return birdFlyingInfoMapper.deleteBirdFlyingInfoById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdGenusServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdGenusServiceImpl.java new file mode 100644 index 0000000..99b4330 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdGenusServiceImpl.java @@ -0,0 +1,170 @@ +package net.hzvtc.bird.service.impl; + +import net.hzvtc.bird.domain.BirdFamily; +import net.hzvtc.bird.domain.BirdGenus; +import net.hzvtc.bird.mapper.BirdGenusMapper; +import net.hzvtc.bird.service.BirdFamilyService; +import net.hzvtc.bird.service.BirdGenusService; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import javax.validation.Validator; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * 鸟类属Service业务层处理 + * + * @author admin + * @date 2022-07-18 + */ +@Service +public class BirdGenusServiceImpl implements BirdGenusService { + private static final Logger log = LoggerFactory.getLogger(BirdGenusServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private BirdGenusMapper birdGenusMapper; + @Autowired + private BirdFamilyService familyService; + + /** + * 查询鸟类属 + * + * @param id 鸟类属主键 + * @return 鸟类属 + */ + @Override + public BirdGenus selectBirdGenusById(Long id) { + BirdGenus data = birdGenusMapper.selectBirdGenusById(id); + if (data.getFamilyId() != null) { + BirdFamily birdFamily = familyService.selectBirdFamilyById(data.getFamilyId()); + data.setCatalogueId(birdFamily.getCatalogueId()); + } + return data; + } + + /** + * 查询鸟类属列表 + * + * @param birdGenus 鸟类属 + * @return 鸟类属 + */ + @Override + public List selectBirdGenusList(BirdGenus birdGenus) { + return birdGenusMapper.selectBirdGenusList(birdGenus); + } + + /** + * 新增鸟类属 + * + * @param birdGenus 鸟类属 + * @return 结果 + */ + @Override + public int insertBirdGenus(BirdGenus birdGenus) { + return birdGenusMapper.insertBirdGenus(birdGenus); + } + + /** + * 修改鸟类属 + * + * @param birdGenus 鸟类属 + * @return 结果 + */ + @Override + public int updateBirdGenus(BirdGenus birdGenus) { + return birdGenusMapper.updateBirdGenus(birdGenus); + } + + /** + * 批量删除鸟类属 + * + * @param ids 需要删除的鸟类属主键 + * @return 结果 + */ + @Override + public int deleteBirdGenusByIds(Long[] ids) { + return birdGenusMapper.deleteBirdGenusByIds(ids); + } + + /** + * 删除鸟类属信息 + * + * @param id 鸟类属主键 + * @return 结果 + */ + @Override + public int deleteBirdGenusById(Long id) { + return birdGenusMapper.deleteBirdGenusById(id); + } + + @Override + public List getBirdGenusListByFamilyId(Long familyId) { + return birdGenusMapper.getBirdGenusListByFamilyId(familyId); + } + + @Override + public String importData(List list, boolean isUpdateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("导入鸟类属数据不能为空!"); + } + AtomicInteger[] successNum = {new AtomicInteger()}; + int[] failureNum = {0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + BirdGenus birdGenus = birdGenusMapper.selectBirdGenusByName(data.getName()); + BirdFamily birdFamily = familyService.selectBirdFamilyByName(data.getFamilyName()); + if (Objects.isNull(birdFamily)) { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟科 " + data.getFamilyName() + " 不存在"); + } else { + if (Objects.isNull(birdGenus)) { + BeanValidators.validateWithException(validator, data); + data.setIsDeleted(0); + data.setFamilyId(birdFamily.getId()); + insertBirdGenus(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟属 " + data.getFamilyName() + " 导入成功"); + } else if (isUpdateSupport) { + BeanValidators.validateWithException(validator, data); + data.setId(birdGenus.getId()); + data.setFamilyId(birdFamily.getId()); + updateBirdGenus(data); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "、鸟属 " + data.getFamilyName() + " 更新成功"); + } else { + failureNum[0]++; + failureMsg.append("
" + failureNum[0] + "、鸟属 " + data.getFamilyName() + " 已存在"); + } + } + } catch (Exception e) { + failureNum[0]++; + String msg = "
" + failureNum + "、鸟属 " + data.getFamilyName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum[0] + " 条数据格式不正确,错误如下:"); + throw new ServiceException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } + + @Override + public BirdGenus selectBirdGenusByName(String name) { + return birdGenusMapper.selectBirdGenusByName(name); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdLeaveArriveInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdLeaveArriveInfoServiceImpl.java new file mode 100644 index 0000000..e014d99 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdLeaveArriveInfoServiceImpl.java @@ -0,0 +1,107 @@ +package net.hzvtc.bird.service.impl; + +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.bird.domain.BirdLeaveArriveInfo; +import net.hzvtc.bird.mapper.BirdLeaveArriveInfoMapper; +import net.hzvtc.bird.service.BirdLeaveArriveInfoService; +import net.hzvtc.data.check.service.ResultRecordService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BirdLeaveArriveInfoServiceImpl +implements BirdLeaveArriveInfoService { + private static final Logger log = LoggerFactory.getLogger(BirdLeaveArriveInfoServiceImpl.class); + @Resource + private BirdLeaveArriveInfoMapper birdLeaveArriveInfoMapper; + @Autowired + private ResultRecordService resultRecordService; + + @Override + public BirdLeaveArriveInfo selectBirdLeaveArriveInfoById(Long id) { + return this.birdLeaveArriveInfoMapper.selectBirdLeaveArriveInfoById(id); + } + + @Override + public List selectBirdLeaveArriveInfoList(BirdLeaveArriveInfo birdLeaveArriveInfo) { + return this.birdLeaveArriveInfoMapper.selectBirdLeaveArriveInfoList(birdLeaveArriveInfo); + } + + @Override + public int insertBirdLeaveArriveInfo(BirdLeaveArriveInfo birdLeaveArriveInfo) { + return this.birdLeaveArriveInfoMapper.insertBirdLeaveArriveInfo(birdLeaveArriveInfo); + } + + @Override + public int updateBirdLeaveArriveInfo(BirdLeaveArriveInfo birdLeaveArriveInfo) { + return this.birdLeaveArriveInfoMapper.updateBirdLeaveArriveInfo(birdLeaveArriveInfo); + } + + @Override + public int deleteBirdLeaveArriveInfoByIds(Long[] ids) { + return this.birdLeaveArriveInfoMapper.deleteBirdLeaveArriveInfoByIds(ids); + } + + @Override + public int deleteBirdLeaveArriveInfoById(Long id) { + return this.birdLeaveArriveInfoMapper.deleteBirdLeaveArriveInfoById(id); + } + + @Override + public void calcBirdLeaveArriveInfoByParam() { + Integer statYear = LocalDate.now().getYear() - 1; + HashMap map = new HashMap(); + List areaIds = this.resultRecordService.getResultAreaListByParam(map); + ArrayList allList = new ArrayList(); + areaIds.stream().forEach(areaId -> { + map.put("areaId", areaId); + map.put("statYear", statYear + 1); + List leaveList = this.birdLeaveArriveInfoMapper.getBirdLeaveDateByParam(map); + map.put("statYear", statYear); + List arriveList = this.birdLeaveArriveInfoMapper.getBirdArrivalDateByParam(map); + leaveList = this.concatList(leaveList, arriveList); + if (leaveList != null) { + leaveList.stream().forEach(item -> { + item.setAreaId((Long)areaId); + item.setStatYear(statYear); + item.setIsDeleted(0); + }); + allList.addAll(leaveList); + } + }); + if (allList.size() > 0) { + this.birdLeaveArriveInfoMapper.batchInsertBirdLeaveArriveInfo(allList); + } + } + + private List concatList(List leaveList, List arriveList) { + if (leaveList == null || leaveList.isEmpty()) { + return arriveList; + } + if (arriveList == null || arriveList.isEmpty()) { + return leaveList; + } + leaveList.stream().forEach(item -> { + List sameList = arriveList.stream().filter(aitem -> aitem.getSpeciesId() == item.getSpeciesId()).collect(Collectors.toList()); + if (sameList != null && !sameList.isEmpty()) { + item.setArriveDate(((BirdLeaveArriveInfo)sameList.get(0)).getArriveDate()); + } + }); + arriveList.stream().forEach(item -> { + List sameList = leaveList.stream().filter(aitem -> aitem.getSpeciesId() == item.getSpeciesId()).collect(Collectors.toList()); + if (sameList == null || sameList.size() == 0) { + leaveList.add((BirdLeaveArriveInfo)item); + } + }); + return leaveList; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdMediaServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdMediaServiceImpl.java new file mode 100644 index 0000000..ea247d1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdMediaServiceImpl.java @@ -0,0 +1,117 @@ +package net.hzvtc.bird.service.impl; + +import java.io.IOException; +import java.util.List; +import javax.annotation.Resource; +import net.hzvtc.bird.domain.BirdMedia; +import net.hzvtc.bird.mapper.BirdMediaMapper; +import net.hzvtc.bird.service.BirdMediaService; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +@Service +public class BirdMediaServiceImpl +implements BirdMediaService { + @Resource + private BirdMediaMapper birdMediaMapper; + private final RedisCache redisCache; + + @Override + public BirdMedia selectBirdMediaById(Long id) { + return this.birdMediaMapper.selectBirdMediaById(id); + } + + @Override + public List selectBirdMediaList(BirdMedia birdMedia) { + return this.birdMediaMapper.selectBirdMediaList(birdMedia); + } + + @Override + public int insertBirdMedia(BirdMedia birdMedia) { + birdMedia.setCreateTime(DateUtils.getNowDate()); + return this.birdMediaMapper.insertBirdMedia(birdMedia); + } + + @Override + public int updateBirdMedia(BirdMedia birdMedia) { + return this.birdMediaMapper.updateBirdMedia(birdMedia); + } + + @Override + public int deleteBirdMediaByIds(Long[] ids) { + return this.birdMediaMapper.deleteBirdMediaByIds(ids); + } + + @Override + public int deleteBirdMediaById(Long id) { + return this.birdMediaMapper.deleteBirdMediaById(id); + } + + @Override + public AjaxResult uploadFile(MultipartFile file) { + String fileName = file.getOriginalFilename(); + String mediaType = this.getMediaType(fileName); + String baseDir = FileUploadUtils.getBirdMediaPath() + "/" + mediaType; + try { + BirdMedia data = new BirdMedia(); + String path = FileUploadUtils.upload((String)baseDir, (MultipartFile)file); + data.setMediaType(mediaType); + data.setName(this.removeFileExt(fileName)); + data.setUrl(path); + return AjaxResult.success((Object)((Object)data)); + } + catch (IOException e) { + return AjaxResult.error((String)e.getMessage()); + } + } + + @Override + public String getBirdIconImageBySpeciesId(Long speciesId) { + String key = "birdIcon_" + speciesId; + String str = (String)this.redisCache.getCacheObject(key); + if (str == null) { + str = this.birdMediaMapper.getBirdIconImageBySpeciesId(speciesId); + this.redisCache.setCacheObject(key, (Object)str); + } + return str; + } + + private String removeFileExt(String fileName) { + int pos = fileName.lastIndexOf("."); + if (pos == -1) { + return fileName; + } + return fileName.substring(0, pos); + } + + private String getMediaType(String fileName) { + if (fileName == null) { + return ""; + } + int pos = fileName.lastIndexOf("."); + if (pos == -1) { + return ""; + } + String ext = fileName.substring(pos + 1); + if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")) { + return "images"; + } + if (ext.equalsIgnoreCase("mp3") || ext.equalsIgnoreCase("wav")) { + return "audio"; + } + if (ext.equalsIgnoreCase("mp4") || ext.equalsIgnoreCase("mkv") || ext.equalsIgnoreCase("m4v") || ext.equalsIgnoreCase("wmv")) { + return "video"; + } + return "file"; + } + + public BirdMediaServiceImpl(RedisCache redisCache) { + this.redisCache = redisCache; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdSpeciesServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdSpeciesServiceImpl.java new file mode 100644 index 0000000..13b4055 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/BirdSpeciesServiceImpl.java @@ -0,0 +1,263 @@ +package net.hzvtc.bird.service.impl; + +import com.alibaba.fastjson.JSONObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Resource; +import javax.validation.Validator; +import net.hzvtc.bird.domain.BirdGenus; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.domain.SpeciesList; +import net.hzvtc.bird.mapper.BirdSpeciesMapper; +import net.hzvtc.bird.service.BirdGenusService; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.service.ResultMediaService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BirdSpeciesServiceImpl +implements BirdSpeciesService { + private static final Logger log = LoggerFactory.getLogger(BirdSpeciesServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private BirdSpeciesMapper birdSpeciesMapper; + @Autowired + private BirdGenusService genusService; + @Autowired + private ResultMediaService resultMediaService; + + @Override + public BirdSpecies selectBirdSpeciesById(Long id) { + return this.birdSpeciesMapper.selectBirdSpeciesById(id); + } + + @Override + public BirdSpecies selectBirdSpeciesByName(String name) { + return this.birdSpeciesMapper.selectBirdSpeciesByName(name); + } + + @Override + public List selectBirdSpeciesList(BirdSpecies birdSpecies) { + return this.birdSpeciesMapper.selectBirdSpeciesList(birdSpecies); + } + + @Override + public int insertBirdSpecies(BirdSpecies birdSpecies) { + birdSpecies.setCreateTime(DateUtils.getNowDate()); + birdSpecies.setIsDeleted(0); + birdSpecies.setCreateBy(SecurityUtils.getUsername()); + return this.birdSpeciesMapper.insertBirdSpecies(birdSpecies); + } + + @Override + public int updateBirdSpecies(BirdSpecies birdSpecies) { + birdSpecies.setUpdateTime(DateUtils.getNowDate()); + birdSpecies.setUpdateBy(SecurityUtils.getUsername()); + return this.birdSpeciesMapper.updateBirdSpecies(birdSpecies); + } + + @Override + public int deleteBirdSpeciesByIds(Long[] ids) { + return this.birdSpeciesMapper.deleteBirdSpeciesByIds(ids); + } + + @Override + public int deleteBirdSpeciesById(Long id) { + return this.birdSpeciesMapper.deleteBirdSpeciesById(id); + } + + @Override + public String importData(List list, boolean updateSupport) { + if (StringUtils.isNull(list) || list.size() == 0) { + throw new ServiceException("\u5bfc\u5165\u9e1f\u7c7b\u6570\u636e\u4e0d\u80fd\u4e3a\u7a7a\uff01"); + } + AtomicInteger[] successNum = new AtomicInteger[]{new AtomicInteger()}; + int[] failureNum = new int[]{0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.stream().forEach(data -> { + try { + BirdSpecies birdSpecies = this.birdSpeciesMapper.selectBirdSpeciesByName(data.getName()); + BirdGenus birdGenus = this.genusService.selectBirdGenusByName(data.getGenusName()); + if (Objects.isNull((Object)birdGenus)) { + failureNum[0] = failureNum[0] + 1; + failureMsg.append("
" + failureNum[0] + "\u3001\u9e1f\u5c5e " + data.getGenusName() + " \u4e0d\u5b58\u5728"); + } else if (Objects.isNull((Object)birdSpecies)) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setIsDeleted(0); + data.setGenusId(birdGenus.getId()); + data.setFamilyId(birdGenus.getFamilyId()); + this.insertBirdSpecies((BirdSpecies)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u9e1f\u7c7b " + data.getName() + " \u5bfc\u5165\u6210\u529f"); + } else if (updateSupport) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setId(birdSpecies.getId()); + data.setGenusId(birdGenus.getId()); + data.setFamilyId(birdGenus.getFamilyId()); + this.updateBirdSpecies((BirdSpecies)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u9e1f\u7c7b " + data.getName() + " \u66f4\u65b0\u6210\u529f"); + } else { + failureNum[0] = failureNum[0] + 1; + failureMsg.append("
" + failureNum[0] + "\u3001\u9e1f\u7c7b " + data.getName() + " \u5df2\u5b58\u5728"); + } + } + catch (Exception e) { + failureNum[0] = failureNum[0] + 1; + String msg = "
" + failureNum + "\u3001\u9e1f\u7c7b " + data.getName() + " \u5bfc\u5165\u5931\u8d25\uff1a"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, (Throwable)e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "\u5f88\u62b1\u6b49\uff0c\u5bfc\u5165\u5931\u8d25\uff01\u5171 " + failureNum[0] + " \u6761\u6570\u636e\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c\u9519\u8bef\u5982\u4e0b\uff1a"); + throw new ServiceException(failureMsg.toString()); + } + successMsg.insert(0, "\u606d\u559c\u60a8\uff0c\u6570\u636e\u5df2\u5168\u90e8\u5bfc\u5165\u6210\u529f\uff01\u5171 " + successNum + " \u6761\uff0c\u6570\u636e\u5982\u4e0b\uff1a"); + return successMsg.toString(); + } + + @Override + public List getResultMediaListByParam(JSONObject jsonObject) { + Long mediaId = jsonObject.getLong("mediaId"); + if (mediaId != null) { + ArrayList list = new ArrayList(); + ResultMedia data = this.resultMediaService.getResultMediaListById(mediaId); + list.add(data); + return list; + } + return this.resultMediaService.getResultMediaListByParam(this.createQueryParameter(jsonObject)); + } + + @Override + public int recoverResultMediaStateByParam(JSONObject jsonObject) { + return this.resultMediaService.recoverResultMediaStateByParam(this.createQueryParameter(jsonObject)); + } + + private Map createQueryParameter(JSONObject jsonObject) { + HashMap map = new HashMap(); + Long mediaId = jsonObject.getLong("mediaId"); + map.put("mediaId", mediaId); + Long areaId = jsonObject.getLong("areaId"); + map.put("areaId", areaId); + String mediaType = jsonObject.getString("mediaType"); + map.put("mediaType", mediaType); + Long speciesId = jsonObject.getLong("speciesId"); + map.put("speciesId", speciesId); + Long deviceId = jsonObject.getLong("deviceId"); + map.put("deviceId", deviceId); + String mediaTypes = jsonObject.getString("mediaTypes"); + if (mediaTypes != null && !mediaTypes.isEmpty()) { + String[] arr = mediaTypes.split(","); + map.put("mediaTypes", arr); + } + Integer isDeleted = jsonObject.getInteger("isDeleted"); + map.put("isDeleted", isDeleted); + String dateFrom = jsonObject.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = jsonObject.getString("dateTo"); + map.put("dateTo", dateTo); + Integer limit = jsonObject.getInteger("limit"); + map.put("limit", limit); + Integer isCommon = jsonObject.getInteger("isCommon"); + map.put("isCommon", isCommon); + return map; + } + + @Override + public List getResultAudioMediaListByParam(JSONObject jsonObject) { + return this.resultMediaService.getResultAudioMediaListByParam(this.createQueryParameter(jsonObject)); + } + + @Override + public List getBirdMediaListByParam(JSONObject jsonObject) { + Map map = this.createQueryParameter(jsonObject); + String dateFrom = jsonObject.getString("dateFrom"); + String dateTo = jsonObject.getString("dateTo"); + map.put("dateFrom", dateFrom); + map.put("dateTo", dateTo); + Integer recordType = jsonObject.getInteger("recordType"); + map.put("recordType", recordType); + Integer recordTypeNot = jsonObject.getInteger("recordTypeNot"); + map.put("recordTypeNot", recordTypeNot); + Integer pageLimit = jsonObject.getInteger("pageLimit"); + map.put("pageLimit", pageLimit); + return this.resultMediaService.getBirdMediaListByParam(map); + } + + @Override + public List getBirdSpeciesListByQuery(Map map) { + return this.birdSpeciesMapper.getBirdSpeciesListByQuery(map); + } + + @Override + public Long getBirdSpeciesInfoIdByName(String name) { + List list = this.birdSpeciesMapper.getBirdSpeciesInfoByName(name); + if (list != null && !list.isEmpty()) { + return list.get(0).getId(); + } + return null; + } + + @Override + public Long getBirdSpeciesInfoIdByScientificName(String name) { + return 0L; + } + + @Override + public BirdSpecies selectBirdSpeciesForEsById(Long id) { + return this.birdSpeciesMapper.selectBirdSpeciesForEsById(id); + } + + @Override + public BirdSpecies getBirdSpeciesInfoById(Long id) { + return this.birdSpeciesMapper.getBirdSpeciesInfoById(id); + } + + @Override + public List getSpeciesSelectListByParam(Map param) { + return this.birdSpeciesMapper.getSpeciesSelectListByParam(param); + } + + @Override + public Long getBirdSpeciesIdByScientificName(String name) { + return this.birdSpeciesMapper.getBirdSpeciesIdByScientificName(name); + } + + @Override + public Long getBirdSpeciesIdByName(String name) { + return this.birdSpeciesMapper.getBirdSpeciesIdByName(name); + } + + @Override + public List getSpeciesSelectListFromDetails(JSONObject params) { + HashMap map = new HashMap(); + Integer mediaType = params.getInteger("mediaType"); + map.put("mediaType", mediaType); + Integer subType = params.getInteger("subType"); + map.put("subType", subType); + return this.birdSpeciesMapper.getSpeciesSelectListFromDetails(map); + } + + @Override + public List getSpeciesListPages() { + return this.birdSpeciesMapper.getSpeciesListPages(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesAnswerServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesAnswerServiceImpl.java new file mode 100644 index 0000000..128d64c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesAnswerServiceImpl.java @@ -0,0 +1,33 @@ +package net.hzvtc.bird.service.impl; + +import java.util.List; +import javax.annotation.Resource; +import net.hzvtc.bird.domain.SpeciesAnswer; +import net.hzvtc.bird.domain.SpeciesAnswerItem; +import net.hzvtc.bird.mapper.SpeciesAnswerMapper; +import net.hzvtc.bird.service.SpeciesAnswerService; +import org.springframework.stereotype.Service; + +@Service +public class SpeciesAnswerServiceImpl +implements SpeciesAnswerService { + @Resource + private SpeciesAnswerMapper speciesAnswerMapper; + + @Override + public void addSpeciesAnswer(SpeciesAnswer speciesAnswer) { + this.speciesAnswerMapper.addSpeciesAnswer(speciesAnswer); + } + + @Override + public void batchAddSpeciesAnswerItem(List list) { + this.speciesAnswerMapper.batchAddSpeciesAnswerItem(list); + } + + @Override + public List getSpeciesAnswerList() { + return this.speciesAnswerMapper.getSpeciesAnswerList(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesIntroServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesIntroServiceImpl.java new file mode 100644 index 0000000..f08ead5 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/bird/service/impl/SpeciesIntroServiceImpl.java @@ -0,0 +1,42 @@ +package net.hzvtc.bird.service.impl; + +import java.util.List; +import javax.annotation.Resource; +import net.hzvtc.bird.domain.SpeciesIntro; +import net.hzvtc.bird.mapper.SpeciesIntroMapper; +import net.hzvtc.bird.service.SpeciesIntroService; +import org.springframework.stereotype.Service; + +@Service +public class SpeciesIntroServiceImpl +implements SpeciesIntroService { + @Resource + private SpeciesIntroMapper speciesIntroMapper; + + @Override + public int addSpeciesIntro(SpeciesIntro data) { + return this.speciesIntroMapper.addSpeciesIntro(data); + } + + @Override + public void batchAddSpeciesIntro(List list) { + this.speciesIntroMapper.batchAddSpeciesIntro(list); + } + + @Override + public List getSpeciesIntroList(SpeciesIntro param) { + return this.speciesIntroMapper.getSpeciesIntroList(param); + } + + @Override + public List getSpeciesIntroOtherList(SpeciesIntro param) { + return this.speciesIntroMapper.getSpeciesIntroOtherList(param); + } + + @Override + public void updateImageUrl(SpeciesIntro data) { + this.speciesIntroMapper.updateImageUrl(data); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/FavoriteMediaController.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/FavoriteMediaController.java new file mode 100644 index 0000000..ac88ba2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/FavoriteMediaController.java @@ -0,0 +1,101 @@ +package net.hzvtc.data.check.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.domain.FavoriteMedia; +import net.hzvtc.data.check.service.FavoriteMediaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 收藏的视频Controller + * + * @author admin + * @date 2024-06-18 + */ +@RestController +@RequestMapping("/media/favorite") +public class FavoriteMediaController extends BaseController { + @Autowired + private FavoriteMediaService favoriteMediaService; + + /** + * 查询收藏的视频列表 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:list')") + @GetMapping("/list") + public TableDataInfo list(FavoriteMedia favoriteMedia) { + startPage(); + List list = favoriteMediaService.selectFavoriteMediaList(favoriteMedia); + return getDataTable(list); + } + + /** + * 导出收藏的视频列表 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:export')") + @Log(title = "收藏的视频", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, FavoriteMedia favoriteMedia) { + List list = favoriteMediaService.selectFavoriteMediaList(favoriteMedia); + ExcelUtil util = new ExcelUtil(FavoriteMedia.class); + util.exportExcel(response, list, "收藏的视频数据"); + } + + /** + * 获取收藏的视频详细信息 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(favoriteMediaService.selectFavoriteMediaById(id)); + } + + /** + * 新增收藏的视频 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:add')") + @Log(title = "收藏的视频", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody FavoriteMedia favoriteMedia) { + return toAjax(favoriteMediaService.insertFavoriteMedia(favoriteMedia)); + } + + /** + * 修改收藏的视频 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:edit')") + @Log(title = "收藏的视频", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody FavoriteMedia favoriteMedia) { + return toAjax(favoriteMediaService.updateFavoriteMedia(favoriteMedia)); + } + + /** + * 删除收藏的视频 + */ + @PreAuthorize("@ss.hasPermi('media:favorite:remove')") + @Log(title = "收藏的视频", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(favoriteMediaService.deleteFavoriteMediaByIds(ids)); + } + + @GetMapping(value = "/byMediaId/{id}") + public AjaxResult getFavoriteIdByMediaId(@PathVariable("id") Long id) { + return AjaxResult.success(favoriteMediaService.getFavoriteMediaByMediaId(id)); + } + + @PostMapping("/handle") + public AjaxResult handleAction(@RequestBody FavoriteMedia favoriteMedia) { + return AjaxResult.success(favoriteMediaService.handleAction(favoriteMedia)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/MediaItemController.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/MediaItemController.java new file mode 100644 index 0000000..c318705 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/MediaItemController.java @@ -0,0 +1,23 @@ +package net.hzvtc.data.check.controller; + +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.data.check.service.MediaItemService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/dataCheck/mediaItem") +public class MediaItemController extends BaseController { + @Autowired + private MediaItemService mediaItemService; + + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(mediaItemService.selectMediaItemById(id)); + } + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultMediaController.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultMediaController.java new file mode 100644 index 0000000..f8e737c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultMediaController.java @@ -0,0 +1,77 @@ +package net.hzvtc.data.check.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.service.ResultMediaService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/dataCheck/resultMedia"}) +public class ResultMediaController +extends BaseController { + @Autowired + private ResultMediaService resultMediaService; + + @PreAuthorize(value="@ss.hasPermi('dataCheck:resultMedia:list')") + @GetMapping(value={"/list"}) + public TableDataInfo list(ResultMedia resultMedia) { + this.startPage(); + List list = this.resultMediaService.selectResultMediaListByParam(resultMedia); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:resultMedia:export')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u9644\u4ef6", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, ResultMedia resultMedia) { + List list = this.resultMediaService.selectResultMediaList(resultMedia); + ExcelUtil util = new ExcelUtil(ResultMedia.class); + util.exportExcel(response, list, "\u76d1\u6d4b\u5a92\u4f53\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:resultMedia:add')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u9644\u4ef6", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ResultMedia resultMedia) { + return this.toAjax(this.resultMediaService.insertResultMedia(resultMedia)); + } + + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u9644\u4ef6", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{mediaIds}"}) + public AjaxResult remove(@PathVariable Long[] mediaIds) { + return this.toAjax(this.resultMediaService.deleteResultMediaByMediaIds(mediaIds)); + } + + @PostMapping(value={"/updateStatus"}) + public AjaxResult updateStatus(@RequestBody ResultMedia param) { + return AjaxResult.success((Object)this.resultMediaService.updateResultMediaStatusByParam(param)); + } + + @PostMapping(value={"/favoriteList"}) + public AjaxResult getFavoriteList(@RequestBody JSONObject object) { + return AjaxResult.success(this.resultMediaService.getFavoriteVideoListByParam(object)); + } + + @GetMapping(value={"/mediaStatInfo"}) + public JSONObject getStatAmount() { + return this.resultMediaService.getResultMediaStatByParam(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordController.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordController.java new file mode 100644 index 0000000..6ecba63 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordController.java @@ -0,0 +1,180 @@ +package net.hzvtc.data.check.controller; + +import com.alibaba.fastjson.JSONObject; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.service.ResultRecordExtractService; +import net.hzvtc.data.check.service.ResultRecordService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping(value={"/dataCheck/checkRecord"}) +public class ResultRecordController +extends BaseController { + private static final Logger log = LoggerFactory.getLogger(ResultRecordController.class); + @Autowired + private ResultRecordService resultRecordService; + @Autowired + private ResultRecordExtractService resultRecordExtractService; + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:list')") + @GetMapping(value={"/list"}) + public TableDataInfo list(ResultRecord resultRecord) { + this.startPage(); + List list = this.resultRecordService.selectResultRecordList(resultRecord); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:export')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u8bb0\u5f55", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, ResultRecord resultRecord) { + List list = this.resultRecordService.selectResultRecordList(resultRecord); + ExcelUtil util = new ExcelUtil(ResultRecord.class); + util.exportExcel(response, list, "\u76d1\u6d4b\u7ed3\u679c\u8bb0\u5f55\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:query')") + @GetMapping(value={"/{recordId}"}) + public AjaxResult getInfo(@PathVariable(value="recordId") Long recordId) { + return AjaxResult.success((Object)((Object)this.resultRecordService.selectResultRecordByRecordId(recordId))); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:add')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u8bb0\u5f55", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ResultRecord resultRecord) { + return this.toAjax(this.resultRecordService.insertResultRecord(resultRecord)); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:edit')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u8bb0\u5f55", businessType=BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ResultRecord resultRecord) { + return this.toAjax(this.resultRecordService.updateResultRecord(resultRecord)); + } + + @PreAuthorize(value="@ss.hasPermi('dataCheck:checkRecord:remove')") + @Log(title="\u76d1\u6d4b\u7ed3\u679c\u8bb0\u5f55", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{recordIds}"}) + public AjaxResult remove(@PathVariable Long[] recordIds) { + return this.toAjax(this.resultRecordService.deleteResultRecordByRecordIds(recordIds)); + } + + @PostMapping(value={"/getBirdStatData"}) + public AjaxResult getBirdStatData(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordService.getBirdDataStatByParam(object)); + } + + @PostMapping(value={"/getBirdWeeklyStatData"}) + public AjaxResult getBirdWeeklyStatData(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordService.getBirdDataWeeklyStatByParam(object)); + } + + @PostMapping(value={"/sendEmail"}) + public AjaxResult sendEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordService.sendBirdDataStatEmail(object)); + } + + @PostMapping(value={"/sendWeeklyEmail"}) + public AjaxResult sendWeeklyEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordService.sendBirdDataWeeklyStatEmail(object)); + } + + @PostMapping(value={"/downloadReport"}) + public void downloadReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + String filePath = this.resultRecordService.getBirdDataStatFileByParam(obj); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception exception) { + // empty catch block + } + } + } + + @PostMapping(value={"/downloadWeeklyReport"}) + public void downloadWeeklyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + JSONObject obj = new JSONObject(); + obj.put("areaId", params.get("areaId")); + obj.put("calcDate", params.get("calcDate")); + String filePath = this.resultRecordService.getBirdDataWeeklyStatFileByParam(obj); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + } + + @GetMapping(value={"/test"}) + public void doTest() { + this.resultRecordExtractService.extraAudioRecordDataList(); + } + + @GetMapping(value={"/maxId"}) + public Long getMaxId() { + return this.resultRecordExtractService.getMaxId(null); + } + + @GetMapping(value={"/extractAudioList"}) + public AjaxResult extractAudioList() { + this.resultRecordExtractService.extraAudioRecordDataList(); + return AjaxResult.success(); + } + + @PostMapping(value={"/savePushDataList"}) + public AjaxResult pushResultRecordDataList(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordExtractService.saveResultRecordPostData(object)); + } + + @PostMapping(value={"/pushDataList"}) + public AjaxResult getResultRecordListToPush(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.resultRecordExtractService.getResultRecordListToPush(object)); + } + + @PostMapping(value={"/pushFileToServer"}) + public AjaxResult receiveFile(@RequestParam(value="file") MultipartFile file, @RequestParam(value="fileName") String fileName) { + return AjaxResult.success((Object)this.resultRecordExtractService.saveRemoteFile(file, fileName)); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordDetailsController.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordDetailsController.java new file mode 100644 index 0000000..514b516 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/controller/ResultRecordDetailsController.java @@ -0,0 +1,185 @@ +package net.hzvtc.data.check.controller; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.Map; + +/** + * 监测记录详细信息Controller + * + * @author admin + * @date 2022-08-22 + */ +@RestController +@RequestMapping("/dataCheck/checkDetails") +public class ResultRecordDetailsController extends BaseController { + @Autowired + private ResultRecordDetailsService resultRecordDetailsService; + + /** + * 查询监测记录详细信息列表 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:list')") + @GetMapping("/list") + public TableDataInfo list(ResultRecordDetails resultRecordDetails) { + startPage(); + List list = resultRecordDetailsService.selectResultRecordDetailsList(resultRecordDetails); + return getDataTable(list); + } + + /** + * 导出监测记录详细信息列表 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:export')") + @Log(title = "监测记录详细信息", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, ResultRecordDetails resultRecordDetails) { + List list = resultRecordDetailsService.selectResultRecordDetailsList(resultRecordDetails); + ExcelUtil util = new ExcelUtil(ResultRecordDetails.class); + util.exportExcel(response, list, "监测记录详细信息数据"); + } + + /** + * 获取监测记录详细信息详细信息 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:query')") + @GetMapping(value = "/{detailsId}") + public AjaxResult getInfo(@PathVariable("detailsId") Long detailsId) { + return AjaxResult.success(resultRecordDetailsService.selectResultRecordDetailsByDetailsId(detailsId)); + } + + /** + * 新增监测记录详细信息 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:add')") + @Log(title = "监测记录详细信息", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ResultRecordDetails resultRecordDetails) { + return toAjax(resultRecordDetailsService.insertResultRecordDetails(resultRecordDetails)); + } + + /** + * 修改监测记录详细信息 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:edit')") + @Log(title = "监测记录详细信息", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ResultRecordDetails resultRecordDetails) { + return toAjax(resultRecordDetailsService.updateResultRecordDetails(resultRecordDetails)); + } + + @PostMapping("/updateByIds") + public AjaxResult updateByIds(@RequestBody JSONObject object) { + return toAjax(resultRecordDetailsService.updateResultRecordDetailsByIds(object)); + } + + /** + * 删除监测记录详细信息 + */ +// @PreAuthorize("@ss.hasPermi('dataCheck:checkDetails:remove')") + @Log(title = "监测记录详细信息", businessType = BusinessType.DELETE) + @DeleteMapping("/{detailsIds}") + public AjaxResult remove(@PathVariable Long[] detailsIds) { + return toAjax(resultRecordDetailsService.deleteResultRecordDetailsByDetailsIds(detailsIds)); + } + + + @PostMapping("/areaSpeciesListByParam") + public AjaxResult getSpeciesListByParam(@RequestBody JSONObject params) { + return AjaxResult.success(resultRecordDetailsService.getSpeciesListByParam(params)); + } + + @PostMapping("/updateCheckState") + public AjaxResult updateCheckedState(@RequestBody JSONObject params) { + Long id = params.getLong("id"); + return AjaxResult.success(resultRecordDetailsService.updateResultRecordDetailsCheckState(id)); + } + + + @PostMapping("/updateCheckStateByIds") + public AjaxResult updateCheckedStateByIds(@RequestBody JSONObject params) { + String ids = params.getString("ids"); + return AjaxResult.success(resultRecordDetailsService.updateResultRecordDetailsCheckState(ids)); + } + + @PostMapping("/delRecordDetails") + public AjaxResult delRecordDetails(@RequestBody JSONObject obj) { + return AjaxResult.success(resultRecordDetailsService.deleteResultRecordDetails(obj)); + } + + @PostMapping("/delRecordDetailsByIds") + public AjaxResult delRecordDetailsByIds(@RequestBody JSONObject object) { + return AjaxResult.success(resultRecordDetailsService.deleteResultRecordDetailsByParam(object)); + } + + @GetMapping("/speciesListByUserId") + public AjaxResult getSpeciesListByUserId(Long areaId) { + return AjaxResult.success(resultRecordDetailsService.getSpeciesListByUserId(areaId)); + } + + @PostMapping("/speciesMediaList") + public TableDataInfo getSpeciesMediaListByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize); + List list = resultRecordDetailsService.getSpeciesMediaListByParam(params); + return getDataTable(list); + } + + @PostMapping("/speciesHourAmount") + public JSONArray getSpeciesHourAmountListByParam(@RequestBody JSONObject params) { + return resultRecordDetailsService.getSpeciesHourAmountListByParam(params); + } + + @PostMapping("/speciesAudioAmountListByParam") + public JSONObject getSpeciesAudioAmountReportByParam(@RequestBody JSONObject param) { + return resultRecordDetailsService.getSpeciesAudioAmountReportByParam(param); + } + + @PostMapping("/audioReportList") + public List getAudioStatListByParam(@RequestBody JSONObject param) { + return resultRecordDetailsService.getAudioStatListByParam(param); + } + + @PostMapping("/audioErrorStat") + public long getAudioErrorStatByParam(@RequestBody JSONObject param) { + return resultRecordDetailsService.getAudioErrorStatByParam(param); + } + + @PostMapping("/updateStatus") + public AjaxResult updateStatus(@RequestBody JSONObject param) { + return AjaxResult.success(resultRecordDetailsService.updateResultRecordDetailsStatusById(param)); + } + + @PostMapping("/downloadAudioReport") + public void downloadAudioReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + String filePath = resultRecordDetailsService.createAudioReportFile(params); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader(response, realFileName); + FileUtils.writeBytes(filePath, response.getOutputStream()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } +} \ No newline at end of file diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/FavoriteMedia.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/FavoriteMedia.java new file mode 100644 index 0000000..c921cdd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/FavoriteMedia.java @@ -0,0 +1,17 @@ +package net.hzvtc.data.check.domain; + +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="FavoriteMedia") +@Data +public class FavoriteMedia { + private static final long serialVersionUID = 1L; + private Long id; + private Long mediaId; + private Long userId; + private Date createDate; + private int isDeleted; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/MediaItem.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/MediaItem.java new file mode 100644 index 0000000..34a5551 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/MediaItem.java @@ -0,0 +1,22 @@ +package net.hzvtc.data.check.domain; + +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="MediaItem") +@Data +public class MediaItem { + private static final long serialVersionUID = 1L; + private Long id; + private Long deviceId; + private double cameraVolt; + private double solarVolt; + private double extraVolt; + private double temperature; + private double humidity; + private double atmosphere; + private String lat; + private String lon; + private Long parentId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultMedia.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultMedia.java new file mode 100644 index 0000000..37013d1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultMedia.java @@ -0,0 +1,467 @@ +package net.hzvtc.data.check.domain; + +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="ResultMedia") +public class ResultMedia +extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long mediaId; + private Long areaId; + private String areaName; + @Excel(name="\u8bbe\u5907id") + private Long deviceId; + @Excel(name="\u8bbe\u5907\u540d\u79f0") + private String deviceName; + @Excel(name="\u7c7b\u578b") + private Integer mediaType; + @Excel(name="\u5a92\u4f53url") + private String mediaUrl; + @Excel(name="\u89c6\u9891\u53ca\u58f0\u97f3URL") + private String metaUrl; + @JsonFormat(pattern="yyyy\u5e74MM\u6708dd\u65e5 HH:mm:ss", timezone="GMT+8") + @Excel(name="\u65f6\u95f4", width=30.0, dateFormat="yyyy\u5e74MM\u6708dd\u65e5 HH\u65f6mm\u5206ss\u79d2") + private Date time; + private String strTime; + private Integer width; + private Integer height; + private Long speciesId; + private String speciesName; + private Integer limit; + private int isDeleted; + private Long itemId; + private Long oldMediaId; + private BigDecimal longitude; + private BigDecimal latitude; + private String description; + private Integer subType; + private String fileUrl; + private List array; + + public String getMediaTypeName() { + if (this.mediaType == null) { + return null; + } + if (this.mediaType == 1) { + return "audio"; + } + if (this.mediaType == 2) { + return "image"; + } + if (this.mediaType == 3) { + return "video"; + } + if (this.mediaType == 4) { + return "real"; + } + return ""; + } + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("mediaId", (Object)this.getMediaId()).append("deviceId", (Object)this.getDeviceId()).append("mediaType", (Object)this.getMediaType()).append("mediaUrl", (Object)this.getMediaUrl()).append("metaUrl", (Object)this.getMetaUrl()).append("time", (Object)this.getTime()).toString(); + } + + public static ResultMedia parserObject(JSONObject object) { + ResultMedia data = new ResultMedia(); + data.setMediaId(object.getLong("mediaId")); + data.setDeviceId(object.getLong("deviceId")); + data.setMediaType(object.getInteger("mediaType")); + data.setMediaUrl(object.getString("mediaUrl")); + data.setMetaUrl(object.getString("metaUrl")); + data.setStrTime(object.getString("strTime")); + data.setWidth(object.getInteger("width")); + data.setHeight(object.getInteger("height")); + data.setIsDeleted(object.getInteger("isDeleted")); + return data; + } + + public Long getMediaId() { + return this.mediaId; + } + + public Long getAreaId() { + return this.areaId; + } + + public String getAreaName() { + return this.areaName; + } + + public Long getDeviceId() { + return this.deviceId; + } + + public String getDeviceName() { + return this.deviceName; + } + + public Integer getMediaType() { + return this.mediaType; + } + + public String getMediaUrl() { + return this.mediaUrl; + } + + public String getMetaUrl() { + return this.metaUrl; + } + + public Date getTime() { + return this.time; + } + + public String getStrTime() { + return this.strTime; + } + + public Integer getWidth() { + return this.width; + } + + public Integer getHeight() { + return this.height; + } + + public Long getSpeciesId() { + return this.speciesId; + } + + public String getSpeciesName() { + return this.speciesName; + } + + public Integer getLimit() { + return this.limit; + } + + public int getIsDeleted() { + return this.isDeleted; + } + + public Long getItemId() { + return this.itemId; + } + + public Long getOldMediaId() { + return this.oldMediaId; + } + + public BigDecimal getLongitude() { + return this.longitude; + } + + public BigDecimal getLatitude() { + return this.latitude; + } + + public String getDescription() { + return this.description; + } + + public Integer getSubType() { + return this.subType; + } + + public String getFileUrl() { + return this.fileUrl; + } + + public List getArray() { + return this.array; + } + + public void setMediaId(Long mediaId) { + this.mediaId = mediaId; + } + + public void setAreaId(Long areaId) { + this.areaId = areaId; + } + + public void setAreaName(String areaName) { + this.areaName = areaName; + } + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public void setMediaType(Integer mediaType) { + this.mediaType = mediaType; + } + + public void setMediaUrl(String mediaUrl) { + this.mediaUrl = mediaUrl; + } + + public void setMetaUrl(String metaUrl) { + this.metaUrl = metaUrl; + } + + @JsonFormat(pattern="yyyy\u5e74MM\u6708dd\u65e5 HH:mm:ss", timezone="GMT+8") + public void setTime(Date time) { + this.time = time; + } + + public void setStrTime(String strTime) { + this.strTime = strTime; + } + + public void setWidth(Integer width) { + this.width = width; + } + + public void setHeight(Integer height) { + this.height = height; + } + + public void setSpeciesId(Long speciesId) { + this.speciesId = speciesId; + } + + public void setSpeciesName(String speciesName) { + this.speciesName = speciesName; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + public void setIsDeleted(int isDeleted) { + this.isDeleted = isDeleted; + } + + public void setItemId(Long itemId) { + this.itemId = itemId; + } + + public void setOldMediaId(Long oldMediaId) { + this.oldMediaId = oldMediaId; + } + + public void setLongitude(BigDecimal longitude) { + this.longitude = longitude; + } + + public void setLatitude(BigDecimal latitude) { + this.latitude = latitude; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setSubType(Integer subType) { + this.subType = subType; + } + + public void setFileUrl(String fileUrl) { + this.fileUrl = fileUrl; + } + + public void setArray(List array) { + this.array = array; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ResultMedia)) { + return false; + } + ResultMedia other = (ResultMedia)((Object)o); + if (!other.canEqual((Object)this)) { + return false; + } + if (this.getIsDeleted() != other.getIsDeleted()) { + return false; + } + Long this$mediaId = this.getMediaId(); + Long other$mediaId = other.getMediaId(); + if (this$mediaId == null ? other$mediaId != null : !((Object)this$mediaId).equals(other$mediaId)) { + return false; + } + Long this$areaId = this.getAreaId(); + Long other$areaId = other.getAreaId(); + if (this$areaId == null ? other$areaId != null : !((Object)this$areaId).equals(other$areaId)) { + return false; + } + Long this$deviceId = this.getDeviceId(); + Long other$deviceId = other.getDeviceId(); + if (this$deviceId == null ? other$deviceId != null : !((Object)this$deviceId).equals(other$deviceId)) { + return false; + } + Integer this$mediaType = this.getMediaType(); + Integer other$mediaType = other.getMediaType(); + if (this$mediaType == null ? other$mediaType != null : !((Object)this$mediaType).equals(other$mediaType)) { + return false; + } + Integer this$width = this.getWidth(); + Integer other$width = other.getWidth(); + if (this$width == null ? other$width != null : !((Object)this$width).equals(other$width)) { + return false; + } + Integer this$height = this.getHeight(); + Integer other$height = other.getHeight(); + if (this$height == null ? other$height != null : !((Object)this$height).equals(other$height)) { + return false; + } + Long this$speciesId = this.getSpeciesId(); + Long other$speciesId = other.getSpeciesId(); + if (this$speciesId == null ? other$speciesId != null : !((Object)this$speciesId).equals(other$speciesId)) { + return false; + } + Integer this$limit = this.getLimit(); + Integer other$limit = other.getLimit(); + if (this$limit == null ? other$limit != null : !((Object)this$limit).equals(other$limit)) { + return false; + } + Long this$itemId = this.getItemId(); + Long other$itemId = other.getItemId(); + if (this$itemId == null ? other$itemId != null : !((Object)this$itemId).equals(other$itemId)) { + return false; + } + Long this$oldMediaId = this.getOldMediaId(); + Long other$oldMediaId = other.getOldMediaId(); + if (this$oldMediaId == null ? other$oldMediaId != null : !((Object)this$oldMediaId).equals(other$oldMediaId)) { + return false; + } + Integer this$subType = this.getSubType(); + Integer other$subType = other.getSubType(); + if (this$subType == null ? other$subType != null : !((Object)this$subType).equals(other$subType)) { + return false; + } + String this$areaName = this.getAreaName(); + String other$areaName = other.getAreaName(); + if (this$areaName == null ? other$areaName != null : !this$areaName.equals(other$areaName)) { + return false; + } + String this$deviceName = this.getDeviceName(); + String other$deviceName = other.getDeviceName(); + if (this$deviceName == null ? other$deviceName != null : !this$deviceName.equals(other$deviceName)) { + return false; + } + String this$mediaUrl = this.getMediaUrl(); + String other$mediaUrl = other.getMediaUrl(); + if (this$mediaUrl == null ? other$mediaUrl != null : !this$mediaUrl.equals(other$mediaUrl)) { + return false; + } + String this$metaUrl = this.getMetaUrl(); + String other$metaUrl = other.getMetaUrl(); + if (this$metaUrl == null ? other$metaUrl != null : !this$metaUrl.equals(other$metaUrl)) { + return false; + } + Date this$time = this.getTime(); + Date other$time = other.getTime(); + if (this$time == null ? other$time != null : !((Object)this$time).equals(other$time)) { + return false; + } + String this$strTime = this.getStrTime(); + String other$strTime = other.getStrTime(); + if (this$strTime == null ? other$strTime != null : !this$strTime.equals(other$strTime)) { + return false; + } + String this$speciesName = this.getSpeciesName(); + String other$speciesName = other.getSpeciesName(); + if (this$speciesName == null ? other$speciesName != null : !this$speciesName.equals(other$speciesName)) { + return false; + } + BigDecimal this$longitude = this.getLongitude(); + BigDecimal other$longitude = other.getLongitude(); + if (this$longitude == null ? other$longitude != null : !((Object)this$longitude).equals(other$longitude)) { + return false; + } + BigDecimal this$latitude = this.getLatitude(); + BigDecimal other$latitude = other.getLatitude(); + if (this$latitude == null ? other$latitude != null : !((Object)this$latitude).equals(other$latitude)) { + return false; + } + String this$description = this.getDescription(); + String other$description = other.getDescription(); + if (this$description == null ? other$description != null : !this$description.equals(other$description)) { + return false; + } + String this$fileUrl = this.getFileUrl(); + String other$fileUrl = other.getFileUrl(); + if (this$fileUrl == null ? other$fileUrl != null : !this$fileUrl.equals(other$fileUrl)) { + return false; + } + List this$array = this.getArray(); + List other$array = other.getArray(); + return !(this$array == null ? other$array != null : !((Object)this$array).equals(other$array)); + } + + protected boolean canEqual(Object other) { + return other instanceof ResultMedia; + } + + public int hashCode() { + int PRIME = 59; + int result = 1; + result = result * 59 + this.getIsDeleted(); + Long $mediaId = this.getMediaId(); + result = result * 59 + ($mediaId == null ? 43 : ((Object)$mediaId).hashCode()); + Long $areaId = this.getAreaId(); + result = result * 59 + ($areaId == null ? 43 : ((Object)$areaId).hashCode()); + Long $deviceId = this.getDeviceId(); + result = result * 59 + ($deviceId == null ? 43 : ((Object)$deviceId).hashCode()); + Integer $mediaType = this.getMediaType(); + result = result * 59 + ($mediaType == null ? 43 : ((Object)$mediaType).hashCode()); + Integer $width = this.getWidth(); + result = result * 59 + ($width == null ? 43 : ((Object)$width).hashCode()); + Integer $height = this.getHeight(); + result = result * 59 + ($height == null ? 43 : ((Object)$height).hashCode()); + Long $speciesId = this.getSpeciesId(); + result = result * 59 + ($speciesId == null ? 43 : ((Object)$speciesId).hashCode()); + Integer $limit = this.getLimit(); + result = result * 59 + ($limit == null ? 43 : ((Object)$limit).hashCode()); + Long $itemId = this.getItemId(); + result = result * 59 + ($itemId == null ? 43 : ((Object)$itemId).hashCode()); + Long $oldMediaId = this.getOldMediaId(); + result = result * 59 + ($oldMediaId == null ? 43 : ((Object)$oldMediaId).hashCode()); + Integer $subType = this.getSubType(); + result = result * 59 + ($subType == null ? 43 : ((Object)$subType).hashCode()); + String $areaName = this.getAreaName(); + result = result * 59 + ($areaName == null ? 43 : $areaName.hashCode()); + String $deviceName = this.getDeviceName(); + result = result * 59 + ($deviceName == null ? 43 : $deviceName.hashCode()); + String $mediaUrl = this.getMediaUrl(); + result = result * 59 + ($mediaUrl == null ? 43 : $mediaUrl.hashCode()); + String $metaUrl = this.getMetaUrl(); + result = result * 59 + ($metaUrl == null ? 43 : $metaUrl.hashCode()); + Date $time = this.getTime(); + result = result * 59 + ($time == null ? 43 : ((Object)$time).hashCode()); + String $strTime = this.getStrTime(); + result = result * 59 + ($strTime == null ? 43 : $strTime.hashCode()); + String $speciesName = this.getSpeciesName(); + result = result * 59 + ($speciesName == null ? 43 : $speciesName.hashCode()); + BigDecimal $longitude = this.getLongitude(); + result = result * 59 + ($longitude == null ? 43 : ((Object)$longitude).hashCode()); + BigDecimal $latitude = this.getLatitude(); + result = result * 59 + ($latitude == null ? 43 : ((Object)$latitude).hashCode()); + String $description = this.getDescription(); + result = result * 59 + ($description == null ? 43 : $description.hashCode()); + String $fileUrl = this.getFileUrl(); + result = result * 59 + ($fileUrl == null ? 43 : $fileUrl.hashCode()); + List $array = this.getArray(); + result = result * 59 + ($array == null ? 43 : ((Object)$array).hashCode()); + return result; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecord.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecord.java new file mode 100644 index 0000000..c65f3b0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecord.java @@ -0,0 +1,209 @@ +package net.hzvtc.data.check.domain; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import java.util.List; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="ResultRecord") +public class ResultRecord +extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long recordId; + @Excel(name="\u8bbe\u5907id") + private Long deviceId; + @Excel(name="\u8bbe\u5907\u540d\u79f0") + private String deviceName; + private Long areaId; + @JsonFormat(pattern="yyyy-MM-dd") + @Excel(name="\u76d1\u6d4b\u65f6\u95f4", width=30.0, dateFormat="yyyy-MM-dd HH:mm:ss") + private Date recordTime; + private String strRecordTime; + @Excel(name="\u76d1\u6d4b\u7c7b\u578b") + private String recordType; + private Long oldRecordId; + private List list; + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("recordId", (Object)this.getRecordId()).append("deviceId", (Object)this.getDeviceId()).append("recordTime", (Object)this.getRecordTime()).append("recordType", (Object)this.getRecordType()).toString(); + } + + public static ResultRecord parserObject(JSONObject object) { + ResultRecord data = new ResultRecord(); + data.setRecordId(object.getLong("recordId")); + data.setRecordType(object.getString("recordType")); + data.setDeviceId(object.getLong("deviceId")); + data.setStrRecordTime(object.getString("strRecordTime")); + JSONArray array = JSONArray.parseArray((String)object.getString("list")); + if (array != null) { + data.setList(array.toJavaList(ResultRecordDetails.class)); + } + return data; + } + + public Long getRecordId() { + return this.recordId; + } + + public Long getDeviceId() { + return this.deviceId; + } + + public String getDeviceName() { + return this.deviceName; + } + + public Long getAreaId() { + return this.areaId; + } + + public Date getRecordTime() { + return this.recordTime; + } + + public String getStrRecordTime() { + return this.strRecordTime; + } + + public String getRecordType() { + return this.recordType; + } + + public Long getOldRecordId() { + return this.oldRecordId; + } + + public List getList() { + return this.list; + } + + public void setRecordId(Long recordId) { + this.recordId = recordId; + } + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + public void setDeviceName(String deviceName) { + this.deviceName = deviceName; + } + + public void setAreaId(Long areaId) { + this.areaId = areaId; + } + + @JsonFormat(pattern="yyyy-MM-dd") + public void setRecordTime(Date recordTime) { + this.recordTime = recordTime; + } + + public void setStrRecordTime(String strRecordTime) { + this.strRecordTime = strRecordTime; + } + + public void setRecordType(String recordType) { + this.recordType = recordType; + } + + public void setOldRecordId(Long oldRecordId) { + this.oldRecordId = oldRecordId; + } + + public void setList(List list) { + this.list = list; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ResultRecord)) { + return false; + } + ResultRecord other = (ResultRecord)((Object)o); + if (!other.canEqual((Object)this)) { + return false; + } + Long this$recordId = this.getRecordId(); + Long other$recordId = other.getRecordId(); + if (this$recordId == null ? other$recordId != null : !((Object)this$recordId).equals(other$recordId)) { + return false; + } + Long this$deviceId = this.getDeviceId(); + Long other$deviceId = other.getDeviceId(); + if (this$deviceId == null ? other$deviceId != null : !((Object)this$deviceId).equals(other$deviceId)) { + return false; + } + Long this$areaId = this.getAreaId(); + Long other$areaId = other.getAreaId(); + if (this$areaId == null ? other$areaId != null : !((Object)this$areaId).equals(other$areaId)) { + return false; + } + Long this$oldRecordId = this.getOldRecordId(); + Long other$oldRecordId = other.getOldRecordId(); + if (this$oldRecordId == null ? other$oldRecordId != null : !((Object)this$oldRecordId).equals(other$oldRecordId)) { + return false; + } + String this$deviceName = this.getDeviceName(); + String other$deviceName = other.getDeviceName(); + if (this$deviceName == null ? other$deviceName != null : !this$deviceName.equals(other$deviceName)) { + return false; + } + Date this$recordTime = this.getRecordTime(); + Date other$recordTime = other.getRecordTime(); + if (this$recordTime == null ? other$recordTime != null : !((Object)this$recordTime).equals(other$recordTime)) { + return false; + } + String this$strRecordTime = this.getStrRecordTime(); + String other$strRecordTime = other.getStrRecordTime(); + if (this$strRecordTime == null ? other$strRecordTime != null : !this$strRecordTime.equals(other$strRecordTime)) { + return false; + } + String this$recordType = this.getRecordType(); + String other$recordType = other.getRecordType(); + if (this$recordType == null ? other$recordType != null : !this$recordType.equals(other$recordType)) { + return false; + } + List this$list = this.getList(); + List other$list = other.getList(); + return !(this$list == null ? other$list != null : !((Object)this$list).equals(other$list)); + } + + protected boolean canEqual(Object other) { + return other instanceof ResultRecord; + } + + public int hashCode() { + int PRIME = 59; + int result = 1; + Long $recordId = this.getRecordId(); + result = result * 59 + ($recordId == null ? 43 : ((Object)$recordId).hashCode()); + Long $deviceId = this.getDeviceId(); + result = result * 59 + ($deviceId == null ? 43 : ((Object)$deviceId).hashCode()); + Long $areaId = this.getAreaId(); + result = result * 59 + ($areaId == null ? 43 : ((Object)$areaId).hashCode()); + Long $oldRecordId = this.getOldRecordId(); + result = result * 59 + ($oldRecordId == null ? 43 : ((Object)$oldRecordId).hashCode()); + String $deviceName = this.getDeviceName(); + result = result * 59 + ($deviceName == null ? 43 : $deviceName.hashCode()); + Date $recordTime = this.getRecordTime(); + result = result * 59 + ($recordTime == null ? 43 : ((Object)$recordTime).hashCode()); + String $strRecordTime = this.getStrRecordTime(); + result = result * 59 + ($strRecordTime == null ? 43 : $strRecordTime.hashCode()); + String $recordType = this.getRecordType(); + result = result * 59 + ($recordType == null ? 43 : $recordType.hashCode()); + List $list = this.getList(); + result = result * 59 + ($list == null ? 43 : ((Object)$list).hashCode()); + return result; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecordDetails.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecordDetails.java new file mode 100644 index 0000000..6909f14 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/domain/ResultRecordDetails.java @@ -0,0 +1,345 @@ +package net.hzvtc.data.check.domain; + +import com.alibaba.fastjson.JSONObject; +import java.io.Serializable; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.data.check.domain.ResultMedia; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="ResultRecordDetails") +public class ResultRecordDetails +implements Serializable { + private static final long serialVersionUID = 1L; + private Long detailsId; + @Excel(name="\u8bb0\u5f55id") + private Long recordId; + @Excel(name="\u7269\u79cdid") + private Long speciesId; + @Excel(name="\u7269\u79cd\u540d\u79f0") + private String speciesName; + @Excel(name="\u751f\u5883") + private String habitat; + @Excel(name="\u6570\u91cf") + private int count; + @Excel(name="\u4f4d\u7f6e") + private String location; + @Excel(name="\u7f6e\u4fe1\u5ea6") + private double confidence; + @Excel(name="\u5a92\u4f53id") + private Long mediaId; + @Excel(name="\u4f4d\u7f6e\u6a2a\u5750\u6807") + private String locationSiteX; + @Excel(name="\u4f4d\u7f6e\u7eb5\u5750\u6807") + private String locationSiteY; + private boolean checked; + private int isDeleted = 0; + private ResultMedia resultMedia; + private Long oldRecordId; + private Long oldMediaId; + private Long areaId; + private String recordTime; + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("detailsId", (Object)this.getDetailsId()).append("recordId", (Object)this.getRecordId()).append("speciesId", (Object)this.getSpeciesId()).append("habitat", (Object)this.getHabitat()).append("count", this.getCount()).append("location", (Object)this.getLocation()).append("confidence", this.getConfidence()).append("mediaId", (Object)this.getMediaId()).append("locationSiteX", (Object)this.getLocationSiteX()).append("locationSiteY", (Object)this.getLocationSiteY()).toString(); + } + + public static ResultRecordDetails parserObject(JSONObject object) { + ResultRecordDetails data = new ResultRecordDetails(); + data.setDetailsId(object.getLong("detailsId")); + data.setRecordId(object.getLong("recordId")); + data.setHabitat(object.getString("habitat")); + data.setCount(object.getInteger("count")); + data.setSpeciesId(object.getLong("speciesId")); + data.setConfidence(object.getDouble("confidence")); + data.setMediaId(object.getLong("mediaId")); + data.setLocationSiteX(object.getString("locationSiteX")); + data.setLocationSiteY(object.getString("locationSiteY")); + data.setChecked(object.getBoolean("checked")); + data.setIsDeleted(object.getInteger("isDeleted")); + return data; + } + + public Long getDetailsId() { + return this.detailsId; + } + + public Long getRecordId() { + return this.recordId; + } + + public Long getSpeciesId() { + return this.speciesId; + } + + public String getSpeciesName() { + return this.speciesName; + } + + public String getHabitat() { + return this.habitat; + } + + public int getCount() { + return this.count; + } + + public String getLocation() { + return this.location; + } + + public double getConfidence() { + return this.confidence; + } + + public Long getMediaId() { + return this.mediaId; + } + + public String getLocationSiteX() { + return this.locationSiteX; + } + + public String getLocationSiteY() { + return this.locationSiteY; + } + + public boolean isChecked() { + return this.checked; + } + + public int getIsDeleted() { + return this.isDeleted; + } + + public ResultMedia getResultMedia() { + return this.resultMedia; + } + + public Long getOldRecordId() { + return this.oldRecordId; + } + + public Long getOldMediaId() { + return this.oldMediaId; + } + + public Long getAreaId() { + return this.areaId; + } + + public String getRecordTime() { + return this.recordTime; + } + + public void setDetailsId(Long detailsId) { + this.detailsId = detailsId; + } + + public void setRecordId(Long recordId) { + this.recordId = recordId; + } + + public void setSpeciesId(Long speciesId) { + this.speciesId = speciesId; + } + + public void setSpeciesName(String speciesName) { + this.speciesName = speciesName; + } + + public void setHabitat(String habitat) { + this.habitat = habitat; + } + + public void setCount(int count) { + this.count = count; + } + + public void setLocation(String location) { + this.location = location; + } + + public void setConfidence(double confidence) { + this.confidence = confidence; + } + + public void setMediaId(Long mediaId) { + this.mediaId = mediaId; + } + + public void setLocationSiteX(String locationSiteX) { + this.locationSiteX = locationSiteX; + } + + public void setLocationSiteY(String locationSiteY) { + this.locationSiteY = locationSiteY; + } + + public void setChecked(boolean checked) { + this.checked = checked; + } + + public void setIsDeleted(int isDeleted) { + this.isDeleted = isDeleted; + } + + public void setResultMedia(ResultMedia resultMedia) { + this.resultMedia = resultMedia; + } + + public void setOldRecordId(Long oldRecordId) { + this.oldRecordId = oldRecordId; + } + + public void setOldMediaId(Long oldMediaId) { + this.oldMediaId = oldMediaId; + } + + public void setAreaId(Long areaId) { + this.areaId = areaId; + } + + public void setRecordTime(String recordTime) { + this.recordTime = recordTime; + } + + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof ResultRecordDetails)) { + return false; + } + ResultRecordDetails other = (ResultRecordDetails)o; + if (!other.canEqual(this)) { + return false; + } + if (this.getCount() != other.getCount()) { + return false; + } + if (Double.compare(this.getConfidence(), other.getConfidence()) != 0) { + return false; + } + if (this.isChecked() != other.isChecked()) { + return false; + } + if (this.getIsDeleted() != other.getIsDeleted()) { + return false; + } + Long this$detailsId = this.getDetailsId(); + Long other$detailsId = other.getDetailsId(); + if (this$detailsId == null ? other$detailsId != null : !((Object)this$detailsId).equals(other$detailsId)) { + return false; + } + Long this$recordId = this.getRecordId(); + Long other$recordId = other.getRecordId(); + if (this$recordId == null ? other$recordId != null : !((Object)this$recordId).equals(other$recordId)) { + return false; + } + Long this$speciesId = this.getSpeciesId(); + Long other$speciesId = other.getSpeciesId(); + if (this$speciesId == null ? other$speciesId != null : !((Object)this$speciesId).equals(other$speciesId)) { + return false; + } + Long this$mediaId = this.getMediaId(); + Long other$mediaId = other.getMediaId(); + if (this$mediaId == null ? other$mediaId != null : !((Object)this$mediaId).equals(other$mediaId)) { + return false; + } + Long this$oldRecordId = this.getOldRecordId(); + Long other$oldRecordId = other.getOldRecordId(); + if (this$oldRecordId == null ? other$oldRecordId != null : !((Object)this$oldRecordId).equals(other$oldRecordId)) { + return false; + } + Long this$oldMediaId = this.getOldMediaId(); + Long other$oldMediaId = other.getOldMediaId(); + if (this$oldMediaId == null ? other$oldMediaId != null : !((Object)this$oldMediaId).equals(other$oldMediaId)) { + return false; + } + Long this$areaId = this.getAreaId(); + Long other$areaId = other.getAreaId(); + if (this$areaId == null ? other$areaId != null : !((Object)this$areaId).equals(other$areaId)) { + return false; + } + String this$speciesName = this.getSpeciesName(); + String other$speciesName = other.getSpeciesName(); + if (this$speciesName == null ? other$speciesName != null : !this$speciesName.equals(other$speciesName)) { + return false; + } + String this$habitat = this.getHabitat(); + String other$habitat = other.getHabitat(); + if (this$habitat == null ? other$habitat != null : !this$habitat.equals(other$habitat)) { + return false; + } + String this$location = this.getLocation(); + String other$location = other.getLocation(); + if (this$location == null ? other$location != null : !this$location.equals(other$location)) { + return false; + } + String this$locationSiteX = this.getLocationSiteX(); + String other$locationSiteX = other.getLocationSiteX(); + if (this$locationSiteX == null ? other$locationSiteX != null : !this$locationSiteX.equals(other$locationSiteX)) { + return false; + } + String this$locationSiteY = this.getLocationSiteY(); + String other$locationSiteY = other.getLocationSiteY(); + if (this$locationSiteY == null ? other$locationSiteY != null : !this$locationSiteY.equals(other$locationSiteY)) { + return false; + } + ResultMedia this$resultMedia = this.getResultMedia(); + ResultMedia other$resultMedia = other.getResultMedia(); + if (this$resultMedia == null ? other$resultMedia != null : !((Object)((Object)this$resultMedia)).equals((Object)other$resultMedia)) { + return false; + } + String this$recordTime = this.getRecordTime(); + String other$recordTime = other.getRecordTime(); + return !(this$recordTime == null ? other$recordTime != null : !this$recordTime.equals(other$recordTime)); + } + + protected boolean canEqual(Object other) { + return other instanceof ResultRecordDetails; + } + + public int hashCode() { + int PRIME = 59; + int result = 1; + result = result * 59 + this.getCount(); + long $confidence = Double.doubleToLongBits(this.getConfidence()); + result = result * 59 + (int)($confidence >>> 32 ^ $confidence); + result = result * 59 + (this.isChecked() ? 79 : 97); + result = result * 59 + this.getIsDeleted(); + Long $detailsId = this.getDetailsId(); + result = result * 59 + ($detailsId == null ? 43 : ((Object)$detailsId).hashCode()); + Long $recordId = this.getRecordId(); + result = result * 59 + ($recordId == null ? 43 : ((Object)$recordId).hashCode()); + Long $speciesId = this.getSpeciesId(); + result = result * 59 + ($speciesId == null ? 43 : ((Object)$speciesId).hashCode()); + Long $mediaId = this.getMediaId(); + result = result * 59 + ($mediaId == null ? 43 : ((Object)$mediaId).hashCode()); + Long $oldRecordId = this.getOldRecordId(); + result = result * 59 + ($oldRecordId == null ? 43 : ((Object)$oldRecordId).hashCode()); + Long $oldMediaId = this.getOldMediaId(); + result = result * 59 + ($oldMediaId == null ? 43 : ((Object)$oldMediaId).hashCode()); + Long $areaId = this.getAreaId(); + result = result * 59 + ($areaId == null ? 43 : ((Object)$areaId).hashCode()); + String $speciesName = this.getSpeciesName(); + result = result * 59 + ($speciesName == null ? 43 : $speciesName.hashCode()); + String $habitat = this.getHabitat(); + result = result * 59 + ($habitat == null ? 43 : $habitat.hashCode()); + String $location = this.getLocation(); + result = result * 59 + ($location == null ? 43 : $location.hashCode()); + String $locationSiteX = this.getLocationSiteX(); + result = result * 59 + ($locationSiteX == null ? 43 : $locationSiteX.hashCode()); + String $locationSiteY = this.getLocationSiteY(); + result = result * 59 + ($locationSiteY == null ? 43 : $locationSiteY.hashCode()); + ResultMedia $resultMedia = this.getResultMedia(); + result = result * 59 + ($resultMedia == null ? 43 : ((Object)((Object)$resultMedia)).hashCode()); + String $recordTime = this.getRecordTime(); + result = result * 59 + ($recordTime == null ? 43 : $recordTime.hashCode()); + return result; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/FavoriteMediaMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/FavoriteMediaMapper.java new file mode 100644 index 0000000..40b9aec --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/FavoriteMediaMapper.java @@ -0,0 +1,24 @@ +package net.hzvtc.data.check.mapper; + +import java.util.List; +import net.hzvtc.data.check.domain.FavoriteMedia; + +public interface FavoriteMediaMapper { + public FavoriteMedia selectFavoriteMediaById(Long var1); + + public List selectFavoriteMediaList(FavoriteMedia var1); + + public int insertFavoriteMedia(FavoriteMedia var1); + + public int updateFavoriteMedia(FavoriteMedia var1); + + public int deleteFavoriteMediaById(Long var1); + + public int deleteFavoriteMediaByIds(Long[] var1); + + public Long getFavoriteMediaByMediaId(Long var1); + + public int deleteFavoriteMediaByMediaId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/MediaItemMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/MediaItemMapper.java new file mode 100644 index 0000000..f02ab9a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/MediaItemMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.data.check.mapper; + +import java.util.List; +import net.hzvtc.data.check.domain.MediaItem; + +/** + * 视频(图像)状态参数Mapper接口 + * + * @author admin + * @date 2024-06-18 + */ +public interface MediaItemMapper +{ + /** + * 查询视频(图像)状态参数 + * + * @param id 视频(图像)状态参数主键 + * @return 视频(图像)状态参数 + */ + public MediaItem selectMediaItemById(Long id); + + /** + * 查询视频(图像)状态参数列表 + * + * @param mediaItem 视频(图像)状态参数 + * @return 视频(图像)状态参数集合 + */ + public List selectMediaItemList(MediaItem mediaItem); + + /** + * 新增视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + public int insertMediaItem(MediaItem mediaItem); + + /** + * 修改视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + public int updateMediaItem(MediaItem mediaItem); + + /** + * 删除视频(图像)状态参数 + * + * @param id 视频(图像)状态参数主键 + * @return 结果 + */ + public int deleteMediaItemById(Long id); + + /** + * 批量删除视频(图像)状态参数 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteMediaItemByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultMediaMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultMediaMapper.java new file mode 100644 index 0000000..5f4528e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultMediaMapper.java @@ -0,0 +1,69 @@ +package net.hzvtc.data.check.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.data.check.domain.ResultMedia; + +public interface ResultMediaMapper { + public List selectResultMediaList(ResultMedia var1); + + public List selectResultMediaListByParam(ResultMedia var1); + + public List getResultMediaListByParam(Map var1); + + public List getResultAudioMediaListByParam(Map var1); + + public ResultMedia getResultMediaListById(Long var1); + + public List getBirdMediaListByParam(Map var1); + + public List getSpeciesMediaListForQuery(Map var1); + + public List getVideoMediaListByParam(Map var1); + + public List getAudioMediaListByParam(Map var1); + + public List getFavoriteVideoListByParam(Map var1); + + public Integer getResultMediaStatAmountByParam(Map var1); + + public int deleteResultRealMediaByParam(Long var1); + + public int insertResultMedia(ResultMedia var1); + + public int deleteResultMediaByMediaIds(Long[] var1); + + public ResultMedia getResultMediaById(Long var1); + + public int deleteResultMediaById(Long var1); + + public ResultMedia getResultInfoForStatByParam(Map var1); + + public int getResultMediaAmountByParam(Map var1); + + public List getResultMediaDeviceListByParam(Map var1); + + public int updateResultMediaStatusByParam(ResultMedia var1); + + public int recoverResultMediaStateByParam(Map var1); + + public List getRecordMediaDataList(Map var1); + + public long getMaxMediaId(); + + public List getVideoListForPush(Map var1); + + public List getResultMediaByIds(List var1); + + public int batchInsertResultMedia(List var1); + + public List getVideoListForPostByParam(Map var1); + + public List getMediaVideoUrlListByParam(Map var1); + + public List getResultMediaEmptyFileUrlList(); + + public int updateFileUrl(ResultMedia var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordDetailsMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordDetailsMapper.java new file mode 100644 index 0000000..3b41f19 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordDetailsMapper.java @@ -0,0 +1,71 @@ +package net.hzvtc.data.check.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface ResultRecordDetailsMapper { + public ResultRecordDetails selectResultRecordDetailsByDetailsId(Long var1); + + public List selectResultRecordDetailsList(ResultRecordDetails var1); + + public int insertResultRecordDetails(ResultRecordDetails var1); + + public int updateResultRecordDetails(ResultRecordDetails var1); + + public int updateResultRecordDetailsByIds(Map var1); + + public List checkResultRecordsByParam(ResultRecordDetails var1); + + public int updateResultRecordDetailsCheckState(Long var1); + + public int updateResultStatByIds(List var1); + + public int deleteResultRecordDetailsByDetailsId(Long var1); + + public int updateResultRecordDetailsStatusById(Map var1); + + public int deleteResultRecordDetailsByDetailsIds(Long[] var1); + + public List querySpeciesRecordListByParam(Map var1); + + public List querySpeciesRecordNewListByParam(Map var1); + + public List getSpeciesMediaListByParam(Map var1); + + public List getResultMediaVideoListByParam(Map var1); + + public List getSpeciesListByParam(Long var1); + + public List getSpeciesListByUserId(Map var1); + + public List getSpeciesDateListByParam(Map var1); + + public List checkIsNewSpeciesByParam(Map var1); + + public List getLevelOneSpeciesLitByParam(Map var1); + + public List getCrOrEnSpeciesLitByParam(Map var1); + + public List getSpeciesHourAmountListByParam(Map var1); + + public List getSpeciesAudioAmountReportByParam(Map var1); + + public List getAudioStatListByParam(Map var1); + + public long getAudioErrorStatByParam(Map var1); + + public List getResultMediaByMediaId(Long var1); + + public long getRecordDetailCountByDeviceId(long var1); + + public int batchInsertResultRecordDetails(List var1); + + public int updateByOldRecordId(Long var1); + + public int updateByOldMediaId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordMapper.java new file mode 100644 index 0000000..b3e5992 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/mapper/ResultRecordMapper.java @@ -0,0 +1,37 @@ +package net.hzvtc.data.check.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.data.check.domain.ResultRecord; + +public interface ResultRecordMapper { + public ResultRecord selectResultRecordByRecordId(Long var1); + + public List selectResultRecordList(ResultRecord var1); + + public List getResultAreaListByParam(Map var1); + + public List getResultRecordIdsByParam(Map var1); + + public int insertResultRecord(ResultRecord var1); + + public int updateResultRecord(ResultRecord var1); + + public int deleteResultRecordByRecordId(Long var1); + + public int deleteResultRecordByRecordIds(Long[] var1); + + public List getCurrentDateResultRecordList(Map var1); + + public List getAudioResultRecordDataListForApi(Map var1); + + public List getResultRecordDataPushList(Map var1); + + public int batchInsertResultRecord(List var1); + + public ResultRecord getResultRecordInfoBySpeciesId(Map var1); + + public long getMaxId(Integer var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/FavoriteMediaService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/FavoriteMediaService.java new file mode 100644 index 0000000..65f3447 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/FavoriteMediaService.java @@ -0,0 +1,24 @@ +package net.hzvtc.data.check.service; + +import java.util.List; +import net.hzvtc.data.check.domain.FavoriteMedia; + +public interface FavoriteMediaService { + public FavoriteMedia selectFavoriteMediaById(Long var1); + + public List selectFavoriteMediaList(FavoriteMedia var1); + + public int insertFavoriteMedia(FavoriteMedia var1); + + public int updateFavoriteMedia(FavoriteMedia var1); + + public int deleteFavoriteMediaByIds(Long[] var1); + + public int deleteFavoriteMediaById(Long var1); + + public Long getFavoriteMediaByMediaId(Long var1); + + public Long handleAction(FavoriteMedia var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/MediaItemService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/MediaItemService.java new file mode 100644 index 0000000..f114ff6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/MediaItemService.java @@ -0,0 +1,61 @@ +package net.hzvtc.data.check.service; + +import net.hzvtc.data.check.domain.MediaItem; + +import java.util.List; + +/** + * 视频(图像)状态参数Service接口 + * + * @author admin + * @date 2024-06-18 + */ +public interface MediaItemService { + /** + * 查询视频(图像)状态参数 + * + * @param id 视频(图像)状态参数主键 + * @return 视频(图像)状态参数 + */ + public MediaItem selectMediaItemById(Long id); + + /** + * 查询视频(图像)状态参数列表 + * + * @param mediaItem 视频(图像)状态参数 + * @return 视频(图像)状态参数集合 + */ + public List selectMediaItemList(MediaItem mediaItem); + + /** + * 新增视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + public int insertMediaItem(MediaItem mediaItem); + + /** + * 修改视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + public int updateMediaItem(MediaItem mediaItem); + + /** + * 批量删除视频(图像)状态参数 + * + * @param ids 需要删除的视频(图像)状态参数主键集合 + * @return 结果 + */ + public int deleteMediaItemByIds(Long[] ids); + + /** + * 删除视频(图像)状态参数信息 + * + * @param id 视频(图像)状态参数主键 + * @return 结果 + */ + public int deleteMediaItemById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultMediaService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultMediaService.java new file mode 100644 index 0000000..2edc5cd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultMediaService.java @@ -0,0 +1,68 @@ +package net.hzvtc.data.check.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.data.check.domain.ResultMedia; + +public interface ResultMediaService { + public List selectResultMediaList(ResultMedia var1); + + public List getResultMediaListByParam(Map var1); + + public List getResultAudioMediaListByParam(Map var1); + + public List getBirdMediaListByParam(Map var1); + + public List selectResultMediaListByParam(ResultMedia var1); + + public List getSpeciesMediaListForQuery(JSONObject var1); + + public int deleteResultRealMediaByParam(Long var1); + + public int insertResultMedia(ResultMedia var1); + + public ResultMedia getResultMediaListById(Long var1); + + public int deleteResultMediaByMediaIds(Long[] var1); + + public ResultMedia getResultInfoForStatByParam(Map var1); + + public int updateResultMediaStatusByParam(ResultMedia var1); + + public int recoverResultMediaStateByParam(Map var1); + + public List getVideoMediaListByParam(Map var1); + + public int getResultMediaAmountByParam(Map var1); + + public List getResultMediaDeviceListByParam(Map var1); + + public List getFavoriteVideoListByParam(JSONObject var1); + + public JSONObject getResultMediaStatByParam(); + + public List getRecordMediaDataList(JSONObject var1); + + public long getMaxMediaId(); + + public int batchInsertResultMedia(List var1); + + public int deleteResultMediaById(Long var1); + + public void getVideoListForPush(Long var1); + + public void getVideoListForHuiXianPost(); + + public List getAudioMediaListByParam(Map var1); + + public ResultMedia getMediaVideoUrlListByParam(Map var1); + + public List getResultMediaByIds(List var1); + + public List getResultMediaEmptyFileUrlList(); + + public int updateFileUrl(ResultMedia var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordDetailsService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordDetailsService.java new file mode 100644 index 0000000..8b682d2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordDetailsService.java @@ -0,0 +1,73 @@ +package net.hzvtc.data.check.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface ResultRecordDetailsService { + public ResultRecordDetails selectResultRecordDetailsByDetailsId(Long var1); + + public List selectResultRecordDetailsList(ResultRecordDetails var1); + + public int insertResultRecordDetails(ResultRecordDetails var1); + + public int updateResultRecordDetails(ResultRecordDetails var1); + + public int updateResultRecordDetailsByIds(JSONObject var1); + + public int deleteResultRecordDetailsByDetailsIds(Long[] var1); + + public int deleteResultRecordDetails(JSONObject var1); + + public int deleteResultRecordDetailsByParam(JSONObject var1); + + public int deleteResultRecordDetailsByDetailsId(Long var1); + + public List querySpeciesRecordListByParam(JSONObject var1); + + public List getSpeciesMediaListByParam(JSONObject var1); + + public List getResultMediaVideoListByParam(JSONObject var1); + + public JSONArray getSpeciesHourAmountListByParam(JSONObject var1); + + public JSONArray getSpeciesListByParam(JSONObject var1); + + public int updateResultRecordDetailsCheckState(Long var1); + + public int updateResultRecordDetailsCheckState(String var1); + + public List getLevelOneSpeciesLitByParam(Map var1); + + public List getCrOrEnSpeciesLitByParam(Map var1); + + public List getSpeciesListByUserId(Long var1); + + public List getSpeciesDateListByParam(Map var1); + + public List checkIsNewSpeciesByParam(Map var1); + + public JSONObject getSpeciesAudioAmountReportByParam(JSONObject var1); + + public long getRecordDetailCountByDeviceId(long var1); + + public int batchInsertResultRecordDetails(List var1); + + public int updateByOldRecordId(Long var1); + + public int updateByOldMediaId(Long var1); + + public List getAudioStatListByParam(JSONObject var1); + + public long getAudioErrorStatByParam(JSONObject var1); + + public String createAudioReportFile(Map var1); + + public int updateResultRecordDetailsStatusById(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordExtractService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordExtractService.java new file mode 100644 index 0000000..8c78197 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordExtractService.java @@ -0,0 +1,18 @@ +package net.hzvtc.data.check.service; + +import com.alibaba.fastjson.JSONObject; +import org.springframework.web.multipart.MultipartFile; + +public interface ResultRecordExtractService { + public void extraAudioRecordDataList(); + + public long getMaxId(Integer var1); + + public boolean saveResultRecordPostData(JSONObject var1); + + public boolean getResultRecordListToPush(JSONObject var1); + + public boolean saveRemoteFile(MultipartFile var1, String var2); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordService.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordService.java new file mode 100644 index 0000000..c229e2d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/ResultRecordService.java @@ -0,0 +1,52 @@ +package net.hzvtc.data.check.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.data.check.domain.ResultRecord; + +public interface ResultRecordService { + public ResultRecord selectResultRecordByRecordId(Long var1); + + public List selectResultRecordList(ResultRecord var1); + + public int insertResultRecord(ResultRecord var1); + + public int updateResultRecord(ResultRecord var1); + + public int deleteResultRecordByRecordIds(Long[] var1); + + public int deleteResultRecordByRecordId(Long var1); + + public JSONObject getBirdDataStatByParam(JSONObject var1); + + public String getBirdDataStatFileByParam(JSONObject var1); + + public void sendBirdDataStatEmail(); + + public void sendBirdDataWeeklyStatEmail(); + + public boolean sendBirdDataStatEmail(JSONObject var1); + + public boolean sendBirdDataWeeklyStatEmail(JSONObject var1); + + public JSONObject getBirdDataWeeklyStatByParam(JSONObject var1); + + public String getBirdDataWeeklyStatFileByParam(JSONObject var1); + + public String getBirdDataMonthlyStatFileByParam(JSONObject var1); + + public List getResultAreaListByParam(Map var1); + + public List getResultRecordIdsByParam(Map var1); + + public List getCurrentDateResultRecordList(JSONObject var1); + + public JSONObject getAudioResultRecordDataListForApi(JSONObject var1); + + public int batchInsertResultRecord(List var1); + + public ResultRecord getResultRecordInfoBySpeciesId(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/FavoriteMediaServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/FavoriteMediaServiceImpl.java new file mode 100644 index 0000000..2b4f80c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/FavoriteMediaServiceImpl.java @@ -0,0 +1,108 @@ +package net.hzvtc.data.check.service.impl; + +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.domain.FavoriteMedia; +import net.hzvtc.data.check.mapper.FavoriteMediaMapper; +import net.hzvtc.data.check.service.FavoriteMediaService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; + +/** + * 收藏的视频Service业务层处理 + * + * @author admin + * @date 2024-06-18 + */ +@Service +public class FavoriteMediaServiceImpl implements FavoriteMediaService { + @Resource + private FavoriteMediaMapper favoriteMediaMapper; + + /** + * 查询收藏的视频 + * + * @param id 收藏的视频主键 + * @return 收藏的视频 + */ + @Override + public FavoriteMedia selectFavoriteMediaById(Long id) { + return favoriteMediaMapper.selectFavoriteMediaById(id); + } + + /** + * 查询收藏的视频列表 + * + * @param favoriteMedia 收藏的视频 + * @return 收藏的视频 + */ + @Override + public List selectFavoriteMediaList(FavoriteMedia favoriteMedia) { + return favoriteMediaMapper.selectFavoriteMediaList(favoriteMedia); + } + + /** + * 新增收藏的视频 + * + * @param favoriteMedia 收藏的视频 + * @return 结果 + */ + @Override + public int insertFavoriteMedia(FavoriteMedia favoriteMedia) { + return favoriteMediaMapper.insertFavoriteMedia(favoriteMedia); + } + + /** + * 修改收藏的视频 + * + * @param favoriteMedia 收藏的视频 + * @return 结果 + */ + @Override + public int updateFavoriteMedia(FavoriteMedia favoriteMedia) { + return favoriteMediaMapper.updateFavoriteMedia(favoriteMedia); + } + + /** + * 批量删除收藏的视频 + * + * @param ids 需要删除的收藏的视频主键 + * @return 结果 + */ + @Override + public int deleteFavoriteMediaByIds(Long[] ids) { + return favoriteMediaMapper.deleteFavoriteMediaByIds(ids); + } + + /** + * 删除收藏的视频信息 + * + * @param id 收藏的视频主键 + * @return 结果 + */ + @Override + public int deleteFavoriteMediaById(Long id) { + return favoriteMediaMapper.deleteFavoriteMediaById(id); + } + + @Override + public Long getFavoriteMediaByMediaId(Long id) { + return favoriteMediaMapper.getFavoriteMediaByMediaId(id); + } + + @Override + public Long handleAction(FavoriteMedia favoriteMedia) { + if (favoriteMedia.getId() == null || favoriteMedia.getId() == 0L) { + favoriteMedia.setUserId(SecurityUtils.getUserId()); + favoriteMedia.setCreateDate(new Date()); + favoriteMedia.setIsDeleted(0); + favoriteMediaMapper.insertFavoriteMedia(favoriteMedia); + return favoriteMedia.getId(); + } else { + favoriteMediaMapper.deleteFavoriteMediaByMediaId(favoriteMedia.getMediaId()); + return 0L; + } + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/MediaItemServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/MediaItemServiceImpl.java new file mode 100644 index 0000000..87e8210 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/MediaItemServiceImpl.java @@ -0,0 +1,87 @@ +package net.hzvtc.data.check.service.impl; + +import java.util.List; +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import net.hzvtc.data.check.mapper.MediaItemMapper; +import net.hzvtc.data.check.domain.MediaItem; +import net.hzvtc.data.check.service.MediaItemService; + +/** + * 视频(图像)状态参数Service业务层处理 + * + * @author admin + * @date 2024-06-18 + */ +@Service +public class MediaItemServiceImpl implements MediaItemService { + @Resource + private MediaItemMapper mediaItemMapper; + + /** + * 查询视频(图像)状态参数 + * + * @param id 视频(图像)状态参数主键 + * @return 视频(图像)状态参数 + */ + @Override + public MediaItem selectMediaItemById(Long id) { + return mediaItemMapper.selectMediaItemById(id); + } + + /** + * 查询视频(图像)状态参数列表 + * + * @param mediaItem 视频(图像)状态参数 + * @return 视频(图像)状态参数 + */ + @Override + public List selectMediaItemList(MediaItem mediaItem) { + return mediaItemMapper.selectMediaItemList(mediaItem); + } + + /** + * 新增视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + @Override + public int insertMediaItem(MediaItem mediaItem) { + return mediaItemMapper.insertMediaItem(mediaItem); + } + + /** + * 修改视频(图像)状态参数 + * + * @param mediaItem 视频(图像)状态参数 + * @return 结果 + */ + @Override + public int updateMediaItem(MediaItem mediaItem) { + return mediaItemMapper.updateMediaItem(mediaItem); + } + + /** + * 批量删除视频(图像)状态参数 + * + * @param ids 需要删除的视频(图像)状态参数主键 + * @return 结果 + */ + @Override + public int deleteMediaItemByIds(Long[] ids) { + return mediaItemMapper.deleteMediaItemByIds(ids); + } + + /** + * 删除视频(图像)状态参数信息 + * + * @param id 视频(图像)状态参数主键 + * @return 结果 + */ + @Override + public int deleteMediaItemById(Long id) { + return mediaItemMapper.deleteMediaItemById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultMediaServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultMediaServiceImpl.java new file mode 100644 index 0000000..08eebdf --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultMediaServiceImpl.java @@ -0,0 +1,388 @@ +package net.hzvtc.data.check.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Resource; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.mapper.ResultMediaMapper; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.job.domain.TableStatInfo; +import net.hzvtc.data.job.service.TableStatInfoService; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class ResultMediaServiceImpl +implements ResultMediaService { + private static final Logger log = LoggerFactory.getLogger(ResultMediaServiceImpl.class); + @Resource + private ResultMediaMapper resultMediaMapper; + @Value(value="${VideoPostUrl.yuyuantanUrl}") + private String postUrl; + @Value(value="${VideoPostUrl.huiXianPostUrl}") + private String huixianPostUrl; + @Value(value="${hzvtc.fileServerUrl}") + private String fileServerUrl; + private final TableStatInfoService tableStatInfoService; + + @Override + public List selectResultMediaList(ResultMedia resultMedia) { + return this.resultMediaMapper.selectResultMediaList(resultMedia); + } + + @Override + public List getResultMediaListByParam(Map map) { + return this.resultMediaMapper.getResultMediaListByParam(map); + } + + @Override + public List getResultAudioMediaListByParam(Map map) { + return this.resultMediaMapper.getResultAudioMediaListByParam(map); + } + + @Override + public List getBirdMediaListByParam(Map map) { + return this.resultMediaMapper.getBirdMediaListByParam(map); + } + + @Override + public List selectResultMediaListByParam(ResultMedia resultMedia) { + return this.resultMediaMapper.selectResultMediaListByParam(resultMedia); + } + + @Override + public List getSpeciesMediaListForQuery(JSONObject object) { + HashMap map = new HashMap(); + Long areaId = object.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = object.getLong("deviceId"); + map.put("deviceId", deviceId); + String dateFrom = object.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = object.getString("dateTo"); + map.put("dateTo", dateTo); + String mediaTypes = object.getString("mediaTypes"); + if (mediaTypes != null && !mediaTypes.isEmpty()) { + String[] arrs = mediaTypes.split(","); + int[] arr = Arrays.stream(arrs).mapToInt(Integer::parseInt).toArray(); + map.put("mediaTypes", arr); + } + Integer limit = object.getInteger("limit"); + map.put("limit", limit); + return this.resultMediaMapper.getSpeciesMediaListForQuery(map); + } + + @Override + public int deleteResultRealMediaByParam(Long deviceId) { + return this.resultMediaMapper.deleteResultRealMediaByParam(deviceId); + } + + @Override + public int insertResultMedia(ResultMedia data) { + return this.resultMediaMapper.insertResultMedia(data); + } + + @Override + public ResultMedia getResultMediaListById(Long id) { + return this.resultMediaMapper.getResultMediaListById(id); + } + + @Override + public int deleteResultMediaByMediaIds(Long[] mediaIds) { + return this.resultMediaMapper.deleteResultMediaByMediaIds(mediaIds); + } + + @Override + public ResultMedia getResultInfoForStatByParam(Map map) { + return this.resultMediaMapper.getResultInfoForStatByParam(map); + } + + @Override + @Transactional + public int updateResultMediaStatusByParam(ResultMedia param) { + HashMap data = new HashMap(); + data.put("isDeleted", param.getIsDeleted()); + data.put("mediaId", param.getMediaId()); + return this.resultMediaMapper.updateResultMediaStatusByParam(param); + } + + @Override + public int recoverResultMediaStateByParam(Map map) { + return this.resultMediaMapper.recoverResultMediaStateByParam(map); + } + + @Override + public List getVideoMediaListByParam(Map map) { + return this.resultMediaMapper.getVideoMediaListByParam(map); + } + + @Override + public int getResultMediaAmountByParam(Map map) { + return this.resultMediaMapper.getResultMediaAmountByParam(map); + } + + @Override + public List getResultMediaDeviceListByParam(Map map) { + return this.resultMediaMapper.getResultMediaDeviceListByParam(map); + } + + @Override + public List getFavoriteVideoListByParam(JSONObject object) { + HashMap map = new HashMap(); + return this.resultMediaMapper.getFavoriteVideoListByParam(map); + } + + @Override + public JSONObject getResultMediaStatByParam() { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + map.put("mediaType", 3); + Integer count = this.resultMediaMapper.getResultMediaStatAmountByParam(map); + result.put("videoAmount", (Object)(count == null ? 0 : count)); + map.put("mediaType", 2); + count = this.resultMediaMapper.getResultMediaStatAmountByParam(map); + result.put("imageAmount", (Object)(count == null ? 0 : count)); + return result; + } + + @Override + public List getRecordMediaDataList(JSONObject param) { + HashMap map = new HashMap(); + map.put("mediaType", 1); + Long mediaId = param.getLong("mediaId"); + map.put("mediaId", mediaId); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + return this.resultMediaMapper.getRecordMediaDataList(map); + } + + @Override + public long getMaxMediaId() { + return this.resultMediaMapper.getMaxMediaId(); + } + + @Override + public int batchInsertResultMedia(List list) { + return this.resultMediaMapper.batchInsertResultMedia(list); + } + + @Override + public int deleteResultMediaById(Long mediaId) { + return this.resultMediaMapper.deleteResultMediaById(mediaId); + } + + @Override + public void getVideoListForPush(Long areaId) { + TableStatInfo data = new TableStatInfo(); + data.setType(2); + List list = this.tableStatInfoService.selectTableStatInfoList(data); + Long maxId = 0L; + if (list != null && !list.isEmpty()) { + maxId = list.get(0).getTableId(); + data = list.get(0); + } + HashMap map = new HashMap(); + map.put("areaId", areaId); + map.put("maxId", maxId); + List mediaList = this.resultMediaMapper.getVideoListForPush(map); + if (mediaList != null && !mediaList.isEmpty()) { + JSONArray array = new JSONArray(); + mediaList.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("mediaId", (Object)item.getMediaId()); + String url = item.getMediaUrl(); + if (url.startsWith("/")) { + obj.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + obj.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + url = item.getMetaUrl(); + if (url.startsWith("/")) { + obj.put("posterImg", (Object)(this.fileServerUrl + url)); + } else { + obj.put("posterImg", (Object)(this.fileServerUrl + "/" + url)); + } + obj.put("time", (Object)item.getTime()); + obj.put("deviceId", (Object)item.getDeviceId()); + obj.put("deviceName", (Object)item.getDeviceName()); + array.add((Object)obj); + }); + JSONObject postData = new JSONObject(); + postData.put("data", (Object)array); + postData.put("type", (Object)"type1"); + this.postVideoData(postData); + maxId = mediaList.get(mediaList.size() - 1).getMediaId(); + data.setTableId(maxId); + if (data.getId() == null) { + this.tableStatInfoService.insertTableStatInfo(data); + } else { + this.tableStatInfoService.updateTableStatInfo(data); + } + } + } + + @Override + public void getVideoListForHuiXianPost() { + TableStatInfo data = new TableStatInfo(); + data.setType(5); + List list = this.tableStatInfoService.selectTableStatInfoList(data); + Long maxId = 0L; + if (list != null && !list.isEmpty()) { + maxId = list.get(0).getTableId(); + data = list.get(0); + } + HashMap map = new HashMap(); + map.put("areaId", 58); + map.put("maxId", maxId); + List resultMedias = this.resultMediaMapper.getVideoListForPostByParam(map); + if (resultMedias == null || resultMedias.isEmpty()) { + return; + } + for (ResultMedia item : resultMedias) { + JSONObject object = new JSONObject(); + object.put("speciesName", (Object)item.getSpeciesName()); + String url = item.getMediaUrl(); + if (url != null) { + if (url.startsWith("/")) { + object.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + object.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + } + if ((url = item.getMetaUrl()) != null) { + if (url.startsWith("/")) { + object.put("imgPath", (Object)(this.fileServerUrl + url)); + } else { + object.put("imgPath", (Object)(this.fileServerUrl + "/" + url)); + } + } + object.put("time", (Object)item.getTime()); + object.put("mediaId", (Object)item.getMediaId()); + object.put("deviceId", (Object)item.getDeviceId()); + object.put("deviceName", (Object)item.getDeviceName()); + object.put("lat", (Object)item.getLatitude()); + object.put("lon", (Object)item.getLongitude()); + this.sentData(object); + } + maxId = resultMedias.get(resultMedias.size() - 1).getMediaId(); + data.setTableId(maxId); + if (data.getId() == null) { + this.tableStatInfoService.insertTableStatInfo(data); + } else { + this.tableStatInfoService.updateTableStatInfo(data); + } + } + + @Override + public List getAudioMediaListByParam(Map map) { + return this.resultMediaMapper.getAudioMediaListByParam(map); + } + + @Override + public ResultMedia getMediaVideoUrlListByParam(Map param) { + List list = this.resultMediaMapper.getMediaVideoUrlListByParam(param); + if (list.isEmpty()) { + return null; + } + for (ResultMedia item : list) { + if (item.getMetaUrl() == null) continue; + return item; + } + return list.get(0); + } + + @Override + public List getResultMediaByIds(List list) { + return this.resultMediaMapper.getResultMediaByIds(list); + } + + @Override + public List getResultMediaEmptyFileUrlList() { + return this.resultMediaMapper.getResultMediaEmptyFileUrlList(); + } + + @Override + public int updateFileUrl(ResultMedia resultMedia) { + return this.resultMediaMapper.updateFileUrl(resultMedia); + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + private void sentData(JSONObject object) { + CloseableHttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(this.huixianPostUrl); + try { + StringEntity s = new StringEntity(object.toString(), StandardCharsets.UTF_8); + log.info(object.toString()); + s.setContentEncoding("UTF-8"); + s.setContentType("application/json"); + post.setEntity((HttpEntity)s); + CloseableHttpResponse res = client.execute((HttpUriRequest)post); + if (res.getStatusLine().getStatusCode() == 200) { + HttpEntity entity = res.getEntity(); + String result = EntityUtils.toString((HttpEntity)res.getEntity()); + System.out.println(result); + } + } + catch (Exception e) { + log.error("===error===", (Throwable)e); + } + finally { + try { + client.close(); + } + catch (Exception exception) {} + } + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + private void postVideoData(JSONObject data) { + CloseableHttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(this.postUrl); + try { + StringEntity s = new StringEntity(data.toString(), StandardCharsets.UTF_8); + s.setContentEncoding("UTF-8"); + s.setContentType("application/json"); + post.setEntity((HttpEntity)s); + CloseableHttpResponse res = client.execute((HttpUriRequest)post); + if (res.getStatusLine().getStatusCode() == 200) { + String result = EntityUtils.toString((HttpEntity)res.getEntity()); + System.out.println(result); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + finally { + try { + client.close(); + } + catch (Exception exception) {} + } + } + + public ResultMediaServiceImpl(TableStatInfoService tableStatInfoService) { + this.tableStatInfoService = tableStatInfoService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordDetailsServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordDetailsServiceImpl.java new file mode 100644 index 0000000..d70f5dc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordDetailsServiceImpl.java @@ -0,0 +1,686 @@ +package net.hzvtc.data.check.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.area.mapper.SpeciesAbnormalInfoMapper; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.common.utils.CommonUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.data.check.mapper.ResultMediaMapper; +import net.hzvtc.data.check.mapper.ResultRecordDetailsMapper; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xddf.usermodel.chart.*; +import org.apache.poi.xssf.usermodel.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.time.LocalDate; +import java.util.*; +import java.util.stream.Collectors; + +/** + * 监测记录详细信息Service业务层处理 + * + * @author admin + * @date 2022-08-22 + */ +@Service +@RequiredArgsConstructor +public class ResultRecordDetailsServiceImpl implements ResultRecordDetailsService { + @Resource + private ResultRecordDetailsMapper resultRecordDetailsMapper; + @Resource + private ResultMediaMapper resultMediaMapper; + + private final ProtectedAreaService protectedAreaService; + + private final SpeciesDailyStatService speciesDailyStatService; + + private final ProtectedAreaSpeciesService protectedAreaSpeciesService; + + @Resource + private SpeciesAbnormalInfoMapper speciesAbnormalInfoMapper; + + @Value("${hzvtc.dailyReportFilePath}") + private String dailyReportFilePath; + + @Value("${hzvtc.dailyReportFileOutPath}") + private String dailyReportFileOutPath; + + /** + * 查询监测记录详细信息 + * + * @param detailsId 监测记录详细信息主键 + * @return 监测记录详细信息 + */ + @Override + public ResultRecordDetails selectResultRecordDetailsByDetailsId(Long detailsId) { + return resultRecordDetailsMapper.selectResultRecordDetailsByDetailsId(detailsId); + } + + /** + * 查询监测记录详细信息列表 + * + * @param resultRecordDetails 监测记录详细信息 + * @return 监测记录详细信息 + */ + @Override + public List selectResultRecordDetailsList(ResultRecordDetails resultRecordDetails) { + return resultRecordDetailsMapper.selectResultRecordDetailsList(resultRecordDetails); + } + + /** + * 新增监测记录详细信息 + * + * @param resultRecordDetails 监测记录详细信息 + * @return 结果 + */ + @Override + public int insertResultRecordDetails(ResultRecordDetails resultRecordDetails) { + return resultRecordDetailsMapper.insertResultRecordDetails(resultRecordDetails); + } + + /** + * 修改监测记录详细信息 + * + * @param resultRecordDetails 监测记录详细信息 + * @return 结果 + */ + @Override + @Transactional + public int updateResultRecordDetails(ResultRecordDetails resultRecordDetails) { + List list = resultRecordDetailsMapper.checkResultRecordsByParam(resultRecordDetails); + if (list == null || list.isEmpty()) { + resultRecordDetailsMapper.updateResultRecordDetails(resultRecordDetails); + } else { + resultRecordDetailsMapper.deleteResultRecordDetailsByDetailsId(resultRecordDetails.getDetailsId()); + } + JSONObject param = new JSONObject(); + param.put("areaId", resultRecordDetails.getAreaId()); + if (resultRecordDetails.getRecordTime() != null) { + param.put("calcDate", resultRecordDetails.getRecordTime().substring(0, 10)); + } + speciesDailyStatService.calculateDailyResultRecordByParam(param); + return 1; + } + + @Override + @Transactional + public int updateResultRecordDetailsByIds(JSONObject object) { + List list = new ArrayList<>(); + String location = object.getString("location"); + String[] arr = location.split(","); + for (String str : arr) { + list.add(Long.parseLong(str)); + } + Map map = new HashMap<>(); + map.put("list", list); + map.put("speciesId", object.getLong("speciesId")); + map.put("checked", true); + resultRecordDetailsMapper.updateResultRecordDetailsByIds(map); + String str = object.getString("recordTime"); + if (str != null) { + String[] array = str.split(","); + JSONObject param = new JSONObject(); + param.put("areaId", object.getLong("areaId")); + for (String time : array) { + param.put("calcDate", time.substring(0, 10)); + speciesDailyStatService.calculateDailyResultRecordByParam(param); + } + } + return 1; + } + + /** + * 批量删除监测记录详细信息 + * + * @param detailsIds 需要删除的监测记录详细信息主键 + * @return 结果 + */ + @Override + public int deleteResultRecordDetailsByDetailsIds(Long[] detailsIds) { + return resultRecordDetailsMapper.deleteResultRecordDetailsByDetailsIds(detailsIds); + } + + @Override + @Transactional + public int deleteResultRecordDetails(JSONObject obj) { + Long id = obj.getLong("id"); + int count = resultRecordDetailsMapper.deleteResultRecordDetailsByDetailsId(id); + Long mediaId = obj.getLong("mediaId"); + String recordTime = obj.getString("recordTime"); + if (recordTime != null && !recordTime.isEmpty()) { + recordTime = recordTime.substring(0, 10); + obj.put("calcDate", recordTime); + } + speciesDailyStatService.calculateDailyResultRecordByParam(obj); + List list = resultRecordDetailsMapper.getResultMediaByMediaId(mediaId); + speciesAbnormalInfoMapper.deleteSpeciesAbnormalInfoByMediaId(mediaId); + + if (list == null || list.isEmpty()) { + resultMediaMapper.deleteResultMediaById(mediaId); + } + return count; + } + + @Override + @Transactional + public int deleteResultRecordDetailsByParam(JSONObject object) { + + JSONArray array = object.getJSONArray("list"); + if (array.isEmpty()) { + return 0; + } + Long areaId = object.getLong("areaId"); + Set dateSet = new HashSet<>(); + Long[] mids = new Long[array.size()]; + Long[] ids = new Long[array.size()]; + int i = 0; + for (Object obj : array) { + JSONObject jobj = JSONObject.parseObject(JSON.toJSONString(obj)); + mids[i] = jobj.getLong("mediaId"); + ids[i++] = jobj.getLong("id"); + String recordTime = jobj.getString("recordTime"); + if (recordTime != null && !recordTime.isEmpty()) { + dateSet.add(recordTime.substring(0, 10)); + } + } + resultRecordDetailsMapper.deleteResultRecordDetailsByDetailsIds(ids); + for (Long mediaId : mids) { + List list = resultRecordDetailsMapper.getResultMediaByMediaId(mediaId); + if (list == null || list.isEmpty()) { + resultMediaMapper.deleteResultMediaById(mediaId); + } + } + JSONObject obj = new JSONObject(); + obj.put("areaId", areaId); + dateSet.forEach(item -> { +// System.out.println("================" + item); + obj.put("calcDate", item); + speciesDailyStatService.calculateDailyResultRecordByParam(obj); + }); +// resultMediaMapper.deleteResultMediaByMediaIds(mids); + return array.size(); + } + + /** + * 删除监测记录详细信息信息 + * + * @param detailsId 监测记录详细信息主键 + * @return 结果 + */ + @Override + public int deleteResultRecordDetailsByDetailsId(Long detailsId) { + return resultRecordDetailsMapper.deleteResultRecordDetailsByDetailsId(detailsId); + } + + @Override + public List querySpeciesRecordListByParam(JSONObject obj) { + Map map = new HashMap<>(); + Integer queryType = obj.getInteger("queryType"); + if (queryType == null || queryType != 1) { + Long areaId = obj.getLong("areaId"); + if (areaId == null) { + Long userId = SecurityUtils.getUserId(); + if (userId != 1L) { + List ids = protectedAreaService.getAreaIdsByUserId(userId); + if (ids != null && !ids.isEmpty()) { + map.put("areaIds", ids); + } else { + return new ArrayList<>(); + } + } + } else { + map.put("areaId", areaId); + } + } + + Long speciesId = obj.getLong("speciesId"); + map.put("speciesId", speciesId); + String dateFrom = obj.getString("dateFrom"); + String dateTo = obj.getString("dateTo"); + map.put("dateFrom", dateFrom); + map.put("dateTo", dateTo); + Long deviceId = obj.getLong("deviceId"); + map.put("deviceId", deviceId); + Integer mediaType = obj.getInteger("mediaType"); + map.put("mediaType", mediaType); + String mediaTypes = obj.getString("mediaTypes"); + if (mediaTypes != null && !mediaTypes.isEmpty()) { + String[] arr = mediaTypes.split(","); + map.put("mediaTypes", arr); + } +// return resultRecordDetailsMapper.querySpeciesRecordListByParam(map); + return resultRecordDetailsMapper.querySpeciesRecordNewListByParam(map); + } + + @Override + public List getSpeciesMediaListByParam(JSONObject obj) { + Map map = new HashMap<>(); + Long areaId = obj.getLong("areaId"); + map.put("areaId", areaId); + Integer mediaType = obj.getInteger("mediaType"); + map.put("mediaType", mediaType); + Long deviceId = obj.getLong("deviceId"); + map.put("deviceId", deviceId); + String dateFrom = obj.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = obj.getString("dateTo"); + map.put("dateTo", dateTo); + return resultRecordDetailsMapper.getSpeciesMediaListByParam(map); + } + + @Override + public List getResultMediaVideoListByParam(JSONObject obj) { + Map map = new HashMap<>(); + Long areaId = obj.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = obj.getLong("deviceId"); + map.put("deviceId", deviceId); + String dateFrom = obj.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = obj.getString("dateTo"); + map.put("dateTo", dateTo); + return resultRecordDetailsMapper.getResultMediaVideoListByParam(map); + } + + @Override + public JSONArray getSpeciesHourAmountListByParam(JSONObject param) { + JSONArray result = new JSONArray(); + Map map = new HashMap<>(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + if (deviceId == null && areaId == null) { + return result; + } + Integer recordTypeNot = param.getInteger("recordTypeNot"); + map.put("recordTypeNot", recordTypeNot); + Integer recordType = param.getInteger("recordType"); + map.put("recordType", recordType); + Integer calcYear = param.getInteger("calcYear"); + if (calcYear == null) { + calcYear = LocalDate.now().getYear(); + } + map.put("calcYear", calcYear); + for (int i = 0; i < 4; i++) { + JSONObject obj = new JSONObject(); + obj.put("name", (i + 1) + "季度"); + obj.put("code", i + 1); + map.put("monthFrom", i * 3 + 1); + map.put("monthTo", i * 3 + 3); + List list = resultRecordDetailsMapper.getSpeciesHourAmountListByParam(map); + obj.put("list", list); + result.add(obj); + } + return result; + } + + @Override + public JSONArray getSpeciesListByParam(JSONObject obj) { + Long areaId = obj.getLong("areaId"); + JSONArray array = new JSONArray(); + if (areaId == null) { + return array; + } + + List list = resultRecordDetailsMapper.getSpeciesListByParam(areaId); + if (list == null || list.isEmpty()) { + return array; + } else { + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("speciesId", item.getSpeciesId()); + object.put("speciesName", item.getSpeciesName()); + array.add(object); + }); + List ids = protectedAreaSpeciesService.getProtectedAreaSpeciesListByParams(obj); + if (ids != null && !ids.isEmpty()) { + CommonUtils.sortArrayByParam(array, ids); + } + } + return array; + } + + @Override + public int updateResultRecordDetailsCheckState(Long id) { + return resultRecordDetailsMapper.updateResultRecordDetailsCheckState(id); + } + + @Override + public int updateResultRecordDetailsCheckState(String ids) { + String[] arr = ids.split(","); + List list = new ArrayList<>(); + for (String str : arr) { + list.add(Long.parseLong(str)); + } + return resultRecordDetailsMapper.updateResultStatByIds(list); + } + + @Override + public List getLevelOneSpeciesLitByParam(Map map) { + return resultRecordDetailsMapper.getLevelOneSpeciesLitByParam(map); + } + + @Override + public List getCrOrEnSpeciesLitByParam(Map map) { + return resultRecordDetailsMapper.getCrOrEnSpeciesLitByParam(map); + } + + @Override + public List getSpeciesListByUserId(Long areaId) { + Map map = new HashMap<>(); + if (areaId != null) { + map.put("areaId", areaId); + } else { + Long userId = SecurityUtils.getUserId(); + if (userId == null) { + userId = 0L; + } else if (userId <= 1L) { + userId = null; + } + map.put("userId", userId); + } + return resultRecordDetailsMapper.getSpeciesListByUserId(map); + } + + @Override + public List getSpeciesDateListByParam(Map map) { + return resultRecordDetailsMapper.getSpeciesDateListByParam(map); + } + + @Override + public List checkIsNewSpeciesByParam(Map map) { + return resultRecordDetailsMapper.checkIsNewSpeciesByParam(map); + } + + @Override + public JSONObject getSpeciesAudioAmountReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + Long deviceId = param.getLong("deviceId"); + if (areaId == null && deviceId == null) { + return result; + } + Map map = new HashMap<>(); + map.put("areaId", areaId); + map.put("deviceId", deviceId); + Integer calcYear = param.getInteger("calcYear"); + map.put("calcYear", calcYear); + Integer calcMonth = param.getInteger("calcMonth"); + map.put("calcMonth", calcMonth); + Integer monthFrom = param.getInteger("monthFrom"); + map.put("monthFrom", monthFrom); + Integer monthTo = param.getInteger("monthTo"); + map.put("monthTo", monthTo); + List list = resultRecordDetailsMapper.getSpeciesAudioAmountReportByParam(map); + result.put("list", list); + result.put("catalogueAmount", speciesDailyStatService.getBirdCatalogueAmount()); + result.put("familyAmount", speciesDailyStatService.getBirdFamilyAmount()); + result.put("genusAmount", speciesDailyStatService.getBirdGenusAmount()); + return result; + } + + @Override + public long getRecordDetailCountByDeviceId(long deviceId) { + return resultRecordDetailsMapper.getRecordDetailCountByDeviceId(deviceId); + } + + @Override + public int batchInsertResultRecordDetails(List list) { + return resultRecordDetailsMapper.batchInsertResultRecordDetails(list); + } + + @Override + public int updateByOldRecordId(Long oldRecordId) { + return resultRecordDetailsMapper.updateByOldRecordId(oldRecordId); + } + + @Override + public int updateByOldMediaId(Long oldRecordId) { + return resultRecordDetailsMapper.updateByOldMediaId(oldRecordId); + } + + @Override + public List getAudioStatListByParam(JSONObject param) { + Map map = new HashMap<>(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return new ArrayList<>(); + } + map.put("areaId", areaId); + String dateFrom = param.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = param.getString("dateTo"); + map.put("dateTo", dateTo); + + String calcDate = param.getString("calcDate"); + map.put("calcDate", calcDate); + +// try { +// createAudioReportFile(null); +// } catch (Exception ex) { +// ex.printStackTrace(); +// } + + return resultRecordDetailsMapper.getAudioStatListByParam(map); + } + + @Override + public long getAudioErrorStatByParam(JSONObject param) { + Map map = new HashMap<>(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return 0; + } + map.put("areaId", areaId); + String dateFrom = param.getString("dateFrom"); + map.put("dateFrom", dateFrom); + String dateTo = param.getString("dateTo"); + map.put("dateTo", dateTo); + String calcDate = param.getString("calcDate"); + map.put("calcDate", calcDate); + return resultRecordDetailsMapper.getAudioErrorStatByParam(map); + } + + @Override + public String createAudioReportFile(Map param) { + String str = (String) param.get("areaId"); + if (str == null || str.isEmpty()) { + return "500"; + } + Long areaId = Long.parseLong(str); + String areaName = ""; + if (areaId != null) { + ProtectedArea protectedArea = protectedAreaService.selectProtectedAreaById(areaId); + areaName = protectedArea.getName(); + } + + try { + XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(dailyReportFilePath + "audio_report_tmpl.xlsx")); + + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(0).getCell(0).setCellValue(areaName + "鸟类音频监测简报"); + String calcDate = (String) param.get("calcDate"); + String dateFrom = ""; + String dateTo = ""; + if (calcDate != null) { + String arr[] = calcDate.split("-"); + dateFrom = arr[0] + "年" + arr[1] + "月" + arr[2] + "日"; + dateTo = dateFrom; + } else { + dateFrom = (String) param.get("dateFrom"); + if (dateFrom == null) { + dateFrom = "系统部署开始"; + } else { + String arr[] = dateFrom.split("-"); + dateFrom = arr[0] + "年" + arr[1] + "月"; + } + + dateTo = (String) param.get("dateFrom"); + if (dateTo == null) { + dateFrom = "今天"; + } else { + String arr[] = dateTo.split("-"); + dateTo = arr[0] + "年" + arr[1] + "月"; + } + } + + long errorRecords = resultRecordDetailsMapper.getAudioErrorStatByParam(param); + List list = resultRecordDetailsMapper.getAudioStatListByParam(param); + long totalRecords = list.stream().mapToLong(BirdStatDataVo::getCount).sum(); + Map> groupedByDate = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getShortDate)); + Map> groupedBySpeciesId = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getId)); + sheet.getRow(2).getCell(0).setCellValue(String.format(" 中国科学院半导体研究所联合%s管理单位在%s开展鸟类音频智能监测示范应用,截止到%s,系统共采集有效音频记录%d条,经过智能识别与校对,监测到有效物种%d种。", areaName, areaName, dateTo, totalRecords, groupedBySpeciesId.size())); + sheet.getRow(4).getCell(0).setCellValue(String.format(" 从%s开始,统计截止%s,系统共收到%d条音频记录,有效音频记录%d条,共监测到%d个物种。", dateFrom, dateTo, totalRecords + errorRecords, totalRecords, groupedBySpeciesId.size())); + sheet.getRow(5).getCell(0).setCellValue(String.format("%s至%s监测记录柱状图及饼图如下:", dateFrom, dateTo)); + int row = 0; + for (Map.Entry> entry : groupedByDate.entrySet()) { + XSSFCell cell = sheet.getRow(row).getCell(3); + if (cell == null) { + cell = sheet.getRow(row).createCell(3); + } + cell.setCellValue(entry.getKey()); + List elist = entry.getValue(); + long amount = elist.stream().mapToLong(BirdStatDataVo::getCount).sum(); + cell = sheet.getRow(row).getCell(4); + if (cell == null) { + cell = sheet.getRow(row).createCell(4); + } + cell.setCellValue(amount); + row++; + } +// sheet.setColumnHidden(3, true); +// sheet.setColumnHidden(4, true); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); +// XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 6, 3, 6); + XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 6, 3, 11); + XSSFChart chart = drawing.createChart(anchor); + chart.setTitleText("鸟类声音监测按月统计"); + chart.setTitleOverlay(false); + int len = groupedByDate.size(); + + XDDFDataSource categories = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, len - 1, 3, 3)); + XDDFNumericalDataSource values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, len - 1, 4, 4)); + XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); + XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); + XDDFBarChartData dataChart = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis); + XDDFChartData.Series series = dataChart.addSeries(categories, values); + series.setTitle("Values", null); + dataChart.setBarDirection(BarDirection.COL); +// XDDFBarChart barChart = (XDDFBarChart) dataChart; +// barChart.setBarDirection(BarDirection.BAR); + chart.plot(dataChart); + + row = 19; + long sum = 0; + XSSFRow xlsRow = null; + XSSFCell cell = null; + len = groupedBySpeciesId.size(); + for (Map.Entry> entry : groupedBySpeciesId.entrySet()) { + List elist = entry.getValue(); + BirdStatDataVo data = elist.get(0); + long amount = elist.stream().mapToLong(BirdStatDataVo::getCount).sum(); + sum += amount; + xlsRow = sheet.getRow(row); + if (xlsRow == null) { + xlsRow = sheet.createRow(row); + } + cell = xlsRow.getCell(0); + if (cell == null) { + cell = xlsRow.createCell(0); + } + cell.setCellValue(data.getName()); + + cell = xlsRow.getCell(1); + if (cell == null) { + cell = xlsRow.createCell(1); + } + cell.setCellValue(data.getEname()); + + cell = xlsRow.getCell(2); + if (cell == null) { + cell = xlsRow.createCell(2); + } + cell.setCellValue(amount); + row++; + } + xlsRow = sheet.getRow(row); + if (xlsRow == null) { + xlsRow = sheet.createRow(row); + } + cell = xlsRow.getCell(0); + if (cell == null) { + cell = xlsRow.createCell(0); + } + cell.setCellValue("总计"); + cell = xlsRow.getCell(2); + if (cell == null) { + cell = xlsRow.createCell(2); + } + cell.setCellValue(sum); + + drawing = sheet.createDrawingPatriarch(); + + xlsRow = sheet.getRow(7); + if (xlsRow == null) { + xlsRow = sheet.createRow(7); + } + cell = xlsRow.getCell(0); + if (cell == null) { + cell = xlsRow.createCell(0); + } + // Define the anchor point for the chart + anchor = drawing.createAnchor(0, 0, 0, 0, 0, 11, 3, 18); + + // Create a chart object + chart = drawing.createChart(anchor); + chart.setTitleText("鸟类物种监测统计"); + chart.setTitleOverlay(false); + + // Create a data source for the chart + categories = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(19, 19 + len - 1, 0, 0)); + values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(19, 19 + len - 1, 2, 2)); + + // Create the pie chart data + XDDFChartData pieChart = chart.createData(ChartTypes.PIE, null, null); + series = pieChart.addSeries(categories, values); + series.setTitle("Categories", null); + chart.plot(pieChart); + String outfile = dailyReportFileOutPath + areaName + "(鸟类音频监测简报)" + ".xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write(fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } catch (Exception ex) { +// ex.printStackTrace(); + return null; + } + + } + + @Override + public int updateResultRecordDetailsStatusById(JSONObject param) { + Map data = new HashMap<>(); + Integer isDeleted = param.getInteger("isDeleted"); + data.put("isDeleted", isDeleted); + Long id = param.getLong("detailsId"); + data.put("id", id); + return resultRecordDetailsMapper.updateResultRecordDetailsStatusById(data); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordExtractServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordExtractServiceImpl.java new file mode 100644 index 0000000..fbf865b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordExtractServiceImpl.java @@ -0,0 +1,304 @@ +package net.hzvtc.data.check.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.FileAttribute; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.data.check.mapper.ResultRecordMapper; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.data.check.service.ResultRecordExtractService; +import net.hzvtc.data.check.service.ResultRecordService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.multipart.MultipartFile; + +@Service +public class ResultRecordExtractServiceImpl +implements ResultRecordExtractService { + private static final Logger log = LoggerFactory.getLogger(ResultRecordExtractServiceImpl.class); + private final ResultRecordService resultRecordService; + @Value(value="${hzvtc.extractServerUrl}") + private String extractServerUrl; + @Value(value="${hzvtc.birdMediaPath}") + private String mediaRootPath; + private final ResultRecordDetailsService resultRecordDetailsService; + private final ResultMediaService resultMediaService; + @Resource + private ResultRecordMapper resultRecordMapper; + @Value(value="${hzvtc.dianChiServerUrl}") + private String dianChiServerUrl; + @Value(value="${hzvtc.extractFileServerUrl}") + private String extractFileServerUrl; + + @Override + @Transactional + public void extraAudioRecordDataList() { + JSONArray mediaArray; + JSONObject param = new JSONObject(); + param.put("areaId", (Object)36); + long maxRecordId = this.getMaxId(3); + param.put("recordId", (Object)maxRecordId); + String url = this.extractServerUrl + "/web/species/api/recordAudioList"; + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity request = new HttpEntity((Object)param, (MultiValueMap)headers); + RestTemplate restTemplate = new RestTemplate(); + JSONObject jsonObject = (JSONObject)restTemplate.exchange(url, HttpMethod.POST, request, JSONObject.class, new Object[0]).getBody(); + if (jsonObject == null) { + return; + } + ArrayList list = new ArrayList(); + JSONArray array = jsonObject.getJSONArray("recordList"); + if (array == null || array.isEmpty()) { + return; + } + array.forEach(obj -> { + String jsonStr = JSON.toJSONString((Object)obj); + JSONObject data = JSON.parseObject((String)jsonStr); + ResultRecord record = ResultRecord.parserObject(data); + list.add(record); + }); + ArrayList details = new ArrayList(); + if (!list.isEmpty()) { + this.resultRecordMapper.batchInsertResultRecord(list); + list.forEach(record -> details.addAll(record.getList())); + this.resultRecordDetailsService.batchInsertResultRecordDetails(details); + } + if ((mediaArray = jsonObject.getJSONArray("mediaList")) == null || mediaArray.isEmpty()) { + return; + } + ArrayList mediaList = new ArrayList(); + mediaArray.forEach(obj -> { + String jsonStr = JSON.toJSONString((Object)obj); + JSONObject data = JSON.parseObject((String)jsonStr); + mediaList.add(ResultMedia.parserObject(data)); + }); + if (!mediaList.isEmpty()) { + this.resultMediaService.batchInsertResultMedia(mediaList); + } + } + + private void saveMediaFile(List mediaList) { + mediaList.forEach(item -> { + if (item.getMetaUrl() != null && !item.getMetaUrl().isEmpty()) { + this.downloadMediaFile(item.getMetaUrl()); + } + if (item.getMediaUrl() != null && !item.getMediaUrl().isEmpty()) { + this.downloadMediaFile(item.getMediaUrl()); + } + }); + } + + @Override + public long getMaxId(Integer recordType) { + return this.resultRecordMapper.getMaxId(recordType); + } + + @Override + public boolean saveResultRecordPostData(JSONObject data) { + JSONArray array = data.getJSONArray("recordList"); + ArrayList list = new ArrayList(); + ArrayList details = new ArrayList(); + if (array != null && !array.isEmpty()) { + array.forEach(obj -> { + String jsonStr = JSON.toJSONString((Object)obj); + JSONObject jsonObject = JSON.parseObject((String)jsonStr); + ResultRecord record = ResultRecord.parserObject(jsonObject); + list.add(record); + }); + if (!list.isEmpty()) { + this.resultRecordMapper.batchInsertResultRecord(list); + list.forEach(record -> details.addAll(record.getList())); + this.resultRecordDetailsService.batchInsertResultRecordDetails(details); + } + ArrayList mediaList = new ArrayList(); + array = data.getJSONArray("mediaList"); + if (array != null && !array.isEmpty()) { + array.forEach(obj -> { + String jsonStr = JSON.toJSONString((Object)obj); + JSONObject jsonObject = JSON.parseObject((String)jsonStr); + ResultMedia item = ResultMedia.parserObject(jsonObject); + mediaList.add(item); + }); + this.resultMediaService.batchInsertResultMedia(mediaList); + } + } + return true; + } + + @Override + @Transactional + public boolean getResultRecordListToPush(JSONObject data) { + HashMap map = new HashMap(); + Long areaId = data.getLong("areaId"); + map.put("areaId", areaId); + String url = this.dianChiServerUrl + "/dataCheck/checkRecord/maxId"; + RestTemplate restTemplate = new RestTemplate(); + Long maxRecordId = (Long)restTemplate.exchange(url, HttpMethod.GET, null, Long.class, new Object[0]).getBody(); + map.put("recordId", maxRecordId); + JSONObject object = new JSONObject(); + List list = this.resultRecordMapper.getResultRecordDataPushList(map); + if (list != null && !list.isEmpty()) { + object.put("maxRecordId", (Object)maxRecordId); + object.put("recordList", list); + List mediaIds = list.stream().flatMap(item -> item.getList().stream()).map(ResultRecordDetails::getMediaId).collect(Collectors.toList()); + List mediaList = this.resultMediaService.getResultMediaByIds(mediaIds); + object.put("mediaList", mediaList); + url = this.dianChiServerUrl + "/dataCheck/checkRecord/savePushDataList"; + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + HttpEntity request = new HttpEntity((Object)object, (MultiValueMap)headers); + AjaxResult result = (AjaxResult)restTemplate.exchange(url, HttpMethod.POST, request, AjaxResult.class, new Object[0]).getBody(); + log.info("===={}", (Object)result); + } + return true; + } + + @Override + public boolean saveRemoteFile(MultipartFile file, String fileName) { + try { + Path destination = Paths.get(this.mediaRootPath + "/test" + File.separator + fileName, new String[0]).toAbsolutePath().normalize(); + Path parentDir = destination.getParent(); + if (parentDir != null && !Files.exists(parentDir, new LinkOption[0])) { + Files.createDirectories(parentDir, new FileAttribute[0]); + } + try (InputStream is = file.getInputStream();){ + Files.copy(is, destination, StandardCopyOption.REPLACE_EXISTING); + } + return true; + } + catch (Exception e) { + log.error("error", (Throwable)e); + return false; + } + } + + private void downloadMediaFile(String mediaUrl) { + try { + HttpURLConnection httpConn; + block30: { + Path destination = Paths.get(this.mediaRootPath + File.separator + mediaUrl, new String[0]).toAbsolutePath().normalize(); + if (Files.exists(destination, new LinkOption[0])) { + return; + } + URL url = new URL(this.extractFileServerUrl + "/" + mediaUrl); + httpConn = (HttpURLConnection)url.openConnection(); + Path parentDir = destination.getParent(); + if (parentDir != null && !Files.exists(parentDir, new LinkOption[0])) { + Files.createDirectories(parentDir, new FileAttribute[0]); + } + httpConn.setRequestMethod("GET"); + httpConn.setConnectTimeout(10000); + httpConn.setReadTimeout(10000); + int responseCode = httpConn.getResponseCode(); + if (responseCode == 200) { + try (BufferedInputStream inputStream = new BufferedInputStream(httpConn.getInputStream()); + FileOutputStream outputStream = new FileOutputStream(destination.toString());){ + int bytesRead; + byte[] buffer = new byte[4096]; + while ((bytesRead = ((InputStream)inputStream).read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + log.info("\u6587\u4ef6\u4e0b\u8f7d\u5b8c\u6210\uff0c\u4fdd\u5b58\u8def\u5f84\u4e3a\uff1a" + destination.toAbsolutePath()); + break block30; + } + } + log.error("\u4e0b\u8f7d\u5931\u8d25\uff0c\u54cd\u5e94\u7801\uff1a" + responseCode); + } + httpConn.disconnect(); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + private Path resolveSymbolicLink(String linkPath) { + try { + Path path = Paths.get(linkPath, new String[0]).toAbsolutePath(); + while (Files.isSymbolicLink(path)) { + if ((path = Files.readSymbolicLink(path)).isAbsolute()) continue; + path = path.toAbsolutePath(); + } + if (Files.exists(path = path.normalize(), new LinkOption[0]) && !Files.isDirectory(path, new LinkOption[0])) { + return path; + } + return null; + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + return null; + } + } + + private void pushFileToRemote(List list) { + if (list == null || list.isEmpty()) { + return; + } + String remoteUrl = this.dianChiServerUrl + "/dataCheck/checkRecord/pushFileToServer"; + list.forEach(item -> { + String mediaPath = item.getMediaUrl(); + if (mediaPath != null && !mediaPath.isEmpty()) { + this.pushFile(mediaPath, remoteUrl); + } + if ((mediaPath = item.getMetaUrl()) != null && !mediaPath.isEmpty()) { + this.pushFile(mediaPath, remoteUrl); + } + }); + } + + private void pushFile(String mediaPath, String remoteUrl) { + Path path = this.resolveSymbolicLink(this.mediaRootPath + File.separator + mediaPath); + if (path != null) { + LinkedMultiValueMap body = new LinkedMultiValueMap(); + body.add((Object)"file", (Object)new FileSystemResource(path.toFile())); + body.add((Object)"fileName", (Object)mediaPath); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.MULTIPART_FORM_DATA); + HttpEntity requestEntity = new HttpEntity((Object)body, (MultiValueMap)headers); + RestTemplate restTemplate = new RestTemplate(); + ResponseEntity response = restTemplate.postForEntity(remoteUrl, (Object)requestEntity, String.class, new Object[0]); + log.info("\u8fdc\u7a0b\u63a5\u53e3\u54cd\u5e94: {}", response.getBody()); + } + } + + public ResultRecordExtractServiceImpl(ResultRecordService resultRecordService, ResultRecordDetailsService resultRecordDetailsService, ResultMediaService resultMediaService) { + this.resultRecordService = resultRecordService; + this.resultRecordDetailsService = resultRecordDetailsService; + this.resultMediaService = resultMediaService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordServiceImpl.java new file mode 100644 index 0000000..414fcfc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/check/service/impl/ResultRecordServiceImpl.java @@ -0,0 +1,689 @@ +package net.hzvtc.data.check.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.data.check.mapper.ResultRecordMapper; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.echart.service.BirdDataStatService; +import net.hzvtc.email.service.EmailService; +import org.apache.commons.io.IOUtils; +import org.apache.poi.ss.usermodel.CellCopyPolicy; +import org.apache.poi.ss.usermodel.ClientAnchor; +import org.apache.poi.ss.usermodel.Picture; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCreationHelper; +import org.apache.poi.xssf.usermodel.XSSFDrawing; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class ResultRecordServiceImpl +implements ResultRecordService { + private static final Logger log = LoggerFactory.getLogger(ResultRecordServiceImpl.class); + @Resource + private ResultRecordMapper resultRecordMapper; + private final BirdDataStatService birdDataStatService; + private final ProtectedAreaService protectedAreaService; + @Value(value="${hzvtc.dailyReportFilePath}") + private String dailyReportFilePath; + @Value(value="${hzvtc.dailyReportFileOutPath}") + private String dailyReportFileOutPath; + private final EmailService emailService; + private final ResultMediaService resultMediaService; + + @Override + public ResultRecord selectResultRecordByRecordId(Long recordId) { + return this.resultRecordMapper.selectResultRecordByRecordId(recordId); + } + + @Override + public List selectResultRecordList(ResultRecord resultRecord) { + return this.resultRecordMapper.selectResultRecordList(resultRecord); + } + + @Override + public int insertResultRecord(ResultRecord resultRecord) { + return this.resultRecordMapper.insertResultRecord(resultRecord); + } + + @Override + public int updateResultRecord(ResultRecord resultRecord) { + return this.resultRecordMapper.updateResultRecord(resultRecord); + } + + @Override + public int deleteResultRecordByRecordIds(Long[] recordIds) { + return this.resultRecordMapper.deleteResultRecordByRecordIds(recordIds); + } + + @Override + public int deleteResultRecordByRecordId(Long recordId) { + return this.resultRecordMapper.deleteResultRecordByRecordId(recordId); + } + + @Override + public JSONObject getBirdDataStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + map.put("calcDate", df.format(new Date())); + } else { + map.put("calcDate", calcDate); + } + String birdCode = param.getString("birdCode"); + if (birdCode != null && !birdCode.isEmpty()) { + map.put("birdCode", birdCode); + } + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + String isCommon = param.getString("isCommon"); + if (isCommon != null && !isCommon.isEmpty()) { + map.put("isCommon", Integer.parseInt(isCommon)); + } else { + map.put("isCommon", 1); + } + map.put("limit", 8); + result.put("deviceData", (Object)this.birdDataStatService.getBirdCountInfoListByDevice(map)); + result.put("speciesData", (Object)this.birdDataStatService.getBirdCountInfoListBySpeciesId(map)); + result.put("habitatData", (Object)this.birdDataStatService.getBirdCountInfoListByHabit(map)); + ResultMedia media = new ResultMedia(); + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(areaId); + media.setAreaId(areaId); + if (protectedArea.getPicWidth() > 0) { + media.setWidth(protectedArea.getPicWidth()); + } else { + media.setWidth(100); + } + if (protectedArea.getPicHeight() > 0) { + media.setHeight(protectedArea.getPicHeight()); + } else { + media.setHeight(100); + } + if (protectedArea.getPicNum() > 0) { + media.setLimit(protectedArea.getPicNum()); + } else { + media.setLimit(8); + } + media.setMediaType(2); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + try { + media.setTime(df.parse(calcDate)); + } + catch (Exception ex) { + log.error(ex.getMessage()); + } + List mediaList = this.resultMediaService.selectResultMediaList(media); + result.put("mediaList", mediaList); + return result; + } + + @Override + public String getBirdDataStatFileByParam(JSONObject param) { + try { + AtomicInteger starRow; + SimpleDateFormat df; + Long areaId = param.getLong("areaId"); + String areaCode = ""; + String areaName = ""; + if (areaId == null) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(areaId); + areaCode = protectedArea.getCode(); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "daily_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + df = new SimpleDateFormat("yyyyMMddHHmmss"); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + calcDate); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u65e5\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u5206\u65f6\u76d1\u6d4b\u6570\u91cf"); + JSONObject result = this.getBirdDataStatByParam(param); + JSONArray array = result.getJSONArray("deviceData"); + int[] sum = new int[]{0, 0, 0}; + if (array != null) { + int i; + starRow = new AtomicInteger(8); + array.forEach(data -> { + int i; + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] value = new int[]{0, 0, 0}; + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + int hour = element.getHour(); + int count = element.getCount(); + if (hour <= 12) { + if (value[0] < count) { + value[0] = count; + } + } else if (value[1] < count) { + value[1] = count; + } + value[2] = value[0] > value[1] ? value[0] : value[1]; + }); + } + for (i = 0; i < sum.length; ++i) { + int n = i; + sum[n] = sum[n] + value[i]; + } + for (i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + starRow.getAndIncrement(); + }); + int cell = 2; + for (i = 0; i < sum.length; ++i) { + sheet.getRow(28).getCell(cell++).setCellValue((double)sum[i]); + } + for (i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(8 + array.size() + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(32); + List list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + array.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] value = new int[]{0, 0, 0, 0, 0}; + JSONArray subArray = obj.getJSONArray("list"); + if (subArray != null) { + subArray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + String code = element.getCode(); + if ("ground".equals(code)) { + value[0] = element.getCount(); + } else if ("shoreside".equals(code)) { + value[1] = element.getCount(); + } else if ("water".equals(code)) { + value[2] = element.getCount(); + } else if ("tree".equals(code)) { + value[3] = element.getCount(); + } else { + value[4] = element.getCount(); + } + }); + } + for (int i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + List list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.stream().forEach(data -> { + XSSFCell xssfCell; + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] value = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + JSONArray subArray = obj.getJSONArray("list"); + if (subArray != null) { + subArray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + int hour = element.getHour(); + int index = hour - 8; + if (index >= 0 && index <= 11) { + value[index] = element.getCount(); + } + }); + } + for (int i = 0; i < value.length; ++i) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)value[i]); + } + Arrays.sort(value); + int max = value[value.length - 1]; + XSSFRow row = sheet.getRow(starRow.get()); + if (row == null) { + row = sheet.createRow(starRow.get()); + } + if ((xssfCell = row.getCell(cell)) == null) { + xssfCell = row.createCell(cell); + } + xssfCell.setCellValue((double)max); + ++cell; + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("mediaList")) != null) { + starRow = new AtomicInteger(51); + List list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + array.stream().forEach(data -> { + ResultMedia obj = (ResultMedia)((Object)((Object)data)); + String path = obj.getMediaUrl(); + if (path != null && !path.isEmpty()) { + try { + InputStream is = this.getFileInputStream(AiBirdSysConfig.getBirdImagePath() + path); + if (is != null) { + byte[] bytes = IOUtils.toByteArray((InputStream)is); + int pictureIdx = xssfWorkbook.addPicture(bytes, 5); + is.close(); + XSSFCreationHelper helper = xssfWorkbook.getCreationHelper(); + ClientAnchor anchor = helper.createClientAnchor(); + XSSFDrawing drawing = sheet.createDrawingPatriarch(); + XSSFRow row = sheet.getRow(starRow.get()); + if (row == null) { + row = sheet.createRow(starRow.get()); + } + row.setHeightInPoints((float)obj.getHeight().intValue()); + anchor.setCol1(1); + anchor.setRow1(starRow.get()); + Picture pict = drawing.createPicture(anchor, pictureIdx); + pict.resize(); + starRow.getAndIncrement(); + } + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5(\u65e5\u671f" + calcDate + ").xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception exception) { + return null; + } + } + + private InputStream getFileInputStream(String filePath) { + try { + boolean flag; + File file = new File(filePath); + Path path = file.toPath().toRealPath(new LinkOption[0]); + boolean bl = flag = !path.equals(file.toPath()); + if (flag) { + return Files.newInputStream(path.toFile().toPath(), new OpenOption[0]); + } + return Files.newInputStream(Paths.get(filePath, new String[0]), new OpenOption[0]); + } + catch (Exception exception) { + return null; + } + } + + @Override + public void sendBirdDataStatEmail() { + List list = this.protectedAreaService.getProtectedAreaEmailList(); + JSONObject obj = new JSONObject(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + String calcDate = df.format(new Date()); + obj.put("calcDate", (Object)calcDate); + if (list != null && !list.isEmpty()) { + list.forEach(data -> { + obj.put("areaCode", (Object)data.getCode()); + obj.put("areaId", (Object)data.getId()); + String filePath = this.getBirdDataStatFileByParam(obj); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + calcDate, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5,\u8bf7\u67e5\u6536", filePath, data.getEmail()); + } + }); + } + } + + @Override + public void sendBirdDataWeeklyStatEmail() { + List list = this.protectedAreaService.getProtectedAreaEmailList(); + JSONObject obj = new JSONObject(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + String calcDate = df.format(new Date()); + obj.put("calcDate", (Object)calcDate); + if (list != null && !list.isEmpty()) { + list.forEach(data -> { + obj.put("areaCode", (Object)data.getCode()); + obj.put("areaId", (Object)data.getId()); + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + String filePath = this.getBirdDataWeeklyStatFileByParam(obj); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + dateBegin + "~" + dateEnd, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + dateBegin + "~" + dateEnd + ",\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + } + }); + } + } + + @Override + public boolean sendBirdDataStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + String filePath = this.getBirdDataStatFileByParam(param); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + calcDate, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u65e5\u62a5,\u8bf7\u67e5\u6536", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataWeeklyStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String areaCode = ""; + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + areaCode = data.getCode(); + param.put("areaCode", (Object)areaCode); + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + String filePath = this.getBirdDataWeeklyStatFileByParam(param); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + dateBegin + "~" + dateEnd, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + dateBegin + "~" + dateEnd + ",\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public JSONObject getBirdDataWeeklyStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("dateBegin", DateUtils.getFirstDayOfWeek((String)calcDate)); + map.put("dateEnd", DateUtils.getLastDayOfWeek((String)calcDate)); + String areaId = param.getString("areaId"); + if (areaId != null && !areaId.isEmpty()) { + map.put("areaId", Long.parseLong(areaId)); + } + map.put("isCommon", param.getInteger("isCommon")); + result.put("areaData", (Object)this.birdDataStatService.getBirdWeeklyStatByDeviceParam(map)); + result.put("speciesData", (Object)this.birdDataStatService.getBirdWeeklyStatBySpecies(map)); + result.put("habitatData", (Object)this.birdDataStatService.getBirdWeeklyStatByHabit(map)); + return result; + } + + private int getBirdCount(String count) { + if (count != null && !count.isEmpty()) { + return Integer.parseInt(count); + } + return 0; + } + + @Override + public String getBirdDataWeeklyStatFileByParam(JSONObject param) { + try { + List list; + AtomicInteger starRow; + String areaId = param.getString("areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook(Files.newInputStream(Paths.get(this.dailyReportFilePath + "weekly_report_tmpl.xlsx", new String[0]), new OpenOption[0])); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + dateBegin + "~" + dateEnd); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u5468\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("dateBegin", (Object)dateBegin); + param.put("dateEnd", (Object)dateEnd); + param.put("limit", (Object)8); + param.put("isCommon", (Object)1); + JSONObject result = this.getBirdDataWeeklyStatByParam(param); + JSONArray array = result.getJSONArray("areaData"); + if (array != null) { + int[] sum = new int[8]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + counts[element.getWeekDay().intValue()] = element.getCount(); + }); + } + int i = 0; + for (int val : counts) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + int n = i; + sum[n] = sum[n] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 9 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = result.getJSONArray("speciesData")) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + counts[element.getWeekDay().intValue()] = element.getCount(); + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = result.getJSONArray("habitatData")) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + if ("ground".equals(element.getCode())) { + counts[0] = element.getCount(); + } else if ("shoreside".equals(element.getCode())) { + counts[1] = element.getCount(); + } else if ("water".equals(element.getCode())) { + counts[2] = element.getCount(); + } else if ("tree".equals(element.getCode())) { + counts[3] = element.getCount(); + } else { + counts[4] = element.getCount(); + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + dateBegin + "-" + dateEnd + ").xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception exception) { + return null; + } + } + + @Override + public String getBirdDataMonthlyStatFileByParam(JSONObject param) { + return null; + } + + @Override + public List getResultAreaListByParam(Map map) { + return this.resultRecordMapper.getResultAreaListByParam(map); + } + + @Override + public List getResultRecordIdsByParam(Map map) { + return this.resultRecordMapper.getResultRecordIdsByParam(map); + } + + @Override + public List getCurrentDateResultRecordList(JSONObject param) { + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return null; + } + HashMap map = new HashMap(); + map.put("areaId", areaId); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = LocalDate.now().toString(); + } + map.put("calcDate", calcDate); + return this.resultRecordMapper.getCurrentDateResultRecordList(map); + } + + @Override + public JSONObject getAudioResultRecordDataListForApi(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + HashMap map = new HashMap(); + map.put("areaId", areaId); + map.put("recordType", 3); + Long recordId = param.getLong("recordId"); + if (recordId == null) { + return result; + } + map.put("recordId", recordId); + List list = this.resultRecordMapper.getResultRecordDataPushList(map); + result.put("recordList", list); + List mediaIds = list.stream().flatMap(item -> item.getList().stream()).map(ResultRecordDetails::getMediaId).collect(Collectors.toList()); + List mediaList = this.resultMediaService.getResultMediaByIds(mediaIds); + result.put("mediaList", mediaList); + return result; + } + + @Override + public int batchInsertResultRecord(List list) { + return this.resultRecordMapper.batchInsertResultRecord(list); + } + + @Override + public ResultRecord getResultRecordInfoBySpeciesId(Map map) { + return this.resultRecordMapper.getResultRecordInfoBySpeciesId(map); + } + + private int appendSheetRow(int len, int size, int startRow, XSSFSheet sheet) { + int diff = 0; + if (len > size) { + diff = len - size; + sheet.shiftRows(startRow, sheet.getLastRowNum(), diff); + for (int i = 0; i < diff; ++i) { + XSSFRow newRow = sheet.createRow(startRow + i); + sheet.copyRows(startRow - 1, startRow - 1, startRow + i, new CellCopyPolicy()); + } + } + return diff; + } + + public ResultRecordServiceImpl(BirdDataStatService birdDataStatService, ProtectedAreaService protectedAreaService, EmailService emailService, ResultMediaService resultMediaService) { + this.birdDataStatService = birdDataStatService; + this.protectedAreaService = protectedAreaService; + this.emailService = emailService; + this.resultMediaService = resultMediaService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/job/controller/TableStatInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/data/job/controller/TableStatInfoController.java new file mode 100644 index 0000000..14d264f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/job/controller/TableStatInfoController.java @@ -0,0 +1,81 @@ +package net.hzvtc.data.job.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.data.job.domain.TableStatInfo; +import net.hzvtc.data.job.service.TableStatInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * job生成数据Controller + * + * @author admin + * @date 2023-08-17 + */ +@RestController +@RequestMapping("/stat/tableStat") +public class TableStatInfoController extends BaseController { + @Autowired + private TableStatInfoService tableStatInfoService; + + /** + * 查询job生成数据列表 + */ + @PreAuthorize("@ss.hasPermi('stat:tableStat:list')") + @GetMapping("/list") + public TableDataInfo list(TableStatInfo tableStatInfo) { + startPage(); + List list = tableStatInfoService.selectTableStatInfoList(tableStatInfo); + return getDataTable(list); + } + + /** + * 导出job生成数据列表 + */ + @PreAuthorize("@ss.hasPermi('stat:tableStat:export')") + @Log(title = "job生成数据", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, TableStatInfo tableStatInfo) { + List list = tableStatInfoService.selectTableStatInfoList(tableStatInfo); + ExcelUtil util = new ExcelUtil(TableStatInfo.class); + util.exportExcel(response, list, "job生成数据数据"); + } + + /** + * 获取job生成数据详细信息 + */ + @PreAuthorize("@ss.hasPermi('stat:tableStat:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(tableStatInfoService.selectTableStatInfoById(id)); + } + + /** + * 新增job生成数据 + */ + @PreAuthorize("@ss.hasPermi('stat:tableStat:add')") + @Log(title = "job生成数据", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody TableStatInfo tableStatInfo) { + return toAjax(tableStatInfoService.insertTableStatInfo(tableStatInfo)); + } + + /** + * 修改job生成数据 + */ + @PreAuthorize("@ss.hasPermi('stat:tableStat:edit')") + @Log(title = "job生成数据", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody TableStatInfo tableStatInfo) { + return toAjax(tableStatInfoService.updateTableStatInfo(tableStatInfo)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/job/domain/TableStatInfo.java b/ai-bird-system/src/main/java/net/hzvtc/data/job/domain/TableStatInfo.java new file mode 100644 index 0000000..5e038a6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/job/domain/TableStatInfo.java @@ -0,0 +1,14 @@ +package net.hzvtc.data.job.domain; + +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="TableStatInfo") +@Data +public class TableStatInfo { + private static final long serialVersionUID = 1L; + private Long id; + private Long tableId; + private int type; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/job/mapper/TableStatInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/data/job/mapper/TableStatInfoMapper.java new file mode 100644 index 0000000..3d73063 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/job/mapper/TableStatInfoMapper.java @@ -0,0 +1,20 @@ +package net.hzvtc.data.job.mapper; + +import java.util.List; +import net.hzvtc.data.job.domain.TableStatInfo; + +public interface TableStatInfoMapper { + public TableStatInfo selectTableStatInfoById(Long var1); + + public List selectTableStatInfoList(TableStatInfo var1); + + public int insertTableStatInfo(TableStatInfo var1); + + public int updateTableStatInfo(TableStatInfo var1); + + public int deleteTableStatInfoById(Long var1); + + public TableStatInfo getTableStatInfoByType(int var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/job/service/TableStatInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/data/job/service/TableStatInfoService.java new file mode 100644 index 0000000..a0e5736 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/job/service/TableStatInfoService.java @@ -0,0 +1,20 @@ +package net.hzvtc.data.job.service; + +import java.util.List; +import net.hzvtc.data.job.domain.TableStatInfo; + +public interface TableStatInfoService { + public TableStatInfo selectTableStatInfoById(Long var1); + + public List selectTableStatInfoList(TableStatInfo var1); + + public int insertTableStatInfo(TableStatInfo var1); + + public int updateTableStatInfo(TableStatInfo var1); + + public int deleteTableStatInfoById(Long var1); + + public TableStatInfo getTableStatInfoByType(int var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/data/job/service/impl/TableStatInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/data/job/service/impl/TableStatInfoServiceImpl.java new file mode 100644 index 0000000..58c1787 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/data/job/service/impl/TableStatInfoServiceImpl.java @@ -0,0 +1,81 @@ +package net.hzvtc.data.job.service.impl; + +import net.hzvtc.data.job.domain.TableStatInfo; +import net.hzvtc.data.job.mapper.TableStatInfoMapper; +import net.hzvtc.data.job.service.TableStatInfoService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * job生成数据Service业务层处理 + * + * @author admin + * @date 2023-08-17 + */ +@Service +public class TableStatInfoServiceImpl implements TableStatInfoService { + @Resource + private TableStatInfoMapper tableStatInfoMapper; + + /** + * 查询job生成数据 + * + * @param id job生成数据主键 + * @return job生成数据 + */ + @Override + public TableStatInfo selectTableStatInfoById(Long id) { + return tableStatInfoMapper.selectTableStatInfoById(id); + } + + /** + * 查询job生成数据列表 + * + * @param tableStatInfo job生成数据 + * @return job生成数据 + */ + @Override + public List selectTableStatInfoList(TableStatInfo tableStatInfo) { + return tableStatInfoMapper.selectTableStatInfoList(tableStatInfo); + } + + /** + * 新增job生成数据 + * + * @param tableStatInfo job生成数据 + * @return 结果 + */ + @Override + public int insertTableStatInfo(TableStatInfo tableStatInfo) { + return tableStatInfoMapper.insertTableStatInfo(tableStatInfo); + } + + /** + * 修改job生成数据 + * + * @param tableStatInfo job生成数据 + * @return 结果 + */ + @Override + public int updateTableStatInfo(TableStatInfo tableStatInfo) { + return tableStatInfoMapper.updateTableStatInfo(tableStatInfo); + } + + /** + * 删除job生成数据信息 + * + * @param id job生成数据主键 + * @return 结果 + */ + @Override + public int deleteTableStatInfoById(Long id) { + return tableStatInfoMapper.deleteTableStatInfoById(id); + } + + @Override + public TableStatInfo getTableStatInfoByType(int type) { + return tableStatInfoMapper.getTableStatInfoByType(type); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/controller/DeviceInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/device/controller/DeviceInfoController.java new file mode 100644 index 0000000..51a1ba9 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/controller/DeviceInfoController.java @@ -0,0 +1,159 @@ +package net.hzvtc.device.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.service.DeviceInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +/** + * 设备Controller + * + * @author admin + * @date 2022-07-28 + */ +@RestController +@RequestMapping("/device/baseInfo") +public class DeviceInfoController extends BaseController { + @Autowired + private DeviceInfoService deviceInfoService; + + /** + * 查询设备列表 + */ +// @PreAuthorize("@ss.hasPermi('device:baseInfo:list')") + @GetMapping("/list") + public TableDataInfo list(DeviceInfo deviceInfo) { +// if (deviceInfo.getDeptId() != null) { +// if (deviceInfo.getDeptId() != 0L) { +// deviceInfo.setGridInfo(deviceInfoService.getAncestorsById(deviceInfo.getDeptId())); +// } else { +// deviceInfo.setDeptId(null); +// } +// } + if (deviceInfo == null) { + deviceInfo = new DeviceInfo(); + } + Long userId = SecurityUtils.getUserId(); + if (userId != 1L) { + Set areaIds = SecurityUtils.getLoginUser().getAreaIds(); + if (areaIds == null) { + return new TableDataInfo(); + } else { + deviceInfo.setAreaIds(new ArrayList<>(areaIds)); + } + } + startPage(); + List list = deviceInfoService.selectDeviceInfoList(deviceInfo); + return getDataTable(list); + } + + @GetMapping("/listByParam") + public AjaxResult getListByParam(DeviceInfo deviceInfo) { + return AjaxResult.success(deviceInfoService.getDeviceInfoListForPage(deviceInfo)); + } + + /** + * 导出设备列表 + */ + @PreAuthorize("@ss.hasPermi('device:baseInfo:export')") + @Log(title = "设备", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, DeviceInfo deviceInfo) { + List list = deviceInfoService.selectDeviceInfoList(deviceInfo); + ExcelUtil util = new ExcelUtil(DeviceInfo.class); + util.exportExcel(response, list, "设备数据"); + } + + /** + * 获取设备详细信息 + */ + @PreAuthorize("@ss.hasPermi('device:baseInfo:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(deviceInfoService.selectDeviceInfoById(id)); + } + + @GetMapping(value = "/liveUrl/{id}") + public AjaxResult getDeviceUrl(@PathVariable("id") Long id) { + return AjaxResult.success(deviceInfoService.getDeviceLiveUrlById(id)); + } + + /** + * 新增设备 + */ + @PreAuthorize("@ss.hasPermi('device:baseInfo:add')") + @Log(title = "设备", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody DeviceInfo deviceInfo) { + return toAjax(deviceInfoService.insertDeviceInfo(deviceInfo)); + } + + /** + * 修改设备 + */ + @PreAuthorize("@ss.hasPermi('device:baseInfo:edit')") + @Log(title = "设备", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody DeviceInfo deviceInfo) { + return toAjax(deviceInfoService.updateDeviceInfo(deviceInfo)); + } + + /** + * 删除设备 + */ + @PreAuthorize("@ss.hasPermi('device:baseInfo:remove')") + @Log(title = "设备", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(deviceInfoService.deleteDeviceInfoByIds(ids)); + } + + @PostMapping("/importData") + public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { + ExcelUtil util = new ExcelUtil<>(DeviceInfo.class); + List list = util.importExcel(file.getInputStream()); + String message = deviceInfoService.importData(list, updateSupport); + return AjaxResult.success(message); + } + + @PostMapping("/importTemplate") + public void importTemplate(HttpServletResponse response) { + ExcelUtil util = new ExcelUtil<>(DeviceInfo.class); + util.importTemplateExcel(response, "设备信息"); + } + + @PostMapping("/updateDeletedValue") + public AjaxResult updateDeletedValue(@RequestBody DeviceInfo data) { + return AjaxResult.success(deviceInfoService.updateDeviceDeletedValueById(data)); + } + + @GetMapping(value = "/list/{areaId}") + public AjaxResult getVideoDeviceListByAreaId(@PathVariable("areaId") Long areaId) { + return AjaxResult.success(deviceInfoService.getDeviceStatInfoByAreaId(areaId)); + } + + @GetMapping("/listForSelect") + public List getDeviceListForSelect() { + return deviceInfoService.getDeviceInfoListForSel(); + } + + @GetMapping("/listForMap") + public List getDeviceListForGisMap() { + return deviceInfoService.getDeviceInfoListForGisMap(); + } + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/controller/HeatmapInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/device/controller/HeatmapInfoController.java new file mode 100644 index 0000000..b9cf7ab --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/controller/HeatmapInfoController.java @@ -0,0 +1,97 @@ +package net.hzvtc.device.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.device.domain.HeatmapInfo; +import net.hzvtc.device.service.HeatmapInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 热力图配置Controller + * + * @author admin + * @date 2022-11-29 + */ +@RestController +@RequestMapping("/heatmap/heatmapInfo") +public class HeatmapInfoController extends BaseController { + @Autowired + private HeatmapInfoService heatmapInfoService; + + /** + * 查询热力图配置列表 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:list')") + @GetMapping("/list") + public TableDataInfo list(HeatmapInfo heatmapInfo) { + startPage(); + List list = heatmapInfoService.selectHeatmapInfoList(heatmapInfo); + return getDataTable(list); + } + + /** + * 导出热力图配置列表 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:export')") + @Log(title = "热力图配置", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, HeatmapInfo heatmapInfo) { + List list = heatmapInfoService.selectHeatmapInfoList(heatmapInfo); + ExcelUtil util = new ExcelUtil(HeatmapInfo.class); + util.exportExcel(response, list, "热力图配置数据"); + } + + /** + * 获取热力图配置详细信息 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(heatmapInfoService.selectHeatmapInfoById(id)); + } + + /** + * 新增热力图配置 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:add')") + @Log(title = "热力图配置", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody HeatmapInfo heatmapInfo) { + return toAjax(heatmapInfoService.insertHeatmapInfo(heatmapInfo)); + } + + /** + * 修改热力图配置 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:edit')") + @Log(title = "热力图配置", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody HeatmapInfo heatmapInfo) { + return toAjax(heatmapInfoService.updateHeatmapInfo(heatmapInfo)); + } + + /** + * 删除热力图配置 + */ + @PreAuthorize("@ss.hasPermi('heatmap:heatmapInfo:remove')") + @Log(title = "热力图配置", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(heatmapInfoService.deleteHeatmapInfoByIds(ids)); + } + + @PostMapping("/heatmapListByParam") + public AjaxResult getBirdHeatmapList(@RequestBody JSONObject obj) { + return AjaxResult.success(heatmapInfoService.getBirdHeatmapListByParam(obj)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/domain/DeviceInfo.java b/ai-bird-system/src/main/java/net/hzvtc/device/domain/DeviceInfo.java new file mode 100644 index 0000000..53b3593 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/domain/DeviceInfo.java @@ -0,0 +1,40 @@ +package net.hzvtc.device.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.math.BigDecimal; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="DeviceInfo") +@Data +public class DeviceInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String deviceName; + private Long protectedAreaId; + private String protectedAreaName; + private String manufacturer; + private String model; + private String serialNumber; + private String description; + private BigDecimal longitude; + private BigDecimal latitude; + private String gridInfo; + private int status; + private String deviceIp; + private String deviceUser; + private String devicePassword; + private String rtsp; + private String rtspInner; + private String rtspOut; + private String areaCode; + private String deviceType; + private ResultMedia resultMedia; + private int locationX; + private int locationY; + private Long deptId; + private String deptName; + private long recordCount; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/domain/HeatmapInfo.java b/ai-bird-system/src/main/java/net/hzvtc/device/domain/HeatmapInfo.java new file mode 100644 index 0000000..ac758fe --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/domain/HeatmapInfo.java @@ -0,0 +1,24 @@ +package net.hzvtc.device.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="HeatmapInfo") +@Data +public class HeatmapInfo extends BaseEntity { + private static final Long serialVersionUID = 1L; + private Long id; + private String name; + private int centerX; + private int centerY; + private int startX; + private int endX; + private int startY; + private int endY; + private Long deviceId; + private Long areaId; + private int count; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/mapper/DeviceInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/device/mapper/DeviceInfoMapper.java new file mode 100644 index 0000000..672aafe --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/mapper/DeviceInfoMapper.java @@ -0,0 +1,51 @@ +package net.hzvtc.device.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.device.domain.DeviceInfo; + +public interface DeviceInfoMapper { + public DeviceInfo selectDeviceInfoById(Long var1); + + public DeviceInfo selectDeviceInfoByParam(DeviceInfo var1); + + public List selectDeviceInfoList(DeviceInfo var1); + + public List getDeviceInfoListForPage(DeviceInfo var1); + + public List getDeviceInfoListByUserId(Long var1); + + public List getDeviceStatInfoByAreaId(Long var1); + + public List getDeviceListInfoByParam(Map var1); + + public List getDeviceCameraInfoByAreaId(Long var1); + + public int insertDeviceInfo(DeviceInfo var1); + + public int updateDeviceInfo(DeviceInfo var1); + + public int deleteDeviceInfoById(Long var1); + + public int updateDeviceDeletedValueById(DeviceInfo var1); + + public int deleteDeviceInfoByIds(Long[] var1); + + public List getDeviceInfoListByAreaId(Long var1); + + public List getDeviceInfoConnectionList(); + + public List getDeviceOfflineList(); + + public DeviceInfo getDeviceLiveUrlById(Long var1); + + public int updateDeviceStatus(DeviceInfo var1); + + public List getDeviceInfoListForSel(DeviceInfo var1); + + public List getDeviceInfoListForMap(DeviceInfo var1); + + public Long getDeviceInfoIdByName(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/mapper/HeatmapInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/device/mapper/HeatmapInfoMapper.java new file mode 100644 index 0000000..c481a60 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/mapper/HeatmapInfoMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.device.mapper; + +import java.util.List; +import net.hzvtc.device.domain.HeatmapInfo; + +/** + * 热力图配置Mapper接口 + * + * @author admin + * @date 2022-11-29 + */ +public interface HeatmapInfoMapper +{ + /** + * 查询热力图配置 + * + * @param id 热力图配置主键 + * @return 热力图配置 + */ + public HeatmapInfo selectHeatmapInfoById(Long id); + + /** + * 查询热力图配置列表 + * + * @param heatmapInfo 热力图配置 + * @return 热力图配置集合 + */ + public List selectHeatmapInfoList(HeatmapInfo heatmapInfo); + + /** + * 新增热力图配置 + * + * @param heatmapInfo 热力图配置 + * @return 结果 + */ + public int insertHeatmapInfo(HeatmapInfo heatmapInfo); + + /** + * 修改热力图配置 + * + * @param heatmapInfo 热力图配置 + * @return 结果 + */ + public int updateHeatmapInfo(HeatmapInfo heatmapInfo); + + /** + * 删除热力图配置 + * + * @param id 热力图配置主键 + * @return 结果 + */ + public int deleteHeatmapInfoById(Long id); + + /** + * 批量删除热力图配置 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteHeatmapInfoByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/service/DeviceInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/device/service/DeviceInfoService.java new file mode 100644 index 0000000..fbfd6ac --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/service/DeviceInfoService.java @@ -0,0 +1,52 @@ +package net.hzvtc.device.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.device.domain.DeviceInfo; + +public interface DeviceInfoService { + public DeviceInfo selectDeviceInfoById(Long var1); + + public List selectDeviceInfoList(DeviceInfo var1); + + public List getDeviceInfoListForPage(DeviceInfo var1); + + public int insertDeviceInfo(DeviceInfo var1); + + public int updateDeviceInfo(DeviceInfo var1); + + public int deleteDeviceInfoByIds(Long[] var1); + + public String getAncestorsById(Long var1); + + public int deleteDeviceInfoById(Long var1); + + public String importData(List var1, boolean var2); + + public List getDeviceInfoListByUserId(Long var1); + + public List getDeviceCameraInfoByAreaId(Long var1); + + public List getDeviceStatInfoByAreaId(Long var1); + + public List getDeviceInfoListByAreaId(Long var1); + + public void updateDeviceConnectState(); + + public void sendDeviceConnectStateEmail(); + + public List getDeviceInfoListForSel(); + + public List getDeviceInfoListForGisMap(); + + public DeviceInfo getDeviceLiveUrlById(Long var1); + + public List getDeviceListInfoByParam(Map var1); + + public int updateDeviceDeletedValueById(DeviceInfo var1); + + public Long getDeviceInfoIdByName(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/service/HeatmapInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/device/service/HeatmapInfoService.java new file mode 100644 index 0000000..e5216e5 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/service/HeatmapInfoService.java @@ -0,0 +1,23 @@ +package net.hzvtc.device.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.device.domain.HeatmapInfo; + +public interface HeatmapInfoService { + public HeatmapInfo selectHeatmapInfoById(Long var1); + + public List selectHeatmapInfoList(HeatmapInfo var1); + + public int insertHeatmapInfo(HeatmapInfo var1); + + public int updateHeatmapInfo(HeatmapInfo var1); + + public int deleteHeatmapInfoByIds(Long[] var1); + + public int deleteHeatmapInfoById(Long var1); + + public List getBirdHeatmapListByParam(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/DeviceInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/DeviceInfoServiceImpl.java new file mode 100644 index 0000000..30932fa --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/DeviceInfoServiceImpl.java @@ -0,0 +1,303 @@ +package net.hzvtc.device.service.impl; + +import com.alibaba.fastjson.JSONObject; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import javax.validation.Validator; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.common.core.domain.entity.SysDept; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.mapper.DeviceInfoMapper; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.email.service.EmailService; +import net.hzvtc.system.service.SysDeptService; +import net.hzvtc.system.service.SysUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class DeviceInfoServiceImpl +implements DeviceInfoService { + private static final Logger log = LoggerFactory.getLogger(DeviceInfoServiceImpl.class); + @Resource + protected Validator validator; + @Resource + private DeviceInfoMapper deviceInfoMapper; + private final ProtectedAreaService protectedAreaService; + private final ResultMediaService resultMediaService; + private final SysDeptService sysDeptService; + private final EmailService emailService; + private final SysUserService sysUserService; + + @Override + public DeviceInfo selectDeviceInfoById(Long id) { + return this.deviceInfoMapper.selectDeviceInfoById(id); + } + + @Override + public List selectDeviceInfoList(DeviceInfo deviceInfo) { + return this.deviceInfoMapper.selectDeviceInfoList(deviceInfo); + } + + @Override + public String getAncestorsById(Long id) { + SysDept data = this.sysDeptService.selectDeptById(id); + return data.getAncestors() + "," + data.getDeptId(); + } + + @Override + public List getDeviceInfoListForPage(DeviceInfo deviceInfo) { + return this.deviceInfoMapper.getDeviceInfoListForPage(deviceInfo); + } + + @Override + @Transactional + public int insertDeviceInfo(DeviceInfo deviceInfo) { + int count = this.deviceInfoMapper.insertDeviceInfo(deviceInfo); + if (deviceInfo.getRtsp() != null && !deviceInfo.getRtsp().isEmpty()) { + this.resultMediaService.insertResultMedia(this.createResultMedia(deviceInfo)); + } + return count; + } + + private ResultMedia createResultMedia(DeviceInfo deviceInfo) { + ResultMedia data = new ResultMedia(); + data.setDeviceId(deviceInfo.getId()); + data.setMediaType(4); + data.setMediaUrl(deviceInfo.getRtsp()); + data.setMetaUrl(deviceInfo.getRtspInner()); + data.setTime(new Date()); + return data; + } + + @Override + @Transactional + public int updateDeviceInfo(DeviceInfo deviceInfo) { + int count = this.deviceInfoMapper.updateDeviceInfo(deviceInfo); + this.resultMediaService.deleteResultRealMediaByParam(deviceInfo.getId()); + if (deviceInfo.getRtsp() != null && !deviceInfo.getRtsp().isEmpty()) { + this.resultMediaService.insertResultMedia(this.createResultMedia(deviceInfo)); + } + return count; + } + + @Override + public int deleteDeviceInfoByIds(Long[] ids) { + return this.deviceInfoMapper.deleteDeviceInfoByIds(ids); + } + + @Override + public int deleteDeviceInfoById(Long id) { + return this.deviceInfoMapper.deleteDeviceInfoById(id); + } + + @Override + public String importData(List list, boolean updateSupport) { + if (StringUtils.isNull(list) || list.isEmpty()) { + throw new ServiceException("\u5bfc\u5165\u4fdd\u62a4\u533a\u8bbe\u5907\u4e0d\u80fd\u4e3a\u7a7a\uff01"); + } + AtomicInteger[] successNum = new AtomicInteger[]{new AtomicInteger()}; + int[] failureNum = new int[]{0}; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + list.forEach(data -> { + try { + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaByName(data.getProtectedAreaName()); + if (Objects.isNull((Object)protectedArea)) { + failureNum[0] = failureNum[0] + 1; + failureMsg.append("
" + failureNum[0] + "\u3001\u4fdd\u62a4\u533a " + data.getProtectedAreaName() + " \u4e0d\u5b58\u5728"); + } else { + DeviceInfo param = new DeviceInfo(); + param.setProtectedAreaId(protectedArea.getId()); + param.setDeviceName(data.getDeviceName()); + DeviceInfo deviceInfo = this.deviceInfoMapper.selectDeviceInfoByParam(param); + if (Objects.isNull((Object)deviceInfo)) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setIsDeleted(0); + data.setProtectedAreaId(protectedArea.getId()); + data.setCreateTime(new Date()); + this.insertDeviceInfo((DeviceInfo)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u8bbe\u5907 " + data.getDeviceName() + " \u5bfc\u5165\u6210\u529f"); + } else if (updateSupport) { + BeanValidators.validateWithException((Validator)this.validator, (Object)data, (Class[])new Class[0]); + data.setId(deviceInfo.getId()); + this.updateDeviceInfo((DeviceInfo)((Object)data)); + successNum[0].getAndIncrement(); + successMsg.append("
" + successNum[0] + "\u3001\u8bbe\u5907 " + data.getDeviceName() + " \u66f4\u65b0\u6210\u529f"); + } else { + failureNum[0] = failureNum[0] + 1; + failureMsg.append("
" + failureNum[0] + "\u3001\u8bbe\u5907 " + data.getDeviceName() + " \u5df2\u5b58\u5728"); + } + } + } + catch (Exception e) { + failureNum[0] = failureNum[0] + 1; + String msg = "
" + failureNum + "\u3001\u8bbe\u5907 " + data.getDeviceName() + " \u5bfc\u5165\u5931\u8d25\uff1a"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, (Throwable)e); + } + }); + if (failureNum[0] > 0) { + failureMsg.insert(0, "\u5f88\u62b1\u6b49\uff0c\u5bfc\u5165\u5931\u8d25\uff01\u5171 " + failureNum[0] + " \u6761\u6570\u636e\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c\u9519\u8bef\u5982\u4e0b\uff1a"); + throw new ServiceException(failureMsg.toString()); + } + successMsg.insert(0, "\u606d\u559c\u60a8\uff0c\u6570\u636e\u5df2\u5168\u90e8\u5bfc\u5165\u6210\u529f\uff01\u5171 " + successNum + " \u6761\uff0c\u6570\u636e\u5982\u4e0b\uff1a"); + return successMsg.toString(); + } + + @Override + public List getDeviceInfoListByUserId(Long userId) { + if (userId <= 1L) { + userId = null; + } + List list = this.deviceInfoMapper.getDeviceInfoListByUserId(userId); + List objectList = list.stream().map(item -> { + JSONObject obj = new JSONObject(); + obj.put("id", (Object)item.getId()); + obj.put("name", (Object)item.getDeviceName()); + obj.put("areaId", (Object)item.getProtectedAreaId()); + obj.put("type", (Object)item.getDeviceType()); + obj.put("rtsp", (Object)item.getRtsp()); + obj.put("lon", (Object)item.getLongitude()); + obj.put("lat", (Object)item.getLatitude()); + return obj; + }).collect(Collectors.toList()); + return objectList; + } + + @Override + public List getDeviceCameraInfoByAreaId(Long areaId) { + return this.deviceInfoMapper.getDeviceCameraInfoByAreaId(areaId); + } + + @Override + public List getDeviceStatInfoByAreaId(Long areaId) { + return this.deviceInfoMapper.getDeviceStatInfoByAreaId(areaId); + } + + @Override + public List getDeviceInfoListByAreaId(Long areaId) { + return this.deviceInfoMapper.getDeviceInfoListByAreaId(areaId); + } + + @Override + public void updateDeviceConnectState() { + log.info("=====updateDeviceConnectState start======="); + List list = this.deviceInfoMapper.getDeviceInfoConnectionList(); + if (list != null) { + list.forEach(item -> { + boolean flag = this.isActive(item.getRtsp()); + if (flag && item.getStatus() == 0) { + item.setStatus(1); + this.deviceInfoMapper.updateDeviceStatus((DeviceInfo)((Object)item)); + } else if (!flag && item.getStatus() == 1) { + item.setStatus(0); + this.deviceInfoMapper.updateDeviceStatus((DeviceInfo)((Object)item)); + } + }); + } + log.info("=====updateDeviceConnectState end======="); + } + + @Override + public void sendDeviceConnectStateEmail() { + SysUser user = this.sysUserService.getUserInfoById(1L); + if (user == null || user.getEmail() == null || user.getEmail().trim().isEmpty()) { + return; + } + this.updateDeviceConnectState(); + List list = this.deviceInfoMapper.getDeviceOfflineList(); + if (list != null && !list.isEmpty()) { + StringBuilder builder = new StringBuilder(); + builder.append("\u4ee5\u4e0b\u89c6\u9891\u8bbe\u5907\u76ee\u524d\u5904\u4e8e\u79bb\u7ebf\u72b6\u6001\uff0c\u8bf7\u68c0\u67e5\uff1a\n"); + AtomicInteger i = new AtomicInteger(1); + list.forEach(item -> builder.append(String.format("%02d. \u4fdd\u62a4\u533a\uff1a%s\uff0c\u8bbe\u5907\u540d\u79f0\uff1a%s\uff0c\u5e8f\u5217\u53f7\uff1a%s\n", i.getAndIncrement(), item.getProtectedAreaName(), item.getDeviceName(), item.getSerialNumber()))); + this.emailService.sendSimpleEmail("\u89c6\u9891\u8bbe\u5907\u79bb\u7ebf\u5217\u8868", builder.toString(), user.getEmail()); + } + } + + @Override + public List getDeviceInfoListForSel() { + SysUser user = SecurityUtils.getLoginUser().getUser(); + DeviceInfo param = new DeviceInfo(); + if (user.getUserId() > 1L) { + param.setGridInfo(this.getAncestorsById(user.getDeptId())); + } + return this.deviceInfoMapper.getDeviceInfoListForSel(param); + } + + @Override + public List getDeviceInfoListForGisMap() { + SysUser user = SecurityUtils.getLoginUser().getUser(); + DeviceInfo param = new DeviceInfo(); + if (user.getUserId() > 1L) { + param.setGridInfo(this.getAncestorsById(user.getDeptId())); + } + return this.deviceInfoMapper.getDeviceInfoListForMap(param); + } + + @Override + public DeviceInfo getDeviceLiveUrlById(Long id) { + return this.deviceInfoMapper.getDeviceLiveUrlById(id); + } + + @Override + public List getDeviceListInfoByParam(Map map) { + return this.deviceInfoMapper.getDeviceListInfoByParam(map); + } + + @Override + public int updateDeviceDeletedValueById(DeviceInfo data) { + return this.deviceInfoMapper.updateDeviceDeletedValueById(data); + } + + @Override + public Long getDeviceInfoIdByName(String name) { + return this.deviceInfoMapper.getDeviceInfoIdByName(name); + } + + private boolean isActive(String str) { + if (str == null || str.isEmpty()) { + return false; + } + try { + URL url = new URL(str); + HttpURLConnection connection = (HttpURLConnection)url.openConnection(); + connection.setConnectTimeout(30000); + connection.setReadTimeout(30000); + int code = connection.getResponseCode(); + return code == 200; + } + catch (Exception ex) { + return false; + } + } + + public DeviceInfoServiceImpl(ProtectedAreaService protectedAreaService, ResultMediaService resultMediaService, SysDeptService sysDeptService, EmailService emailService, SysUserService sysUserService) { + this.protectedAreaService = protectedAreaService; + this.resultMediaService = resultMediaService; + this.sysDeptService = sysDeptService; + this.emailService = emailService; + this.sysUserService = sysUserService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/HeatmapInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/HeatmapInfoServiceImpl.java new file mode 100644 index 0000000..3c98a42 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/device/service/impl/HeatmapInfoServiceImpl.java @@ -0,0 +1,128 @@ +package net.hzvtc.device.service.impl; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.device.domain.HeatmapInfo; +import net.hzvtc.device.mapper.HeatmapInfoMapper; +import net.hzvtc.device.service.HeatmapInfoService; +import net.hzvtc.echart.service.BirdDataStatService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 热力图配置Service业务层处理 + * + * @author admin + * @date 2022-11-29 + */ +@Service +public class HeatmapInfoServiceImpl implements HeatmapInfoService { + @Resource + private HeatmapInfoMapper heatmapInfoMapper; + @Autowired + private BirdDataStatService birdDataStatService; + + /** + * 查询热力图配置 + * + * @param id 热力图配置主键 + * @return 热力图配置 + */ + @Override + public HeatmapInfo selectHeatmapInfoById(Long id) { + return heatmapInfoMapper.selectHeatmapInfoById(id); + } + + /** + * 查询热力图配置列表 + * + * @param heatmapInfo 热力图配置 + * @return 热力图配置 + */ + @Override + public List selectHeatmapInfoList(HeatmapInfo heatmapInfo) { + return heatmapInfoMapper.selectHeatmapInfoList(heatmapInfo); + } + + /** + * 新增热力图配置 + * + * @param heatmapInfo 热力图配置 + * @return 结果 + */ + @Override + public int insertHeatmapInfo(HeatmapInfo heatmapInfo) { + heatmapInfo.setCreateTime(DateUtils.getNowDate()); + return heatmapInfoMapper.insertHeatmapInfo(heatmapInfo); + } + + /** + * 修改热力图配置 + * + * @param heatmapInfo 热力图配置 + * @return 结果 + */ + @Override + public int updateHeatmapInfo(HeatmapInfo heatmapInfo) { + return heatmapInfoMapper.updateHeatmapInfo(heatmapInfo); + } + + /** + * 批量删除热力图配置 + * + * @param ids 需要删除的热力图配置主键 + * @return 结果 + */ + @Override + public int deleteHeatmapInfoByIds(Long[] ids) { + return heatmapInfoMapper.deleteHeatmapInfoByIds(ids); + } + + /** + * 删除热力图配置信息 + * + * @param id 热力图配置主键 + * @return 结果 + */ + @Override + public int deleteHeatmapInfoById(Long id) { + return heatmapInfoMapper.deleteHeatmapInfoById(id); + } + + @Override + public List getBirdHeatmapListByParam(JSONObject obj) { + Map map = new HashMap<>(); + String calcDate = obj.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + + HeatmapInfo param = new HeatmapInfo(); + param.setAreaId(obj.getLong("areaId")); + List list = heatmapInfoMapper.selectHeatmapInfoList(param); + if (list != null) { + list.forEach(item -> { + map.put("deviceId", item.getDeviceId()); + map.put("startX", item.getStartX()); + map.put("endX", item.getEndX()); + map.put("startY", item.getStartY()); + map.put("endY", item.getEndY()); + Integer count = birdDataStatService.getBirdCountForHeatMapByParam(map); + if (count == null) { + count = 0; + } + item.setCount(count); + }); + } + return list; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/echart/controller/BirdRealTimeController.java b/ai-bird-system/src/main/java/net/hzvtc/echart/controller/BirdRealTimeController.java new file mode 100644 index 0000000..60507ee --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/echart/controller/BirdRealTimeController.java @@ -0,0 +1,110 @@ +package net.hzvtc.echart.controller; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.echart.service.BirdDataStatService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/echart/real"}) +public class BirdRealTimeController { + private static final Logger log = LoggerFactory.getLogger(BirdRealTimeController.class); + @Autowired + private BirdDataStatService birdRealTimeService; + + @PostMapping(value={"/list"}) + public AjaxResult getBirdRealTimeList(@RequestBody JSONObject param) { + List list = this.birdRealTimeService.getBirdRealTimeList(param); + return AjaxResult.success(list); + } + + @PostMapping(value={"/monthList"}) + public AjaxResult getBirdMonthList(@RequestBody JSONObject param) { + List list = this.birdRealTimeService.getBirdMonthList(param); + return AjaxResult.success(list); + } + + @GetMapping(value={"/count"}) + public AjaxResult getBirdRealTimeCount(@RequestParam(name="birdCode", required=true) String birdCode) { + long count = this.birdRealTimeService.getBirdRealTimeCount(birdCode); + return AjaxResult.success((Object)count); + } + + @PostMapping(value={"/countList"}) + public AjaxResult getBirdRealTimeCount(@RequestBody JSONArray array) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdRealTimeCount(array)); + } + + @PostMapping(value={"/countListByCode"}) + public AjaxResult getBirdRealTimeAmountByArea(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdRealTimeService.getBirdRealTimeAmountByCode(obj)); + } + + @PostMapping(value={"/boardListByParam"}) + public AjaxResult getBirdBoardListByParam(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdRealTimeService.getBirdSpeciesBoardListByParam(obj)); + } + + @PostMapping(value={"/dailyRealCount"}) + public AjaxResult getBirdRealTimeDailyAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdRealTimeDailyAmountByParam(obj)); + } + + @PostMapping(value={"/weeklyCount"}) + public AjaxResult getBirdRealTimeWeeklyAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdRealTimeWeeklyAmountByParam(obj)); + } + + @PostMapping(value={"/yearCount"}) + public AjaxResult getBirdYearAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdYearStatListByParam(obj)); + } + + @PostMapping(value={"/dayCountByMonth"}) + public AjaxResult getBirdDailyAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdDailyStatByMonth(obj)); + } + + @PostMapping(value={"/dailyMaxAmount"}) + public AjaxResult getBirdDailyMaxAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdMaxAmountByParam(obj)); + } + + @PostMapping(value={"/totalBird"}) + public AjaxResult getBirdTotalAmount(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdTotalAmountByParam(obj)); + } + + @PostMapping(value={"/listByHabit"}) + public AjaxResult getBirdAmountByHabit(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdRealTimeService.getBirdCountInfoListByHabit(obj)); + } + + @PostMapping(value={"/birdHabitList"}) + public AjaxResult getBirdHabitAmountByParam(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdRealTimeService.getBirdHabitListByParam(obj)); + } + + @PostMapping(value={"/realStatForPage"}) + public AjaxResult getBirdRealStatByParam(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdRealTimeService.getBirdRealStatByParam(obj)); + } + + @PostMapping(value={"/dailyBirdMaxAmount"}) + public AjaxResult getBirdDailyMaxAmountByParam(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdRealTimeService.getBirdDailyMaxAmountByParam(obj)); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/echart/domain/vo/BirdStatDataVo.java b/ai-bird-system/src/main/java/net/hzvtc/echart/domain/vo/BirdStatDataVo.java new file mode 100644 index 0000000..1eb0648 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/echart/domain/vo/BirdStatDataVo.java @@ -0,0 +1,54 @@ +package net.hzvtc.echart.domain.vo; + +import java.util.List; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="BirdStatDataVo") +@Data +public class BirdStatDataVo { + private Long id; + private Long speciesId; + private Long familyId; + private Long itemId; + private String familyName; + private String code; + private String codeName; + private String location; + private String mediaType; + private String mediaUrl; + private Long mediaId; + private String metaUrl; + private int hour; + private int count; + private int month; + private int year; + private int today; + private int yesterday; + private int total; + private String name; + private String ename; + private String deviceName; + private Integer weekDay; + private int value; + private int avgCount; + private String shortDate; + private String dateTime; + private boolean checked; + private String birdIcon; + private String iucnCode; + private String iucnName; + private String protectedCode; + private String protectedName; + private String residentCode; + private String residentName; + private Long catalogueId; + private String catalogueName; + private Long genusId; + private String genusName; + private String serialNumber; + private int videoCount; + private int imageCount; + private String fileUrl; + private List deviceIds; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/echart/mapper/BirdDataStatMapper.java b/ai-bird-system/src/main/java/net/hzvtc/echart/mapper/BirdDataStatMapper.java new file mode 100644 index 0000000..8b17135 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/echart/mapper/BirdDataStatMapper.java @@ -0,0 +1,55 @@ +package net.hzvtc.echart.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface BirdDataStatMapper { + public Integer getBirdRealTimeCount(String var1); + + public Integer getBirdRealTimeMaxCount(Map var1); + + public List getBirdRealTimeList(Map var1); + + public List getBirdCountInfoListByArea(Map var1); + + public List getBirdDailyMaxAmountByParam(Map var1); + + public List getBirdRealStatByParam(Map var1); + + public List getDeviceListByParam(Map var1); + + public List getBirdCountInfoListByDevice(Map var1); + + public List getBirdCountInfoListBySpeciesId(Map var1); + + public List getAreaBirdSpeciesByParam(Map var1); + + public Integer getBirdCountForHeatMapByParam(Map var1); + + public List getBirdCountInfoListByHabit(Map var1); + + public List getBirdSpeciesBoardListByParam(Map var1); + + public List getBirdMonthList(Map var1); + + public List getBirdWeeklyStatByDeviceParam(Map var1); + + public List getBirdWeeklyStatBySpecies(Map var1); + + public List getBirdWeeklyStatByHabit(Map var1); + + public List getBirdRealTimeStatByParam(Map var1); + + public List getBirdYearStatListByParam(Map var1); + + public List getBirdDailyStatByMonth(Map var1); + + public Integer getBirdMaxAmountByParam(Map var1); + + public Long getBirdTotalAmountByParam(Map var1); + + public Integer getBirdRealStatAmountByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/echart/service/BirdDataStatService.java b/ai-bird-system/src/main/java/net/hzvtc/echart/service/BirdDataStatService.java new file mode 100644 index 0000000..0363ea0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/echart/service/BirdDataStatService.java @@ -0,0 +1,61 @@ +package net.hzvtc.echart.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface BirdDataStatService { + public List getBirdRealTimeList(JSONObject var1); + + public List getBirdMonthList(JSONObject var1); + + public List getBirdCountInfoListByArea(Map var1); + + public JSONArray getBirdCountInfoListByDevice(Map var1); + + public JSONArray getBirdCountInfoListBySpeciesId(Map var1); + + public JSONArray getBirdCountInfoListByHabit(Map var1); + + public JSONArray getBirdCountInfoListByHabit(JSONObject var1); + + public List getBirdHabitListByParam(JSONObject var1); + + public int getBirdRealTimeCount(String var1); + + public JSONArray getBirdRealTimeCount(JSONArray var1); + + public JSONArray getBirdWeeklyStatByDeviceParam(Map var1); + + public JSONArray getBirdWeeklyStatBySpecies(Map var1); + + public JSONArray getBirdWeeklyStatByHabit(Map var1); + + public List getBirdRealTimeAmountByCode(JSONObject var1); + + public JSONObject getBirdRealTimeDailyAmountByParam(JSONObject var1); + + public JSONObject getBirdRealTimeWeeklyAmountByParam(JSONObject var1); + + public JSONObject getBirdYearStatListByParam(JSONObject var1); + + public JSONObject getBirdDailyStatByMonth(JSONObject var1); + + public JSONObject getBirdMaxAmountByParam(JSONObject var1); + + public JSONObject getBirdTotalAmountByParam(JSONObject var1); + + public List getBirdRealStatByParam(JSONObject var1); + + public List getBirdSpeciesBoardListByParam(JSONObject var1); + + public List getBirdDailyMaxAmountByParam(JSONObject var1); + + public Integer getBirdCountForHeatMapByParam(Map var1); + + public List getAreaBirdSpeciesByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/echart/service/impl/BirdDataStatServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/echart/service/impl/BirdDataStatServiceImpl.java new file mode 100644 index 0000000..e1fc280 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/echart/service/impl/BirdDataStatServiceImpl.java @@ -0,0 +1,530 @@ +package net.hzvtc.echart.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.echart.mapper.BirdDataStatMapper; +import net.hzvtc.echart.service.BirdDataStatService; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; + +@Service +public class BirdDataStatServiceImpl +implements BirdDataStatService { + private static final Logger log = LoggerFactory.getLogger(BirdDataStatServiceImpl.class); + @Resource + private BirdDataStatMapper birdRealTimeMapper; + private final ProtectedAreaService protectedAreaService; + private final SpeciesDailyStatService speciesDailyStatService; + private final ProtectedAreaSpeciesService protectedAreaSpeciesService; + + @Override + public List getBirdRealTimeList(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + String birdCode = param.getString("birdCode"); + map.put("birdCode", birdCode); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + return this.birdRealTimeMapper.getBirdRealTimeList(map); + } + + @Override + public List getBirdMonthList(JSONObject param) { + HashMap map = new HashMap(); + String year = param.getString("year"); + if (year == null || year.isEmpty()) { + year = Integer.toString(Calendar.getInstance().get(1)); + } + map.put("year", year); + String birdCode = param.getString("birdCode"); + map.put("birdCode", birdCode); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + return this.birdRealTimeMapper.getBirdMonthList(map); + } + + @Override + public List getBirdCountInfoListByArea(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + List sublist = this.birdRealTimeMapper.getBirdCountInfoListBySpeciesId(map); + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return this.birdRealTimeMapper.getBirdCountInfoListByArea(map); + } + + @Override + public JSONArray getBirdCountInfoListByDevice(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getDeviceListByParam(map); + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("deviceId", item.getId()); + map.put("recordType", 1); + List sublist = this.birdRealTimeMapper.getBirdCountInfoListByDevice(map); + if (sublist != null && !sublist.isEmpty()) { + List ids = sublist.stream().map(BirdStatDataVo::getSpeciesId).collect(Collectors.toList()); + map.put("list", ids); + map.put("recordType", 2); + List otherList = this.birdRealTimeMapper.getBirdCountInfoListByDevice(map); + sublist.addAll(otherList); + obj.put("list", sublist); + } else { + map.put("recordType", 2); + List otherList = this.birdRealTimeMapper.getBirdCountInfoListByDevice(map); + obj.put("list", otherList); + } + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public JSONArray getBirdCountInfoListBySpeciesId(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + map.put("recordType", 1); + List sublist = this.birdRealTimeMapper.getBirdCountInfoListBySpeciesId(map); + if (sublist == null || sublist.isEmpty()) { + map.put("recordType", 2); + sublist = this.birdRealTimeMapper.getBirdCountInfoListBySpeciesId(map); + } + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public JSONArray getBirdCountInfoListByHabit(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + map.put("recordType", 1); + List sublist = this.birdRealTimeMapper.getBirdCountInfoListByHabit(map); + if (sublist == null || sublist.isEmpty()) { + map.put("recordType", 2); + sublist = this.birdRealTimeMapper.getBirdCountInfoListByHabit(map); + } + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public JSONArray getBirdCountInfoListByHabit(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Integer isCommon = param.getInteger("isCommon"); + map.put("isCommon", isCommon); + Integer limit = param.getInteger("limit"); + map.put("limit", limit); + return this.getBirdCountInfoListByHabit(map); + } + + @Override + public List getBirdHabitListByParam(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + return this.birdRealTimeMapper.getBirdCountInfoListByHabit(map); + } + + @Override + public int getBirdRealTimeCount(String birdCode) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + HashMap map = new HashMap(); + map.put("calcDate", df.format(new Date())); + map.put("birdCode", birdCode); + Integer count = this.birdRealTimeMapper.getBirdRealTimeMaxCount(map); + return count == null ? 0 : count; + } + + @Override + public JSONArray getBirdRealTimeCount(JSONArray array) { + JSONArray arr = new JSONArray(); + array.stream().forEach(obj -> { + JSONObject jsonObject = JSONObject.parseObject((String)JSON.toJSONString((Object)obj)); + String id = jsonObject.getString("id"); + JSONObject object = new JSONObject(); + object.put("value", (Object)this.getBirdRealTimeCount(id)); + object.put("name", jsonObject.get((Object)"name")); + arr.add((Object)object); + }); + return arr; + } + + @Override + public JSONArray getBirdWeeklyStatByDeviceParam(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getDeviceListByParam(map); + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("deviceId", item.getId()); + List sublist = this.birdRealTimeMapper.getBirdWeeklyStatByDeviceParam(map); + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public JSONArray getBirdWeeklyStatBySpecies(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.stream().forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + List sublist = this.birdRealTimeMapper.getBirdWeeklyStatBySpecies(map); + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public JSONArray getBirdWeeklyStatByHabit(Map map) { + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.stream().forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + List sublist = this.birdRealTimeMapper.getBirdWeeklyStatByHabit(map); + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + return jsonArray; + } + + @Override + public List getBirdRealTimeAmountByCode(JSONObject obj) { + HashMap map = new HashMap(); + Long areaId = obj.getLong("areaId"); + map.put("areaId", areaId); + String calcDate = obj.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + map.put("calcDate", df.format(new Date())); + } + Integer isCommon = obj.getInteger("isCommon"); + map.put("isCommon", isCommon); + return this.birdRealTimeMapper.getBirdRealTimeStatByParam(map); + } + + @Override + public JSONObject getBirdRealTimeDailyAmountByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long birdCode = param.getLong("birdCode"); + if (birdCode != null) { + map.put("birdCode", birdCode); + } + Integer isCommon = param.getInteger("isCommon"); + map.put("isCommon", isCommon); + List list = this.birdRealTimeMapper.getBirdCountInfoListByArea(map); + if (list != null && list.size() > 0) { + JSONArray array = new JSONArray(); + Map arealist = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getCodeName, LinkedHashMap::new, Collectors.toList())); + arealist.forEach((key, data) -> { + JSONObject obj = new JSONObject(); + obj.put("name", key); + int[] data1 = new int[]{0}; + int[] data2 = new int[]{0}; + data.stream().forEach(item -> { + if (item.getHour() <= 12) { + if (item.getCount() > data1[0]) { + data1[0] = item.getCount(); + } + } else if (item.getCount() > data2[0]) { + data2[0] = item.getCount(); + } + }); + obj.put("data1", (Object)data1[0]); + obj.put("data2", (Object)data2[0]); + array.add((Object)obj); + }); + result.put("areaData", (Object)array); + } + return result; + } + + @Override + public JSONObject getBirdRealTimeWeeklyAmountByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("dateBegin", DateUtils.getFirstDayOfWeek((String)calcDate)); + map.put("dateEnd", DateUtils.getLastDayOfWeek((String)calcDate)); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + JSONArray jsonArray = new JSONArray(); + List list = this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + list.stream().forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + List sublist = this.birdRealTimeMapper.getBirdWeeklyStatBySpecies(map); + obj.put("list", sublist); + jsonArray.add((Object)obj); + }); + result.put("speciesData", (Object)jsonArray); + return result; + } + + @Override + public JSONObject getBirdYearStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcYear = param.getString("calcYear"); + if (calcYear == null || calcYear.isEmpty()) { + LocalDate currentDate = LocalDate.now(); + map.put("year", currentDate.getYear()); + } else { + map.put("year", Integer.parseInt(calcYear)); + } + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + List list = this.birdRealTimeMapper.getBirdYearStatListByParam(map); + int[] month = new int[12]; + if (list != null && list.size() > 0) { + JSONArray array = new JSONArray(); + list.forEach(item -> { + if (item.getCode() != null) { + JSONObject obj = new JSONObject(); + String name = "data" + item.getCode(); + obj.put(name, (Object)item.getCount()); + array.add((Object)obj); + month[Integer.parseInt((String)item.getCode())] = item.getCount(); + } + }); + result.put("yearData", (Object)array); + } + result.put("monthData", (Object)month); + return result; + } + + @Override + public JSONObject getBirdDailyStatByMonth(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + int daysOfMonth = 30; + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + daysOfMonth = this.getDaysOfMonth(new Date()); + } else { + try { + daysOfMonth = this.getDaysOfMonth(df.parse(calcDate)); + } + catch (Exception ex) { + daysOfMonth = 1; + } + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + result.put("daysOfMonth", (Object)daysOfMonth); + result.put("calcDate", (Object)calcDate); + int[] arr = new int[daysOfMonth]; + List list = this.birdRealTimeMapper.getBirdDailyStatByMonth(map); + if (list != null && list.size() > 0) { + list.stream().forEach(item -> { + arr[Integer.parseInt((String)item.getCode()) - 1] = item.getCount(); + }); + } + result.put("list", (Object)arr); + return result; + } + + @Override + public JSONObject getBirdMaxAmountByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Integer amount = this.birdRealTimeMapper.getBirdMaxAmountByParam(map); + result.put("amount", (Object)(amount == null ? 0 : amount)); + return result; + } + + @Override + public JSONObject getBirdTotalAmountByParam(JSONObject param) { + String areaCode; + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + if (areaId == null && (areaCode = param.getString("areaCode")) != null && !areaCode.isEmpty()) { + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaByCode(areaCode); + areaId = protectedArea.getId(); + } + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Long total = this.birdRealTimeMapper.getBirdTotalAmountByParam(map); + result.put("total", (Object)(total == null ? 0L : total)); + return result; + } + + @Override + public List getBirdRealStatByParam(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return null; + } + map.put("areaId", areaId); + map.put("isCommon", 1); + map.put("recordType", 1); + List list = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByAreaId(map); + list.forEach(item -> { + if (item.getCount() == 0) { + map.put("speciesId", item.getSpeciesId()); + Integer count = this.speciesDailyStatService.getSpeciesDailySpeciesAmountByParam(map); + item.setCount(count == null ? 0 : count); + } + }); + return list; + } + + @Override + public List getBirdSpeciesBoardListByParam(JSONObject obj) { + HashMap map = new HashMap(); + String calcDate = obj.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = obj.getLong("areaId"); + map.put("areaId", areaId); + return this.birdRealTimeMapper.getBirdSpeciesBoardListByParam(map); + } + + @Override + public List getBirdDailyMaxAmountByParam(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + return this.birdRealTimeMapper.getBirdDailyMaxAmountByParam(map); + } + + @Override + public Integer getBirdCountForHeatMapByParam(Map map) { + return this.birdRealTimeMapper.getBirdCountForHeatMapByParam(map); + } + + @Override + public List getAreaBirdSpeciesByParam(Map map) { + return this.birdRealTimeMapper.getAreaBirdSpeciesByParam(map); + } + + private int getDaysOfMonth(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + return calendar.getActualMaximum(5); + } + + @Lazy + public BirdDataStatServiceImpl(ProtectedAreaService protectedAreaService, SpeciesDailyStatService speciesDailyStatService, ProtectedAreaSpeciesService protectedAreaSpeciesService) { + this.protectedAreaService = protectedAreaService; + this.speciesDailyStatService = speciesDailyStatService; + this.protectedAreaSpeciesService = protectedAreaSpeciesService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/email/service/EmailService.java b/ai-bird-system/src/main/java/net/hzvtc/email/service/EmailService.java new file mode 100644 index 0000000..c8afea3 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/email/service/EmailService.java @@ -0,0 +1,9 @@ +package net.hzvtc.email.service; + +public interface EmailService { + public void sendSimpleEmail(String var1, String var2, String var3); + + public void sendEmailWithAttachment(String var1, String var2, String var3, String var4); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/email/service/impl/EmailServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/email/service/impl/EmailServiceImpl.java new file mode 100644 index 0000000..19abe00 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/email/service/impl/EmailServiceImpl.java @@ -0,0 +1,62 @@ +package net.hzvtc.email.service.impl; + +import java.io.File; +import javax.mail.internet.MimeMessage; +import net.hzvtc.email.service.EmailService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; + +@Service +public class EmailServiceImpl +implements EmailService { + private static final Logger log = LoggerFactory.getLogger(EmailServiceImpl.class); + @Value(value="${spring.mail.username}") + private String sendName; + @Autowired + private JavaMailSender mailSender; + + @Override + public void sendSimpleEmail(String topic, String content, String email) { + try { + SimpleMailMessage mail = new SimpleMailMessage(); + mail.setFrom(this.sendName); + String[] receives = email.split(";"); + mail.setTo(receives); + mail.setSubject(topic); + mail.setText(content); + this.mailSender.send(mail); + log.info("\u90ae\u4ef6\u5df2\u6210\u529f\u53d1\u9001\u81f3:" + email); + } + catch (Exception ex) { + log.error("\u90ae\u4ef6\u53d1\u9001\u81f3:" + email + "\u5931\u8d25"); + } + } + + @Override + public void sendEmailWithAttachment(String topic, String content, String filePath, String email) { + try { + MimeMessage message = this.mailSender.createMimeMessage(); + MimeMessageHelper messageHelper = new MimeMessageHelper(message, true); + messageHelper.setFrom(this.sendName); + String[] receives = email.split(";"); + messageHelper.setTo(receives); + messageHelper.setSubject(topic); + messageHelper.setText(content); + File file = new File(filePath); + messageHelper.addAttachment(file.getName(), file); + this.mailSender.send(message); + log.info("\u5e26\u9644\u4ef6\u90ae\u4ef6\u5df2\u6210\u529f\u53d1\u9001\u81f3:" + email); + } + catch (Exception ex) { + log.error("\u5e26\u9644\u4ef6\u90ae\u4ef6\u53d1\u9001\u81f3:" + email + "\u5931\u8d25"); + } + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileInfoController.java new file mode 100644 index 0000000..3e51fe2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileInfoController.java @@ -0,0 +1,262 @@ +package net.hzvtc.file.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.file.domain.MediaFileInfo; +import net.hzvtc.file.service.MediaFileInfoService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/media/file"}) +public class MediaFileInfoController +extends BaseController { + private static final Logger log = LoggerFactory.getLogger(MediaFileInfoController.class); + @Autowired + private MediaFileInfoService mediaFileInfoService; + + @PreAuthorize(value="@ss.hasPermi('media:file:list')") + @GetMapping(value={"/list"}) + public TableDataInfo list(MediaFileInfo mediaFileInfo) { + this.startPage(); + List list = this.mediaFileInfoService.selectMediaFileInfoList(mediaFileInfo); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('media:file:export')") + @Log(title="\u591a\u6e90\u6570\u636e\u6587\u4ef6", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, MediaFileInfo mediaFileInfo) { + List list = this.mediaFileInfoService.selectMediaFileInfoList(mediaFileInfo); + ExcelUtil util = new ExcelUtil(MediaFileInfo.class); + util.exportExcel(response, list, "\u591a\u6e90\u6570\u636e\u6587\u4ef6\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('media:file:query')") + @GetMapping(value={"/{id}"}) + public AjaxResult getInfo(@PathVariable(value="id") Long id) { + return AjaxResult.success((Object)((Object)this.mediaFileInfoService.selectMediaFileInfoById(id))); + } + + @PreAuthorize(value="@ss.hasPermi('media:file:add')") + @Log(title="\u591a\u6e90\u6570\u636e\u6587\u4ef6", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody MediaFileInfo mediaFileInfo) { + return this.toAjax(this.mediaFileInfoService.insertMediaFileInfo(mediaFileInfo)); + } + + @PostMapping(value={"/save"}) + public AjaxResult save(@RequestBody MediaFileInfo mediaFileInfo) { + return AjaxResult.success((Object)this.mediaFileInfoService.saveMediaFileInfo(mediaFileInfo)); + } + + @PreAuthorize(value="@ss.hasPermi('media:file:edit')") + @Log(title="\u591a\u6e90\u6570\u636e\u6587\u4ef6", businessType=BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody MediaFileInfo mediaFileInfo) { + return this.toAjax(this.mediaFileInfoService.updateMediaFileInfo(mediaFileInfo)); + } + + @PreAuthorize(value="@ss.hasPermi('media:file:remove')") + @Log(title="\u591a\u6e90\u6570\u636e\u6587\u4ef6", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{ids}"}) + public AjaxResult remove(@PathVariable Long[] ids) { + return this.toAjax(this.mediaFileInfoService.deleteMediaFileInfoByIds(ids)); + } + + @PostMapping(value={"/fileToDb"}) + public AjaxResult saveFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.saveMovFilesToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/imageFileToDb"}) + public AjaxResult saveNetFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importImageFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/detectedFileToDb"}) + public AjaxResult importDeactivateFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importDetectedImageFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/testTxtFileToDb"}) + public AjaxResult saveTestTextFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importTextFileToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/tuweiduiFileToDb"}) + public AjaxResult saveTextFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importTextFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/docxFileToDb"}) + public AjaxResult saveDocxFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importDocxToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/audioFileToDb"}) + public AjaxResult saveAudioFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importAudioFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/extractImageFromVideo"}) + public AjaxResult extractImageFromVideo(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.extractImageFromVideo(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/convertVideo"}) + public AjaxResult convertH264Video(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.convertH264Video(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/importIntroFiles"}) + public AjaxResult convertIntroFile(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importIntroFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/importAnswerFile"}) + public AjaxResult importAnswerFile(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importAnswerFileToTable(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/videoFileToDb"}) + public AjaxResult saveVideoFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importVideoFileToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/jsonFileToDb"}) + public AjaxResult saveJSONFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importJsonVideoFileToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/csvFileToDb"}) + public AjaxResult saveCsvFileToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.importCsvVideoFileToDb(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @PostMapping(value={"/updateFileUrl"}) + public AjaxResult updateFileUrlToDb(@RequestBody JSONObject object) { + try { + this.mediaFileInfoService.updateFileUrlPath(object); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } + + @GetMapping(value={"/updateBridImageUrlForUpdate"}) + public AjaxResult updateBridImageUrlForUpdate() { + try { + this.mediaFileInfoService.updateBirdFileImagePath(null); + } + catch (Exception ex) { + ex.printStackTrace(); + log.error("error", (Throwable)ex); + } + return AjaxResult.success(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileItemController.java b/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileItemController.java new file mode 100644 index 0000000..55b324b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/controller/MediaFileItemController.java @@ -0,0 +1,98 @@ +package net.hzvtc.file.controller; + +import java.util.List; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.file.domain.MediaFileItem; +import net.hzvtc.file.service.MediaFileItemService; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.common.core.page.TableDataInfo; + +/** + * 多源数据文件列Controller + * + * @author admin + * @date 2024-06-04 + */ +@RestController +@RequestMapping("/media/item") +public class MediaFileItemController extends BaseController { + @Autowired + private MediaFileItemService mediaFileItemService; + +/** + * 查询多源数据文件列列表 + */ +@PreAuthorize("@ss.hasPermi('media:item:list')") +@GetMapping("/list") + public TableDataInfo list(MediaFileItem mediaFileItem) { + startPage(); + List list = mediaFileItemService.selectMediaFileItemList(mediaFileItem); + return getDataTable(list); + } + + /** + * 导出多源数据文件列列表 + */ + @PreAuthorize("@ss.hasPermi('media:item:export')") + @Log(title = "多源数据文件列", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, MediaFileItem mediaFileItem) { + List list = mediaFileItemService.selectMediaFileItemList(mediaFileItem); + ExcelUtil util = new ExcelUtil(MediaFileItem. class); + util.exportExcel(response, list, "多源数据文件列数据"); + } + + /** + * 获取多源数据文件列详细信息 + */ + @PreAuthorize("@ss.hasPermi('media:item:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(mediaFileItemService.selectMediaFileItemById(id)); + } + + /** + * 新增多源数据文件列 + */ + @PreAuthorize("@ss.hasPermi('media:item:add')") + @Log(title = "多源数据文件列", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody MediaFileItem mediaFileItem) { + return toAjax(mediaFileItemService.insertMediaFileItem(mediaFileItem)); + } + + /** + * 修改多源数据文件列 + */ + @PreAuthorize("@ss.hasPermi('media:item:edit')") + @Log(title = "多源数据文件列", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody MediaFileItem mediaFileItem) { + return toAjax(mediaFileItemService.updateMediaFileItem(mediaFileItem)); + } + + /** + * 删除多源数据文件列 + */ + @PreAuthorize("@ss.hasPermi('media:item:remove')") + @Log(title = "多源数据文件列", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(mediaFileItemService.deleteMediaFileItemByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileInfo.java b/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileInfo.java new file mode 100644 index 0000000..1464d3f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileInfo.java @@ -0,0 +1,24 @@ +package net.hzvtc.file.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import java.util.List; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="MediaFileInfo") +@Data +public class MediaFileInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private int uploadType; + private Long deviceId; + private Long userId; + private String version; + private Date createDate; + private int isDeleted; + private List fileItems; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileItem.java b/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileItem.java new file mode 100644 index 0000000..7440a70 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/domain/MediaFileItem.java @@ -0,0 +1,22 @@ +package net.hzvtc.file.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="MediaFileItem") +@Data +public class MediaFileItem extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String fileName; + private String fileType; + private String urlPath; + private String metaPath; + private Date time; + private Long parentId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileInfoMapper.java new file mode 100644 index 0000000..5d6418d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileInfoMapper.java @@ -0,0 +1,20 @@ +package net.hzvtc.file.mapper; + +import java.util.List; +import net.hzvtc.file.domain.MediaFileInfo; + +public interface MediaFileInfoMapper { + public MediaFileInfo selectMediaFileInfoById(Long var1); + + public List selectMediaFileInfoList(MediaFileInfo var1); + + public int insertMediaFileInfo(MediaFileInfo var1); + + public int updateMediaFileInfo(MediaFileInfo var1); + + public int deleteMediaFileInfoById(Long var1); + + public int deleteMediaFileInfoByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileItemMapper.java b/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileItemMapper.java new file mode 100644 index 0000000..fab2f54 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/mapper/MediaFileItemMapper.java @@ -0,0 +1,22 @@ +package net.hzvtc.file.mapper; + +import java.util.List; +import net.hzvtc.file.domain.MediaFileItem; + +public interface MediaFileItemMapper { + public MediaFileItem selectMediaFileItemById(Long var1); + + public List selectMediaFileItemList(MediaFileItem var1); + + public int insertMediaFileItem(MediaFileItem var1); + + public int updateMediaFileItem(MediaFileItem var1); + + public int batchInsertMediaFileItem(List var1); + + public int deleteMediaFileItemById(Long var1); + + public int deleteMediaFileItemByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileInfoService.java new file mode 100644 index 0000000..93d69d6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileInfoService.java @@ -0,0 +1,57 @@ +package net.hzvtc.file.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.file.domain.MediaFileInfo; + +public interface MediaFileInfoService { + public MediaFileInfo selectMediaFileInfoById(Long var1); + + public List selectMediaFileInfoList(MediaFileInfo var1); + + public int insertMediaFileInfo(MediaFileInfo var1); + + public int updateMediaFileInfo(MediaFileInfo var1); + + public int deleteMediaFileInfoByIds(Long[] var1); + + public int deleteMediaFileInfoById(Long var1); + + public int saveMediaFileInfo(MediaFileInfo var1); + + public void saveMovFilesToDb(JSONObject var1) throws Exception; + + public void saveNetFilesToDb(JSONObject var1) throws Exception; + + public void importImageFileToTable(JSONObject var1); + + public void importTextFileToTable(JSONObject var1); + + public void importAudioFileToTable(JSONObject var1); + + public void extractImageFromVideo(JSONObject var1); + + public void convertH264Video(JSONObject var1); + + public void importVideoFileToDb(JSONObject var1); + + public void importJsonVideoFileToDb(JSONObject var1); + + public void importCsvVideoFileToDb(JSONObject var1); + + public void importTextFileToDb(JSONObject var1); + + public void importDocxToDb(JSONObject var1); + + public void importDetectedImageFileToTable(JSONObject var1); + + public void updateFileUrlPath(JSONObject var1); + + public void importIntroFileToTable(JSONObject var1); + + public void importAnswerFileToTable(JSONObject var1); + + public void updateBirdFileImagePath(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileItemService.java b/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileItemService.java new file mode 100644 index 0000000..e696396 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/service/MediaFileItemService.java @@ -0,0 +1,22 @@ +package net.hzvtc.file.service; + +import java.util.List; +import net.hzvtc.file.domain.MediaFileItem; + +public interface MediaFileItemService { + public MediaFileItem selectMediaFileItemById(Long var1); + + public List selectMediaFileItemList(MediaFileItem var1); + + public int insertMediaFileItem(MediaFileItem var1); + + public int updateMediaFileItem(MediaFileItem var1); + + public int deleteMediaFileItemByIds(Long[] var1); + + public int deleteMediaFileItemById(Long var1); + + public int batchInsertMediaFileItem(List var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileInfoServiceImpl.java new file mode 100644 index 0000000..7c4ca8a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileInfoServiceImpl.java @@ -0,0 +1,1559 @@ +package net.hzvtc.file.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.xuggle.xuggler.ICodec; +import com.xuggle.xuggler.IContainer; +import com.xuggle.xuggler.IPacket; +import com.xuggle.xuggler.IPixelFormat; +import com.xuggle.xuggler.IStream; +import com.xuggle.xuggler.IStreamCoder; +import com.xuggle.xuggler.IVideoPicture; +import com.xuggle.xuggler.IVideoResampler; +import java.awt.image.BufferedImage; +import java.awt.image.RenderedImage; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileVisitOption; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Random; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.annotation.Resource; +import javax.imageio.ImageIO; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.domain.SpeciesAnswer; +import net.hzvtc.bird.domain.SpeciesAnswerItem; +import net.hzvtc.bird.domain.SpeciesIntro; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.bird.service.SpeciesAnswerService; +import net.hzvtc.bird.service.SpeciesIntroService; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.domain.MediaItem; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.domain.ResultRecordDetails; +import net.hzvtc.data.check.service.MediaItemService; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordDetailsService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.file.domain.MediaFileInfo; +import net.hzvtc.file.domain.MediaFileItem; +import net.hzvtc.file.mapper.MediaFileInfoMapper; +import net.hzvtc.file.service.MediaFileInfoService; +import net.hzvtc.file.service.MediaFileItemService; +import org.apache.commons.io.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class MediaFileInfoServiceImpl +implements MediaFileInfoService { + private static final Logger log = LoggerFactory.getLogger(MediaFileInfoServiceImpl.class); + @Resource + private MediaFileInfoMapper mediaFileInfoMapper; + @Autowired + private MediaFileItemService mediaFileItemService; + @Autowired + private ResultMediaService resultMediaService; + @Autowired + private ResultRecordService resultRecordService; + @Autowired + private ResultRecordDetailsService resultRecordDetailsService; + @Autowired + private BirdSpeciesService birdSpeciesService; + @Autowired + private MediaItemService mediaItemService; + @Autowired + private DeviceInfoService deviceInfoService; + @Autowired + private SpeciesIntroService speciesIntroService; + @Autowired + private SpeciesAnswerService speciesAnswerService; + private String prefixPath; + private Map mapSpeciesName = new HashMap(); + private Map mapDeviceName = new HashMap(); + + @Override + public MediaFileInfo selectMediaFileInfoById(Long id) { + return this.mediaFileInfoMapper.selectMediaFileInfoById(id); + } + + @Override + public List selectMediaFileInfoList(MediaFileInfo mediaFileInfo) { + return this.mediaFileInfoMapper.selectMediaFileInfoList(mediaFileInfo); + } + + @Override + public int insertMediaFileInfo(MediaFileInfo mediaFileInfo) { + return this.mediaFileInfoMapper.insertMediaFileInfo(mediaFileInfo); + } + + @Override + public int updateMediaFileInfo(MediaFileInfo mediaFileInfo) { + return this.mediaFileInfoMapper.updateMediaFileInfo(mediaFileInfo); + } + + @Override + public int deleteMediaFileInfoByIds(Long[] ids) { + return this.mediaFileInfoMapper.deleteMediaFileInfoByIds(ids); + } + + @Override + public int deleteMediaFileInfoById(Long id) { + return this.mediaFileInfoMapper.deleteMediaFileInfoById(id); + } + + @Override + @Transactional + public int saveMediaFileInfo(MediaFileInfo mediaFileInfo) { + mediaFileInfo.setIsDeleted(0); + mediaFileInfo.setCreateDate(new Date()); + mediaFileInfo.setUserId(SecurityUtils.getUserId()); + int count = this.mediaFileInfoMapper.insertMediaFileInfo(mediaFileInfo); + List list = mediaFileInfo.getFileItems(); + list.forEach(item -> item.setParentId(mediaFileInfo.getId())); + this.mediaFileItemService.batchInsertMediaFileItem(list); + return count; + } + + @Override + public void saveMovFilesToDb(JSONObject object) throws Exception { + String basePath = object.getString("filePath"); + String serialNo = object.getString("serialNo"); + File dir = new File(basePath + "/DCIM/100MEDIA"); + if (dir.exists()) { + String jsonFilePath; + Long deviceId = object.getLong("deviceId"); + SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); + File[] fileList = dir.listFiles(); + ArrayList movFiles = new ArrayList(); + ArrayList jpgFiles = new ArrayList(); + ArrayList txtFiles = new ArrayList(); + ArrayList jsonFiles = new ArrayList(); + ArrayList txtImageFiles = new ArrayList(); + for (File file : fileList) { + if (file.isDirectory()) continue; + String name = file.getName(); + if (name.toLowerCase().endsWith(".mov")) { + movFiles.add(name); + continue; + } + if (!name.toLowerCase().endsWith(".txt")) continue; + txtFiles.add(name); + } + String imageFile = basePath.replaceAll("videos_camera", "images_camera"); + dir = new File(imageFile + "/DCIM/100MEDIA"); + if (dir.exists()) { + for (File file : fileList = dir.listFiles()) { + if (file.isDirectory()) continue; + String name = file.getName(); + if (name.toLowerCase().endsWith(".jpg")) { + jpgFiles.add(name); + continue; + } + if (!name.toLowerCase().endsWith(".txt")) continue; + txtImageFiles.add(name); + } + } + if ((dir = new File((jsonFilePath = (basePath = basePath.replaceAll("\\\\", "/")).replaceAll("/data5/file/ghy_xb/videos_camera/", "/data5/PartDataset/001_GHY/00_20240415_2023Data_02-06/data/")) + "/Upload_que")).exists()) { + for (File file : fileList = dir.listFiles()) { + String name; + if (file.isDirectory() || !(name = file.getName()).toLowerCase().endsWith(".json")) continue; + jsonFiles.add(name); + } + } + for (String jsonFile : jsonFiles) { + String input; + JSONObject jsonObject; + File file; + String filePath = jsonFilePath + "/Upload_que/" + jsonFile; + file = new File(filePath); + if (!file.exists() || (jsonObject = JSON.parseObject((String)(input = FileUtils.readFileToString((File)file, (String)"UTF-8")))) == null) continue; + Long itemId = this.saveToJsonFile(jsonObject, deviceId); + JSONArray array = jsonObject.getJSONArray("file_inf"); + for (Object obj : array) { + String name = ((JSONObject)obj).getString("F_FileName"); + String time = ((JSONObject)obj).getString("F_FileTime"); + this.saveToTable(name, time, basePath, movFiles, jpgFiles, txtFiles, txtImageFiles, deviceId, itemId); + } + } + } + } + + @Override + public void saveNetFilesToDb(JSONObject jsonObject) throws Exception { + String basePath = jsonObject.getString("filePath"); + File dir = new File(basePath + "/DCIM/100MEDIA"); + if (dir.exists()) { + Calendar cal = Calendar.getInstance(); + Long deviceId = jsonObject.getLong("deviceId"); + SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); + File[] fileList = dir.listFiles(); + ArrayList movFiles = new ArrayList(); + ArrayList jpgFiles = new ArrayList(); + ArrayList txtFiles = new ArrayList(); + ArrayList txtImageFiles = new ArrayList(); + for (File file : fileList) { + if (file.isDirectory()) continue; + String name = file.getName(); + if (name.toLowerCase().endsWith(".mov")) { + movFiles.add(name); + continue; + } + if (!name.toLowerCase().endsWith(".txt")) continue; + txtFiles.add(name); + } + String imageFile = basePath.replaceAll("videos_camera", "images_camera"); + dir = new File(imageFile + "/DCIM/100MEDIA"); + if (dir.exists()) { + for (File file : fileList = dir.listFiles()) { + if (file.isDirectory()) continue; + String name = file.getName(); + if (name.toLowerCase().endsWith(".jpg")) { + jpgFiles.add(name); + continue; + } + if (!name.toLowerCase().endsWith(".txt")) continue; + txtImageFiles.add(name); + } + } + for (String name : movFiles) { + String[] arr = name.split("\\."); + String name1 = this.getNetFile(arr[0]); + String imageName = this.getFileFromList(name1, jpgFiles); + if (imageName == null) { + return; + } + Long itemId = this.saveToJsonFile(deviceId); + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setMediaId(itemId); + String[] arr1 = arr[0].split("_"); + Date date = arr1.length > 2 ? df.parse(arr1[1] + arr1[2]) : df.parse(arr1[0] + arr1[1]); + resultMedia.setTime(date); + resultMedia.setMediaType(3); + String path = basePath.replaceAll("/data5/file", ""); + resultMedia.setMediaUrl(path + "/DCIM/100MEDIA/" + name); + path = basePath.replaceAll("/data5/file", ""); + path = path.replaceAll("videos_camera", "images_camera"); + resultMedia.setMetaUrl(path + "/DCIM/100MEDIA/" + imageName); + resultMedia.setDeviceId(deviceId); + this.resultMediaService.insertResultMedia(resultMedia); + ResultRecord resultRecord = new ResultRecord(); + resultRecord.setDeviceId(deviceId); + resultRecord.setRecordType("1"); + resultRecord.setRecordTime(resultMedia.getTime()); + this.resultRecordService.insertResultRecord(resultRecord); + this.saveToTable(name1, txtFiles, resultRecord.getRecordId(), resultMedia.getMediaId()); + this.saveImageFileToTable(basePath, name1, date, jpgFiles, txtImageFiles, deviceId, resultMedia.getMediaId()); + } + for (String string : jpgFiles) { + } + } + } + + private String getSpeciesName(String path) { + int pos = path.lastIndexOf("/"); + return path.substring(pos + 1).replaceAll("_", " "); + } + + @Override + public void importImageFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer type = object.getInteger("type"); + Integer subType = object.getInteger("subType"); + String source = object.getString("source"); + String target = object.getString("target"); + try { + Map> map = this.getImageFile(basePath); + if (map.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + for (String key : map.keySet()) { + String speciesName = this.getSpeciesName(key); + Long speciesId = this.getSpeciesIdByScientificName(speciesName.trim()); + List paths = map.get(key); + for (Path path : paths) { + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(0L); + resultMedia.setMediaType(type); + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + resultMedia.setMediaUrl(path.toString().replace(this.prefixPath, "")); + resultMedia.setSubType(subType); + if (source != null && !source.isEmpty()) { + resultMedia.setFileUrl(resultMedia.getMediaUrl().replaceAll(source, target)); + } + resultMedia.setSpeciesId(speciesId); + resultMediaList.add(resultMedia); + if (resultMediaList.size() <= 20000) continue; + this.addListToResultMedia(resultMediaList, 2); + resultMediaList.clear(); + } + if (resultMediaList.isEmpty()) continue; + this.addListToResultMedia(resultMediaList, 2); + resultMediaList.clear(); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + } + + @Override + public void importTextFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + String imgPath = object.getString("imgPath"); + String textPath = object.getString("textPath"); + try { + List list = this.findImageFiles(basePath, new String[]{".jpg", ".jpeg", ".png", ".gif", ".bmp"}); + if (list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + for (Path path : list) { + String content = this.getContentFromFile(path); + if (content != null && !content.isEmpty()) { + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(0L); + resultMedia.setMediaType(4); + resultMedia.setSubType(1); + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + resultMedia.setMediaUrl(path.toAbsolutePath().toString().replace(this.prefixPath, "")); + resultMedia.setDescription(content); + resultMediaList.add(resultMedia); + } + if (resultMediaList.size() < 20000) continue; + this.resultMediaService.batchInsertResultMedia(resultMediaList); + resultMediaList.clear(); + } + if (!resultMediaList.isEmpty()) { + this.resultMediaService.batchInsertResultMedia(resultMediaList); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + } + + @Override + public void importAudioFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + String spectrum = object.getString("spectrum"); + Integer hasTime = object.getInteger("hasTime"); + int nameType = object.getIntValue("nameType"); + this.saveToTableByParam(basePath, subType, spectrum, ".wav", 1, 0, nameType, hasTime); + } + + private void saveToTableByParam(String basePath, Integer subType, String spectrum, String suffix, int mediaType, int type, int nameType, int hasTime) { + try { + Map> map = this.getFilesAndDirectoriesByPram(Paths.get(basePath, new String[0]), suffix); + if (map.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + ArrayList resultRecordDetailsList = new ArrayList(); + map.forEach((key, list) -> { + String speciesName = this.getSpeciesName((String)key); + Long speciesId = null; + if (nameType == 0) { + speciesId = this.getSpeciesIdByScientificName(speciesName); + } else if (nameType == 1) { + speciesId = this.getSpeciesIdByName(speciesName); + } + Long finalSpeciesId = speciesId; + list.forEach(file -> { + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(0L); + resultMedia.setMediaType(mediaType); + resultMedia.setSubType(subType); + if (hasTime == 1) { + String fileName = Paths.get(file, new String[0]).getFileName().toString(); + Date dateTime = this.extractDateTimeFromFile(fileName); + if (dateTime != null) { + resultMedia.setTime(dateTime); + } else { + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + } + } else { + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + } + resultMedia.setMediaUrl(file.replace(this.prefixPath, "")); + if (type == 0) { + resultMedia.setMetaUrl(resultMedia.getMediaUrl().replace(spectrum, spectrum + "_Spectrum").replace(suffix, ".png")); + } else if (type == 1) { + Path parantPath = Paths.get(file, new String[0]); + String metaUrl = parantPath.getParent().toString() + "/images/" + parantPath.getFileName().toString().replace(suffix, ".jpg"); + if (Files.exists(parantPath = Paths.get(metaUrl, new String[0]), new LinkOption[0])) { + resultMedia.setMetaUrl(metaUrl.replace(this.prefixPath, "")); + } else { + resultMedia.setMetaUrl(null); + } + } + resultMedia.setSpeciesId(finalSpeciesId); + resultMediaList.add(resultMedia); + }); + if (resultMediaList.size() >= 20000) { + this.addListToResultMedia((List)resultMediaList, resultRecordDetailsList); + resultRecordDetailsList.clear(); + resultMediaList.clear(); + } + }); + if (!resultMediaList.isEmpty()) { + this.addListToResultMedia(resultMediaList, resultRecordDetailsList); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + } + + private Date extractDateTimeFromFile(String fileName) { + String pattern = ".*(\\d{8})-(\\d{6})[^0-9].*"; + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(fileName); + if (m.find()) { + String dateTimeStr = m.group(1) + m.group(2); + SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHHmmss"); + try { + return dt.parse(dateTimeStr); + } + catch (Exception e) { + return null; + } + } + return null; + } + + @Override + public void extractImageFromVideo(JSONObject object) { + String basePath = object.getString("filePath"); + try { + List list = MediaFileInfoServiceImpl.findVideoFiles(basePath); + if (list == null || list.isEmpty()) { + return; + } + list.forEach(path -> { + try { + MediaFileInfoServiceImpl.extractFirstFrame(path, 1.0); + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + }); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + @Override + public void convertH264Video(JSONObject object) { + String basePath = object.getString("filePath"); + try { + List list = MediaFileInfoServiceImpl.findVideoFiles(basePath); + if (list == null || list.isEmpty()) { + return; + } + list.forEach(path -> this.convertToH264InPlace(path.toString())); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + private void convertToH264InPlace(String videoPath) { + try { + Path input = Paths.get(videoPath, new String[0]); + Path dir = input.getParent(); + String baseName = this.stripExtension(input.getFileName().toString()); + Path tmp = dir.resolve(baseName + ".h264.tmp.mp4"); + List command = Arrays.asList("ffmpeg", "-hide_banner", "-y", "-i", input.toString(), "-c:v", "libx264", "-preset", "fast", "-crf", "23", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", tmp.toString()); + ProcessBuilder pb = new ProcessBuilder(command); + pb.redirectErrorStream(true); + Process process = pb.start(); + try (BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));){ + String line; + while ((line = r.readLine()) != null) { + log.info(line); + } + } + int exit = process.waitFor(); + if (exit != 0) { + Files.deleteIfExists(tmp); + throw new RuntimeException("ffmpeg \u8f6c\u7801\u5931\u8d25\uff0c\u9000\u51fa\u7801: " + exit); + } + try { + Files.move(tmp, input, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); + } + catch (AtomicMoveNotSupportedException e) { + Files.move(tmp, input, StandardCopyOption.REPLACE_EXISTING); + } + log.info("\u8f6c\u7801\u5b8c\u6210\u5e76\u8986\u76d6: " + videoPath); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + private String stripExtension(String name) { + int dot = name.lastIndexOf(46); + return dot == -1 ? name : name.substring(0, dot); + } + + @Override + public void importVideoFileToDb(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + String spectrum = object.getString("spectrum"); + Integer hasTime = object.getInteger("hasTime"); + this.saveToTableByParam(basePath, subType, spectrum, ".mp4", 3, 1, 0, hasTime); + } + + @Override + public void importJsonVideoFileToDb(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + String source = object.getString("source"); + String target = object.getString("target"); + try { + List list = this.findImageFiles(basePath, new String[]{".json"}); + if (list == null || list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + list.forEach(path -> { + List array = this.parserJSONFile((Path)path); + if (array != null) { + Date date; + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(null); + resultMedia.setMediaType(3); + resultMedia.setSubType(subType); + resultMedia.setMediaUrl(path.toString().replace(this.prefixPath, "").replaceAll("_metadata.json$", "").replace("json/", "video/")); + Path temp = Paths.get(resultMedia.getMediaUrl(), new String[0]); + String newFileName = temp.getFileName().toString().replaceAll("\\.mp4$", ".jpg"); + Path newParentDir = temp.getParent().resolve("images"); + String metaUrl = this.prefixPath + newParentDir.resolve(newFileName); + Path imgPath = Paths.get(metaUrl, new String[0]); + if (Files.exists(imgPath, new LinkOption[0])) { + resultMedia.setMetaUrl(newParentDir.resolve(newFileName).toString()); + } + if ((date = this.extractDateTime(path.getFileName().toString())) != null) { + resultMedia.setTime(date); + } else { + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + } + String fileStr = target + "annotated_" + path.getFileName().toString().replaceAll("_metadata.json$", ""); + Path filePath = Paths.get(fileStr, new String[0]); + if (Files.exists(filePath, new LinkOption[0])) { + resultMedia.setFileUrl(fileStr.replace(this.prefixPath, "")); + } + resultMedia.setArray(array); + resultMediaList.add(resultMedia); + if (resultMediaList.size() >= 20000) { + this.addListToResultMedia((List)resultMediaList, 0); + resultMediaList.clear(); + } + } + }); + if (!resultMediaList.isEmpty()) { + this.addListToResultMedia(resultMediaList, 0); + resultMediaList.clear(); + } + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + @Override + public void importCsvVideoFileToDb(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + String source = object.getString("source"); + String target = object.getString("target"); + try { + List list = this.findImageFiles(basePath, new String[]{".csv"}); + if (list == null || list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + list.forEach(path -> { + JSONObject obj = this.parserCsvFile(path.toString()); + if (obj != null) { + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(null); + resultMedia.setMediaType(3); + resultMedia.setSubType(subType); + Path videoPath = path.getParent().getParent().resolve("videos").resolve(path.getFileName()); + resultMedia.setMediaUrl(videoPath.toString().replace(this.prefixPath, "").replaceAll("\\.csv$", "\\.mp4")); + Path metaPath = videoPath.getParent().resolve("images").resolve(videoPath.getFileName()); + metaPath = Paths.get(metaPath.toString().replaceAll(".csv$", ".jpg"), new String[0]); + if (Files.exists(metaPath, new LinkOption[0])) { + resultMedia.setMetaUrl(metaPath.toString().replace(this.prefixPath, "")); + } + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + String fileStr = target + "annotated_" + path.getFileName().toString().replaceAll("\\.csv$", "\\.mp4"); + Path filePath = Paths.get(fileStr, new String[0]); + if (Files.exists(filePath, new LinkOption[0])) { + resultMedia.setFileUrl(fileStr.replace(this.prefixPath, "")); + } + resultMedia.setSpeciesName(obj.getString("name")); + resultMedia.setWidth(obj.getInteger("count")); + resultMediaList.add(resultMedia); + } + if (resultMediaList.size() >= 20000) { + this.addListToResultMedia((List)resultMediaList, 1); + resultMediaList.clear(); + } + }); + if (!resultMediaList.isEmpty()) { + this.addListToResultMedia(resultMediaList, 1); + resultMediaList.clear(); + } + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + @Override + public void importTextFileToDb(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + String REGEX = "\u5728[^\u7684]+\u7684([^\uff0c]+)\uff0c\u4e8e(\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2})\uff0c[^\u53d1\u73b0]+\u53d1\u73b0[^\u53ea]+\u53ea([^\u7684]+)\u7684(\u56fe\u50cf|\u97f3\u9891)\uff0c\u6570\u636e\u5b58\u50a8\u5728\uff1a([^\\s;]+)"; + Pattern PATTERN = Pattern.compile(REGEX); + DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + try { + List list = this.findImageFiles(basePath, new String[]{".txt"}); + if (list == null || list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + list.forEach(path -> { + try (Stream lines = Files.lines(path);){ + lines.filter(line -> !line.trim().isEmpty()).forEach(line -> { + Matcher matcher = PATTERN.matcher(line.trim()); + if (matcher.find()) { + String deviceName = matcher.group(1).trim(); + String dateTimeStr = matcher.group(2).trim(); + String animal = matcher.group(3).trim(); + String dataPath = matcher.group(5).trim(); + LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, FORMATTER); + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + Long deviceId = this.mapDeviceName.get(deviceName); + if (deviceId == null) { + deviceId = this.deviceInfoService.getDeviceInfoIdByName(deviceName); + if (deviceId == null) { + deviceId = 0L; + } + this.mapDeviceName.put(deviceName, deviceId); + } + resultMedia.setDeviceId(deviceId); + resultMedia.setTime(Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant())); + resultMedia.setMediaUrl(dataPath); + resultMedia.setSpeciesId(this.getSpeciesIdByName(animal)); + resultMedia.setMediaType(4); + resultMedia.setDescription((String)line); + resultMedia.setSubType(subType); + resultMediaList.add(resultMedia); + if (resultMediaList.size() > 20000) { + this.addListToResultMedia((List)resultMediaList, 2); + resultMediaList.clear(); + } + } else { + System.out.println("\u672a\u5339\u914d\u884c: " + line); + } + }); + } + catch (IOException e) { + System.err.println("\u8bfb\u53d6\u6587\u4ef6\u5931\u8d25: " + e.getMessage()); + e.printStackTrace(); + } + if (!resultMediaList.isEmpty()) { + this.addListToResultMedia((List)resultMediaList, 2); + resultMediaList.clear(); + } + }); + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + /* + * Exception decompiling + */ + private String getContentFromDocx(Path path) { + /* + * This method has failed to decompile. When submitting a bug report, please provide this stack trace, and (if you hold appropriate legal rights) the relevant class file. + * + * org.benf.cfr.reader.util.ConfusedCFRException: Started 2 blocks at once + * at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.getStartingBlocks(Op04StructuredStatement.java:412) + * at org.benf.cfr.reader.bytecode.analysis.opgraph.Op04StructuredStatement.buildNestedBlocks(Op04StructuredStatement.java:487) + * at org.benf.cfr.reader.bytecode.analysis.opgraph.Op03SimpleStatement.createInitialStructuredBlock(Op03SimpleStatement.java:736) + * at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisInner(CodeAnalyser.java:850) + * at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysisOrWrapFail(CodeAnalyser.java:278) + * at org.benf.cfr.reader.bytecode.CodeAnalyser.getAnalysis(CodeAnalyser.java:201) + * at org.benf.cfr.reader.entities.attributes.AttributeCode.analyse(AttributeCode.java:94) + * at org.benf.cfr.reader.entities.Method.analyse(Method.java:531) + * at org.benf.cfr.reader.entities.ClassFile.analyseMid(ClassFile.java:1055) + * at org.benf.cfr.reader.entities.ClassFile.analyseTop(ClassFile.java:942) + * at org.benf.cfr.reader.Driver.doJarVersionTypes(Driver.java:257) + * at org.benf.cfr.reader.Driver.doJar(Driver.java:139) + * at org.benf.cfr.reader.CfrDriverImpl.analyse(CfrDriverImpl.java:76) + * at org.benf.cfr.reader.Main.main(Main.java:54) + */ + throw new IllegalStateException("Decompilation failed"); + } + + @Override + public void importDocxToDb(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getIntValue("subType"); + try { + List list = this.findImageFiles(basePath, new String[]{".docx"}); + if (list == null || list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + list.forEach(path -> { + String content = this.getContentFromDocx((Path)path); + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(0L); + resultMedia.setMediaType(4); + resultMedia.setSubType(subType); + resultMedia.setDescription(content); + String name = path.getFileName().toString().replaceAll(".docx", ""); + Long speciesId = this.getSpeciesIdByScientificName(name); + resultMedia.setSpeciesId(speciesId); + resultMediaList.add(resultMedia); + if (resultMediaList.size() > 20000) { + this.addListToResultMedia((List)resultMediaList, 2); + resultMediaList.clear(); + } + }); + if (!resultMediaList.isEmpty()) { + this.addListToResultMedia(resultMediaList, 2); + resultMediaList.clear(); + } + } + catch (Exception ex) { + log.error("error", (Throwable)ex); + } + } + + @Override + public void importDetectedImageFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + Integer subType = object.getInteger("subType"); + String source = object.getString("source"); + String target = object.getString("target"); + try { + List list = this.findImageFiles(basePath, new String[]{".png", ".jpg"}); + if (list == null || list.isEmpty()) { + return; + } + ArrayList resultMediaList = new ArrayList(); + list.forEach(path -> { + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setMediaType(2); + resultMedia.setTime(Date.from(this.getDateTime().atZone(ZoneId.systemDefault()).toInstant())); + resultMedia.setMediaUrl(path.toString().replace(this.prefixPath, "")); + resultMedia.setSubType(subType); + String fileString = target + path.getFileName().toString(); + if (Files.exists(Paths.get(fileString, new String[0]), new LinkOption[0])) { + resultMedia.setFileUrl(fileString.replace(this.prefixPath, "")); + } + resultMediaList.add(resultMedia); + if (resultMediaList.size() > 20000) { + this.resultMediaService.batchInsertResultMedia(resultMediaList); + resultMediaList.clear(); + } + }); + if (!resultMediaList.isEmpty()) { + this.resultMediaService.batchInsertResultMedia(resultMediaList); + resultMediaList.clear(); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + } + + @Override + public void updateFileUrlPath(JSONObject jsonObject) { + List list = this.resultMediaService.getResultMediaEmptyFileUrlList(); + if (list == null || list.isEmpty()) { + return; + } + String prefixPath = jsonObject.getString("prefixPath"); + String filePath = jsonObject.getString("filePath"); + list.forEach(resultMedia -> { + String mediaUrl = resultMedia.getMediaUrl(); + if (mediaUrl != null) { + String[] array = mediaUrl.split("/"); + String fileName = "annotated_" + array[array.length - 1]; + String path = filePath + "/" + fileName; + log.info("=======path========{}", (Object)path); + if (Files.exists(Paths.get(path, new String[0]), new LinkOption[0])) { + resultMedia.setFileUrl(path.replace(prefixPath, "")); + this.resultMediaService.updateFileUrl((ResultMedia)((Object)resultMedia)); + } + } + }); + } + + @Override + public void importIntroFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + this.prefixPath = object.getString("prefixPath"); + File rootDir = new File(basePath); + if (!rootDir.exists() || !rootDir.isDirectory()) { + return; + } + ArrayList list = new ArrayList(); + for (File speciesDir : Objects.requireNonNull(rootDir.listFiles(File::isDirectory))) { + SpeciesIntro res = new SpeciesIntro(); + String speciesName = speciesDir.getName(); + Long speciesId = this.getSpeciesIdByScientificName(speciesName.replaceAll("_", " ")); + res.setSpeciesId(speciesId); + for (File categoryDir : Objects.requireNonNull(speciesDir.listFiles(File::isDirectory))) { + String category = categoryDir.getName(); + for (File file : Objects.requireNonNull(categoryDir.listFiles(File::isFile))) { + if ("audio".equalsIgnoreCase(category)) { + res.setAudio(file.getAbsolutePath().replace(this.prefixPath, "")); + continue; + } + if ("images".equalsIgnoreCase(category)) { + res.setImage(file.getAbsolutePath().replace(this.prefixPath, "")); + continue; + } + if ("video".equalsIgnoreCase(category)) { + res.setVideo(file.getAbsolutePath().replace(this.prefixPath, "")); + continue; + } + if ("text".equalsIgnoreCase(category)) { + res.setTxt(MediaFileInfoServiceImpl.readTextFile(file)); + continue; + } + if ("frames".equalsIgnoreCase(category)) { + res.setVideoImg(file.getAbsolutePath().replace(this.prefixPath, "")); + continue; + } + if (!"spectrogram".equalsIgnoreCase(category)) continue; + res.setSpectrogram(file.getAbsolutePath().replace(this.prefixPath, "")); + } + } + list.add(res); + } + if (!list.isEmpty()) { + this.speciesIntroService.batchAddSpeciesIntro(list); + } + } + + @Override + public void importAnswerFileToTable(JSONObject object) { + String basePath = object.getString("filePath"); + File rootDir = new File(basePath); + if (!rootDir.exists() || !rootDir.isDirectory()) { + return; + } + ArrayList list = new ArrayList(); + for (File speciesDir : Objects.requireNonNull(rootDir.listFiles(File::isDirectory))) { + SpeciesAnswer res = new SpeciesAnswer(); + String speciesName = speciesDir.getName(); + Long speciesId = this.getSpeciesIdByName(speciesName); + res.setSpeciesId(speciesId); + ArrayList sublist = new ArrayList(); + for (File file : Objects.requireNonNull(speciesDir.listFiles(File::isFile))) { + String path = file.getAbsolutePath(); + if (!path.contains(".txt")) continue; + SpeciesAnswerItem data = new SpeciesAnswerItem(); + data.setCn(MediaFileInfoServiceImpl.readTextFile(file)); + File enFile = new File(path.replace("/Chinese/bird_des_data/", "/English/bird_des_data_en/")); + if (enFile.exists()) { + data.setEn(MediaFileInfoServiceImpl.readEnTextFile(enFile)); + } + sublist.add(data); + } + res.setList(sublist); + list.add(res); + } + for (SpeciesAnswer data : list) { + this.speciesAnswerService.addSpeciesAnswer(data); + data.getList().forEach(speciesAnswer -> speciesAnswer.setPid(data.getId())); + this.speciesAnswerService.batchAddSpeciesAnswerItem(data.getList()); + } + } + + @Override + public void updateBirdFileImagePath(JSONObject object) { + List list = this.speciesIntroService.getSpeciesIntroOtherList(null); + for (SpeciesIntro data : list) { + File file = new File(object.getString("/data5/file" + data.getVideoImg())); + if (file.exists()) continue; + this.speciesIntroService.updateImageUrl(data); + } + } + + private static String readTextFile(File file) { + try { + String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); + return content.replace("\r\n", "
").replace("\n", "
").replace("\r", "
"); + } + catch (IOException e) { + return null; + } + } + + private static String readEnTextFile(File file) { + StringBuilder sb = new StringBuilder(); + try (BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8);){ + String line; + reader.readLine(); + while ((line = reader.readLine()) != null) { + if (sb.length() > 0) { + sb.append("
"); + } + sb.append(line); + } + } + catch (IOException e) { + return null; + } + return sb.toString(); + } + + private Long getDeviceIdByName(String name) { + return null; + } + + /* + * Enabled aggressive block sorting + * Enabled unnecessary exception pruning + * Enabled aggressive exception aggregation + */ + private JSONObject parserCsvFile(String path) { + try (Stream lines = Files.lines(Paths.get(path, new String[0]));){ + Optional maxLineParts = lines.filter(line -> !line.trim().isEmpty()).map(line -> line.trim().split(",")).filter(parts -> ((String[])parts).length >= 2).max((a, b) -> { + try { + int valA = Integer.parseInt(a[((String[])a).length - 1].trim()); + int valB = Integer.parseInt(b[((String[])b).length - 1].trim()); + return Integer.compare(valA, valB); + } + catch (NumberFormatException e) { + return 0; + } + }); + if (maxLineParts.isPresent()) { + JSONObject object = new JSONObject(); + String[] parts2 = maxLineParts.get(); + object.put("name", (Object)parts2[parts2.length - 2].trim().replaceAll("_", " ")); + try { + object.put("count", (Object)Integer.parseInt(parts2[parts2.length - 1].trim())); + } + catch (Exception e) { + object.put("count", (Object)1); + } + JSONObject jSONObject2 = object; + return jSONObject2; + } + JSONObject jSONObject = null; + return jSONObject; + } + catch (IOException e) { + return null; + } + } + + private Date extractDateTime(String fileName) { + String pattern = ".*(\\d{8})-(\\d{6})\\."; + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(fileName); + if (m.find()) { + String dateTimeStr = m.group(1) + m.group(2); + SimpleDateFormat dt = new SimpleDateFormat("yyyyMMddHHmmss"); + try { + return dt.parse(dateTimeStr); + } + catch (Exception e) { + return null; + } + } + return null; + } + + private List parserJSONFile(Path path) { + try { + byte[] bytes = Files.readAllBytes(path); + String content = new String(bytes, StandardCharsets.UTF_8); + JSONObject jsonObj = JSON.parseObject((String)content); + JSONObject metaArray = jsonObj.getJSONObject("meta_array"); + if (metaArray == null) { + return null; + } + ArrayList array = new ArrayList(); + HashMap map = new HashMap(); + for (Map.Entry entry : metaArray.entrySet()) { + String key2 = (String)entry.getKey(); + JSONObject cameraData = (JSONObject)entry.getValue(); + Integer trackerId = cameraData.getInteger("tracker_id"); + Integer voteClassId = cameraData.getInteger("vote_class_id"); + String className = cameraData.getString("vote_class_name"); + double confidence = cameraData.getDouble("vote_class_confidence"); + String mapKey = trackerId + "_" + voteClassId; + JSONObject mapData = (JSONObject)map.get(mapKey); + if (mapData != null) continue; + mapData = new JSONObject(); + mapData.put("tracker_id", (Object)trackerId); + mapData.put("vote_class_id", (Object)voteClassId); + mapData.put("class_name", (Object)className); + mapData.put("confidence", (Object)confidence); + map.put(mapKey, mapData); + } + HashMap voteClassMap = new HashMap(); + map.forEach((key, object) -> { + Integer voteClassId = object.getInteger("vote_class_id"); + JSONObject voteClassData = (JSONObject)voteClassMap.get(voteClassId); + if (voteClassData == null) { + object.put("count", (Object)1); + voteClassMap.put(voteClassId, (JSONObject)object); + } else { + voteClassData.put("count", (Object)(voteClassData.getInteger("count") + 1)); + voteClassMap.put(voteClassId, voteClassData); + } + }); + voteClassMap.forEach((key, value) -> array.add((JSONObject)value)); + return array; + } + catch (IOException e) { + log.error("error", (Throwable)e); + return null; + } + } + + public static List findVideoFiles(String directoryPath) throws IOException { + try (Stream paths = Files.walk(Paths.get(directoryPath, new String[0]), new FileVisitOption[0]);){ + List list = paths.filter(x$0 -> Files.isRegularFile(x$0, new LinkOption[0])).filter(path -> MediaFileInfoServiceImpl.isVideoFile(path)).collect(Collectors.toList()); + return list; + } + } + + private static boolean isVideoFile(Path path) { + String fileName = path.toString().toLowerCase(); + for (String extension : Arrays.asList(".mp4", ".avi", ".mov", ".mkv")) { + if (!fileName.endsWith(extension)) continue; + return true; + } + return false; + } + + public static void extractFirstFrame(Path videoPath, double time) throws IOException, InterruptedException { + String outputImagePath = videoPath.getParent() + File.separator + "images" + File.separator + videoPath.getFileName().toString().replace(".mp4", ".jpg"); + File videoFile = new File(videoPath.toString()); + if (!videoFile.exists()) { + throw new IOException("\u89c6\u9891\u6587\u4ef6\u4e0d\u5b58\u5728: " + videoPath); + } + Path imagePath = Paths.get(outputImagePath, new String[0]); + if (!Files.exists(imagePath.getParent(), new LinkOption[0])) { + Files.createDirectories(imagePath.getParent(), new FileAttribute[0]); + } + String[] cmd = new String[]{"ffmpeg", "-y", "-ss", String.valueOf(time), "-i", videoPath.toString(), "-frames:v", "1", "-q:v", "2", outputImagePath}; + ProcessBuilder pb = new ProcessBuilder(cmd); + pb.redirectErrorStream(true); + Process process = pb.start(); + int exitCode = process.waitFor(); + if (exitCode != 0) { + throw new IOException("ffmpeg \u6267\u884c\u5931\u8d25\uff0c\u9000\u51fa\u7801\uff1a" + exitCode); + } + } + + private void extractFirstFrame(Path videoPath) throws Exception { + IContainer container; + String outputImagePath = videoPath.getParent() + File.separator + "images" + File.separator + videoPath.getFileName().toString().replace(".mp4", ".jpg"); + Path imagePath = Paths.get(outputImagePath, new String[0]); + if (!Files.exists(imagePath.getParent(), new LinkOption[0])) { + Files.createDirectories(imagePath.getParent(), new FileAttribute[0]); + } + if ((container = IContainer.make()).open(videoPath.toString(), IContainer.Type.READ, null) < 0) { + throw new IOException("\u65e0\u6cd5\u6253\u5f00\u89c6\u9891\u6587\u4ef6: " + videoPath); + } + int numStreams = container.getNumStreams(); + int videoStreamIndex = -1; + IStreamCoder videoCoder = null; + for (int i = 0; i < numStreams; ++i) { + IStream stream = container.getStream((long)i); + IStreamCoder coder = stream.getStreamCoder(); + if (coder.getCodecType() != ICodec.Type.CODEC_TYPE_VIDEO) continue; + videoStreamIndex = i; + videoCoder = coder; + break; + } + if (videoStreamIndex == -1) { + throw new Exception("\u89c6\u9891\u6d41\u672a\u627e\u5230!"); + } + if (videoCoder.open() < 0) { + throw new IOException("\u65e0\u6cd5\u6253\u5f00\u89c6\u9891\u89e3\u7801\u5668!"); + } + IVideoResampler resampler = null; + if (videoCoder.getPixelType() != IPixelFormat.Type.RGB24) { + resampler = IVideoResampler.make((int)videoCoder.getWidth(), (int)videoCoder.getHeight(), (IPixelFormat.Type)IPixelFormat.Type.RGB24, (int)videoCoder.getWidth(), (int)videoCoder.getHeight(), (IPixelFormat.Type)videoCoder.getPixelType()); + } + IVideoPicture picture = IVideoPicture.make((IPixelFormat.Type)IPixelFormat.Type.RGB24, (int)videoCoder.getWidth(), (int)videoCoder.getHeight()); + IPacket frame = IPacket.make(); + int frameNumber = 0; + boolean firstFrameExtracted = false; + while (container.readNextPacket(frame) >= 0) { + if (frame.getStreamIndex() != videoStreamIndex) continue; + int bytesDecoded = videoCoder.decodeVideo(picture, frame, frameNumber); + if (bytesDecoded < 0) { + throw new IOException("\u89c6\u9891\u89e3\u7801\u5931\u8d25!"); + } + if (!picture.isComplete() || firstFrameExtracted) continue; + BufferedImage image = this.pictureToImage(picture); + ImageIO.write((RenderedImage)image, "JPG", new File(outputImagePath)); + firstFrameExtracted = true; + } + videoCoder.close(); + container.close(); + } + + private BufferedImage pictureToImage(IVideoPicture picture) { + int width = picture.getWidth(); + int height = picture.getHeight(); + byte[] data = picture.getData().getByteArray(0, picture.getData().getSize()); + BufferedImage image = new BufferedImage(width, height, 1); + if (picture.getPixelType() != IPixelFormat.Type.RGB24) { + IVideoResampler resampler = IVideoResampler.make((int)width, (int)height, (IPixelFormat.Type)IPixelFormat.Type.RGB24, (int)width, (int)height, (IPixelFormat.Type)picture.getPixelType()); + IVideoPicture rgbPicture = IVideoPicture.make((IPixelFormat.Type)IPixelFormat.Type.RGB24, (int)width, (int)height); + resampler.resample(rgbPicture, picture); + data = rgbPicture.getData().getByteArray(0, rgbPicture.getData().getSize()); + } + int dataIndex = 0; + for (int i = 0; i < height; ++i) { + for (int j = 0; j < width; ++j) { + int r = data[dataIndex++] & 0xFF; + int g = data[dataIndex++] & 0xFF; + int b = data[dataIndex++] & 0xFF; + image.setRGB(j, i, r << 16 | g << 8 | b); + } + } + return image; + } + + private void addListToResultMedia(List resultMediaList, int type) { + ArrayList resultRecordDetailsList = new ArrayList(); + this.resultMediaService.batchInsertResultMedia(resultMediaList); + resultMediaList.forEach(item -> { + if (type == 0) { + List array = item.getArray(); + if (array != null) { + array.forEach(jsonObject -> { + String name = jsonObject.getString("class_name"); + if (name != null && !name.trim().isEmpty()) { + ResultRecordDetails data = new ResultRecordDetails(); + data.setIsDeleted(0); + data.setRecordId(0L); + data.setHabitat(""); + data.setMediaId(item.getMediaId()); + Long speciesId = this.getSpeciesIdByName(name); + data.setSpeciesId(speciesId); + data.setCount(jsonObject.getInteger("count")); + data.setConfidence(jsonObject.getDouble("confidence")); + resultRecordDetailsList.add(data); + } + }); + } + } else if (type == 1) { + ResultRecordDetails data = new ResultRecordDetails(); + data.setIsDeleted(0); + data.setRecordId(0L); + data.setHabitat(""); + data.setMediaId(item.getMediaId()); + Long speciesId = this.getSpeciesIdByScientificName(item.getSpeciesName()); + data.setSpeciesId(speciesId); + data.setCount(item.getWidth()); + data.setConfidence(0.0); + resultRecordDetailsList.add(data); + } else if (type == 2) { + ResultRecordDetails data = new ResultRecordDetails(); + data.setIsDeleted(0); + data.setRecordId(0L); + data.setHabitat(""); + data.setMediaId(item.getMediaId()); + data.setSpeciesId(item.getSpeciesId()); + data.setCount(1); + data.setConfidence(0.0); + resultRecordDetailsList.add(data); + } + }); + log.info("=======================size======================{}", (Object)resultRecordDetailsList.size()); + this.resultRecordDetailsService.batchInsertResultRecordDetails(resultRecordDetailsList); + } + + private Long getSpeciesIdByScientificName(String scientificName) { + Long speciesId = this.mapSpeciesName.get("scientificName"); + if (speciesId == null) { + speciesId = this.birdSpeciesService.getBirdSpeciesIdByScientificName(scientificName); + if (speciesId == null) { + BirdSpecies data = new BirdSpecies(); + data.setName("\u5f85\u4fee\u6539"); + data.setScientificName(scientificName); + this.birdSpeciesService.insertBirdSpecies(data); + this.mapSpeciesName.put(scientificName, data.getId()); + speciesId = data.getId(); + } else { + this.mapSpeciesName.put(scientificName, speciesId); + } + } + return speciesId; + } + + private void addListToResultMedia(List resultMediaList, List resultRecordDetailsList) { + this.resultMediaService.batchInsertResultMedia(resultMediaList); + resultMediaList.forEach(item -> { + ResultRecordDetails data = new ResultRecordDetails(); + data.setIsDeleted(0); + data.setRecordId(0L); + data.setHabitat(""); + data.setMediaId(item.getMediaId()); + data.setSpeciesId(item.getSpeciesId()); + data.setCount(1); + data.setConfidence(1.0); + resultRecordDetailsList.add(data); + }); + this.resultRecordDetailsService.batchInsertResultRecordDetails(resultRecordDetailsList); + } + + private Map> getFilesAndDirectoriesByPram(Path rootPath, final String suffix) throws IOException { + final HashMap> directoryFilesMap = new HashMap>(); + Files.walkFileTree(rootPath, (FileVisitor)new SimpleFileVisitor(){ + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Path parentDir = file.getParent(); + if (file.toString().toLowerCase().endsWith(suffix)) { + directoryFilesMap.computeIfAbsent(parentDir.getFileName().toString().replaceAll("_", " "), k -> new ArrayList()).add(file.toString()); + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + directoryFilesMap.putIfAbsent(dir.toString(), new ArrayList()); + return FileVisitResult.CONTINUE; + } + }); + return directoryFilesMap; + } + + private String getContentFromFile(Path path) { + try { + String file = path.toAbsolutePath().toString().replace("/Image", "/tuwendui").replace(".jpg", ".txt"); + Path txtPath = Paths.get(file, new String[0]); + if (txtPath.toFile().exists()) { + return new String(Files.readAllBytes(txtPath)); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + return null; + } + + private String getContentFromFile(Path path, String imgPath, String textPath) { + try { + String file = path.toAbsolutePath().toString().replace(imgPath, textPath).replace(".jpg", ".txt"); + Path txtPath = Paths.get(file, new String[0]); + if (txtPath.toFile().exists()) { + return new String(Files.readAllBytes(txtPath)); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + return null; + } + + private List findImageFiles(String dirPath, String[] suffixes) throws IOException { + try (Stream paths = Files.walk(Paths.get(dirPath, new String[0]), new FileVisitOption[0]);){ + List list = paths.filter(x$0 -> Files.isRegularFile(x$0, new LinkOption[0])).filter(p -> { + String fileName = p.getFileName().toString().toLowerCase(); + for (String suffix : suffixes) { + if (!fileName.endsWith(suffix)) continue; + return true; + } + return false; + }).collect(Collectors.toList()); + return list; + } + } + + private LocalDateTime getDateTime() { + LocalDate startDate = LocalDate.of(2023, 1, 1); + LocalDate endDate = LocalDate.now(); + long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); + Random random = new Random(); + LocalDate randomDate = startDate.plusDays(random.nextInt((int)daysBetween + 1)); + int hour = random.nextInt(24); + int minute = random.nextInt(60); + int second = random.nextInt(60); + LocalTime randomTime = LocalTime.of(hour, minute, second); + return LocalDateTime.of(randomDate, randomTime); + } + + private Map> getImageFile(String rootPath) throws IOException { + try (Stream pathStream = Files.walk(Paths.get(rootPath, new String[0]), new FileVisitOption[0]);){ + Map map = pathStream.filter(x$0 -> Files.isRegularFile(x$0, new LinkOption[0])).filter(p -> { + String fileName = p.getFileName().toString().toLowerCase(); + return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png") || fileName.endsWith(".gif") || fileName.endsWith(".bmp"); + }).collect(Collectors.groupingBy(p -> p.getParent().toAbsolutePath().toString(), LinkedHashMap::new, Collectors.toList())); + return map; + } + } + + private String getNetFile(String name) { + String[] arr = name.split("_"); + return arr[0] + "_" + arr[1] + "_" + arr[2].substring(0, 4); + } + + private void saveImageFileToTable(String basePath, String fileName, Date time, List imageFiles, List txtFiles, Long deviceId, Long itemId) { + String[] arr = fileName.split("\\."); + for (String name : imageFiles) { + if (!name.contains(arr[0])) continue; + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setIsDeleted(0); + resultMedia.setMediaId(itemId); + resultMedia.setTime(time); + resultMedia.setMediaType(2); + String path = basePath.replaceAll("/data5/file", ""); + path = path.replaceAll("videos_camera", "images_camera"); + resultMedia.setMetaUrl(path + "/DCIM/100MEDIA/" + name); + resultMedia.setDeviceId(deviceId); + this.resultMediaService.insertResultMedia(resultMedia); + ResultRecord resultRecord = new ResultRecord(); + resultRecord.setDeviceId(deviceId); + resultRecord.setRecordType("1"); + resultRecord.setRecordTime(resultMedia.getTime()); + this.resultRecordService.insertResultRecord(resultRecord); + String[] arr1 = name.split("\\."); + this.saveToTable(arr1[0], txtFiles, resultRecord.getRecordId(), resultMedia.getMediaId()); + } + } + + private void saveToTable(String fileName, String time, String basePath, List movList, List imageList, List txtList, List txtImageList, Long deviceId, Long itemId) throws Exception { + int mediaType; + String movFile = ""; + String path = basePath; + String[] arr = fileName.split("\\."); + if (fileName.toLowerCase().endsWith(".jpg")) { + mediaType = 2; + } else { + mediaType = 3; + movFile = this.getFileFromList(arr[0], movList); + if (movFile == null) { + return; + } + } + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000+08:00"); + String imgFile = this.getFileFromList(arr[0], imageList); + if (imgFile == null) { + return; + } + ResultMedia resultMedia = new ResultMedia(); + resultMedia.setItemId(itemId); + resultMedia.setTime(sdf.parse(time)); + resultMedia.setMediaType(mediaType); + path = path.replaceAll("/data5/file", ""); + path = path.replaceAll("videos_camera", "images_camera"); + resultMedia.setMetaUrl(path + "/DCIM/100MEDIA/" + imgFile); + if (mediaType == 3) { + path = basePath.replaceAll("/data5/file", ""); + resultMedia.setMediaUrl(path + "/DCIM/100MEDIA/" + movFile); + } + resultMedia.setIsDeleted(0); + resultMedia.setDeviceId(deviceId); + resultMedia.setItemId(itemId); + this.resultMediaService.insertResultMedia(resultMedia); + ResultRecord resultRecord = new ResultRecord(); + resultRecord.setDeviceId(deviceId); + resultRecord.setRecordType("1"); + resultRecord.setRecordTime(resultMedia.getTime()); + this.resultRecordService.insertResultRecord(resultRecord); + if (mediaType == 3) { + this.saveToTable(arr[0], txtList, resultRecord.getRecordId(), resultMedia.getMediaId()); + } else { + this.saveToTable(arr[0], txtImageList, resultRecord.getRecordId(), resultMedia.getMediaId()); + } + } + + private void saveToTable(String name, List list, Long recordId, Long mediaId) { + boolean flag = false; + for (String str : list) { + if (!str.contains(name)) continue; + flag = true; + String[] arr = str.split("\\."); + String[] arr1 = arr[0].split("_"); + int len = arr1.length; + String birdName = arr1[len - 2]; + Long id = this.getSpeciesIdByName(birdName); + int count = Integer.parseInt(arr1[len - 1]); + ResultRecordDetails resultRecordDetails = new ResultRecordDetails(); + resultRecordDetails.setRecordId(recordId); + resultRecordDetails.setSpeciesId(id); + resultRecordDetails.setHabitat("1"); + resultRecordDetails.setCount(count); + resultRecordDetails.setMediaId(mediaId); + resultRecordDetails.setIsDeleted(0); + this.resultRecordDetailsService.insertResultRecordDetails(resultRecordDetails); + } + if (!flag) { + ResultRecordDetails resultRecordDetails = new ResultRecordDetails(); + resultRecordDetails.setRecordId(recordId); + resultRecordDetails.setSpeciesId(0L); + resultRecordDetails.setHabitat("1"); + resultRecordDetails.setCount(0); + resultRecordDetails.setMediaId(mediaId); + resultRecordDetails.setIsDeleted(0); + this.resultRecordDetailsService.insertResultRecordDetails(resultRecordDetails); + } + } + + private Long getSpeciesIdByName(String name) { + Long id = this.mapSpeciesName.get(name); + if (id == null) { + id = this.birdSpeciesService.getBirdSpeciesIdByName(name); + if (id == null) { + BirdSpecies data = new BirdSpecies(); + data.setName(name); + data.setScientificName("revise"); + this.birdSpeciesService.insertBirdSpecies(data); + this.mapSpeciesName.put(name, data.getId()); + return data.getId(); + } + this.mapSpeciesName.put(name, id); + return id; + } + return id; + } + + private Long saveToJsonFile(Long deviceId) { + MediaItem data = new MediaItem(); + data.setDeviceId(deviceId); + data.setCameraVolt(0.0); + data.setSolarVolt(0.0); + data.setExtraVolt(0.0); + data.setTemperature(0.0); + data.setHumidity(0.0); + data.setAtmosphere(0.0); + data.setLat(""); + this.mediaItemService.insertMediaItem(data); + return data.getId(); + } + + private Long saveToJsonFile(JSONObject jsonObject, Long deviceId) { + try { + MediaItem data = new MediaItem(); + data.setDeviceId(deviceId); + if (jsonObject != null) { + JSONObject object = jsonObject.getJSONObject("device"); + String str = object.getString("Battery1"); + if (str != null && !str.isEmpty()) { + data.setCameraVolt(Double.parseDouble(str)); + } + if ((str = object.getString("SPower")) != null && !str.isEmpty()) { + data.setSolarVolt(Double.parseDouble(str)); + } + if ((str = object.getString("EPower")) != null && !str.isEmpty()) { + data.setExtraVolt(Double.parseDouble(str)); + } + if ((str = object.getString("GP")) != null && !str.isEmpty()) { + data.setLat(str); + } + if ((str = (object = jsonObject.getJSONObject("data")).getString("D_Temperature")) != null && !str.isEmpty()) { + data.setTemperature(Double.parseDouble(str)); + } + if ((str = object.getString("D_Humidity")) != null && !str.isEmpty()) { + data.setHumidity(Double.parseDouble(str)); + } + if ((str = object.getString("D_Atmos")) != null && !str.isEmpty()) { + data.setAtmosphere(Double.parseDouble(str)); + } + } + this.mediaItemService.insertMediaItem(data); + return data.getId(); + } + catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + private String getFileFromList(String name, List list) { + for (String str : list) { + if (!str.contains(name)) continue; + return str; + } + return null; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileItemServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileItemServiceImpl.java new file mode 100644 index 0000000..eb95630 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/file/service/impl/MediaFileItemServiceImpl.java @@ -0,0 +1,92 @@ +package net.hzvtc.file.service.impl; + +import net.hzvtc.file.domain.MediaFileItem; +import net.hzvtc.file.mapper.MediaFileItemMapper; +import net.hzvtc.file.service.MediaFileItemService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 多源数据文件列Service业务层处理 + * + * @author admin + * @date 2024-06-04 + */ +@Service +public class MediaFileItemServiceImpl implements MediaFileItemService { + @Resource + private MediaFileItemMapper mediaFileItemMapper; + + /** + * 查询多源数据文件列 + * + * @param id 多源数据文件列主键 + * @return 多源数据文件列 + */ + @Override + public MediaFileItem selectMediaFileItemById(Long id) { + return mediaFileItemMapper.selectMediaFileItemById(id); + } + + /** + * 查询多源数据文件列列表 + * + * @param mediaFileItem 多源数据文件列 + * @return 多源数据文件列 + */ + @Override + public List selectMediaFileItemList(MediaFileItem mediaFileItem) { + return mediaFileItemMapper.selectMediaFileItemList(mediaFileItem); + } + + /** + * 新增多源数据文件列 + * + * @param mediaFileItem 多源数据文件列 + * @return 结果 + */ + @Override + public int insertMediaFileItem(MediaFileItem mediaFileItem) { + return mediaFileItemMapper.insertMediaFileItem(mediaFileItem); + } + + /** + * 修改多源数据文件列 + * + * @param mediaFileItem 多源数据文件列 + * @return 结果 + */ + @Override + public int updateMediaFileItem(MediaFileItem mediaFileItem) { + return mediaFileItemMapper.updateMediaFileItem(mediaFileItem); + } + + /** + * 批量删除多源数据文件列 + * + * @param ids 需要删除的多源数据文件列主键 + * @return 结果 + */ + @Override + public int deleteMediaFileItemByIds(Long[] ids) { + return mediaFileItemMapper.deleteMediaFileItemByIds(ids); + } + + /** + * 删除多源数据文件列信息 + * + * @param id 多源数据文件列主键 + * @return 结果 + */ + @Override + public int deleteMediaFileItemById(Long id) { + return mediaFileItemMapper.deleteMediaFileItemById(id); + } + + @Override + public int batchInsertMediaFileItem(List list) { + return mediaFileItemMapper.batchInsertMediaFileItem(list); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationFilesController.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationFilesController.java new file mode 100644 index 0000000..f741e4d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationFilesController.java @@ -0,0 +1,98 @@ +package net.hzvtc.naturalist.controller; + +import java.util.List; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.naturalist.domain.ObservationFiles; +import net.hzvtc.naturalist.service.ObservationFilesService; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.common.core.page.TableDataInfo; + +/** + * 文件列Controller + * + * @author admin + * @date 2023-04-25 + */ +@RestController +@RequestMapping("/naturalist/files") +public class ObservationFilesController extends BaseController { + @Autowired + private ObservationFilesService observationFilesService; + +/** + * 查询文件列列表 + */ +@PreAuthorize("@ss.hasPermi('naturalist:files:list')") +@GetMapping("/list") + public TableDataInfo list(ObservationFiles observationFiles) { + startPage(); + List list = observationFilesService.selectObservationFilesList(observationFiles); + return getDataTable(list); + } + + /** + * 导出文件列列表 + */ + @PreAuthorize("@ss.hasPermi('naturalist:files:export')") + @Log(title = "文件列", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, ObservationFiles observationFiles) { + List list = observationFilesService.selectObservationFilesList(observationFiles); + ExcelUtil util = new ExcelUtil(ObservationFiles. class); + util.exportExcel(response, list, "文件列数据"); + } + + /** + * 获取文件列详细信息 + */ + @PreAuthorize("@ss.hasPermi('naturalist:files:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(observationFilesService.selectObservationFilesById(id)); + } + + /** + * 新增文件列 + */ + @PreAuthorize("@ss.hasPermi('naturalist:files:add')") + @Log(title = "文件列", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody ObservationFiles observationFiles) { + return toAjax(observationFilesService.insertObservationFiles(observationFiles)); + } + + /** + * 修改文件列 + */ + @PreAuthorize("@ss.hasPermi('naturalist:files:edit')") + @Log(title = "文件列", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody ObservationFiles observationFiles) { + return toAjax(observationFilesService.updateObservationFiles(observationFiles)); + } + + /** + * 删除文件列 + */ + @PreAuthorize("@ss.hasPermi('naturalist:files:remove')") + @Log(title = "文件列", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(observationFilesService.deleteObservationFilesByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationsController.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationsController.java new file mode 100644 index 0000000..c4acd1b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/controller/ObservationsController.java @@ -0,0 +1,102 @@ +package net.hzvtc.naturalist.controller; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.naturalist.domain.Observations; +import net.hzvtc.naturalist.service.ObservationsService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +@RestController +@RequestMapping(value={"/naturalist/observations"}) +public class ObservationsController +extends BaseController { + private static final Logger log = LoggerFactory.getLogger(ObservationsController.class); + @Autowired + private ObservationsService observationsService; + + @GetMapping(value={"/list"}) + public TableDataInfo list(Observations observations) { + this.startPage(); + List list = this.observationsService.selectObservationsList(observations); + return this.getDataTable(list); + } + + @PostMapping(value={"/listByParam"}) + public TableDataInfo listByParam(@RequestBody JSONObject params) { + Integer pageNum = params.getInteger("pageNum"); + Integer pageSize = params.getInteger("pageSize"); + this.startPage(pageNum, pageSize); + List list = this.observationsService.getObservationsListByParam(params); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('naturalist:observations:export')") + @Log(title="\u89c2\u5bdf\u8bb0\u5f55", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, Observations observations) { + List list = this.observationsService.selectObservationsList(observations); + ExcelUtil util = new ExcelUtil(Observations.class); + util.exportExcel(response, list, "\u89c2\u5bdf\u8bb0\u5f55\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('naturalist:observations:query')") + @GetMapping(value={"/{id}"}) + public AjaxResult getInfo(@PathVariable(value="id") Long id) { + return AjaxResult.success((Object)((Object)this.observationsService.selectObservationsById(id))); + } + + @PreAuthorize(value="@ss.hasPermi('naturalist:observations:add')") + @Log(title="\u89c2\u5bdf\u8bb0\u5f55", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody Observations observations) { + return this.toAjax(this.observationsService.insertObservations(observations)); + } + + @PreAuthorize(value="@ss.hasPermi('naturalist:observations:edit')") + @Log(title="\u89c2\u5bdf\u8bb0\u5f55", businessType=BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody Observations observations) { + return this.toAjax(this.observationsService.updateObservations(observations)); + } + + @PreAuthorize(value="@ss.hasPermi('naturalist:observations:remove')") + @Log(title="\u89c2\u5bdf\u8bb0\u5f55", businessType=BusinessType.DELETE) + @DeleteMapping(value={"/{ids}"}) + public AjaxResult remove(@PathVariable Long[] ids) { + return this.toAjax(this.observationsService.deleteObservationsByIds(ids)); + } + + @PostMapping(value={"/addFiles"}) + public AjaxResult addFile(@RequestPart(value="files") MultipartFile[] files, @RequestParam(name="data") String data) { + this.observationsService.saveObservation(files, data); + return AjaxResult.success((Object)true); + } + + @PostMapping(value={"/judgeImage"}) + public JSONObject judgeImage(@RequestPart(value="file") MultipartFile uploadFile) { + return this.observationsService.judgeImage(uploadFile); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/ObservationFiles.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/ObservationFiles.java new file mode 100644 index 0000000..54cba0e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/ObservationFiles.java @@ -0,0 +1,22 @@ +package net.hzvtc.naturalist.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="ObservationFiles") +@Data +public class ObservationFiles extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String location; + private int fileType; + private String fileExt; + private String fileName; + private Long observationId; + private Date createDate; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/Observations.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/Observations.java new file mode 100644 index 0000000..77a6f23 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/domain/Observations.java @@ -0,0 +1,29 @@ +package net.hzvtc.naturalist.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import java.util.List; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="Observations") +@Data +public class Observations extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Date observedOn; + private String lat; + private String lon; + private String description; + private String speciesGuess; + private Long userId; + private Long taxonId; + private BirdSpecies birdSpecies; + private Date createDate; + private Date updateDate; + private SysUser userInfo; + private List filesList; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationFilesMapper.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationFilesMapper.java new file mode 100644 index 0000000..a8931dd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationFilesMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.naturalist.mapper; + +import java.util.List; +import net.hzvtc.naturalist.domain.ObservationFiles; + +/** + * 文件列Mapper接口 + * + * @author admin + * @date 2023-04-25 + */ +public interface ObservationFilesMapper +{ + /** + * 查询文件列 + * + * @param id 文件列主键 + * @return 文件列 + */ + public ObservationFiles selectObservationFilesById(Long id); + + /** + * 查询文件列列表 + * + * @param observationFiles 文件列 + * @return 文件列集合 + */ + public List selectObservationFilesList(ObservationFiles observationFiles); + + /** + * 新增文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + public int insertObservationFiles(ObservationFiles observationFiles); + + /** + * 修改文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + public int updateObservationFiles(ObservationFiles observationFiles); + + /** + * 删除文件列 + * + * @param id 文件列主键 + * @return 结果 + */ + public int deleteObservationFilesById(Long id); + + /** + * 批量删除文件列 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteObservationFilesByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationsMapper.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationsMapper.java new file mode 100644 index 0000000..aa3ba1b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/mapper/ObservationsMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.naturalist.mapper; + +import java.util.List; +import net.hzvtc.naturalist.domain.Observations; + +/** + * 观察记录Mapper接口 + * + * @author admin + * @date 2023-04-23 + */ +public interface ObservationsMapper +{ + /** + * 查询观察记录 + * + * @param id 观察记录主键 + * @return 观察记录 + */ + public Observations selectObservationsById(Long id); + + /** + * 查询观察记录列表 + * + * @param observations 观察记录 + * @return 观察记录集合 + */ + public List selectObservationsList(Observations observations); + + /** + * 新增观察记录 + * + * @param observations 观察记录 + * @return 结果 + */ + public int insertObservations(Observations observations); + + /** + * 修改观察记录 + * + * @param observations 观察记录 + * @return 结果 + */ + public int updateObservations(Observations observations); + + /** + * 删除观察记录 + * + * @param id 观察记录主键 + * @return 结果 + */ + public int deleteObservationsById(Long id); + + /** + * 批量删除观察记录 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteObservationsByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationFilesService.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationFilesService.java new file mode 100644 index 0000000..c44971b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationFilesService.java @@ -0,0 +1,61 @@ +package net.hzvtc.naturalist.service; + +import java.util.List; + +import net.hzvtc.naturalist.domain.ObservationFiles; + +/** + * 文件列Service接口 + * + * @author admin + * @date 2023-04-25 + */ +public interface ObservationFilesService { + /** + * 查询文件列 + * + * @param id 文件列主键 + * @return 文件列 + */ + public ObservationFiles selectObservationFilesById(Long id); + + /** + * 查询文件列列表 + * + * @param observationFiles 文件列 + * @return 文件列集合 + */ + public List selectObservationFilesList(ObservationFiles observationFiles); + + /** + * 新增文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + public int insertObservationFiles(ObservationFiles observationFiles); + + /** + * 修改文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + public int updateObservationFiles(ObservationFiles observationFiles); + + /** + * 批量删除文件列 + * + * @param ids 需要删除的文件列主键集合 + * @return 结果 + */ + public int deleteObservationFilesByIds(Long[] ids); + + /** + * 删除文件列信息 + * + * @param id 文件列主键 + * @return 结果 + */ + public int deleteObservationFilesById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationsService.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationsService.java new file mode 100644 index 0000000..80e95ae --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/ObservationsService.java @@ -0,0 +1,28 @@ +package net.hzvtc.naturalist.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.naturalist.domain.Observations; +import org.springframework.web.multipart.MultipartFile; + +public interface ObservationsService { + public Observations selectObservationsById(Long var1); + + public List selectObservationsList(Observations var1); + + public List getObservationsListByParam(JSONObject var1); + + public int insertObservations(Observations var1); + + public int updateObservations(Observations var1); + + public int deleteObservationsByIds(Long[] var1); + + public int deleteObservationsById(Long var1); + + public int saveObservation(MultipartFile[] var1, String var2); + + public JSONObject judgeImage(MultipartFile var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationFilesServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationFilesServiceImpl.java new file mode 100644 index 0000000..a8b193d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationFilesServiceImpl.java @@ -0,0 +1,87 @@ +package net.hzvtc.naturalist.service.impl; + +import java.util.List; +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import net.hzvtc.naturalist.mapper.ObservationFilesMapper; +import net.hzvtc.naturalist.domain.ObservationFiles; +import net.hzvtc.naturalist.service.ObservationFilesService; + +/** + * 文件列Service业务层处理 + * + * @author admin + * @date 2023-04-25 + */ +@Service +public class ObservationFilesServiceImpl implements ObservationFilesService { + @Resource + private ObservationFilesMapper observationFilesMapper; + + /** + * 查询文件列 + * + * @param id 文件列主键 + * @return 文件列 + */ + @Override + public ObservationFiles selectObservationFilesById(Long id) { + return observationFilesMapper.selectObservationFilesById(id); + } + + /** + * 查询文件列列表 + * + * @param observationFiles 文件列 + * @return 文件列 + */ + @Override + public List selectObservationFilesList(ObservationFiles observationFiles) { + return observationFilesMapper.selectObservationFilesList(observationFiles); + } + + /** + * 新增文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + @Override + public int insertObservationFiles(ObservationFiles observationFiles) { + return observationFilesMapper.insertObservationFiles(observationFiles); + } + + /** + * 修改文件列 + * + * @param observationFiles 文件列 + * @return 结果 + */ + @Override + public int updateObservationFiles(ObservationFiles observationFiles) { + return observationFilesMapper.updateObservationFiles(observationFiles); + } + + /** + * 批量删除文件列 + * + * @param ids 需要删除的文件列主键 + * @return 结果 + */ + @Override + public int deleteObservationFilesByIds(Long[] ids) { + return observationFilesMapper.deleteObservationFilesByIds(ids); + } + + /** + * 删除文件列信息 + * + * @param id 文件列主键 + * @return 结果 + */ + @Override + public int deleteObservationFilesById(Long id) { + return observationFilesMapper.deleteObservationFilesById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationsServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationsServiceImpl.java new file mode 100644 index 0000000..5fb993c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/naturalist/service/impl/ObservationsServiceImpl.java @@ -0,0 +1,198 @@ +package net.hzvtc.naturalist.service.impl; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import java.nio.charset.Charset; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import javax.annotation.Resource; +import net.hzvtc.common.config.AiBirdSysConfig; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.file.FileUploadUtils; +import net.hzvtc.naturalist.domain.ObservationFiles; +import net.hzvtc.naturalist.domain.Observations; +import net.hzvtc.naturalist.mapper.ObservationsMapper; +import net.hzvtc.naturalist.service.ObservationFilesService; +import net.hzvtc.naturalist.service.ObservationsService; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +@Service +public class ObservationsServiceImpl +implements ObservationsService { + private static final Logger log = LoggerFactory.getLogger(ObservationsServiceImpl.class); + @Resource + private ObservationsMapper observationsMapper; + @Autowired + private ObservationFilesService filesService; + @Value(value="${hzvtc.observationTokenUrl}") + private String observationTokenUrl; + @Value(value="${hzvtc.observationImgCheckUrl}") + private String observationImgCheckUrl; + + @Override + public Observations selectObservationsById(Long id) { + return this.observationsMapper.selectObservationsById(id); + } + + @Override + public List selectObservationsList(Observations observations) { + return this.observationsMapper.selectObservationsList(observations); + } + + @Override + public List getObservationsListByParam(JSONObject params) { + Observations observations = new Observations(); + return this.selectObservationsList(observations); + } + + @Override + public int insertObservations(Observations observations) { + return this.observationsMapper.insertObservations(observations); + } + + @Override + public int updateObservations(Observations observations) { + return this.observationsMapper.updateObservations(observations); + } + + @Override + public int deleteObservationsByIds(Long[] ids) { + return this.observationsMapper.deleteObservationsByIds(ids); + } + + @Override + public int deleteObservationsById(Long id) { + return this.observationsMapper.deleteObservationsById(id); + } + + @Override + public int saveObservation(MultipartFile[] files, String data) { + Long userId = SecurityUtils.getUserId(); + JSONObject jsonObject = JSON.parseObject((String)data); + Observations observations = new Observations(); + String str = jsonObject.getString("observationOn"); + if (str != null && !str.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + try { + observations.setObservedOn(df.parse(str)); + } + catch (Exception ex) { + log.error(ex.getMessage()); + } + } + if ((str = jsonObject.getString("lonlat")) != null && !str.isEmpty()) { + String[] arr = str.split(","); + observations.setLat(arr[0]); + observations.setLon(arr[1]); + } + str = jsonObject.getString("memo"); + observations.setIsDeleted(0); + observations.setCreateDate(new Date()); + observations.setDescription(str); + observations.setUserId(userId); + observations.setCreateDate(new Date()); + this.observationsMapper.insertObservations(observations); + Long id = observations.getId(); + String baseDir = AiBirdSysConfig.getObservationFilePath() + SecurityUtils.getUserId(); + try { + for (MultipartFile file : files) { + String path = FileUploadUtils.upload((String)baseDir, (MultipartFile)file); + path = path.replaceAll("\\\\", "/"); + ObservationFiles item = new ObservationFiles(); + item.setObservationId(id); + String filename = file.getOriginalFilename(); + item.setLocation(path); + item.setFileName(filename); + String ext = filename.substring(filename.lastIndexOf(".") + 1); + item.setFileExt(ext); + item.setFileType(this.getFileType(ext)); + item.setCreateDate(new Date()); + this.filesService.insertObservationFiles(item); + } + } + catch (Exception ex) { + log.error(ex.getMessage()); + } + return 1; + } + + @Override + public JSONObject judgeImage(MultipartFile uploadFile) { + JSONObject result = new JSONObject(); + CloseableHttpClient httpClient = HttpClientBuilder.create().build(); + HttpGet httpGet = new HttpGet(this.observationTokenUrl); + CloseableHttpResponse response = null; + try { + response = httpClient.execute((HttpUriRequest)httpGet); + HttpEntity responseEntity = response.getEntity(); + if (responseEntity != null) { + JSONObject jsonObject = JSON.parseObject((String)EntityUtils.toString((HttpEntity)responseEntity)); + int code = jsonObject.getInteger("code"); + if (code == 0) { + String token = jsonObject.getString("data"); + HttpPost httpPost = new HttpPost(this.observationImgCheckUrl); + MultipartEntityBuilder builder = MultipartEntityBuilder.create(); + builder.setCharset(Charset.forName("UTF-8")); + builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + httpPost.addHeader("AccessToken", token); + builder.addBinaryBody("file", uploadFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, uploadFile.getOriginalFilename()); + HttpEntity entity = builder.build(); + httpPost.setEntity(entity); + response = httpClient.execute((HttpUriRequest)httpPost); + responseEntity = response.getEntity(); + if (responseEntity != null) { + jsonObject = JSON.parseObject((String)EntityUtils.toString((HttpEntity)responseEntity)); + code = jsonObject.getInteger("code"); + if (0 == code) { + result.put("img", (Object)jsonObject.getString("data")); + result.put("code", (Object)200); + } else { + result.put("code", (Object)500); + result.put("msg", (Object)"\u89e3\u6790\u56fe\u7247\u51fa\u9519"); + } + } else { + result.put("code", (Object)500); + result.put("msg", (Object)"\u65e0\u6cd5\u83b7\u53d6\u56fe\u7247\u89e3\u6790\u670d\u52a1"); + } + } else { + result.put("code", (Object)500); + result.put("msg", (Object)"\u65e0\u6cd5\u83b7\u53d6token\u670d\u52a1"); + } + } + } + catch (Exception ex) { + result.put("code", (Object)500); + result.put("msg", (Object)ex.getMessage()); + } + return result; + } + + private int getFileType(String ext) { + if ("jpg".equalsIgnoreCase(ext) || "jpeg".equalsIgnoreCase(ext) || "png".equalsIgnoreCase(ext)) { + return 1; + } + if ("mp3".equalsIgnoreCase(ext) || "wav".equalsIgnoreCase(ext) || "m4v".equalsIgnoreCase(ext)) { + return 2; + } + return 3; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/onvif/controller/CameraOnvifController.java b/ai-bird-system/src/main/java/net/hzvtc/onvif/controller/CameraOnvifController.java new file mode 100644 index 0000000..50f66c8 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/onvif/controller/CameraOnvifController.java @@ -0,0 +1,46 @@ +package net.hzvtc.onvif.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.onvif.service.CameraOnvifService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +@RestController +@RequestMapping("/camera/onvif") +public class CameraOnvifController { + @Autowired + private CameraOnvifService cameraOnvifService; + + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(cameraOnvifService.getCameraOnvifInfo(id)); + } + + @PostMapping("/ptzOperate") + public AjaxResult cameraPtzOperator(@RequestBody JSONObject param) { + return AjaxResult.success(cameraOnvifService.cameraPtzOperateByParam(param)); + } + + @PostMapping("/downloadSnapshotfile") + public void downloadSnapshotfile(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + Long deviceId = Long.parseLong((String) params.get("deviceId")); + String filePath = cameraOnvifService.getSnapshotFile(deviceId); + if (filePath != null) { + try { + String realFileName = "snapshot_" + deviceId + "_" + System.currentTimeMillis() + ".jpg"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader(response, realFileName); + FileUtils.writeBytes(filePath, response.getOutputStream()); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/onvif/service/CameraOnvifService.java b/ai-bird-system/src/main/java/net/hzvtc/onvif/service/CameraOnvifService.java new file mode 100644 index 0000000..890fba8 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/onvif/service/CameraOnvifService.java @@ -0,0 +1,15 @@ +package net.hzvtc.onvif.service; + +import com.alibaba.fastjson.JSONObject; + +public interface CameraOnvifService { + public JSONObject getCameraConnectInfo(Long var1); + + public String getSnapshotFile(Long var1); + + public JSONObject getCameraOnvifInfo(Long var1); + + public boolean cameraPtzOperateByParam(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/onvif/service/impl/CameraOnvifServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/onvif/service/impl/CameraOnvifServiceImpl.java new file mode 100644 index 0000000..34daafe --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/onvif/service/impl/CameraOnvifServiceImpl.java @@ -0,0 +1,198 @@ +package net.hzvtc.onvif.service.impl; + +import com.alibaba.fastjson.JSONObject; +import de.onvif.soap.OnvifDevice; +import de.onvif.soap.devices.PtzDevices; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.ConnectException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Base64; +import java.util.List; +import javax.xml.soap.SOAPException; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.onvif.service.CameraOnvifService; +import org.onvif.ver10.schema.FloatRange; +import org.onvif.ver10.schema.PTZStatus; +import org.onvif.ver10.schema.Profile; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class CameraOnvifServiceImpl +implements CameraOnvifService { + private static final Logger log = LoggerFactory.getLogger(CameraOnvifServiceImpl.class); + @Autowired + private DeviceInfoService deviceInfoService; + @Autowired + private RedisCache redisCache; + private String keyPrefix = "onvif_conntected_info_"; + @Value(value="${hzvtc.cameraSnapshopFilePath}") + private String cameraSnapshopFilePath; + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + private boolean getSnapshotImage(String url, String username, String password, String fileName) { + boolean success = true; + InputStream in = null; + FileOutputStream out = null; + try { + int c; + URL imageUrl = new URL(url); + HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); + conn.setDoOutput(true); + conn.setReadTimeout(30000); + conn.setConnectTimeout(30000); + conn.setUseCaches(false); + conn.setAllowUserInteraction(false); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setRequestProperty("Accept-Charset", "UTF-8"); + conn.setRequestMethod("GET"); + String userCredentials = username.trim() + ":" + password.trim(); + String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes())); + conn.setRequestProperty("Authorization", basicAuth); + in = conn.getInputStream(); + out = new FileOutputStream(this.cameraSnapshopFilePath + fileName); + byte[] b = new byte[4096]; + while ((c = in.read(b)) != -1) { + out.write(b, 0, c); + } + } + catch (Exception ex) { + ex.printStackTrace(); + log.error(ex.getMessage()); + success = false; + } + finally { + if (in != null) { + try { + in.close(); + } + catch (IOException iOException) {} + } + if (out != null) { + try { + out.close(); + } + catch (IOException iOException) {} + } + } + return success; + } + + @Override + public JSONObject getCameraConnectInfo(Long deviceId) { + DeviceInfo deviceInfo; + JSONObject object = (JSONObject)this.redisCache.getCacheObject(this.keyPrefix + deviceId); + if ((object == null || object.getString("OnvifHost") == null || object.getString("OnvifHost").isEmpty()) && (deviceInfo = this.deviceInfoService.selectDeviceInfoById(deviceId)) != null) { + object = new JSONObject(); + object.put("OnvifHost", (Object)deviceInfo.getRtspOut()); + object.put("userName", (Object)deviceInfo.getDeviceUser()); + object.put("password", (Object)deviceInfo.getDevicePassword()); + this.redisCache.setCacheObject(this.keyPrefix + deviceId, (Object)object); + } + return object; + } + + private OnvifDevice connentToOnvifDevice(Long deviceId) { + JSONObject object = this.getCameraConnectInfo(deviceId); + if (object != null) { + try { + OnvifDevice nvt = new OnvifDevice(object.getString("OnvifHost"), object.getString("userName"), object.getString("password")); + return nvt; + } + catch (ConnectException e) { + log.error("Could not connect to NVT."); + } + catch (SOAPException e) { + log.error(e.getMessage()); + } + } + return null; + } + + @Override + public String getSnapshotFile(Long deviceId) { + JSONObject object = this.getCameraConnectInfo(deviceId); + try { + OnvifDevice nvt = this.connentToOnvifDevice(deviceId); + List profiles = nvt.getDevices().getProfiles(); + String profileToken = ((Profile)profiles.get(0)).getToken(); + String snapshotUrl = nvt.getMedia().getSnapshotUri(profileToken); + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + String filename = "camera_" + deviceId + "_" + fmDate.format(LocalDateTime.now()) + ".jpg"; + boolean success = this.getSnapshotImage(snapshotUrl, object.getString("userName"), object.getString("password"), filename); + if (success) { + return this.cameraSnapshopFilePath + filename; + } + } + catch (Exception ex) { + log.error(ex.getMessage()); + } + return null; + } + + @Override + public JSONObject getCameraOnvifInfo(Long deviceId) { + try { + OnvifDevice nvt = this.connentToOnvifDevice(deviceId); + JSONObject config = new JSONObject(); + List profiles = nvt.getDevices().getProfiles(); + String profileToken = ((Profile)profiles.get(0)).getToken(); + PtzDevices ptzDevices = nvt.getPtz(); + PTZStatus ptzStatus = ptzDevices.getStatus(profileToken); + config.put("currentX", (Object)Float.valueOf(ptzStatus.getPosition().getPanTilt().getX())); + config.put("currentY", (Object)Float.valueOf(ptzStatus.getPosition().getPanTilt().getY())); + config.put("currentZoom", (Object)Float.valueOf(ptzStatus.getPosition().getZoom().getX())); + FloatRange panRange = ptzDevices.getPanSpaces(profileToken); + FloatRange tiltRange = ptzDevices.getTiltSpaces(profileToken); + FloatRange zoomRange = ptzDevices.getZoomSpaces(profileToken); + config.put("xmax", (Object)Float.valueOf(panRange.getMax())); + config.put("xmin", (Object)Float.valueOf(panRange.getMin())); + config.put("ymax", (Object)Float.valueOf(tiltRange.getMax())); + config.put("ymin", (Object)Float.valueOf(tiltRange.getMin())); + config.put("zmax", (Object)Float.valueOf(zoomRange.getMax())); + config.put("zmin", (Object)Float.valueOf(zoomRange.getMin())); + return config; + } + catch (Exception ex) { + log.error(ex.getMessage()); + return null; + } + } + + @Override + public boolean cameraPtzOperateByParam(JSONObject param) { + try { + Long deviceId = param.getLong("deviceId"); + OnvifDevice nvt = this.connentToOnvifDevice(deviceId); + List profiles = nvt.getDevices().getProfiles(); + String profileToken = ((Profile)profiles.get(0)).getToken(); + PtzDevices ptzDevices = nvt.getPtz(); + float x = param.getFloat("x").floatValue(); + float y = param.getFloat("y").floatValue(); + float zoom = param.getFloat("zoom").floatValue(); + if (ptzDevices.isAbsoluteMoveSupported(profileToken)) { + ptzDevices.absoluteMove(profileToken, x, y, zoom); + } + return true; + } + catch (Exception ex) { + ex.printStackTrace(); + log.error(ex.getMessage()); + return false; + } + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/controller/MessageReadInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/system/controller/MessageReadInfoController.java new file mode 100644 index 0000000..4635726 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/controller/MessageReadInfoController.java @@ -0,0 +1,86 @@ +package net.hzvtc.system.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.system.domain.MessageReadInfo; +import net.hzvtc.system.service.MessageReadInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 信息阅读情况Controller + * + * @author admin + * @date 2023-10-20 + */ +@RestController +@RequestMapping("/system/msgread") +public class MessageReadInfoController extends BaseController { + @Autowired + private MessageReadInfoService messageReadInfoService; + + /** + * 查询信息阅读情况列表 + */ + @PreAuthorize("@ss.hasPermi('system:msgread:list')") + @GetMapping("/list") + public TableDataInfo list(MessageReadInfo messageReadInfo) { + startPage(); + List list = messageReadInfoService.selectMessageReadInfoList(messageReadInfo); + return getDataTable(list); + } + + /** + * 导出信息阅读情况列表 + */ + @Log(title = "信息阅读情况", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, MessageReadInfo messageReadInfo) { + List list = messageReadInfoService.selectMessageReadInfoList(messageReadInfo); + ExcelUtil util = new ExcelUtil(MessageReadInfo.class); + util.exportExcel(response, list, "信息阅读情况数据"); + } + + /** + * 获取信息阅读情况详细信息 + */ + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(messageReadInfoService.selectMessageReadInfoById(id)); + } + + /** + * 新增信息阅读情况 + */ + @Log(title = "信息阅读情况", businessType = BusinessType.INSERT) + @PostMapping("/addMsgReadInfo") + public AjaxResult add(@RequestBody MessageReadInfo messageReadInfo) { + return toAjax(messageReadInfoService.insertMessageReadInfo(messageReadInfo)); + } + + /** + * 修改信息阅读情况 + */ + @Log(title = "信息阅读情况", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody MessageReadInfo messageReadInfo) { + return toAjax(messageReadInfoService.updateMessageReadInfo(messageReadInfo)); + } + + /** + * 删除信息阅读情况 + */ + @Log(title = "信息阅读情况", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(messageReadInfoService.deleteMessageReadInfoByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/MenuInSys.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/MenuInSys.java new file mode 100644 index 0000000..b2d2de1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/MenuInSys.java @@ -0,0 +1,17 @@ +package net.hzvtc.system.domain; + +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="MenuInSys") +@Data +public class MenuInSys { + private static final long serialVersionUID = 1L; + private Long id; + private Long menuId; + private Long parentId; + private Integer orderNum; + private Integer sysId; + private Integer isDeleted; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/MessageReadInfo.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/MessageReadInfo.java new file mode 100644 index 0000000..9c2a3d7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/MessageReadInfo.java @@ -0,0 +1,20 @@ +package net.hzvtc.system.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="MessageReadInfo") +@Data +public class MessageReadInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long userId; + private Long messageId; + private Date readDate; + private int messageType; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeFileInfo.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeFileInfo.java new file mode 100644 index 0000000..a3fa6c6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeFileInfo.java @@ -0,0 +1,18 @@ +package net.hzvtc.system.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="NoticeFileInfo") +@Data +public class NoticeFileInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private String filePath; + private String fileType; + private String name; + private Long noticeId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReadDept.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReadDept.java new file mode 100644 index 0000000..92cf32a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReadDept.java @@ -0,0 +1,19 @@ +package net.hzvtc.system.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="NoticeReadDept") +@Data +public class NoticeReadDept extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long deptId; + private String deptName; + private String fullPath; + private String ancestorPath; + private Long noticeId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReader.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReader.java new file mode 100644 index 0000000..09d5e36 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/NoticeReader.java @@ -0,0 +1,20 @@ +package net.hzvtc.system.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="NoticeReader") +@Data +public class NoticeReader { + private static final long serialVersionUID = 1L; + private Long id; + private Long personId; + private String personName; + private Long deptId; + private String deptName; + private Date readTime; + private Long noticeId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/RoleInArea.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/RoleInArea.java new file mode 100644 index 0000000..8b9c1ab --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/RoleInArea.java @@ -0,0 +1,12 @@ +package net.hzvtc.system.domain; + +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="RoleInArea") +@Data +public class RoleInArea { + private Long id; + private Long roleId; + private Long areaId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysConfig.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysConfig.java new file mode 100644 index 0000000..1538ef3 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysConfig.java @@ -0,0 +1,77 @@ +package net.hzvtc.system.domain; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysConfig") +public class SysConfig +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u53c2\u6570\u4e3b\u952e", cellType=Excel.ColumnType.NUMERIC) + private Long configId; + @Excel(name="\u53c2\u6570\u540d\u79f0") + private String configName; + @Excel(name="\u53c2\u6570\u952e\u540d") + private String configKey; + @Excel(name="\u53c2\u6570\u952e\u503c") + private String configValue; + @Excel(name="\u7cfb\u7edf\u5185\u7f6e", readConverterExp="Y=\u662f,N=\u5426") + private String configType; + + public Long getConfigId() { + return this.configId; + } + + public void setConfigId(Long configId) { + this.configId = configId; + } + + @NotBlank(message="\u53c2\u6570\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u53c2\u6570\u540d\u79f0\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u53c2\u6570\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u53c2\u6570\u540d\u79f0\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getConfigName() { + return this.configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + @NotBlank(message="\u53c2\u6570\u952e\u540d\u957f\u5ea6\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=100, message="\u53c2\u6570\u952e\u540d\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u53c2\u6570\u952e\u540d\u957f\u5ea6\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=100, message="\u53c2\u6570\u952e\u540d\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7100\u4e2a\u5b57\u7b26") String getConfigKey() { + return this.configKey; + } + + public void setConfigKey(String configKey) { + this.configKey = configKey; + } + + @NotBlank(message="\u53c2\u6570\u952e\u503c\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=500, message="\u53c2\u6570\u952e\u503c\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7500\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u53c2\u6570\u952e\u503c\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=500, message="\u53c2\u6570\u952e\u503c\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc7500\u4e2a\u5b57\u7b26") String getConfigValue() { + return this.configValue; + } + + public void setConfigValue(String configValue) { + this.configValue = configValue; + } + + public String getConfigType() { + return this.configType; + } + + public void setConfigType(String configType) { + this.configType = configType; + } + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("configId", (Object)this.getConfigId()).append("configName", (Object)this.getConfigName()).append("configKey", (Object)this.getConfigKey()).append("configValue", (Object)this.getConfigValue()).append("configType", (Object)this.getConfigType()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysLogininfor.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysLogininfor.java new file mode 100644 index 0000000..f6c0369 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysLogininfor.java @@ -0,0 +1,144 @@ +package net.hzvtc.system.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.annotation.Excel.ColumnType; +import net.hzvtc.common.core.domain.BaseEntity; + +/** + * 系统访问记录表 sys_logininfor + * + * @author admin + */ +public class SysLogininfor extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** ID */ + @Excel(name = "序号", cellType = ColumnType.NUMERIC) + private Long infoId; + + /** 用户账号 */ + @Excel(name = "用户账号") + private String userName; + + /** 登录状态 0成功 1失败 */ + @Excel(name = "登录状态", readConverterExp = "0=成功,1=失败") + private String status; + + /** 登录IP地址 */ + @Excel(name = "登录地址") + private String ipaddr; + + /** 登录地点 */ + @Excel(name = "登录地点") + private String loginLocation; + + /** 浏览器类型 */ + @Excel(name = "浏览器") + private String browser; + + /** 操作系统 */ + @Excel(name = "操作系统") + private String os; + + /** 提示消息 */ + @Excel(name = "提示消息") + private String msg; + + /** 访问时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Excel(name = "访问时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") + private Date loginTime; + + public Long getInfoId() + { + return infoId; + } + + public void setInfoId(Long infoId) + { + this.infoId = infoId; + } + + public String getUserName() + { + return userName; + } + + public void setUserName(String userName) + { + this.userName = userName; + } + + public String getStatus() + { + return status; + } + + public void setStatus(String status) + { + this.status = status; + } + + public String getIpaddr() + { + return ipaddr; + } + + public void setIpaddr(String ipaddr) + { + this.ipaddr = ipaddr; + } + + public String getLoginLocation() + { + return loginLocation; + } + + public void setLoginLocation(String loginLocation) + { + this.loginLocation = loginLocation; + } + + public String getBrowser() + { + return browser; + } + + public void setBrowser(String browser) + { + this.browser = browser; + } + + public String getOs() + { + return os; + } + + public void setOs(String os) + { + this.os = os; + } + + public String getMsg() + { + return msg; + } + + public void setMsg(String msg) + { + this.msg = msg; + } + + public Date getLoginTime() + { + return loginTime; + } + + public void setLoginTime(Date loginTime) + { + this.loginTime = loginTime; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysNotice.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysNotice.java new file mode 100644 index 0000000..fa74b50 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysNotice.java @@ -0,0 +1,25 @@ +package net.hzvtc.system.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import java.util.List; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="SysNotice") +@Data +public class SysNotice extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long noticeId; + private String noticeType; + private String noticeContent; + private Integer status = 1; + private Long createDept; + private String createDeptName; + private String createByName; + private int isDeleted = 0; + private List deptIds; + private List fileInfoList; + private List deptList; + private List readerList; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysOperLog.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysOperLog.java new file mode 100644 index 0000000..64c7fd2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysOperLog.java @@ -0,0 +1,255 @@ +package net.hzvtc.system.domain; + +import java.util.Date; +import com.fasterxml.jackson.annotation.JsonFormat; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.annotation.Excel.ColumnType; +import net.hzvtc.common.core.domain.BaseEntity; + +/** + * 操作日志记录表 oper_log + * + * @author admin + */ +public class SysOperLog extends BaseEntity +{ + private static final long serialVersionUID = 1L; + + /** 日志主键 */ + @Excel(name = "操作序号", cellType = ColumnType.NUMERIC) + private Long operId; + + /** 操作模块 */ + @Excel(name = "操作模块") + private String title; + + /** 业务类型(0其它 1新增 2修改 3删除) */ + @Excel(name = "业务类型", readConverterExp = "0=其它,1=新增,2=修改,3=删除,4=授权,5=导出,6=导入,7=强退,8=生成代码,9=清空数据") + private Integer businessType; + + /** 业务类型数组 */ + private Integer[] businessTypes; + + /** 请求方法 */ + @Excel(name = "请求方法") + private String method; + + /** 请求方式 */ + @Excel(name = "请求方式") + private String requestMethod; + + /** 操作类别(0其它 1后台用户 2手机端用户) */ + @Excel(name = "操作类别", readConverterExp = "0=其它,1=后台用户,2=手机端用户") + private Integer operatorType; + + /** 操作人员 */ + @Excel(name = "操作人员") + private String operName; + + /** 部门名称 */ + @Excel(name = "部门名称") + private String deptName; + + /** 请求url */ + @Excel(name = "请求地址") + private String operUrl; + + /** 操作地址 */ + @Excel(name = "操作地址") + private String operIp; + + /** 操作地点 */ + @Excel(name = "操作地点") + private String operLocation; + + /** 请求参数 */ + @Excel(name = "请求参数") + private String operParam; + + /** 返回参数 */ + @Excel(name = "返回参数") + private String jsonResult; + + /** 操作状态(0正常 1异常) */ + @Excel(name = "状态", readConverterExp = "0=正常,1=异常") + private Integer status; + + /** 错误消息 */ + @Excel(name = "错误消息") + private String errorMsg; + + /** 操作时间 */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") + private Date operTime; + + public Long getOperId() + { + return operId; + } + + public void setOperId(Long operId) + { + this.operId = operId; + } + + public String getTitle() + { + return title; + } + + public void setTitle(String title) + { + this.title = title; + } + + public Integer getBusinessType() + { + return businessType; + } + + public void setBusinessType(Integer businessType) + { + this.businessType = businessType; + } + + public Integer[] getBusinessTypes() + { + return businessTypes; + } + + public void setBusinessTypes(Integer[] businessTypes) + { + this.businessTypes = businessTypes; + } + + public String getMethod() + { + return method; + } + + public void setMethod(String method) + { + this.method = method; + } + + public String getRequestMethod() + { + return requestMethod; + } + + public void setRequestMethod(String requestMethod) + { + this.requestMethod = requestMethod; + } + + public Integer getOperatorType() + { + return operatorType; + } + + public void setOperatorType(Integer operatorType) + { + this.operatorType = operatorType; + } + + public String getOperName() + { + return operName; + } + + public void setOperName(String operName) + { + this.operName = operName; + } + + public String getDeptName() + { + return deptName; + } + + public void setDeptName(String deptName) + { + this.deptName = deptName; + } + + public String getOperUrl() + { + return operUrl; + } + + public void setOperUrl(String operUrl) + { + this.operUrl = operUrl; + } + + public String getOperIp() + { + return operIp; + } + + public void setOperIp(String operIp) + { + this.operIp = operIp; + } + + public String getOperLocation() + { + return operLocation; + } + + public void setOperLocation(String operLocation) + { + this.operLocation = operLocation; + } + + public String getOperParam() + { + return operParam; + } + + public void setOperParam(String operParam) + { + this.operParam = operParam; + } + + public String getJsonResult() + { + return jsonResult; + } + + public void setJsonResult(String jsonResult) + { + this.jsonResult = jsonResult; + } + + public Integer getStatus() + { + return status; + } + + public void setStatus(Integer status) + { + this.status = status; + } + + public String getErrorMsg() + { + return errorMsg; + } + + public void setErrorMsg(String errorMsg) + { + this.errorMsg = errorMsg; + } + + public Date getOperTime() + { + return operTime; + } + + public void setOperTime(Date operTime) + { + this.operTime = operTime; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysPost.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysPost.java new file mode 100644 index 0000000..1f35a76 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysPost.java @@ -0,0 +1,83 @@ +package net.hzvtc.system.domain; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import net.hzvtc.common.annotation.Excel; +import net.hzvtc.common.core.domain.BaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +public class SysPost +extends BaseEntity { + private static final long serialVersionUID = 1L; + @Excel(name="\u5c97\u4f4d\u5e8f\u53f7", cellType=Excel.ColumnType.NUMERIC) + private Long postId; + @Excel(name="\u5c97\u4f4d\u7f16\u7801") + private String postCode; + @Excel(name="\u5c97\u4f4d\u540d\u79f0") + private String postName; + @Excel(name="\u5c97\u4f4d\u6392\u5e8f") + private String postSort; + @Excel(name="\u72b6\u6001", readConverterExp="0=\u6b63\u5e38,1=\u505c\u7528") + private String status; + private boolean flag = false; + + public Long getPostId() { + return this.postId; + } + + public void setPostId(Long postId) { + this.postId = postId; + } + + @NotBlank(message="\u5c97\u4f4d\u7f16\u7801\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=64, message="\u5c97\u4f4d\u7f16\u7801\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc764\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5c97\u4f4d\u7f16\u7801\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=64, message="\u5c97\u4f4d\u7f16\u7801\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc764\u4e2a\u5b57\u7b26") String getPostCode() { + return this.postCode; + } + + public void setPostCode(String postCode) { + this.postCode = postCode; + } + + @NotBlank(message="\u5c97\u4f4d\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") + @Size(min=0, max=50, message="\u5c97\u4f4d\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc750\u4e2a\u5b57\u7b26") + public @NotBlank(message="\u5c97\u4f4d\u540d\u79f0\u4e0d\u80fd\u4e3a\u7a7a") @Size(min=0, max=50, message="\u5c97\u4f4d\u540d\u79f0\u957f\u5ea6\u4e0d\u80fd\u8d85\u8fc750\u4e2a\u5b57\u7b26") String getPostName() { + return this.postName; + } + + public void setPostName(String postName) { + this.postName = postName; + } + + @NotBlank(message="\u663e\u793a\u987a\u5e8f\u4e0d\u80fd\u4e3a\u7a7a") + public @NotBlank(message="\u663e\u793a\u987a\u5e8f\u4e0d\u80fd\u4e3a\u7a7a") String getPostSort() { + return this.postSort; + } + + public void setPostSort(String postSort) { + this.postSort = postSort; + } + + public String getStatus() { + return this.status; + } + + public void setStatus(String status) { + this.status = status; + } + + public boolean isFlag() { + return this.flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + public String toString() { + return new ToStringBuilder((Object)this, ToStringStyle.MULTI_LINE_STYLE).append("postId", (Object)this.getPostId()).append("postCode", (Object)this.getPostCode()).append("postName", (Object)this.getPostName()).append("postSort", (Object)this.getPostSort()).append("status", (Object)this.getStatus()).append("createBy", (Object)this.getCreateBy()).append("createTime", (Object)this.getCreateTime()).append("updateBy", (Object)this.getUpdateBy()).append("updateTime", (Object)this.getUpdateTime()).append("remark", (Object)this.getRemark()).toString(); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleDept.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleDept.java new file mode 100644 index 0000000..81b4186 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleDept.java @@ -0,0 +1,46 @@ +package net.hzvtc.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 角色和部门关联 sys_role_dept + * + * @author admin + */ +public class SysRoleDept +{ + /** 角色ID */ + private Long roleId; + + /** 部门ID */ + private Long deptId; + + public Long getRoleId() + { + return roleId; + } + + public void setRoleId(Long roleId) + { + this.roleId = roleId; + } + + public Long getDeptId() + { + return deptId; + } + + public void setDeptId(Long deptId) + { + this.deptId = deptId; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("roleId", getRoleId()) + .append("deptId", getDeptId()) + .toString(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleMenu.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleMenu.java new file mode 100644 index 0000000..4791775 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysRoleMenu.java @@ -0,0 +1,47 @@ +package net.hzvtc.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +/** + * 角色和菜单关联 sys_role_menu + * + * @author admin + */ +@Alias("SysRoleMenu") +public class SysRoleMenu { + /** + * 角色ID + */ + private Long roleId; + + /** + * 菜单ID + */ + private Long menuId; + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + public Long getMenuId() { + return menuId; + } + + public void setMenuId(Long menuId) { + this.menuId = menuId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("roleId", getRoleId()) + .append("menuId", getMenuId()) + .toString(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserOnline.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserOnline.java new file mode 100644 index 0000000..880e13f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserOnline.java @@ -0,0 +1,113 @@ +package net.hzvtc.system.domain; + +/** + * 当前在线会话 + * + * @author admin + */ +public class SysUserOnline +{ + /** 会话编号 */ + private String tokenId; + + /** 部门名称 */ + private String deptName; + + /** 用户名称 */ + private String userName; + + /** 登录IP地址 */ + private String ipaddr; + + /** 登录地址 */ + private String loginLocation; + + /** 浏览器类型 */ + private String browser; + + /** 操作系统 */ + private String os; + + /** 登录时间 */ + private Long loginTime; + + public String getTokenId() + { + return tokenId; + } + + public void setTokenId(String tokenId) + { + this.tokenId = tokenId; + } + + public String getDeptName() + { + return deptName; + } + + public void setDeptName(String deptName) + { + this.deptName = deptName; + } + + public String getUserName() + { + return userName; + } + + public void setUserName(String userName) + { + this.userName = userName; + } + + public String getIpaddr() + { + return ipaddr; + } + + public void setIpaddr(String ipaddr) + { + this.ipaddr = ipaddr; + } + + public String getLoginLocation() + { + return loginLocation; + } + + public void setLoginLocation(String loginLocation) + { + this.loginLocation = loginLocation; + } + + public String getBrowser() + { + return browser; + } + + public void setBrowser(String browser) + { + this.browser = browser; + } + + public String getOs() + { + return os; + } + + public void setOs(String os) + { + this.os = os; + } + + public Long getLoginTime() + { + return loginTime; + } + + public void setLoginTime(Long loginTime) + { + this.loginTime = loginTime; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserPost.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserPost.java new file mode 100644 index 0000000..c4a1970 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserPost.java @@ -0,0 +1,46 @@ +package net.hzvtc.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +/** + * 用户和岗位关联 sys_user_post + * + * @author admin + */ +public class SysUserPost +{ + /** 用户ID */ + private Long userId; + + /** 岗位ID */ + private Long postId; + + public Long getUserId() + { + return userId; + } + + public void setUserId(Long userId) + { + this.userId = userId; + } + + public Long getPostId() + { + return postId; + } + + public void setPostId(Long postId) + { + this.postId = postId; + } + + @Override + public String toString() { + return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) + .append("userId", getUserId()) + .append("postId", getPostId()) + .toString(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserRole.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserRole.java new file mode 100644 index 0000000..e9846f0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/SysUserRole.java @@ -0,0 +1,47 @@ +package net.hzvtc.system.domain; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.ibatis.type.Alias; + +/** + * 用户和角色关联 sys_user_role + * + * @author admin + */ +@Alias("SysUserRole") +public class SysUserRole { + /** + * 用户ID + */ + private Long userId; + + /** + * 角色ID + */ + private Long roleId; + + public Long getUserId() { + return userId; + } + + public void setUserId(Long userId) { + this.userId = userId; + } + + public Long getRoleId() { + return roleId; + } + + public void setRoleId(Long roleId) { + this.roleId = roleId; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("userId", getUserId()) + .append("roleId", getRoleId()) + .toString(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/DocStateCountVO.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/DocStateCountVO.java new file mode 100644 index 0000000..976ba0a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/DocStateCountVO.java @@ -0,0 +1,11 @@ +package net.hzvtc.system.domain.vo; + +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="DocStateCountVO") +@Data +public class DocStateCountVO { + private Integer state; + private int count = 0; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MessageVo.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MessageVo.java new file mode 100644 index 0000000..05197bb --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MessageVo.java @@ -0,0 +1,17 @@ +package net.hzvtc.system.domain.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import org.apache.ibatis.type.Alias; + +@Alias(value="MessageVo") +@Data +public class MessageVo { + private Long id; + private String title; + private Date time; + private String mediaUrl; + private int msgType; + private Long readId; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MetaVo.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MetaVo.java new file mode 100644 index 0000000..37f25b0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/MetaVo.java @@ -0,0 +1,106 @@ +package net.hzvtc.system.domain.vo; + +import net.hzvtc.common.utils.StringUtils; + +/** + * 路由显示信息 + * + * @author admin + */ +public class MetaVo +{ + /** + * 设置该路由在侧边栏和面包屑中展示的名字 + */ + private String title; + + /** + * 设置该路由的图标,对应路径src/assets/icons/svg + */ + private String icon; + + /** + * 设置为true,则不会被 缓存 + */ + private boolean noCache; + + /** + * 内链地址(http(s)://开头) + */ + private String link; + + public MetaVo() + { + } + + public MetaVo(String title, String icon) + { + this.title = title; + this.icon = icon; + } + + public MetaVo(String title, String icon, boolean noCache) + { + this.title = title; + this.icon = icon; + this.noCache = noCache; + } + + public MetaVo(String title, String icon, String link) + { + this.title = title; + this.icon = icon; + this.link = link; + } + + public MetaVo(String title, String icon, boolean noCache, String link) + { + this.title = title; + this.icon = icon; + this.noCache = noCache; + if (StringUtils.ishttp(link)) + { + this.link = link; + } + } + + public boolean isNoCache() + { + return noCache; + } + + public void setNoCache(boolean noCache) + { + this.noCache = noCache; + } + + public String getTitle() + { + return title; + } + + public void setTitle(String title) + { + this.title = title; + } + + public String getIcon() + { + return icon; + } + + public void setIcon(String icon) + { + this.icon = icon; + } + + public String getLink() + { + return link; + } + + public void setLink(String link) + { + this.link = link; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/RouterVo.java b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/RouterVo.java new file mode 100644 index 0000000..34cf89b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/domain/vo/RouterVo.java @@ -0,0 +1,19 @@ +package net.hzvtc.system.domain.vo; + +import java.util.List; +import lombok.Data; + +@JsonInclude(value=JsonInclude.Include.NON_EMPTY) +@Data +public class RouterVo { + private String name; + private String path; + private boolean hidden; + private String redirect; + private String component; + private String query; + private Boolean alwaysShow; + private MetaVo meta; + private List children; + private boolean showMenu; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MenuInSysMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MenuInSysMapper.java new file mode 100644 index 0000000..33efede --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MenuInSysMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.MenuInSys; + +/** + * 系统菜单Mapper接口 + * + * @author admin + * @date 2023-10-23 + */ +public interface MenuInSysMapper +{ + /** + * 查询系统菜单 + * + * @param id 系统菜单主键 + * @return 系统菜单 + */ + public MenuInSys selectMenuInSysById(Long id); + + /** + * 查询系统菜单列表 + * + * @param menuInSys 系统菜单 + * @return 系统菜单集合 + */ + public List selectMenuInSysList(MenuInSys menuInSys); + + /** + * 新增系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + public int insertMenuInSys(MenuInSys menuInSys); + + /** + * 修改系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + public int updateMenuInSys(MenuInSys menuInSys); + + /** + * 删除系统菜单 + * + * @param id 系统菜单主键 + * @return 结果 + */ + public int deleteMenuInSysById(Long id); + + /** + * 批量删除系统菜单 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteMenuInSysByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MessageReadInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MessageReadInfoMapper.java new file mode 100644 index 0000000..81ff2c1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/MessageReadInfoMapper.java @@ -0,0 +1,22 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.MessageReadInfo; + +public interface MessageReadInfoMapper { + public MessageReadInfo selectMessageReadInfoById(Long var1); + + public List selectMessageReadInfoListByParam(MessageReadInfo var1); + + public List selectMessageReadInfoList(MessageReadInfo var1); + + public int insertMessageReadInfo(MessageReadInfo var1); + + public int updateMessageReadInfo(MessageReadInfo var1); + + public int deleteMessageReadInfoById(Long var1); + + public int deleteMessageReadInfoByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeFileInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeFileInfoMapper.java new file mode 100644 index 0000000..65f7a9d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeFileInfoMapper.java @@ -0,0 +1,23 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.system.domain.NoticeFileInfo; + +public interface NoticeFileInfoMapper { + public NoticeFileInfo selectNoticeFileInfoById(Long var1); + + public List selectNoticeFileInfoList(NoticeFileInfo var1); + + public List getNoticeFileInfoListByPid(Long var1); + + public int insertNoticeFileInfo(NoticeFileInfo var1); + + public int batchInsertNoticeFileInfo(List var1); + + public int deleteNoticeFileInfoById(Long var1); + + public int deleteNoticeFileInfoNotInIds(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReadDeptMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReadDeptMapper.java new file mode 100644 index 0000000..30a3663 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReadDeptMapper.java @@ -0,0 +1,20 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.NoticeReadDept; + +public interface NoticeReadDeptMapper { + public NoticeReadDept selectNoticeReadDeptById(Long var1); + + public List selectNoticeReadDeptList(NoticeReadDept var1); + + public List getNoticeReadDeptListByPid(Long var1); + + public int insertNoticeReadDept(NoticeReadDept var1); + + public int batchInsertNoticeReadDept(List var1); + + public int deleteNoticeReadDeptByNoticeId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReaderMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReaderMapper.java new file mode 100644 index 0000000..c51e780 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/NoticeReaderMapper.java @@ -0,0 +1,40 @@ +package net.hzvtc.system.mapper; + +import net.hzvtc.system.domain.NoticeReader; + +import java.util.List; + +/** + * 公告阅读人员Mapper接口 + * + * @author admin + * @date 2022-05-02 + */ +public interface NoticeReaderMapper { + + /** + * 查询公告阅读人员列表 + * + * @param noticeId 公告阅读人员 + * @return 公告阅读人员集合 + */ + public List selectNoticeReaderListByPid(Long noticeId); + + /** + * 新增公告阅读人员 + * + * @param noticeReader 公告阅读人员 + * @return 结果 + */ + public int insertNoticeReader(NoticeReader noticeReader); + + + /** + * 删除公告阅读人员 + * + * @param id 公告阅读人员主键 + * @return 结果 + */ + public int deleteNoticeReaderById(Long id); + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysConfigMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysConfigMapper.java new file mode 100644 index 0000000..7213c2b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysConfigMapper.java @@ -0,0 +1,68 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysConfig; + +/** + * 参数配置 数据层 + * + * @author admin + */ +public interface SysConfigMapper +{ + /** + * 查询参数配置信息 + * + * @param config 参数配置信息 + * @return 参数配置信息 + */ + public SysConfig selectConfig(SysConfig config); + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + public List selectConfigList(SysConfig config); + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数键名 + * @return 参数配置信息 + */ + public SysConfig checkConfigKeyUnique(String configKey); + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int insertConfig(SysConfig config); + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int updateConfig(SysConfig config); + + /** + * 删除参数配置 + * + * @param configId 参数ID + * @return 结果 + */ + public int deleteConfigById(Long configId); + + /** + * 批量删除参数信息 + * + * @param configIds 需要删除的参数ID + * @return 结果 + */ + public int deleteConfigByIds(Long[] configIds); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDeptMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDeptMapper.java new file mode 100644 index 0000000..95e986b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDeptMapper.java @@ -0,0 +1,49 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.common.core.domain.entity.SysDept; +import org.apache.ibatis.annotations.Param; + +public interface SysDeptMapper { + public List selectDeptList(SysDept var1); + + public List selectDeptListByRoleId(@Param(value="roleId") Long var1, @Param(value="deptCheckStrictly") boolean var2); + + public SysDept selectDeptById(Long var1); + + public SysDept getSysDeptInfoForList(Long var1); + + public List getSysDeptFullPathByParam(Long var1); + + public List getSysDeptListInIds(List var1); + + public List getSysDeptListByParentId(Long var1); + + public List getSysDeptChildrenByParentId(Long var1); + + public List getSysDeptTreeListByIds(List var1); + + public void updateSysdeptAncestorPath(SysDept var1); + + public List selectChildrenDeptById(Long var1); + + public int selectNormalChildrenDeptById(Long var1); + + public int hasChildByDeptId(Long var1); + + public int checkDeptExistUser(Long var1); + + public SysDept checkDeptNameUnique(@Param(value="deptName") String var1, @Param(value="parentId") Long var2); + + public int insertDept(SysDept var1); + + public int updateDept(SysDept var1); + + public void updateDeptStatusNormal(Long[] var1); + + public int updateDeptChildren(@Param(value="depts") List var1); + + public int deleteDeptById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictDataMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictDataMapper.java new file mode 100644 index 0000000..22f43b6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictDataMapper.java @@ -0,0 +1,96 @@ +package net.hzvtc.system.mapper; + +import java.util.List; + +import net.hzvtc.common.core.domain.entity.SysDictData; +import org.apache.ibatis.annotations.Param; + +/** + * 字典表 数据层 + * + * @author admin + */ +public interface SysDictDataMapper +{ + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + public List selectDictDataList(SysDictData dictData); + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + public List selectDictDataByType(String dictType); + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + public String selectDictLabel(@Param("dictType") String dictType, @Param("dictValue") String dictValue); + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + public SysDictData selectDictDataById(Long dictCode); + + /** + * 查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据 + */ + public int countDictDataByType(String dictType); + + /** + * 通过字典ID删除字典数据信息 + * + * @param dictCode 字典数据ID + * @return 结果 + */ + public int deleteDictDataById(Long dictCode); + + /** + * 批量删除字典数据信息 + * + * @param dictCodes 需要删除的字典数据ID + * @return 结果 + */ + public int deleteDictDataByIds(Long[] dictCodes); + + /** + * 新增字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int insertDictData(SysDictData dictData); + + /** + * 修改字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int updateDictData(SysDictData dictData); + + /** + * 同步修改字典类型 + * + * @param oldDictType 旧字典类型 + * @param newDictType 新旧字典类型 + * @return 结果 + */ + public int updateDictDataType(@Param("oldDictType") String oldDictType, @Param("newDictType") String newDictType); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictTypeMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictTypeMapper.java new file mode 100644 index 0000000..3637f1f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysDictTypeMapper.java @@ -0,0 +1,86 @@ +package net.hzvtc.system.mapper; + +import java.util.List; + +import net.hzvtc.common.core.domain.entity.SysDictType; +import org.apache.ibatis.annotations.Mapper; + +/** + * 字典表 数据层 + * + * @author admin + */ +@Mapper +public interface SysDictTypeMapper +{ + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + public List selectDictTypeList(SysDictType dictType); + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + public List selectDictTypeAll(); + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + public SysDictType selectDictTypeById(Long dictId); + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + public SysDictType selectDictTypeByType(String dictType); + + /** + * 通过字典ID删除字典信息 + * + * @param dictId 字典ID + * @return 结果 + */ + public int deleteDictTypeById(Long dictId); + + /** + * 批量删除字典类型信息 + * + * @param dictIds 需要删除的字典ID + * @return 结果 + */ + public int deleteDictTypeByIds(Long[] dictIds); + + /** + * 新增字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int insertDictType(SysDictType dictType); + + /** + * 修改字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int updateDictType(SysDictType dictType); + + /** + * 校验字典类型称是否唯一 + * + * @param dictType 字典类型 + * @return 结果 + */ + public SysDictType checkDictTypeUnique(String dictType); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysLogininforMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysLogininforMapper.java new file mode 100644 index 0000000..7ee82d7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysLogininforMapper.java @@ -0,0 +1,42 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysLogininfor; + +/** + * 系统访问日志情况信息 数据层 + * + * @author admin + */ +public interface SysLogininforMapper +{ + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + public void insertLogininfor(SysLogininfor logininfor); + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + public List selectLogininforList(SysLogininfor logininfor); + + /** + * 批量删除系统登录日志 + * + * @param infoIds 需要删除的登录日志ID + * @return 结果 + */ + public int deleteLogininforByIds(Long[] infoIds); + + /** + * 清空系统登录日志 + * + * @return 结果 + */ + public int cleanLogininfor(); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysMenuMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysMenuMapper.java new file mode 100644 index 0000000..3c579aa --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysMenuMapper.java @@ -0,0 +1,118 @@ +package net.hzvtc.system.mapper; + +import net.hzvtc.common.core.domain.entity.SysMenu; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * 菜单表 数据层 + * + * @author admin + */ +public interface SysMenuMapper { + /** + * 查询系统菜单列表 + * + * @param menu 菜单信息 + * @return 菜单列表 + */ + public List selectMenuList(SysMenu menu); + + /** + * 根据用户所有权限 + * + * @return 权限列表 + */ + public List selectMenuPerms(); + + /** + * 根据用户查询系统菜单列表 + * + * @param menu 菜单信息 + * @return 菜单列表 + */ + public List selectMenuListByUserId(SysMenu menu); + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + public List selectMenuPermsByUserId(Long userId); + + /** + * 根据用户ID查询菜单 + * + * @return 菜单列表 + */ + public List selectMenuTreeAll(Integer sysId); + + /** + * 根据用户ID查询菜单 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuTreeByUserId(Map map); + + /** + * 根据角色ID查询菜单树信息 + * + * @param roleId 角色ID + * @param menuCheckStrictly 菜单树选择项是否关联显示 + * @return 选中菜单列表 + */ + public List selectMenuListByRoleId(@Param("roleId") Long roleId, @Param("menuCheckStrictly") boolean menuCheckStrictly); + + /** + * 根据菜单ID查询信息 + * + * @param menuId 菜单ID + * @return 菜单信息 + */ + public SysMenu selectMenuById(Long menuId); + + /** + * 是否存在菜单子节点 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int hasChildByMenuId(Long menuId); + + /** + * 新增菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int insertMenu(SysMenu menu); + + /** + * 修改菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int updateMenu(SysMenu menu); + + /** + * 删除菜单管理信息 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int deleteMenuById(Long menuId); + + /** + * 校验菜单名称是否唯一 + * + * @param menuName 菜单名称 + * @param parentId 父菜单ID + * @return 结果 + */ + public SysMenu checkMenuNameUnique(@Param("menuName") String menuName, @Param("parentId") Long parentId); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysNoticeMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysNoticeMapper.java new file mode 100644 index 0000000..0460387 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysNoticeMapper.java @@ -0,0 +1,32 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysNotice; +import net.hzvtc.system.domain.vo.DocStateCountVO; +import net.hzvtc.system.domain.vo.MessageVo; + +public interface SysNoticeMapper { + public SysNotice selectNoticeById(Long var1); + + public SysNotice getNoticeForMobileById(Long var1); + + public List getSysNoticeCountGroupByState(Long var1); + + public SysNotice getLastedNoticeByParam(); + + public List selectNoticeList(SysNotice var1); + + public List getSysNoticePubListByParam(SysNotice var1); + + public int insertNotice(SysNotice var1); + + public int updateNotice(SysNotice var1); + + public int deleteNoticeById(Long var1); + + public int deleteNoticeByIds(Long[] var1); + + public int getUnreadAmountByUserId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysOperLogMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysOperLogMapper.java new file mode 100644 index 0000000..8baed37 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysOperLogMapper.java @@ -0,0 +1,48 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysOperLog; + +/** + * 操作日志 数据层 + * + * @author admin + */ +public interface SysOperLogMapper +{ + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + public void insertOperlog(SysOperLog operLog); + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + public List selectOperLogList(SysOperLog operLog); + + /** + * 批量删除系统操作日志 + * + * @param operIds 需要删除的操作日志ID + * @return 结果 + */ + public int deleteOperLogByIds(Long[] operIds); + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + public SysOperLog selectOperLogById(Long operId); + + /** + * 清空操作日志 + */ + public void cleanOperLog(); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysPostMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysPostMapper.java new file mode 100644 index 0000000..774246a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysPostMapper.java @@ -0,0 +1,99 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysPost; + +/** + * 岗位信息 数据层 + * + * @author admin + */ +public interface SysPostMapper +{ + /** + * 查询岗位数据集合 + * + * @param post 岗位信息 + * @return 岗位数据集合 + */ + public List selectPostList(SysPost post); + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + public List selectPostAll(); + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + public SysPost selectPostById(Long postId); + + /** + * 根据用户ID获取岗位选择框列表 + * + * @param userId 用户ID + * @return 选中岗位ID列表 + */ + public List selectPostListByUserId(Long userId); + + /** + * 查询用户所属岗位组 + * + * @param userName 用户名 + * @return 结果 + */ + public List selectPostsByUserName(String userName); + + /** + * 删除岗位信息 + * + * @param postId 岗位ID + * @return 结果 + */ + public int deletePostById(Long postId); + + /** + * 批量删除岗位信息 + * + * @param postIds 需要删除的岗位ID + * @return 结果 + */ + public int deletePostByIds(Long[] postIds); + + /** + * 修改岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int updatePost(SysPost post); + + /** + * 新增岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int insertPost(SysPost post); + + /** + * 校验岗位名称 + * + * @param postName 岗位名称 + * @return 结果 + */ + public SysPost checkPostNameUnique(String postName); + + /** + * 校验岗位编码 + * + * @param postCode 岗位编码 + * @return 结果 + */ + public SysPost checkPostCodeUnique(String postCode); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleDeptMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleDeptMapper.java new file mode 100644 index 0000000..62d9c64 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleDeptMapper.java @@ -0,0 +1,44 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysRoleDept; + +/** + * 角色与部门关联表 数据层 + * + * @author admin + */ +public interface SysRoleDeptMapper +{ + /** + * 通过角色ID删除角色和部门关联 + * + * @param roleId 角色ID + * @return 结果 + */ + public int deleteRoleDeptByRoleId(Long roleId); + + /** + * 批量删除角色部门关联信息 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteRoleDept(Long[] ids); + + /** + * 查询部门使用数量 + * + * @param deptId 部门ID + * @return 结果 + */ + public int selectCountRoleDeptByDeptId(Long deptId); + + /** + * 批量新增角色部门信息 + * + * @param roleDeptList 角色部门列表 + * @return 结果 + */ + public int batchRoleDept(List roleDeptList); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMapper.java new file mode 100644 index 0000000..b6308bc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMapper.java @@ -0,0 +1,107 @@ +package net.hzvtc.system.mapper; + +import net.hzvtc.common.core.domain.entity.SysRole; + +import java.util.List; + +/** + * 角色表 数据层 + * + * @author admin + */ +public interface SysRoleMapper { + /** + * 根据条件分页查询角色数据 + * + * @param role 角色信息 + * @return 角色数据集合信息 + */ + public List selectRoleList(SysRole role); + + /** + * 根据用户ID查询角色 + * + * @param param 用户ID + * @return 角色列表 + */ + public List selectRolePermissionByUserId(SysRole param); + + /** + * 查询所有角色 + * + * @return 角色列表 + */ + public List selectRoleAll(); + + /** + * 根据用户ID获取角色选择框列表 + * + * @param userId 用户ID + * @return 选中角色ID列表 + */ + public List selectRoleListByUserId(Long userId); + + /** + * 通过角色ID查询角色 + * + * @param roleId 角色ID + * @return 角色对象信息 + */ + public SysRole selectRoleById(Long roleId); + + /** + * 根据用户ID查询角色 + * + * @param userName 用户名 + * @return 角色列表 + */ + public List selectRolesByUserName(String userName); + + /** + * 校验角色名称是否唯一 + * + * @param roleName 角色名称 + * @return 角色信息 + */ + public SysRole checkRoleNameUnique(String roleName); + + /** + * 校验角色权限是否唯一 + * + * @param roleKey 角色权限 + * @return 角色信息 + */ + public SysRole checkRoleKeyUnique(String roleKey); + + /** + * 修改角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int updateRole(SysRole role); + + /** + * 新增角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + public int insertRole(SysRole role); + + /** + * 通过角色ID删除角色 + * + * @param roleId 角色ID + * @return 结果 + */ + public int deleteRoleById(Long roleId); + + /** + * 批量删除角色信息 + * + * @param roleIds 需要删除的角色ID + * @return 结果 + */ + public int deleteRoleByIds(Long[] roleIds); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMenuMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMenuMapper.java new file mode 100644 index 0000000..c5791b4 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysRoleMenuMapper.java @@ -0,0 +1,25 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.RoleInArea; +import net.hzvtc.system.domain.SysRoleMenu; + +public interface SysRoleMenuMapper { + public int checkMenuExistRole(Long var1); + + public int deleteRoleMenuByRoleId(Long var1); + + public int deleteRoleMenu(Long[] var1); + + public int deleteAreaIdByRoleId(Long var1); + + public int batchRoleMenu(List var1); + + public int batchInsertArea(List var1); + + public List getRoleInAreaListByUserId(Long var1); + + public List getAllAreaList(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserMapper.java new file mode 100644 index 0000000..7ae71e9 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserMapper.java @@ -0,0 +1,45 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.common.core.domain.entity.SysUser; +import org.apache.ibatis.annotations.Param; + +public interface SysUserMapper { + public List selectUserList(SysUser var1); + + public List selectAllocatedList(SysUser var1); + + public List selectUnallocatedList(SysUser var1); + + public SysUser selectUserByUserName(String var1); + + public SysUser selectUserById(SysUser var1); + + public SysUser getUserInfoById(Long var1); + + public int insertUser(SysUser var1); + + public int updateUser(SysUser var1); + + public int updateUserPassword(SysUser var1); + + public int updateUserStatus(SysUser var1); + + public int updateUserProfile(SysUser var1); + + public int updateUserAvatar(@Param(value="userName") String var1, @Param(value="avatar") String var2); + + public int resetUserPwd(@Param(value="userName") String var1, @Param(value="password") String var2); + + public int deleteUserById(Long var1); + + public int deleteUserByIds(Long[] var1); + + public int checkUserNameUnique(String var1); + + public SysUser checkPhoneUnique(String var1); + + public SysUser checkEmailUnique(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserPostMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserPostMapper.java new file mode 100644 index 0000000..e95da12 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserPostMapper.java @@ -0,0 +1,44 @@ +package net.hzvtc.system.mapper; + +import java.util.List; +import net.hzvtc.system.domain.SysUserPost; + +/** + * 用户与岗位关联表 数据层 + * + * @author admin + */ +public interface SysUserPostMapper +{ + /** + * 通过用户ID删除用户和岗位关联 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserPostByUserId(Long userId); + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + public int countUserPostById(Long postId); + + /** + * 批量删除用户和岗位关联 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUserPost(Long[] ids); + + /** + * 批量新增用户岗位信息 + * + * @param userPostList 用户角色列表 + * @return 结果 + */ + public int batchUserPost(List userPostList); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserRoleMapper.java b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserRoleMapper.java new file mode 100644 index 0000000..e6c0b0f --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/mapper/SysUserRoleMapper.java @@ -0,0 +1,63 @@ +package net.hzvtc.system.mapper; + +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.system.domain.SysUserRole; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 用户与角色关联表 数据层 + * + * @author admin + */ +public interface SysUserRoleMapper { + /** + * 通过用户ID删除用户和角色关联 + * + * @param userId 用户ID + * @return 结果 + */ + public int deleteUserRoleByUserId(SysUser sysUser); + + /** + * 批量删除用户和角色关联 + * + * @param ids 需要删除的数据ID + * @return 结果 + */ + public int deleteUserRole(Long[] ids); + + /** + * 通过角色ID查询角色使用数量 + * + * @param roleId 角色ID + * @return 结果 + */ + public int countUserRoleByRoleId(Long roleId); + + /** + * 批量新增用户角色信息 + * + * @param userRoleList 用户角色列表 + * @return 结果 + */ + public int batchUserRole(List userRoleList); + + /** + * 删除用户和角色关联信息 + * + * @param userRole 用户和角色关联信息 + * @return 结果 + */ + public int deleteUserRoleInfo(SysUserRole userRole); + + /** + * 批量取消授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + public int deleteUserRoleInfos(@Param("roleId") Long roleId, @Param("userIds") Long[] userIds); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/MenuInSysService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/MenuInSysService.java new file mode 100644 index 0000000..18119e4 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/MenuInSysService.java @@ -0,0 +1,61 @@ +package net.hzvtc.system.service; + +import java.util.List; + +import net.hzvtc.system.domain.MenuInSys; + +/** + * 系统菜单Service接口 + * + * @author admin + * @date 2023-10-23 + */ +public interface MenuInSysService { + /** + * 查询系统菜单 + * + * @param id 系统菜单主键 + * @return 系统菜单 + */ + public MenuInSys selectMenuInSysById(Long id); + + /** + * 查询系统菜单列表 + * + * @param menuInSys 系统菜单 + * @return 系统菜单集合 + */ + public List selectMenuInSysList(MenuInSys menuInSys); + + /** + * 新增系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + public int insertMenuInSys(MenuInSys menuInSys); + + /** + * 修改系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + public int updateMenuInSys(MenuInSys menuInSys); + + /** + * 批量删除系统菜单 + * + * @param ids 需要删除的系统菜单主键集合 + * @return 结果 + */ + public int deleteMenuInSysByIds(Long[] ids); + + /** + * 删除系统菜单信息 + * + * @param id 系统菜单主键 + * @return 结果 + */ + public int deleteMenuInSysById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/MessageReadInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/MessageReadInfoService.java new file mode 100644 index 0000000..3c2a743 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/MessageReadInfoService.java @@ -0,0 +1,61 @@ +package net.hzvtc.system.service; + +import java.util.List; + +import net.hzvtc.system.domain.MessageReadInfo; + +/** + * 信息阅读情况Service接口 + * + * @author admin + * @date 2023-10-20 + */ +public interface MessageReadInfoService { + /** + * 查询信息阅读情况 + * + * @param id 信息阅读情况主键 + * @return 信息阅读情况 + */ + public MessageReadInfo selectMessageReadInfoById(Long id); + + /** + * 查询信息阅读情况列表 + * + * @param messageReadInfo 信息阅读情况 + * @return 信息阅读情况集合 + */ + public List selectMessageReadInfoList(MessageReadInfo messageReadInfo); + + /** + * 新增信息阅读情况 + * + * @param messageReadInfo 信息阅读情况 + * @return 结果 + */ + public int insertMessageReadInfo(MessageReadInfo messageReadInfo); + + /** + * 修改信息阅读情况 + * + * @param messageReadInfo 信息阅读情况 + * @return 结果 + */ + public int updateMessageReadInfo(MessageReadInfo messageReadInfo); + + /** + * 批量删除信息阅读情况 + * + * @param ids 需要删除的信息阅读情况主键集合 + * @return 结果 + */ + public int deleteMessageReadInfoByIds(Long[] ids); + + /** + * 删除信息阅读情况信息 + * + * @param id 信息阅读情况主键 + * @return 结果 + */ + public int deleteMessageReadInfoById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeFileInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeFileInfoService.java new file mode 100644 index 0000000..8c403e1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeFileInfoService.java @@ -0,0 +1,21 @@ +package net.hzvtc.system.service; + +import java.util.List; +import java.util.Map; +import net.hzvtc.system.domain.NoticeFileInfo; + +public interface NoticeFileInfoService { + public NoticeFileInfo selectNoticeFileInfoById(Long var1); + + public List selectNoticeFileInfoList(NoticeFileInfo var1); + + public int insertNoticeFileInfo(NoticeFileInfo var1); + + public int batchInsertNoticeFileInfo(List var1); + + public int deleteNoticeFileInfoNotInIds(Map var1); + + public int deleteNoticeFileInfoById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReadDeptService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReadDeptService.java new file mode 100644 index 0000000..ad2ee02 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReadDeptService.java @@ -0,0 +1,18 @@ +package net.hzvtc.system.service; + +import java.util.List; +import net.hzvtc.system.domain.NoticeReadDept; + +public interface NoticeReadDeptService { + public NoticeReadDept selectNoticeReadDeptById(Long var1); + + public List selectNoticeReadDeptList(NoticeReadDept var1); + + public int insertNoticeReadDept(NoticeReadDept var1); + + public int batchInsertNoticeReadDept(List var1); + + public int deleteNoticeReadDeptByNoticeId(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReaderService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReaderService.java new file mode 100644 index 0000000..b96e2a6 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/NoticeReaderService.java @@ -0,0 +1,39 @@ +package net.hzvtc.system.service; + +import net.hzvtc.system.domain.NoticeReader; + +import java.util.List; + +/** + * 公告阅读人员Service接口 + * + * @author admin + * @date 2022-05-02 + */ +public interface NoticeReaderService { + + /** + * 查询公告阅读人员列表 + * + * @param noticeId 公告阅读人员 + * @return 公告阅读人员集合 + */ + public List selectNoticeReaderListByPid(Long noticeId); + + /** + * 新增公告阅读人员 + * + * @param noticeReader 公告阅读人员 + * @return 结果 + */ + public int insertNoticeReader(NoticeReader noticeReader); + + + /** + * 删除公告阅读人员信息 + * + * @param id 公告阅读人员主键 + * @return 结果 + */ + public int deleteNoticeReaderById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysConfigService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysConfigService.java new file mode 100644 index 0000000..d928a44 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysConfigService.java @@ -0,0 +1,90 @@ +package net.hzvtc.system.service; + +import net.hzvtc.system.domain.SysConfig; + +import java.util.List; + +/** + * 参数配置 服务层 + * + * @author admin + */ +public interface SysConfigService { + /** + * 查询参数配置信息 + * + * @param configId 参数配置ID + * @return 参数配置信息 + */ + public SysConfig selectConfigById(Long configId); + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数键名 + * @return 参数键值 + */ + public String selectConfigByKey(String configKey); + + /** + * 获取验证码开关 + * + * @return true开启,false关闭 + */ + public boolean selectCaptchaOnOff(); + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + public List selectConfigList(SysConfig config); + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int insertConfig(SysConfig config); + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + public int updateConfig(SysConfig config); + + /** + * 批量删除参数信息 + * + * @param configIds 需要删除的参数ID + * @return 结果 + */ + public void deleteConfigByIds(Long[] configIds); + + /** + * 加载参数缓存数据 + */ + public void loadingConfigCache(); + + /** + * 清空参数缓存数据 + */ + public void clearConfigCache(); + + /** + * 重置参数缓存数据 + */ + public void resetConfigCache(); + + /** + * 校验参数键名是否唯一 + * + * @param config 参数信息 + * @return 结果 + */ + public String checkConfigKeyUnique(SysConfig config); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDeptService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDeptService.java new file mode 100644 index 0000000..7fa54ac --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDeptService.java @@ -0,0 +1,47 @@ +package net.hzvtc.system.service; + +import java.util.List; +import net.hzvtc.common.core.domain.TreeSelect; +import net.hzvtc.common.core.domain.entity.SysDept; + +public interface SysDeptService { + public List selectDeptList(SysDept var1); + + public List getDeptList(SysDept var1); + + public List buildDeptTree(List var1); + + public List getSysDeptListInIds(List var1); + + public void updateDeptAncestorPath(SysDept var1); + + public List buildDeptTreeSelect(List var1); + + public List buildDeptTreeSelectByIds(List var1); + + public List buildLazyDeptTreeSelect(Long var1); + + public List selectDeptListByRoleId(Long var1); + + public List getSysDeptFullPathByParam(Long var1); + + public SysDept selectDeptById(Long var1); + + public int selectNormalChildrenDeptById(Long var1); + + public boolean hasChildByDeptId(Long var1); + + public boolean checkDeptExistUser(Long var1); + + public String checkDeptNameUnique(SysDept var1); + + public void checkDeptDataScope(Long var1); + + public int insertDept(SysDept var1); + + public int updateDept(SysDept var1); + + public int deleteDeptById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictDataService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictDataService.java new file mode 100644 index 0000000..37c97c7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictDataService.java @@ -0,0 +1,61 @@ +package net.hzvtc.system.service; + +import net.hzvtc.common.core.domain.entity.SysDictData; + +import java.util.List; + +/** + * 字典 业务层 + * + * @author admin + */ +public interface SysDictDataService { + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + public List selectDictDataList(SysDictData dictData); + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + public String selectDictLabel(String dictType, String dictValue); + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + public SysDictData selectDictDataById(Long dictCode); + + /** + * 批量删除字典数据信息 + * + * @param dictCodes 需要删除的字典数据ID + * @return 结果 + */ + public void deleteDictDataByIds(Long[] dictCodes); + + /** + * 新增保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int insertDictData(SysDictData dictData); + + /** + * 修改保存字典数据信息 + * + * @param dictData 字典数据信息 + * @return 结果 + */ + public int updateDictData(SysDictData dictData); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictTypeService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictTypeService.java new file mode 100644 index 0000000..4077730 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysDictTypeService.java @@ -0,0 +1,99 @@ +package net.hzvtc.system.service; + +import net.hzvtc.common.core.domain.entity.SysDictData; +import net.hzvtc.common.core.domain.entity.SysDictType; + +import java.util.List; + +/** + * 字典 业务层 + * + * @author admin + */ +public interface SysDictTypeService { + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + public List selectDictTypeList(SysDictType dictType); + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + public List selectDictTypeAll(); + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + public List selectDictDataByType(String dictType); + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + public SysDictType selectDictTypeById(Long dictId); + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + public SysDictType selectDictTypeByType(String dictType); + + /** + * 批量删除字典信息 + * + * @param dictIds 需要删除的字典ID + * @return 结果 + */ + public void deleteDictTypeByIds(Long[] dictIds); + + /** + * 加载字典缓存数据 + */ + public void loadingDictCache(); + + /** + * 清空字典缓存数据 + */ + public void clearDictCache(); + + /** + * 重置字典缓存数据 + */ + public void resetDictCache(); + + /** + * 新增保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int insertDictType(SysDictType dictType); + + /** + * 修改保存字典类型信息 + * + * @param dictType 字典类型信息 + * @return 结果 + */ + public int updateDictType(SysDictType dictType); + + /** + * 校验字典类型称是否唯一 + * + * @param dictType 字典类型 + * @return 结果 + */ + public String checkDictTypeUnique(SysDictType dictType); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysLogininforService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysLogininforService.java new file mode 100644 index 0000000..6e5babc --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysLogininforService.java @@ -0,0 +1,40 @@ +package net.hzvtc.system.service; + +import net.hzvtc.system.domain.SysLogininfor; + +import java.util.List; + +/** + * 系统访问日志情况信息 服务层 + * + * @author admin + */ +public interface SysLogininforService { + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + public void insertLogininfor(SysLogininfor logininfor); + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + public List selectLogininforList(SysLogininfor logininfor); + + /** + * 批量删除系统登录日志 + * + * @param infoIds 需要删除的登录日志ID + * @return + */ + public int deleteLogininforByIds(Long[] infoIds); + + /** + * 清空系统登录日志 + */ + public void cleanLogininfor(); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysMenuService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysMenuService.java new file mode 100644 index 0000000..c8070ca --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysMenuService.java @@ -0,0 +1,136 @@ +package net.hzvtc.system.service; + +import net.hzvtc.common.core.domain.TreeSelect; +import net.hzvtc.common.core.domain.entity.SysMenu; +import net.hzvtc.system.domain.vo.RouterVo; + +import java.util.List; +import java.util.Set; + +/** + * 菜单 业务层 + * + * @author admin + */ +public interface SysMenuService { + /** + * 根据用户查询系统菜单列表 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuList(Long userId, Integer sysId); + + /** + * 根据用户查询系统菜单列表 + * + * @param menu 菜单信息 + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuList(SysMenu menu, Long userId); + + /** + * 根据用户ID查询权限 + * + * @param userId 用户ID + * @return 权限列表 + */ + public Set selectMenuPermsByUserId(Long userId); + + /** + * 根据用户ID查询菜单树信息 + * + * @param userId 用户ID + * @return 菜单列表 + */ + public List selectMenuTreeByUserId(Long userId, Integer sysId); + + /** + * 根据角色ID查询菜单树信息 + * + * @param roleId 角色ID + * @return 选中菜单列表 + */ + public List selectMenuListByRoleId(Long roleId); + + /** + * 构建前端路由所需要的菜单 + * + * @param menus 菜单列表 + * @return 路由列表 + */ + public List buildMenus(List menus); + + /** + * 构建前端所需要树结构 + * + * @param menus 菜单列表 + * @return 树结构列表 + */ + public List buildMenuTree(List menus); + + /** + * 构建前端所需要下拉树结构 + * + * @param menus 菜单列表 + * @return 下拉树结构列表 + */ + public List buildMenuTreeSelect(List menus); + + /** + * 根据菜单ID查询信息 + * + * @param menuId 菜单ID + * @return 菜单信息 + */ + public SysMenu selectMenuById(Long menuId); + + /** + * 是否存在菜单子节点 + * + * @param menuId 菜单ID + * @return 结果 true 存在 false 不存在 + */ + public boolean hasChildByMenuId(Long menuId); + + /** + * 查询菜单是否存在角色 + * + * @param menuId 菜单ID + * @return 结果 true 存在 false 不存在 + */ + public boolean checkMenuExistRole(Long menuId); + + /** + * 新增保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int insertMenu(SysMenu menu); + + /** + * 修改保存菜单信息 + * + * @param menu 菜单信息 + * @return 结果 + */ + public int updateMenu(SysMenu menu); + + /** + * 删除菜单管理信息 + * + * @param menuId 菜单ID + * @return 结果 + */ + public int deleteMenuById(Long menuId); + + /** + * 校验菜单名称是否唯一 + * + * @param menu 菜单信息 + * @return 结果 + */ + public String checkMenuNameUnique(SysMenu menu); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysNoticeService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysNoticeService.java new file mode 100644 index 0000000..578ac30 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysNoticeService.java @@ -0,0 +1,33 @@ +package net.hzvtc.system.service; + +import com.alibaba.fastjson.JSONArray; +import java.util.List; +import net.hzvtc.system.domain.SysNotice; +import net.hzvtc.system.domain.vo.DocStateCountVO; +import net.hzvtc.system.domain.vo.MessageVo; + +public interface SysNoticeService { + public SysNotice selectNoticeById(Long var1); + + public List selectNoticeList(SysNotice var1); + + public List getSysNoticeCountGroupByState(Long var1); + + public int insertNotice(SysNotice var1); + + public int updateNotice(SysNotice var1); + + public int deleteNoticeById(Long var1); + + public int deleteNoticeByIds(Long[] var1); + + public JSONArray getMessageCatalogueList(); + + public JSONArray getUnreadMessageCatalogueList(); + + public List getMessageInfoList(String var1); + + public SysNotice getNoticeForMobileById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysOperLogService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysOperLogService.java new file mode 100644 index 0000000..8199489 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysOperLogService.java @@ -0,0 +1,48 @@ +package net.hzvtc.system.service; + +import net.hzvtc.system.domain.SysOperLog; + +import java.util.List; + +/** + * 操作日志 服务层 + * + * @author admin + */ +public interface SysOperLogService { + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + public void insertOperlog(SysOperLog operLog); + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + public List selectOperLogList(SysOperLog operLog); + + /** + * 批量删除系统操作日志 + * + * @param operIds 需要删除的操作日志ID + * @return 结果 + */ + public int deleteOperLogByIds(Long[] operIds); + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + public SysOperLog selectOperLogById(Long operId); + + /** + * 清空操作日志 + */ + public void cleanOperLog(); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysPostService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysPostService.java new file mode 100644 index 0000000..3510702 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysPostService.java @@ -0,0 +1,100 @@ +package net.hzvtc.system.service; + +import net.hzvtc.system.domain.SysPost; + +import java.util.List; + +/** + * 岗位信息 服务层 + * + * @author admin + */ +public interface SysPostService { + /** + * 查询岗位信息集合 + * + * @param post 岗位信息 + * @return 岗位列表 + */ + public List selectPostList(SysPost post); + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + public List selectPostAll(); + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + public SysPost selectPostById(Long postId); + + /** + * 根据用户ID获取岗位选择框列表 + * + * @param userId 用户ID + * @return 选中岗位ID列表 + */ + public List selectPostListByUserId(Long userId); + + /** + * 校验岗位名称 + * + * @param post 岗位信息 + * @return 结果 + */ + public String checkPostNameUnique(SysPost post); + + /** + * 校验岗位编码 + * + * @param post 岗位信息 + * @return 结果 + */ + public String checkPostCodeUnique(SysPost post); + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + public int countUserPostById(Long postId); + + /** + * 删除岗位信息 + * + * @param postId 岗位ID + * @return 结果 + */ + public int deletePostById(Long postId); + + /** + * 批量删除岗位信息 + * + * @param postIds 需要删除的岗位ID + * @return 结果 + * @throws Exception 异常 + */ + public int deletePostByIds(Long[] postIds); + + /** + * 新增保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int insertPost(SysPost post); + + /** + * 修改保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + public int updatePost(SysPost post); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysRoleService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysRoleService.java new file mode 100644 index 0000000..697430c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysRoleService.java @@ -0,0 +1,53 @@ +package net.hzvtc.system.service; + +import java.util.List; +import java.util.Set; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.system.domain.SysUserRole; + +public interface SysRoleService { + public List selectRoleList(SysRole var1); + + public List selectRolesByUserId(SysRole var1); + + public Set selectRolePermissionByUserId(SysRole var1); + + public List selectRoleAll(SysRole var1); + + public List selectRoleListByUserId(Long var1); + + public SysRole selectRoleById(Long var1); + + public String checkRoleNameUnique(SysRole var1); + + public String checkRoleKeyUnique(SysRole var1); + + public void checkRoleAllowed(SysRole var1); + + public void checkRoleDataScope(Long var1); + + public int countUserRoleByRoleId(Long var1); + + public int insertRole(SysRole var1); + + public int updateRole(SysRole var1); + + public int updateRoleStatus(SysRole var1); + + public int authDataScope(SysRole var1); + + public int deleteRoleById(Long var1); + + public int deleteRoleByIds(Long[] var1); + + public int deleteAuthUser(SysUserRole var1); + + public int deleteAuthUsers(Long var1, Long[] var2); + + public int insertAuthUsers(Long var1, Long[] var2); + + public Set getAreaIdsByUserId(SysUser var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserOnlineService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserOnlineService.java new file mode 100644 index 0000000..3a184ef --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserOnlineService.java @@ -0,0 +1,47 @@ +package net.hzvtc.system.service; + +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.system.domain.SysUserOnline; + +/** + * 在线用户 服务层 + * + * @author admin + */ +public interface SysUserOnlineService { + /** + * 通过登录地址查询信息 + * + * @param ipaddr 登录地址 + * @param user 用户信息 + * @return 在线用户信息 + */ + public SysUserOnline selectOnlineByIpaddr(String ipaddr, LoginUser user); + + /** + * 通过用户名称查询信息 + * + * @param userName 用户名称 + * @param user 用户信息 + * @return 在线用户信息 + */ + public SysUserOnline selectOnlineByUserName(String userName, LoginUser user); + + /** + * 通过登录地址/用户名称查询信息 + * + * @param ipaddr 登录地址 + * @param userName 用户名称 + * @param user 用户信息 + * @return 在线用户信息 + */ + public SysUserOnline selectOnlineByInfo(String ipaddr, String userName, LoginUser user); + + /** + * 设置在线用户信息 + * + * @param user 用户信息 + * @return 在线用户 + */ + public SysUserOnline loginUserToUserOnline(LoginUser user); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserService.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserService.java new file mode 100644 index 0000000..a3ac599 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/SysUserService.java @@ -0,0 +1,60 @@ +package net.hzvtc.system.service; + +import java.util.List; +import net.hzvtc.common.core.domain.entity.SysUser; + +public interface SysUserService { + public List selectUserList(SysUser var1); + + public List selectAllocatedList(SysUser var1); + + public List selectUnallocatedList(SysUser var1); + + public SysUser selectUserByUserName(String var1); + + public SysUser selectUserById(SysUser var1); + + public String selectUserRoleGroup(String var1); + + public String selectUserPostGroup(String var1); + + public String checkUserNameUnique(String var1); + + public String checkPhoneUnique(SysUser var1); + + public String checkEmailUnique(SysUser var1); + + public void checkUserAllowed(SysUser var1); + + public void checkUserDataScope(Long var1); + + public int insertUser(SysUser var1); + + public void insertUserRole(SysUser var1); + + public boolean registerUser(SysUser var1); + + public int updateUser(SysUser var1); + + public void insertUserAuth(Long var1, Integer var2, Long[] var3); + + public int updateUserStatus(SysUser var1); + + public int updateUserProfile(SysUser var1); + + public boolean updateUserAvatar(String var1, String var2); + + public int resetPwd(SysUser var1); + + public int resetUserPwd(String var1, String var2); + + public int deleteUserById(Long var1, Integer var2); + + public int deleteUserByIds(Long[] var1); + + public String importUser(List var1, Boolean var2, String var3); + + public SysUser getUserInfoById(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MenuInSysServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MenuInSysServiceImpl.java new file mode 100644 index 0000000..728bd6e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MenuInSysServiceImpl.java @@ -0,0 +1,87 @@ +package net.hzvtc.system.service.impl; + +import java.util.List; +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import net.hzvtc.system.mapper.MenuInSysMapper; +import net.hzvtc.system.domain.MenuInSys; +import net.hzvtc.system.service.MenuInSysService; + +/** + * 系统菜单Service业务层处理 + * + * @author admin + * @date 2023-10-23 + */ +@Service +public class MenuInSysServiceImpl implements MenuInSysService { + @Resource + private MenuInSysMapper menuInSysMapper; + + /** + * 查询系统菜单 + * + * @param id 系统菜单主键 + * @return 系统菜单 + */ + @Override + public MenuInSys selectMenuInSysById(Long id) { + return menuInSysMapper.selectMenuInSysById(id); + } + + /** + * 查询系统菜单列表 + * + * @param menuInSys 系统菜单 + * @return 系统菜单 + */ + @Override + public List selectMenuInSysList(MenuInSys menuInSys) { + return menuInSysMapper.selectMenuInSysList(menuInSys); + } + + /** + * 新增系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + @Override + public int insertMenuInSys(MenuInSys menuInSys) { + return menuInSysMapper.insertMenuInSys(menuInSys); + } + + /** + * 修改系统菜单 + * + * @param menuInSys 系统菜单 + * @return 结果 + */ + @Override + public int updateMenuInSys(MenuInSys menuInSys) { + return menuInSysMapper.updateMenuInSys(menuInSys); + } + + /** + * 批量删除系统菜单 + * + * @param ids 需要删除的系统菜单主键 + * @return 结果 + */ + @Override + public int deleteMenuInSysByIds(Long[] ids) { + return menuInSysMapper.deleteMenuInSysByIds(ids); + } + + /** + * 删除系统菜单信息 + * + * @param id 系统菜单主键 + * @return 结果 + */ + @Override + public int deleteMenuInSysById(Long id) { + return menuInSysMapper.deleteMenuInSysById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MessageReadInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MessageReadInfoServiceImpl.java new file mode 100644 index 0000000..9a431ec --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/MessageReadInfoServiceImpl.java @@ -0,0 +1,94 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.system.domain.MessageReadInfo; +import net.hzvtc.system.mapper.MessageReadInfoMapper; +import net.hzvtc.system.service.MessageReadInfoService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 信息阅读情况Service业务层处理 + * + * @author admin + * @date 2023-10-20 + */ +@Service +public class MessageReadInfoServiceImpl implements MessageReadInfoService { + @Resource + private MessageReadInfoMapper messageReadInfoMapper; + + /** + * 查询信息阅读情况 + * + * @param id 信息阅读情况主键 + * @return 信息阅读情况 + */ + @Override + public MessageReadInfo selectMessageReadInfoById(Long id) { + return messageReadInfoMapper.selectMessageReadInfoById(id); + } + + /** + * 查询信息阅读情况列表 + * + * @param messageReadInfo 信息阅读情况 + * @return 信息阅读情况 + */ + @Override + public List selectMessageReadInfoList(MessageReadInfo messageReadInfo) { + return messageReadInfoMapper.selectMessageReadInfoList(messageReadInfo); + } + + /** + * 新增信息阅读情况 + * + * @param messageReadInfo 信息阅读情况 + * @return 结果 + */ + @Override + public int insertMessageReadInfo(MessageReadInfo messageReadInfo) { + messageReadInfo.setUserId(SecurityUtils.getUserId()); + List list = messageReadInfoMapper.selectMessageReadInfoListByParam(messageReadInfo); + if (list == null || list.isEmpty()) { + return messageReadInfoMapper.insertMessageReadInfo(messageReadInfo); + } else { + return 0; + } + } + + /** + * 修改信息阅读情况 + * + * @param messageReadInfo 信息阅读情况 + * @return 结果 + */ + @Override + public int updateMessageReadInfo(MessageReadInfo messageReadInfo) { + return messageReadInfoMapper.updateMessageReadInfo(messageReadInfo); + } + + /** + * 批量删除信息阅读情况 + * + * @param ids 需要删除的信息阅读情况主键 + * @return 结果 + */ + @Override + public int deleteMessageReadInfoByIds(Long[] ids) { + return messageReadInfoMapper.deleteMessageReadInfoByIds(ids); + } + + /** + * 删除信息阅读情况信息 + * + * @param id 信息阅读情况主键 + * @return 结果 + */ + @Override + public int deleteMessageReadInfoById(Long id) { + return messageReadInfoMapper.deleteMessageReadInfoById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeFileInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeFileInfoServiceImpl.java new file mode 100644 index 0000000..8b6862b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeFileInfoServiceImpl.java @@ -0,0 +1,83 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.system.domain.NoticeFileInfo; +import net.hzvtc.system.mapper.NoticeFileInfoMapper; +import net.hzvtc.system.service.NoticeFileInfoService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; +import java.util.Map; + +/** + * 通知公告附件Service业务层处理 + * + * @author admin + * @date 2022-05-02 + */ +@Service +public class NoticeFileInfoServiceImpl implements NoticeFileInfoService { + @Resource + private NoticeFileInfoMapper noticeFileInfoMapper; + + /** + * 查询通知公告附件 + * + * @param id 通知公告附件主键 + * @return 通知公告附件 + */ + @Override + public NoticeFileInfo selectNoticeFileInfoById(Long id) { + return noticeFileInfoMapper.selectNoticeFileInfoById(id); + } + + /** + * 查询通知公告附件列表 + * + * @param noticeFileInfo 通知公告附件 + * @return 通知公告附件 + */ + @Override + public List selectNoticeFileInfoList(NoticeFileInfo noticeFileInfo) { + return noticeFileInfoMapper.selectNoticeFileInfoList(noticeFileInfo); + } + + /** + * 新增通知公告附件 + * + * @param noticeFileInfo 通知公告附件 + * @return 结果 + */ + @Override + public int insertNoticeFileInfo(NoticeFileInfo noticeFileInfo) { + return noticeFileInfoMapper.insertNoticeFileInfo(noticeFileInfo); + } + + @Override + public int batchInsertNoticeFileInfo(List list) { + return noticeFileInfoMapper.batchInsertNoticeFileInfo(list); + } + + + /** + * 批量删除通知公告附件 + * + * @param map 需要删除的通知公告附件主键 + * @return 结果 + */ + @Override + public int deleteNoticeFileInfoNotInIds(Map map) { + return noticeFileInfoMapper.deleteNoticeFileInfoNotInIds(map); + } + + /** + * 删除通知公告附件信息 + * + * @param id 通知公告附件主键 + * @return 结果 + */ + @Override + public int deleteNoticeFileInfoById(Long id) { + return noticeFileInfoMapper.deleteNoticeFileInfoById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReadDeptServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReadDeptServiceImpl.java new file mode 100644 index 0000000..121d74e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReadDeptServiceImpl.java @@ -0,0 +1,70 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.system.domain.NoticeReadDept; +import net.hzvtc.system.mapper.NoticeReadDeptMapper; +import net.hzvtc.system.service.NoticeReadDeptService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 公告阅读范围Service业务层处理 + * + * @author admin + * @date 2022-05-02 + */ +@Service +public class NoticeReadDeptServiceImpl implements NoticeReadDeptService { + @Resource + private NoticeReadDeptMapper noticeReadDeptMapper; + + /** + * 查询公告阅读范围 + * + * @param id 公告阅读范围主键 + * @return 公告阅读范围 + */ + @Override + public NoticeReadDept selectNoticeReadDeptById(Long id) { + return noticeReadDeptMapper.selectNoticeReadDeptById(id); + } + + /** + * 查询公告阅读范围列表 + * + * @param noticeReadDept 公告阅读范围 + * @return 公告阅读范围 + */ + @Override + public List selectNoticeReadDeptList(NoticeReadDept noticeReadDept) { + return noticeReadDeptMapper.selectNoticeReadDeptList(noticeReadDept); + } + + /** + * 新增公告阅读范围 + * + * @param noticeReadDept 公告阅读范围 + * @return 结果 + */ + @Override + public int insertNoticeReadDept(NoticeReadDept noticeReadDept) { + return noticeReadDeptMapper.insertNoticeReadDept(noticeReadDept); + } + + @Override + public int batchInsertNoticeReadDept(List list) { + return noticeReadDeptMapper.batchInsertNoticeReadDept(list); + } + + /** + * 删除公告阅读范围信息 + * + * @param id 公告阅读范围主键 + * @return 结果 + */ + @Override + public int deleteNoticeReadDeptByNoticeId(Long id) { + return noticeReadDeptMapper.deleteNoticeReadDeptByNoticeId(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReaderServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReaderServiceImpl.java new file mode 100644 index 0000000..939d713 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/NoticeReaderServiceImpl.java @@ -0,0 +1,55 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.system.domain.NoticeReader; +import net.hzvtc.system.mapper.NoticeReaderMapper; +import net.hzvtc.system.service.NoticeReaderService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 公告阅读人员Service业务层处理 + * + * @author admin + * @date 2022-05-02 + */ +@Service +public class NoticeReaderServiceImpl implements NoticeReaderService { + @Resource + private NoticeReaderMapper noticeReaderMapper; + + + /** + * 查询公告阅读人员列表 + * + * @param noticeId 公告阅读人员 + * @return 公告阅读人员 + */ + @Override + public List selectNoticeReaderListByPid(Long noticeId) { + return noticeReaderMapper.selectNoticeReaderListByPid(noticeId); + } + + /** + * 新增公告阅读人员 + * + * @param noticeReader 公告阅读人员 + * @return 结果 + */ + @Override + public int insertNoticeReader(NoticeReader noticeReader) { + return noticeReaderMapper.insertNoticeReader(noticeReader); + } + + /** + * 删除公告阅读人员信息 + * + * @param id 公告阅读人员主键 + * @return 结果 + */ + @Override + public int deleteNoticeReaderById(Long id) { + return noticeReaderMapper.deleteNoticeReaderById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysConfigServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysConfigServiceImpl.java new file mode 100644 index 0000000..9667dd7 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysConfigServiceImpl.java @@ -0,0 +1,205 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.annotation.DataSource; +import net.hzvtc.common.constant.Constants; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.redis.RedisCache; +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.common.enums.DataSourceType; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.domain.SysConfig; +import net.hzvtc.system.mapper.SysConfigMapper; +import net.hzvtc.system.service.SysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Collection; +import java.util.List; + +/** + * 参数配置 服务层实现 + * + * @author admin + */ +@Service +public class SysConfigServiceImpl implements SysConfigService { + @Autowired + private SysConfigMapper configMapper; + + @Autowired + private RedisCache redisCache; + + /** + * 项目启动时,初始化参数到缓存 + */ + @PostConstruct + public void init() { + loadingConfigCache(); + } + + /** + * 查询参数配置信息 + * + * @param configId 参数配置ID + * @return 参数配置信息 + */ + @Override + @DataSource(DataSourceType.MASTER) + public SysConfig selectConfigById(Long configId) { + SysConfig config = new SysConfig(); + config.setConfigId(configId); + return configMapper.selectConfig(config); + } + + /** + * 根据键名查询参数配置信息 + * + * @param configKey 参数key + * @return 参数键值 + */ + @Override + public String selectConfigByKey(String configKey) { + String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey))); + if (StringUtils.isNotEmpty(configValue)) { + return configValue; + } + SysConfig config = new SysConfig(); + config.setConfigKey(configKey); + SysConfig retConfig = configMapper.selectConfig(config); + if (StringUtils.isNotNull(retConfig)) { + redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue()); + return retConfig.getConfigValue(); + } + return StringUtils.EMPTY; + } + + /** + * 获取验证码开关 + * + * @return true开启,false关闭 + */ + @Override + public boolean selectCaptchaOnOff() { + String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff"); + if (StringUtils.isEmpty(captchaOnOff)) { + return true; + } + return Convert.toBool(captchaOnOff); + } + + /** + * 查询参数配置列表 + * + * @param config 参数配置信息 + * @return 参数配置集合 + */ + @Override + public List selectConfigList(SysConfig config) { + return configMapper.selectConfigList(config); + } + + /** + * 新增参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public int insertConfig(SysConfig config) { + int row = configMapper.insertConfig(config); + if (row > 0) { + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + } + return row; + } + + /** + * 修改参数配置 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public int updateConfig(SysConfig config) { + int row = configMapper.updateConfig(config); + if (row > 0) { + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + } + return row; + } + + /** + * 批量删除参数信息 + * + * @param configIds 需要删除的参数ID + * @return 结果 + */ + @Override + public void deleteConfigByIds(Long[] configIds) { + for (Long configId : configIds) { + SysConfig config = selectConfigById(configId); + if (StringUtils.equals(UserConstants.YES, config.getConfigType())) { + throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", config.getConfigKey())); + } + configMapper.deleteConfigById(configId); + redisCache.deleteObject(getCacheKey(config.getConfigKey())); + } + } + + /** + * 加载参数缓存数据 + */ + @Override + public void loadingConfigCache() { + List configsList = configMapper.selectConfigList(new SysConfig()); + for (SysConfig config : configsList) { + redisCache.setCacheObject(getCacheKey(config.getConfigKey()), config.getConfigValue()); + } + } + + /** + * 清空参数缓存数据 + */ + @Override + public void clearConfigCache() { + Collection keys = redisCache.keys(Constants.SYS_CONFIG_KEY + "*"); + redisCache.deleteObject(keys); + } + + /** + * 重置参数缓存数据 + */ + @Override + public void resetConfigCache() { + clearConfigCache(); + loadingConfigCache(); + } + + /** + * 校验参数键名是否唯一 + * + * @param config 参数配置信息 + * @return 结果 + */ + @Override + public String checkConfigKeyUnique(SysConfig config) { + Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); + SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); + if (StringUtils.isNotNull(info) && info.getConfigId().longValue() != configId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 设置cache key + * + * @param configKey 参数键 + * @return 缓存键key + */ + private String getCacheKey(String configKey) { + return Constants.SYS_CONFIG_KEY + configKey; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDeptServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDeptServiceImpl.java new file mode 100644 index 0000000..e70a43a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDeptServiceImpl.java @@ -0,0 +1,279 @@ +package net.hzvtc.system.service.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.common.annotation.DataScope; +import net.hzvtc.common.core.domain.TreeSelect; +import net.hzvtc.common.core.domain.entity.SysDept; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.core.text.Convert; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.Chinese2pinyin; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.system.mapper.SysDeptMapper; +import net.hzvtc.system.mapper.SysRoleMapper; +import net.hzvtc.system.service.SysDeptService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class SysDeptServiceImpl +implements SysDeptService { + private static final Logger log = LoggerFactory.getLogger(SysDeptServiceImpl.class); + @Resource + private SysDeptMapper deptMapper; + @Resource + private SysRoleMapper roleMapper; + + @Override + @DataScope(deptAlias="d") + public List selectDeptList(SysDept dept) { + List list = this.deptMapper.selectDeptList(dept); + return list; + } + + @Override + public List getDeptList(SysDept dept) { + return this.deptMapper.selectDeptList(dept); + } + + @Override + public List buildDeptTree(List depts) { + List returnList = new ArrayList(); + ArrayList tempList = new ArrayList(); + for (SysDept dept : depts) { + tempList.add(dept.getDeptId()); + } + for (SysDept dept : depts) { + if (tempList.contains(dept.getParentId())) continue; + this.recursionFn(depts, dept); + returnList.add(dept); + } + if (returnList.isEmpty()) { + returnList = depts; + } + return returnList; + } + + @Override + public List getSysDeptListInIds(List list) { + return this.deptMapper.getSysDeptListInIds(list); + } + + @Override + public void updateDeptAncestorPath(SysDept sysDept) { + List list = this.deptMapper.selectDeptList(sysDept); + list.forEach(item -> { + List ids; + List depts; + String str = item.getAncestors(); + if (str != null && !str.isEmpty() && (depts = this.deptMapper.getSysDeptListInIds(ids = Arrays.stream(str.split(",")).map(id -> Long.parseLong(id)).collect(Collectors.toList()))) != null && depts.size() > 0) { + String fullpath = depts.stream().map(data -> data.getDeptName()).collect(Collectors.joining(",")); + item.setAncestorPath(fullpath); + this.deptMapper.updateSysdeptAncestorPath((SysDept)item); + } + }); + } + + @Override + public List buildDeptTreeSelect(List depts) { + List deptTrees = this.buildDeptTree(depts); + return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList()); + } + + @Override + public List buildDeptTreeSelectByIds(List ids) { + List list = this.deptMapper.getSysDeptListInIds(ids); + list.stream().forEach(item -> { + String str = item.getAncestors(); + if (str != null) { + String[] arr; + for (String id : arr = str.split(",")) { + ids.add(Long.parseLong(id)); + } + } + }); + list = this.deptMapper.getSysDeptListInIds(ids); + List deptTrees = this.buildDeptTree(list); + return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList()); + } + + @Override + public List buildLazyDeptTreeSelect(Long parentId) { + if (parentId == null) { + parentId = 0L; + } + ArrayList treeSelects = new ArrayList(); + List deptList = this.deptMapper.getSysDeptListByParentId(parentId); + deptList.stream().forEach(item -> { + TreeSelect node = new TreeSelect(); + node.setId(item.getDeptId()); + node.setLabel(item.getDeptName()); + node.setFullName(item.getFullName()); + node.setAncestor(item.getAncestors()); + if (item.getAncestorPath() == null || item.getAncestorPath().isEmpty()) { + node.setFullPathName(item.getDeptName()); + } else { + node.setFullPathName(item.getAncestorPath().replaceAll(",", "->") + "->" + item.getDeptName()); + } + if (item.getChildren() == null || item.getChildren().size() == 0) { + node.setLeaf(true); + } else { + node.setLeaf(false); + } + treeSelects.add(node); + }); + return treeSelects; + } + + @Override + public List selectDeptListByRoleId(Long roleId) { + SysRole role = this.roleMapper.selectRoleById(roleId); + return this.deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly()); + } + + @Override + public List getSysDeptFullPathByParam(Long deptId) { + return this.deptMapper.getSysDeptFullPathByParam(deptId); + } + + @Override + public SysDept selectDeptById(Long deptId) { + return this.deptMapper.selectDeptById(deptId); + } + + @Override + public int selectNormalChildrenDeptById(Long deptId) { + return this.deptMapper.selectNormalChildrenDeptById(deptId); + } + + @Override + public boolean hasChildByDeptId(Long deptId) { + int result = this.deptMapper.hasChildByDeptId(deptId); + return result > 0; + } + + @Override + public boolean checkDeptExistUser(Long deptId) { + int result = this.deptMapper.checkDeptExistUser(deptId); + return result > 0; + } + + @Override + public String checkDeptNameUnique(SysDept dept) { + Long deptId = StringUtils.isNull((Object)dept.getDeptId()) ? -1L : dept.getDeptId(); + SysDept info = this.deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); + if (StringUtils.isNotNull((Object)info) && info.getDeptId().longValue() != deptId.longValue()) { + return "1"; + } + return "0"; + } + + @Override + public void checkDeptDataScope(Long deptId) { + if (!SysUser.isAdmin((Long)SecurityUtils.getUserId())) { + SysDept dept = new SysDept(); + dept.setDeptId(deptId); + List depts = ((SysDeptServiceImpl)SpringUtils.getAopProxy((Object)this)).selectDeptList(dept); + if (StringUtils.isEmpty(depts)) { + throw new ServiceException("\u6ca1\u6709\u6743\u9650\u8bbf\u95ee\u90e8\u95e8\u6570\u636e\uff01"); + } + } + } + + @Override + public int insertDept(SysDept dept) { + SysDept info; + if (dept.getDeptName() != null) { + Map map = Chinese2pinyin.changeChinese2Pinyin((String)dept.getDeptName()); + dept.setFullPinyin((String)map.get("fullPinyin")); + dept.setSimplePinyin((String)map.get("simplePinyin")); + } + if (!"0".equals((info = this.deptMapper.selectDeptById(dept.getParentId())).getStatus())) { + throw new ServiceException("\u90e8\u95e8\u505c\u7528\uff0c\u4e0d\u5141\u8bb8\u65b0\u589e"); + } + String ancestors = info.getAncestors() + "," + dept.getParentId(); + String ancestorPath = info.getAncestorPath() + "," + dept.getDeptName(); + dept.setAncestors(ancestors); + dept.setAncestorPath(ancestorPath); + dept.setDeptLevel(ancestors.split(",").length); + return this.deptMapper.insertDept(dept); + } + + @Override + public int updateDept(SysDept dept) { + SysDept newParentDept = this.deptMapper.selectDeptById(dept.getParentId()); + if (dept.getDeptName() != null) { + Map map = Chinese2pinyin.changeChinese2Pinyin((String)dept.getDeptName()); + dept.setFullPinyin((String)map.get("fullPinyin")); + dept.setSimplePinyin((String)map.get("simplePinyin")); + } + SysDept oldDept = this.deptMapper.selectDeptById(dept.getDeptId()); + if (StringUtils.isNotNull((Object)newParentDept) && StringUtils.isNotNull((Object)oldDept)) { + String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId(); + String oldAncestors = oldDept.getAncestors(); + dept.setAncestors(newAncestors); + this.updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors); + } + int result = this.deptMapper.updateDept(dept); + if ("0".equals(dept.getStatus()) && StringUtils.isNotEmpty((String)dept.getAncestors()) && !StringUtils.equals((CharSequence)"0", (CharSequence)dept.getAncestors())) { + this.updateParentDeptStatusNormal(dept); + } + return result; + } + + private void updateParentDeptStatusNormal(SysDept dept) { + String ancestors = dept.getAncestors(); + Long[] deptIds = Convert.toLongArray((String)ancestors); + this.deptMapper.updateDeptStatusNormal(deptIds); + } + + public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) { + List children = this.deptMapper.selectChildrenDeptById(deptId); + for (SysDept child : children) { + String ancestors = child.getAncestors().replaceFirst(oldAncestors, newAncestors); + child.setAncestors(ancestors); + child.setDeptLevel(ancestors.split(",").length); + } + if (children.size() > 0) { + this.deptMapper.updateDeptChildren(children); + } + } + + @Override + public int deleteDeptById(Long deptId) { + return this.deptMapper.deleteDeptById(deptId); + } + + private void recursionFn(List list, SysDept t) { + List childList = this.getChildList(list, t); + t.setChildren(childList); + for (SysDept tChild : childList) { + if (!this.hasChild(list, tChild)) continue; + this.recursionFn(list, tChild); + } + } + + private List getChildList(List list, SysDept t) { + ArrayList tlist = new ArrayList(); + for (SysDept n : list) { + if (!StringUtils.isNotNull((Object)n.getParentId()) || n.getParentId().longValue() != t.getDeptId().longValue()) continue; + tlist.add(n); + } + return tlist; + } + + private boolean hasChild(List list, SysDept t) { + return this.getChildList(list, t).size() > 0; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictDataServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictDataServiceImpl.java new file mode 100644 index 0000000..75fcfc1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictDataServiceImpl.java @@ -0,0 +1,103 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.core.domain.entity.SysDictData; +import net.hzvtc.common.utils.DictUtils; +import net.hzvtc.system.mapper.SysDictDataMapper; +import net.hzvtc.system.service.SysDictDataService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 字典 业务层处理 + * + * @author admin + */ +@Service +public class SysDictDataServiceImpl implements SysDictDataService { + @Autowired + private SysDictDataMapper dictDataMapper; + + /** + * 根据条件分页查询字典数据 + * + * @param dictData 字典数据信息 + * @return 字典数据集合信息 + */ + @Override + public List selectDictDataList(SysDictData dictData) { + return dictDataMapper.selectDictDataList(dictData); + } + + /** + * 根据字典类型和字典键值查询字典数据信息 + * + * @param dictType 字典类型 + * @param dictValue 字典键值 + * @return 字典标签 + */ + @Override + public String selectDictLabel(String dictType, String dictValue) { + return dictDataMapper.selectDictLabel(dictType, dictValue); + } + + /** + * 根据字典数据ID查询信息 + * + * @param dictCode 字典数据ID + * @return 字典数据 + */ + @Override + public SysDictData selectDictDataById(Long dictCode) { + return dictDataMapper.selectDictDataById(dictCode); + } + + /** + * 批量删除字典数据信息 + * + * @param dictCodes 需要删除的字典数据ID + * @return 结果 + */ + @Override + public void deleteDictDataByIds(Long[] dictCodes) { + for (Long dictCode : dictCodes) { + SysDictData data = selectDictDataById(dictCode); + dictDataMapper.deleteDictDataById(dictCode); + List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); + DictUtils.setDictCache(data.getDictType(), dictDatas); + } + } + + /** + * 新增保存字典数据信息 + * + * @param data 字典数据信息 + * @return 结果 + */ + @Override + public int insertDictData(SysDictData data) { + int row = dictDataMapper.insertDictData(data); + if (row > 0) { + List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); + DictUtils.setDictCache(data.getDictType(), dictDatas); + } + return row; + } + + /** + * 修改保存字典数据信息 + * + * @param data 字典数据信息 + * @return 结果 + */ + @Override + public int updateDictData(SysDictData data) { + int row = dictDataMapper.updateDictData(data); + if (row > 0) { + List dictDatas = dictDataMapper.selectDictDataByType(data.getDictType()); + DictUtils.setDictCache(data.getDictType(), dictDatas); + } + return row; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictTypeServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictTypeServiceImpl.java new file mode 100644 index 0000000..4649079 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysDictTypeServiceImpl.java @@ -0,0 +1,203 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.domain.entity.SysDictData; +import net.hzvtc.common.core.domain.entity.SysDictType; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.DictUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.mapper.SysDictDataMapper; +import net.hzvtc.system.mapper.SysDictTypeMapper; +import net.hzvtc.system.service.SysDictTypeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 字典 业务层处理 + * + * @author admin + */ +@Service +public class SysDictTypeServiceImpl implements SysDictTypeService { + @Autowired + private SysDictTypeMapper dictTypeMapper; + + @Autowired + private SysDictDataMapper dictDataMapper; + + /** + * 项目启动时,初始化字典到缓存 + */ + @PostConstruct + public void init() { + loadingDictCache(); + } + + /** + * 根据条件分页查询字典类型 + * + * @param dictType 字典类型信息 + * @return 字典类型集合信息 + */ + @Override + public List selectDictTypeList(SysDictType dictType) { + return dictTypeMapper.selectDictTypeList(dictType); + } + + /** + * 根据所有字典类型 + * + * @return 字典类型集合信息 + */ + @Override + public List selectDictTypeAll() { + return dictTypeMapper.selectDictTypeAll(); + } + + /** + * 根据字典类型查询字典数据 + * + * @param dictType 字典类型 + * @return 字典数据集合信息 + */ + @Override + public List selectDictDataByType(String dictType) { + List dictDatas = DictUtils.getDictCache(dictType); + if (StringUtils.isNotEmpty(dictDatas)) { + return dictDatas; + } + dictDatas = dictDataMapper.selectDictDataByType(dictType); + if (StringUtils.isNotEmpty(dictDatas)) { + DictUtils.setDictCache(dictType, dictDatas); + return dictDatas; + } + return null; + } + + /** + * 根据字典类型ID查询信息 + * + * @param dictId 字典类型ID + * @return 字典类型 + */ + @Override + public SysDictType selectDictTypeById(Long dictId) { + return dictTypeMapper.selectDictTypeById(dictId); + } + + /** + * 根据字典类型查询信息 + * + * @param dictType 字典类型 + * @return 字典类型 + */ + @Override + public SysDictType selectDictTypeByType(String dictType) { + return dictTypeMapper.selectDictTypeByType(dictType); + } + + /** + * 批量删除字典类型信息 + * + * @param dictIds 需要删除的字典ID + * @return 结果 + */ + @Override + public void deleteDictTypeByIds(Long[] dictIds) { + for (Long dictId : dictIds) { + SysDictType dictType = selectDictTypeById(dictId); + if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0) { + throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName())); + } + dictTypeMapper.deleteDictTypeById(dictId); + DictUtils.removeDictCache(dictType.getDictType()); + } + } + + /** + * 加载字典缓存数据 + */ + @Override + public void loadingDictCache() { + SysDictData dictData = new SysDictData(); + dictData.setStatus("0"); + Map> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType)); + for (Map.Entry> entry : dictDataMap.entrySet()) { + DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList())); + } + } + + /** + * 清空字典缓存数据 + */ + @Override + public void clearDictCache() { + DictUtils.clearDictCache(); + } + + /** + * 重置字典缓存数据 + */ + @Override + public void resetDictCache() { + clearDictCache(); + loadingDictCache(); + } + + /** + * 新增保存字典类型信息 + * + * @param dict 字典类型信息 + * @return 结果 + */ + @Override + public int insertDictType(SysDictType dict) { + int row = dictTypeMapper.insertDictType(dict); + if (row > 0) { + DictUtils.setDictCache(dict.getDictType(), null); + } + return row; + } + + /** + * 修改保存字典类型信息 + * + * @param dict 字典类型信息 + * @return 结果 + */ + @Override + @Transactional + public int updateDictType(SysDictType dict) { + SysDictType oldDict = dictTypeMapper.selectDictTypeById(dict.getDictId()); + dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType()); + int row = dictTypeMapper.updateDictType(dict); + if (row > 0) { + List dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType()); + DictUtils.setDictCache(dict.getDictType(), dictDatas); + } + return row; + } + + /** + * 校验字典类型称是否唯一 + * + * @param dict 字典类型 + * @return 结果 + */ + @Override + public String checkDictTypeUnique(SysDictType dict) { + Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); + SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); + if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysLogininforServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysLogininforServiceImpl.java new file mode 100644 index 0000000..3865096 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysLogininforServiceImpl.java @@ -0,0 +1,61 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.system.domain.SysLogininfor; +import net.hzvtc.system.mapper.SysLogininforMapper; +import net.hzvtc.system.service.SysLogininforService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 系统访问日志情况信息 服务层处理 + * + * @author admin + */ +@Service +public class SysLogininforServiceImpl implements SysLogininforService { + + @Autowired + private SysLogininforMapper logininforMapper; + + /** + * 新增系统登录日志 + * + * @param logininfor 访问日志对象 + */ + @Override + public void insertLogininfor(SysLogininfor logininfor) { + logininforMapper.insertLogininfor(logininfor); + } + + /** + * 查询系统登录日志集合 + * + * @param logininfor 访问日志对象 + * @return 登录记录集合 + */ + @Override + public List selectLogininforList(SysLogininfor logininfor) { + return logininforMapper.selectLogininforList(logininfor); + } + + /** + * 批量删除系统登录日志 + * + * @param infoIds 需要删除的登录日志ID + * @return + */ + @Override + public int deleteLogininforByIds(Long[] infoIds) { + return logininforMapper.deleteLogininforByIds(infoIds); + } + + /** + * 清空系统登录日志 + */ + @Override + public void cleanLogininfor() { + logininforMapper.cleanLogininfor(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysMenuServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysMenuServiceImpl.java new file mode 100644 index 0000000..3bb4bbd --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysMenuServiceImpl.java @@ -0,0 +1,306 @@ +package net.hzvtc.system.service.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.common.core.domain.TreeSelect; +import net.hzvtc.common.core.domain.entity.SysMenu; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.domain.MenuInSys; +import net.hzvtc.system.domain.vo.MetaVo; +import net.hzvtc.system.domain.vo.RouterVo; +import net.hzvtc.system.mapper.SysMenuMapper; +import net.hzvtc.system.mapper.SysRoleMapper; +import net.hzvtc.system.mapper.SysRoleMenuMapper; +import net.hzvtc.system.service.MenuInSysService; +import net.hzvtc.system.service.SysMenuService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SysMenuServiceImpl +implements SysMenuService { + private static final Logger log = LoggerFactory.getLogger(SysMenuServiceImpl.class); + public static final String PREMISSION_STRING = "perms[\"{0}\"]"; + @Resource + private SysMenuMapper menuMapper; + @Resource + private SysRoleMapper roleMapper; + @Resource + private SysRoleMenuMapper roleMenuMapper; + @Autowired + private MenuInSysService menuInSysService; + + @Override + public List selectMenuList(Long userId, Integer sysId) { + SysMenu sysMenu = new SysMenu(); + sysMenu.setSysId(sysId); + return this.selectMenuList(sysMenu, userId); + } + + @Override + public List selectMenuList(SysMenu menu, Long userId) { + if (menu.getSysId() == null) { + menu.setSysId(Integer.valueOf(1)); + } + List menuList = null; + if (SysUser.isAdmin((Long)userId)) { + menuList = this.menuMapper.selectMenuList(menu); + } else { + menu.getParams().put("userId", userId); + menuList = this.menuMapper.selectMenuListByUserId(menu); + } + return menuList; + } + + @Override + public Set selectMenuPermsByUserId(Long userId) { + List perms = this.menuMapper.selectMenuPermsByUserId(userId); + HashSet permsSet = new HashSet(); + for (String perm : perms) { + if (!StringUtils.isNotEmpty((String)perm)) continue; + permsSet.addAll(Arrays.asList(perm.trim().split(","))); + } + return permsSet; + } + + @Override + public List selectMenuTreeByUserId(Long userId, Integer sysId) { + List menus = null; + if (SecurityUtils.isAdmin((Long)userId)) { + menus = this.menuMapper.selectMenuTreeAll(sysId); + } else { + HashMap map = new HashMap(); + map.put("userId", userId); + map.put("sysId", sysId); + menus = this.menuMapper.selectMenuTreeByUserId(map); + } + return this.getChildPerms(menus, 0); + } + + @Override + public List selectMenuListByRoleId(Long roleId) { + SysRole role = this.roleMapper.selectRoleById(roleId); + return this.menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly()); + } + + @Override + public List buildMenus(List menus) { + LinkedList routers = new LinkedList(); + for (SysMenu menu : menus) { + RouterVo children; + ArrayList childrenList; + RouterVo router = new RouterVo(); + router.setHidden("1".equals(menu.getVisible())); + router.setName(this.getRouteName(menu)); + router.setPath(this.getRouterPath(menu)); + router.setComponent(this.getComponent(menu)); + router.setQuery(menu.getQuery()); + router.setShowMenu(menu.getIsShow() == 0); + router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals((CharSequence)"1", (CharSequence)menu.getIsCache()), menu.getPath())); + List cMenus = menu.getChildren(); + if (!cMenus.isEmpty() && cMenus.size() > 0 && "M".equals(menu.getMenuType())) { + router.setAlwaysShow(true); + router.setRedirect("noRedirect"); + router.setChildren(this.buildMenus(cMenus)); + } else if (this.isMenuFrame(menu)) { + router.setMeta(null); + childrenList = new ArrayList(); + children = new RouterVo(); + children.setPath(menu.getPath()); + children.setComponent(menu.getComponent()); + children.setName(StringUtils.capitalize((String)menu.getPath())); + children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals((CharSequence)"1", (CharSequence)menu.getIsCache()), menu.getPath())); + children.setQuery(menu.getQuery()); + childrenList.add(children); + router.setChildren(childrenList); + } else if (menu.getParentId().intValue() == 0 && this.isInnerLink(menu)) { + router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon())); + router.setPath("/inner"); + childrenList = new ArrayList(); + children = new RouterVo(); + String routerPath = this.innerLinkReplaceEach(menu.getPath()); + children.setPath(routerPath); + children.setComponent("InnerLink"); + children.setName(StringUtils.capitalize((String)routerPath)); + children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath())); + childrenList.add(children); + router.setChildren(childrenList); + } + routers.add(router); + } + return routers; + } + + @Override + public List buildMenuTree(List menus) { + List returnList = new ArrayList(); + ArrayList tempList = new ArrayList(); + for (SysMenu dept : menus) { + tempList.add(dept.getMenuId()); + } + for (SysMenu menu : menus) { + if (tempList.contains(menu.getParentId())) continue; + this.recursionFn(menus, menu); + returnList.add(menu); + } + if (returnList.isEmpty()) { + returnList = menus; + } + return returnList; + } + + @Override + public List buildMenuTreeSelect(List menus) { + List menuTrees = this.buildMenuTree(menus); + return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList()); + } + + @Override + public SysMenu selectMenuById(Long menuId) { + return this.menuMapper.selectMenuById(menuId); + } + + @Override + public boolean hasChildByMenuId(Long menuId) { + int result = this.menuMapper.hasChildByMenuId(menuId); + return result > 0; + } + + @Override + public boolean checkMenuExistRole(Long menuId) { + int result = this.roleMenuMapper.checkMenuExistRole(menuId); + return result > 0; + } + + @Override + @Transactional + public int insertMenu(SysMenu menu) { + this.menuMapper.insertMenu(menu); + if (!menu.getMenuType().equals("F")) { + MenuInSys data = new MenuInSys(); + data.setSysId(menu.getSysId()); + data.setMenuId(menu.getMenuId()); + data.setParentId(menu.getParentId()); + data.setOrderNum(menu.getOrderNum()); + data.setIsDeleted(0); + this.menuInSysService.insertMenuInSys(data); + } + return 1; + } + + @Override + public int updateMenu(SysMenu menu) { + return this.menuMapper.updateMenu(menu); + } + + @Override + public int deleteMenuById(Long menuId) { + return this.menuMapper.deleteMenuById(menuId); + } + + @Override + public String checkMenuNameUnique(SysMenu menu) { + Long menuId = StringUtils.isNull((Object)menu.getMenuId()) ? -1L : menu.getMenuId(); + SysMenu info = this.menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); + if (StringUtils.isNotNull((Object)info) && info.getMenuId().longValue() != menuId.longValue()) { + return "1"; + } + return "0"; + } + + public String getRouteName(SysMenu menu) { + String routerName = StringUtils.capitalize((String)menu.getPath()); + if (this.isMenuFrame(menu)) { + routerName = ""; + } + return routerName; + } + + public String getRouterPath(SysMenu menu) { + String routerPath = menu.getPath(); + if (menu.getParentId().intValue() != 0 && this.isInnerLink(menu)) { + routerPath = this.innerLinkReplaceEach(routerPath); + } + if (0 == menu.getParentId().intValue() && "M".equals(menu.getMenuType()) && "1".equals(menu.getIsFrame())) { + routerPath = "/" + menu.getPath(); + } else if (this.isMenuFrame(menu)) { + routerPath = "/"; + } + return routerPath; + } + + public String getComponent(SysMenu menu) { + String component = "Layout"; + if (StringUtils.isNotEmpty((String)menu.getComponent()) && !this.isMenuFrame(menu)) { + component = menu.getComponent(); + } else if (StringUtils.isEmpty((String)menu.getComponent()) && menu.getParentId().intValue() != 0 && this.isInnerLink(menu)) { + component = "InnerLink"; + } else if (StringUtils.isEmpty((String)menu.getComponent()) && this.isParentView(menu)) { + component = "ParentView"; + } + return component; + } + + public boolean isMenuFrame(SysMenu menu) { + return menu.getParentId().intValue() == 0 && "C".equals(menu.getMenuType()) && menu.getIsFrame().equals("1"); + } + + public boolean isInnerLink(SysMenu menu) { + return menu.getIsFrame().equals("1") && StringUtils.ishttp((String)menu.getPath()); + } + + public boolean isParentView(SysMenu menu) { + return menu.getParentId().intValue() != 0 && "M".equals(menu.getMenuType()); + } + + public List getChildPerms(List list, int parentId) { + ArrayList returnList = new ArrayList(); + for (SysMenu t : list) { + if (t.getParentId() != (long)parentId) continue; + this.recursionFn(list, t); + returnList.add(t); + } + return returnList; + } + + private void recursionFn(List list, SysMenu t) { + List childList = this.getChildList(list, t); + t.setChildren(childList); + for (SysMenu tChild : childList) { + if (!this.hasChild(list, tChild)) continue; + this.recursionFn(list, tChild); + } + } + + private List getChildList(List list, SysMenu t) { + ArrayList tlist = new ArrayList(); + for (SysMenu n : list) { + if (n.getParentId().longValue() != t.getMenuId().longValue()) continue; + tlist.add(n); + } + return tlist; + } + + private boolean hasChild(List list, SysMenu t) { + return this.getChildList(list, t).size() > 0; + } + + public String innerLinkReplaceEach(String path) { + return StringUtils.replaceEach((String)path, (String[])new String[]{"http://", "https://"}, (String[])new String[]{"", ""}); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysNoticeServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysNoticeServiceImpl.java new file mode 100644 index 0000000..55dc7c1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysNoticeServiceImpl.java @@ -0,0 +1,213 @@ +package net.hzvtc.system.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.SpeciesAbnormalInfo; +import net.hzvtc.area.service.SpeciesAbnormalInfoService; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.system.domain.NoticeFileInfo; +import net.hzvtc.system.domain.NoticeReadDept; +import net.hzvtc.system.domain.SysNotice; +import net.hzvtc.system.domain.vo.DocStateCountVO; +import net.hzvtc.system.domain.vo.MessageVo; +import net.hzvtc.system.mapper.SysNoticeMapper; +import net.hzvtc.system.service.NoticeFileInfoService; +import net.hzvtc.system.service.NoticeReadDeptService; +import net.hzvtc.system.service.SysNoticeService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SysNoticeServiceImpl +implements SysNoticeService { + private static final Logger log = LoggerFactory.getLogger(SysNoticeServiceImpl.class); + @Resource + private SysNoticeMapper noticeMapper; + private NoticeReadDeptService noticeReadDeptService; + private NoticeFileInfoService noticeFileInfoService; + private SpeciesAbnormalInfoService speciesAbnormalInfoService; + + @Autowired + public void setSpeciesAbnormalInfoService(SpeciesAbnormalInfoService speciesAbnormalInfoService) { + this.speciesAbnormalInfoService = speciesAbnormalInfoService; + } + + @Autowired + public void setNoticeFileInfoService(NoticeFileInfoService noticeFileInfoService) { + this.noticeFileInfoService = noticeFileInfoService; + } + + @Autowired + public void setNoticeReadDeptService(NoticeReadDeptService noticeReadDeptService) { + this.noticeReadDeptService = noticeReadDeptService; + } + + @Override + public SysNotice selectNoticeById(Long noticeId) { + return this.noticeMapper.selectNoticeById(noticeId); + } + + @Override + public List selectNoticeList(SysNotice notice) { + if (notice == null) { + notice = new SysNotice(); + } + if (notice.getCreateDept() == null) { + notice.setCreateDept(SecurityUtils.getDeptId()); + } + if (notice.getStatus() == null) { + notice.setStatus(1); + } + return this.noticeMapper.selectNoticeList(notice); + } + + @Override + public List getSysNoticeCountGroupByState(Long deptId) { + return this.noticeMapper.getSysNoticeCountGroupByState(deptId); + } + + @Override + @Transactional + public int insertNotice(SysNotice notice) { + notice.setIsDeleted(0); + notice.setCreateTime(DateUtils.getNowDate()); + notice.setCreateDept(SecurityUtils.getLoginUser().getDeptId()); + this.noticeMapper.insertNotice(notice); + this.saveReadDept(notice.getDeptIds(), notice.getNoticeId()); + this.saveFileList(notice.getFileInfoList(), notice.getNoticeId()); + return 1; + } + + private void saveFileList(List files, Long id) { + if (files != null && files.size() > 0) { + files.stream().forEach(item -> item.setNoticeId(id)); + this.noticeFileInfoService.batchInsertNoticeFileInfo(files); + } + } + + private void saveReadDept(List ids, Long noticeId) { + if (ids != null && ids.size() > 0) { + ArrayList list = new ArrayList(); + ids.stream().forEach(id -> { + NoticeReadDept data = new NoticeReadDept(); + data.setDeptId((Long)id); + data.setNoticeId(noticeId); + list.add(data); + }); + this.noticeReadDeptService.batchInsertNoticeReadDept(list); + } else { + NoticeReadDept data = new NoticeReadDept(); + data.setNoticeId(noticeId); + data.setDeptId(null); + this.noticeReadDeptService.insertNoticeReadDept(data); + } + } + + @Override + @Transactional + public int updateNotice(SysNotice notice) { + notice.setUpdateTime(DateUtils.getNowDate()); + this.noticeMapper.updateNotice(notice); + Long id = notice.getNoticeId(); + this.noticeReadDeptService.deleteNoticeReadDeptByNoticeId(id); + this.saveReadDept(notice.getDeptIds(), notice.getNoticeId()); + if (notice.getFileInfoList() != null && notice.getFileInfoList().size() > 0) { + List list = notice.getFileInfoList(); + List ids = list.stream().filter(item -> item.getId() != null && item.getId() != 0L).map(item -> item.getId()).collect(Collectors.toList()); + if (ids != null && ids.size() > 0) { + HashMap map = new HashMap(); + map.put("noticeId", id); + map.put("list", ids); + this.noticeFileInfoService.deleteNoticeFileInfoNotInIds(map); + } + List fileList = list.stream().filter(item -> item.getId() == null || item.getId() == 0L).collect(Collectors.toList()); + this.saveFileList(fileList, id); + } + return 1; + } + + @Override + public int deleteNoticeById(Long noticeId) { + return this.noticeMapper.deleteNoticeById(noticeId); + } + + @Override + public int deleteNoticeByIds(Long[] noticeIds) { + return this.noticeMapper.deleteNoticeByIds(noticeIds); + } + + @Override + public JSONArray getMessageCatalogueList() { + SpeciesAbnormalInfo info; + JSONArray array = new JSONArray(); + SysNotice data = this.noticeMapper.getLastedNoticeByParam(); + Long userId = SecurityUtils.getUserId(); + if (data != null) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("name", (Object)"\u901a\u77e5\u901a\u544a"); + jsonObject.put("title", (Object)data.getNoticeTitle()); + jsonObject.put("type", (Object)1); + jsonObject.put("date", (Object)data.getCreateTime()); + int count = this.noticeMapper.getUnreadAmountByUserId(userId); + jsonObject.put("num", (Object)count); + array.add((Object)jsonObject); + } + if ((info = this.speciesAbnormalInfoService.getLatestSpeciesAbnormalInfo(userId = userId <= 1L ? null : userId)) != null) { + JSONObject jsonObject = new JSONObject(); + jsonObject.put("title", (Object)"\u5173\u952e\u7269\u79cd"); + jsonObject.put("type", (Object)2); + jsonObject.put("content", (Object)String.format("\u5728%s%s\u76d1\u6d4b\u5230%s%d\u53ea", info.getAreaName(), info.getDeviceName(), info.getSpeciesName(), info.getCount())); + jsonObject.put("date", (Object)info.getHappenTime()); + int count = this.speciesAbnormalInfoService.getSpeciesAbnormalInfoCountByUserId(null); + jsonObject.put("num", (Object)count); + array.add((Object)jsonObject); + } + return array; + } + + @Override + public JSONArray getUnreadMessageCatalogueList() { + JSONArray array = new JSONArray(); + Long userId = SecurityUtils.getUserId(); + JSONObject jsonObject = new JSONObject(); + int count = this.noticeMapper.getUnreadAmountByUserId(userId); + jsonObject.put("type", (Object)1); + jsonObject.put("num", (Object)count); + array.add((Object)jsonObject); + HashMap map = new HashMap(); + map.put("readerId", userId); + if (userId != 1L) { + map.put("userId", userId); + } + int count1 = this.speciesAbnormalInfoService.getSpeciesAbnormalInfoCountByUserId(map); + jsonObject = new JSONObject(); + jsonObject.put("type", (Object)2); + jsonObject.put("num", (Object)count1); + array.add((Object)jsonObject); + return array; + } + + @Override + public List getMessageInfoList(String title) { + SysNotice sysNotice = new SysNotice(); + sysNotice.setNoticeTitle(title); + sysNotice.setCreateDept(SecurityUtils.getUserId()); + return this.noticeMapper.getSysNoticePubListByParam(sysNotice); + } + + @Override + public SysNotice getNoticeForMobileById(Long noticeId) { + return this.noticeMapper.getNoticeForMobileById(noticeId); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysOperLogServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysOperLogServiceImpl.java new file mode 100644 index 0000000..710ec77 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysOperLogServiceImpl.java @@ -0,0 +1,71 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.system.domain.SysOperLog; +import net.hzvtc.system.mapper.SysOperLogMapper; +import net.hzvtc.system.service.SysOperLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 操作日志 服务层处理 + * + * @author admin + */ +@Service +public class SysOperLogServiceImpl implements SysOperLogService { + @Autowired + private SysOperLogMapper operLogMapper; + + /** + * 新增操作日志 + * + * @param operLog 操作日志对象 + */ + @Override + public void insertOperlog(SysOperLog operLog) { + operLogMapper.insertOperlog(operLog); + } + + /** + * 查询系统操作日志集合 + * + * @param operLog 操作日志对象 + * @return 操作日志集合 + */ + @Override + public List selectOperLogList(SysOperLog operLog) { + return operLogMapper.selectOperLogList(operLog); + } + + /** + * 批量删除系统操作日志 + * + * @param operIds 需要删除的操作日志ID + * @return 结果 + */ + @Override + public int deleteOperLogByIds(Long[] operIds) { + return operLogMapper.deleteOperLogByIds(operIds); + } + + /** + * 查询操作日志详细 + * + * @param operId 操作ID + * @return 操作日志对象 + */ + @Override + public SysOperLog selectOperLogById(Long operId) { + return operLogMapper.selectOperLogById(operId); + } + + /** + * 清空操作日志 + */ + @Override + public void cleanOperLog() { + operLogMapper.cleanOperLog(); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysPostServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysPostServiceImpl.java new file mode 100644 index 0000000..42986b2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysPostServiceImpl.java @@ -0,0 +1,164 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.domain.SysPost; +import net.hzvtc.system.mapper.SysPostMapper; +import net.hzvtc.system.mapper.SysUserPostMapper; +import net.hzvtc.system.service.SysPostService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * 岗位信息 服务层处理 + * + * @author admin + */ +@Service +public class SysPostServiceImpl implements SysPostService { + @Autowired + private SysPostMapper postMapper; + + @Autowired + private SysUserPostMapper userPostMapper; + + /** + * 查询岗位信息集合 + * + * @param post 岗位信息 + * @return 岗位信息集合 + */ + @Override + public List selectPostList(SysPost post) { + return postMapper.selectPostList(post); + } + + /** + * 查询所有岗位 + * + * @return 岗位列表 + */ + @Override + public List selectPostAll() { + return postMapper.selectPostAll(); + } + + /** + * 通过岗位ID查询岗位信息 + * + * @param postId 岗位ID + * @return 角色对象信息 + */ + @Override + public SysPost selectPostById(Long postId) { + return postMapper.selectPostById(postId); + } + + /** + * 根据用户ID获取岗位选择框列表 + * + * @param userId 用户ID + * @return 选中岗位ID列表 + */ + @Override + public List selectPostListByUserId(Long userId) { + return postMapper.selectPostListByUserId(userId); + } + + /** + * 校验岗位名称是否唯一 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public String checkPostNameUnique(SysPost post) { + Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); + SysPost info = postMapper.checkPostNameUnique(post.getPostName()); + if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验岗位编码是否唯一 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public String checkPostCodeUnique(SysPost post) { + Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); + SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); + if (StringUtils.isNotNull(info) && info.getPostId().longValue() != postId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 通过岗位ID查询岗位使用数量 + * + * @param postId 岗位ID + * @return 结果 + */ + @Override + public int countUserPostById(Long postId) { + return userPostMapper.countUserPostById(postId); + } + + /** + * 删除岗位信息 + * + * @param postId 岗位ID + * @return 结果 + */ + @Override + public int deletePostById(Long postId) { + return postMapper.deletePostById(postId); + } + + /** + * 批量删除岗位信息 + * + * @param postIds 需要删除的岗位ID + * @return 结果 + * @throws Exception 异常 + */ + @Override + public int deletePostByIds(Long[] postIds) { + for (Long postId : postIds) { + SysPost post = selectPostById(postId); + if (countUserPostById(postId) > 0) { + throw new ServiceException(String.format("%1$s已分配,不能删除", post.getPostName())); + } + } + return postMapper.deletePostByIds(postIds); + } + + /** + * 新增保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public int insertPost(SysPost post) { + return postMapper.insertPost(post); + } + + /** + * 修改保存岗位信息 + * + * @param post 岗位信息 + * @return 结果 + */ + @Override + public int updatePost(SysPost post) { + return postMapper.updatePost(post); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysRoleServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysRoleServiceImpl.java new file mode 100644 index 0000000..9767578 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysRoleServiceImpl.java @@ -0,0 +1,403 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.annotation.DataScope; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.system.domain.RoleInArea; +import net.hzvtc.system.domain.SysRoleDept; +import net.hzvtc.system.domain.SysRoleMenu; +import net.hzvtc.system.domain.SysUserRole; +import net.hzvtc.system.mapper.SysRoleDeptMapper; +import net.hzvtc.system.mapper.SysRoleMapper; +import net.hzvtc.system.mapper.SysRoleMenuMapper; +import net.hzvtc.system.mapper.SysUserRoleMapper; +import net.hzvtc.system.service.SysRoleService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.Resource; +import java.util.*; + +/** + * 角色 业务层处理 + * + * @author admin + */ +@Service +public class SysRoleServiceImpl implements SysRoleService { + @Resource + private SysRoleMapper roleMapper; + @Resource + private SysRoleMenuMapper roleMenuMapper; + @Resource + private SysUserRoleMapper userRoleMapper; + @Resource + private SysRoleDeptMapper roleDeptMapper; + + /** + * 根据条件分页查询角色数据 + * + * @param role 角色信息 + * @return 角色数据集合信息 + */ + @Override + @DataScope(deptAlias = "d") + public List selectRoleList(SysRole role) { + return roleMapper.selectRoleList(role); + } + + /** + * 根据用户ID查询角色 + * + * @param param 用户ID + * @return 角色列表 + */ + @Override + public List selectRolesByUserId(SysRole param) { + List userRoles = roleMapper.selectRolePermissionByUserId(param); + List roles = selectRoleAll(param); + for (SysRole role : roles) { + for (SysRole userRole : userRoles) { + if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) { + role.setFlag(true); + break; + } + } + } + return roles; + } + + /** + * 根据用户ID查询权限 + * + * @param sysRole 用户ID + * @return 权限列表 + */ + @Override + public Set selectRolePermissionByUserId(SysRole sysRole) { + List perms = roleMapper.selectRolePermissionByUserId(sysRole); + Set permsSet = new HashSet<>(); + for (SysRole perm : perms) { + if (StringUtils.isNotNull(perm)) { + permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(","))); + } + } + return permsSet; + } + + /** + * 查询所有角色 + * + * @return 角色列表 + */ + @Override + public List selectRoleAll(SysRole sysRole) { + return SpringUtils.getAopProxy(this).selectRoleList(sysRole); + } + + /** + * 根据用户ID获取角色选择框列表 + * + * @param userId 用户ID + * @return 选中角色ID列表 + */ + @Override + public List selectRoleListByUserId(Long userId) { + return roleMapper.selectRoleListByUserId(userId); + } + + /** + * 通过角色ID查询角色 + * + * @param roleId 角色ID + * @return 角色对象信息 + */ + @Override + public SysRole selectRoleById(Long roleId) { + return roleMapper.selectRoleById(roleId); + } + + /** + * 校验角色名称是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public String checkRoleNameUnique(SysRole role) { + Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); + SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); + if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验角色权限是否唯一 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public String checkRoleKeyUnique(SysRole role) { + Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); + SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); + if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验角色是否允许操作 + * + * @param role 角色信息 + */ + @Override + public void checkRoleAllowed(SysRole role) { + if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) { + throw new ServiceException("不允许操作超级管理员角色"); + } + } + + /** + * 校验角色是否有数据权限 + * + * @param roleId 角色id + */ + @Override + public void checkRoleDataScope(Long roleId) { + if (!SysUser.isAdmin(SecurityUtils.getUserId())) { + SysRole role = new SysRole(); + role.setRoleId(roleId); + List roles = SpringUtils.getAopProxy(this).selectRoleList(role); + if (StringUtils.isEmpty(roles)) { + throw new ServiceException("没有权限访问角色数据!"); + } + } + } + + /** + * 通过角色ID查询角色使用数量 + * + * @param roleId 角色ID + * @return 结果 + */ + @Override + public int countUserRoleByRoleId(Long roleId) { + return userRoleMapper.countUserRoleByRoleId(roleId); + } + + /** + * 新增保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int insertRole(SysRole role) { + // 新增角色信息 + roleMapper.insertRole(role); + return insertRoleMenu(role); + } + + /** + * 修改保存角色信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int updateRole(SysRole role) { + // 修改角色信息 + roleMapper.updateRole(role); + // 删除角色与菜单关联 + roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId()); + roleMenuMapper.deleteAreaIdByRoleId(role.getRoleId()); + return insertRoleMenu(role); + } + + /** + * 修改角色状态 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + public int updateRoleStatus(SysRole role) { + return roleMapper.updateRole(role); + } + + /** + * 修改数据权限信息 + * + * @param role 角色信息 + * @return 结果 + */ + @Override + @Transactional + public int authDataScope(SysRole role) { + // 修改角色信息 + roleMapper.updateRole(role); + // 删除角色与部门关联 + roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId()); + // 新增角色和部门信息(数据权限) + return insertRoleDept(role); + } + + /** + * 新增角色菜单信息 + * + * @param role 角色对象 + */ + public int insertRoleMenu(SysRole role) { + int rows = 1; + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long menuId : role.getMenuIds()) { + SysRoleMenu rm = new SysRoleMenu(); + rm.setRoleId(role.getRoleId()); + rm.setMenuId(menuId); + list.add(rm); + } + List areaList = new ArrayList<>(); + for (Long areaId : role.getAreaIds()) { + RoleInArea data = new RoleInArea(); + data.setAreaId(areaId); + data.setRoleId(role.getRoleId()); + areaList.add(data); + } + if (areaList.size() > 0) { + roleMenuMapper.batchInsertArea(areaList); + } + if (list.size() > 0) { + rows = roleMenuMapper.batchRoleMenu(list); + } + return rows; + } + + /** + * 新增角色部门信息(数据权限) + * + * @param role 角色对象 + */ + public int insertRoleDept(SysRole role) { + int rows = 1; + // 新增角色与部门(数据权限)管理 + List list = new ArrayList(); + for (Long deptId : role.getDeptIds()) { + SysRoleDept rd = new SysRoleDept(); + rd.setRoleId(role.getRoleId()); + rd.setDeptId(deptId); + list.add(rd); + } + if (list.size() > 0) { + rows = roleDeptMapper.batchRoleDept(list); + } + return rows; + } + + /** + * 通过角色ID删除角色 + * + * @param roleId 角色ID + * @return 结果 + */ + @Override + @Transactional + public int deleteRoleById(Long roleId) { + // 删除角色与菜单关联 + roleMenuMapper.deleteRoleMenuByRoleId(roleId); + // 删除角色与部门关联 + roleDeptMapper.deleteRoleDeptByRoleId(roleId); + return roleMapper.deleteRoleById(roleId); + } + + /** + * 批量删除角色信息 + * + * @param roleIds 需要删除的角色ID + * @return 结果 + */ + @Override + @Transactional + public int deleteRoleByIds(Long[] roleIds) { + for (Long roleId : roleIds) { + checkRoleAllowed(new SysRole(roleId)); + checkRoleDataScope(roleId); + SysRole role = selectRoleById(roleId); + if (countUserRoleByRoleId(roleId) > 0) { + throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName())); + } + } + // 删除角色与菜单关联 + roleMenuMapper.deleteRoleMenu(roleIds); + // 删除角色与部门关联 + roleDeptMapper.deleteRoleDept(roleIds); + return roleMapper.deleteRoleByIds(roleIds); + } + + /** + * 取消授权用户角色 + * + * @param userRole 用户和角色关联信息 + * @return 结果 + */ + @Override + public int deleteAuthUser(SysUserRole userRole) { + return userRoleMapper.deleteUserRoleInfo(userRole); + } + + /** + * 批量取消授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要取消授权的用户数据ID + * @return 结果 + */ + @Override + public int deleteAuthUsers(Long roleId, Long[] userIds) { + return userRoleMapper.deleteUserRoleInfos(roleId, userIds); + } + + /** + * 批量选择授权用户角色 + * + * @param roleId 角色ID + * @param userIds 需要删除的用户数据ID + * @return 结果 + */ + @Override + public int insertAuthUsers(Long roleId, Long[] userIds) { + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long userId : userIds) { + SysUserRole ur = new SysUserRole(); + ur.setUserId(userId); + ur.setRoleId(roleId); + list.add(ur); + } + return userRoleMapper.batchUserRole(list); + } + + @Override + public Set getAreaIdsByUserId(SysUser user) { + List list = null; + if (user.isAdmin()) { + list = roleMenuMapper.getAllAreaList(); + } else { + list = roleMenuMapper.getRoleInAreaListByUserId(user.getUserId()); + } + Set areaIds = new HashSet<>(); + areaIds.addAll(list); + return areaIds; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserOnlineServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserOnlineServiceImpl.java new file mode 100644 index 0000000..050486d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserOnlineServiceImpl.java @@ -0,0 +1,86 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.core.domain.model.LoginUser; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.system.domain.SysUserOnline; +import net.hzvtc.system.service.SysUserOnlineService; +import org.springframework.stereotype.Service; + +/** + * 在线用户 服务层处理 + * + * @author admin + */ +@Service +public class SysUserOnlineServiceImpl implements SysUserOnlineService { + /** + * 通过登录地址查询信息 + * + * @param ipaddr 登录地址 + * @param user 用户信息 + * @return 在线用户信息 + */ + @Override + public SysUserOnline selectOnlineByIpaddr(String ipaddr, LoginUser user) { + if (StringUtils.equals(ipaddr, user.getIpaddr())) { + return loginUserToUserOnline(user); + } + return null; + } + + /** + * 通过用户名称查询信息 + * + * @param userName 用户名称 + * @param user 用户信息 + * @return 在线用户信息 + */ + @Override + public SysUserOnline selectOnlineByUserName(String userName, LoginUser user) { + if (StringUtils.equals(userName, user.getUsername())) { + return loginUserToUserOnline(user); + } + return null; + } + + /** + * 通过登录地址/用户名称查询信息 + * + * @param ipaddr 登录地址 + * @param userName 用户名称 + * @param user 用户信息 + * @return 在线用户信息 + */ + @Override + public SysUserOnline selectOnlineByInfo(String ipaddr, String userName, LoginUser user) { + if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) { + return loginUserToUserOnline(user); + } + return null; + } + + /** + * 设置在线用户信息 + * + * @param user 用户信息 + * @return 在线用户 + */ + @Override + public SysUserOnline loginUserToUserOnline(LoginUser user) { + if (StringUtils.isNull(user) || StringUtils.isNull(user.getUser())) { + return null; + } + SysUserOnline sysUserOnline = new SysUserOnline(); + sysUserOnline.setTokenId(user.getToken()); + sysUserOnline.setUserName(user.getUsername()); + sysUserOnline.setIpaddr(user.getIpaddr()); + sysUserOnline.setLoginLocation(user.getLoginLocation()); + sysUserOnline.setBrowser(user.getBrowser()); + sysUserOnline.setOs(user.getOs()); + sysUserOnline.setLoginTime(user.getLoginTime()); + if (StringUtils.isNotNull(user.getUser().getDept())) { + sysUserOnline.setDeptName(user.getUser().getDept().getDeptName()); + } + return sysUserOnline; + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserServiceImpl.java new file mode 100644 index 0000000..6d63d76 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/system/service/impl/SysUserServiceImpl.java @@ -0,0 +1,509 @@ +package net.hzvtc.system.service.impl; + +import net.hzvtc.common.annotation.DataScope; +import net.hzvtc.common.constant.UserConstants; +import net.hzvtc.common.core.domain.entity.SysRole; +import net.hzvtc.common.core.domain.entity.SysUser; +import net.hzvtc.common.exception.ServiceException; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.common.utils.StringUtils; +import net.hzvtc.common.utils.bean.BeanValidators; +import net.hzvtc.common.utils.spring.SpringUtils; +import net.hzvtc.system.domain.SysPost; +import net.hzvtc.system.domain.SysUserPost; +import net.hzvtc.system.domain.SysUserRole; +import net.hzvtc.system.mapper.*; +import net.hzvtc.system.service.SysConfigService; +import net.hzvtc.system.service.SysUserService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; + +import javax.annotation.Resource; +import javax.validation.Validator; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户 业务层处理 + * + * @author admin + */ +@Service +public class SysUserServiceImpl implements SysUserService { + private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class); + @Autowired + protected Validator validator; + @Resource + private SysUserMapper userMapper; + @Resource + private SysRoleMapper roleMapper; + @Resource + private SysPostMapper postMapper; + @Resource + private SysUserRoleMapper userRoleMapper; + @Resource + private SysUserPostMapper userPostMapper; + @Autowired + private SysConfigService configService; + @Autowired + private SysUserMapper sysUserMapper; + + /** + * 根据条件分页查询用户列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @Override + @DataScope(deptAlias = "d", userAlias = "u") + public List selectUserList(SysUser user) { + return userMapper.selectUserList(user); + } + + /** + * 根据条件分页查询已分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @Override + @DataScope(deptAlias = "d", userAlias = "u") + public List selectAllocatedList(SysUser user) { + return userMapper.selectAllocatedList(user); + } + + /** + * 根据条件分页查询未分配用户角色列表 + * + * @param user 用户信息 + * @return 用户信息集合信息 + */ + @Override + @DataScope(deptAlias = "d", userAlias = "u") + public List selectUnallocatedList(SysUser user) { + return userMapper.selectUnallocatedList(user); + } + + /** + * 通过用户名查询用户 + * + * @param userName 用户名 + * @return 用户对象信息 + */ + @Override + public SysUser selectUserByUserName(String userName) { + return userMapper.selectUserByUserName(userName); + } + + /** + * 通过用户ID查询用户 + * + * @param sysUser 用户ID + * @return 用户对象信息 + */ + @Override + public SysUser selectUserById(SysUser sysUser) { + return userMapper.selectUserById(sysUser); + } + + /** + * 查询用户所属角色组 + * + * @param userName 用户名 + * @return 结果 + */ + @Override + public String selectUserRoleGroup(String userName) { + List list = roleMapper.selectRolesByUserName(userName); + if (CollectionUtils.isEmpty(list)) { + return StringUtils.EMPTY; + } + return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(",")); + } + + /** + * 查询用户所属岗位组 + * + * @param userName 用户名 + * @return 结果 + */ + @Override + public String selectUserPostGroup(String userName) { + List list = postMapper.selectPostsByUserName(userName); + if (CollectionUtils.isEmpty(list)) { + return StringUtils.EMPTY; + } + return list.stream().map(SysPost::getPostName).collect(Collectors.joining(",")); + } + + /** + * 校验用户名称是否唯一 + * + * @param userName 用户名称 + * @return 结果 + */ + @Override + public String checkUserNameUnique(String userName) { + int count = userMapper.checkUserNameUnique(userName); + if (count > 0) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验手机号码是否唯一 + * + * @param user 用户信息 + * @return + */ + @Override + public String checkPhoneUnique(SysUser user) { + Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); + SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); + if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验email是否唯一 + * + * @param user 用户信息 + * @return + */ + @Override + public String checkEmailUnique(SysUser user) { + Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); + SysUser info = userMapper.checkEmailUnique(user.getEmail()); + if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) { + return UserConstants.NOT_UNIQUE; + } + return UserConstants.UNIQUE; + } + + /** + * 校验用户是否允许操作 + * + * @param user 用户信息 + */ + @Override + public void checkUserAllowed(SysUser user) { + if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) { + throw new ServiceException("不允许操作超级管理员用户"); + } + } + + /** + * 校验用户是否有数据权限 + * + * @param userId 用户id + */ + @Override + public void checkUserDataScope(Long userId) { + if (!SysUser.isAdmin(SecurityUtils.getUserId())) { + SysUser user = new SysUser(); + user.setUserId(userId); + List users = SpringUtils.getAopProxy(this).selectUserList(user); + if (StringUtils.isEmpty(users)) { + throw new ServiceException("没有权限访问用户数据!"); + } + } + } + + /** + * 新增保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + @Transactional + public int insertUser(SysUser user) { + // 新增用户信息 + int rows = userMapper.insertUser(user); + // 新增用户岗位关联 + insertUserPost(user); + // 新增用户与角色管理 + insertUserRole(user); + return rows; + } + + /** + * 注册用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public boolean registerUser(SysUser user) { + return userMapper.insertUser(user) > 0; + } + + /** + * 修改保存用户信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + @Transactional + public int updateUser(SysUser user) { + Long userId = user.getUserId(); + // 删除用户与角色关联 + userRoleMapper.deleteUserRoleByUserId(user); + // 新增用户与角色管理 + insertUserRole(user); + // 删除用户与岗位关联 + userPostMapper.deleteUserPostByUserId(userId); + // 新增用户与岗位管理 + insertUserPost(user); + return userMapper.updateUser(user); + } + + /** + * 用户授权角色 + * + * @param userId 用户ID + * @param roleIds 角色组 + */ + @Override + @Transactional + public void insertUserAuth(Long userId, Integer sysId, Long[] roleIds) { + SysUser param = new SysUser(); + param.setUserId(userId); + param.setSysId(sysId); + userRoleMapper.deleteUserRoleByUserId(param); + insertUserRole(userId, roleIds); + } + + /** + * 修改用户状态 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int updateUserStatus(SysUser user) { + return userMapper.updateUserStatus(user); + } + + /** + * 修改用户基本信息 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int updateUserProfile(SysUser user) { + return userMapper.updateUserProfile(user); + } + + /** + * 修改用户头像 + * + * @param userName 用户名 + * @param avatar 头像地址 + * @return 结果 + */ + @Override + public boolean updateUserAvatar(String userName, String avatar) { + userMapper.updateUserAvatar(userName, avatar); + return true; + } + + /** + * 重置用户密码 + * + * @param user 用户信息 + * @return 结果 + */ + @Override + public int resetPwd(SysUser user) { + return userMapper.updateUserPassword(user); + } + + /** + * 重置用户密码 + * + * @param userName 用户名 + * @param password 密码 + * @return 结果 + */ + @Override + public int resetUserPwd(String userName, String password) { + return userMapper.resetUserPwd(userName, password); + } + + /** + * 新增用户角色信息 + * + * @param user 用户对象 + */ + @Override + public void insertUserRole(SysUser user) { + Long[] roles = user.getRoleIds(); + if (StringUtils.isNotNull(roles)) { + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long roleId : roles) { + SysUserRole ur = new SysUserRole(); + ur.setUserId(user.getUserId()); + ur.setRoleId(roleId); + list.add(ur); + } + if (list.size() > 0) { + userRoleMapper.batchUserRole(list); + } + } + } + + /** + * 新增用户岗位信息 + * + * @param user 用户对象 + */ + public void insertUserPost(SysUser user) { + Long[] posts = user.getPostIds(); + if (StringUtils.isNotNull(posts)) { + // 新增用户与岗位管理 + List list = new ArrayList(); + for (Long postId : posts) { + SysUserPost up = new SysUserPost(); + up.setUserId(user.getUserId()); + up.setPostId(postId); + list.add(up); + } + if (list.size() > 0) { + userPostMapper.batchUserPost(list); + } + } + } + + /** + * 新增用户角色信息 + * + * @param userId 用户ID + * @param roleIds 角色组 + */ + public void insertUserRole(Long userId, Long[] roleIds) { + if (StringUtils.isNotNull(roleIds)) { + // 新增用户与角色管理 + List list = new ArrayList(); + for (Long roleId : roleIds) { + SysUserRole ur = new SysUserRole(); + ur.setUserId(userId); + ur.setRoleId(roleId); + list.add(ur); + } + if (list.size() > 0) { + userRoleMapper.batchUserRole(list); + } + } + } + + /** + * 通过用户ID删除用户 + * + * @param userId 用户ID + * @return 结果 + */ + @Override + @Transactional + public int deleteUserById(Long userId, Integer sysId) { + // 删除用户与角色关联 + SysUser param = new SysUser(); + param.setUserId(userId); + param.setSysId(sysId); + userRoleMapper.deleteUserRoleByUserId(param); + // 删除用户与岗位表 + userPostMapper.deleteUserPostByUserId(userId); + return userMapper.deleteUserById(userId); + } + + /** + * 批量删除用户信息 + * + * @param userIds 需要删除的用户ID + * @return 结果 + */ + @Override + @Transactional + public int deleteUserByIds(Long[] userIds) { + for (Long userId : userIds) { + checkUserAllowed(new SysUser(userId)); + checkUserDataScope(userId); + } + // 删除用户与角色关联 + userRoleMapper.deleteUserRole(userIds); + // 删除用户与岗位关联 + userPostMapper.deleteUserPost(userIds); + return userMapper.deleteUserByIds(userIds); + } + + /** + * 导入用户数据 + * + * @param userList 用户数据列表 + * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据 + * @param operName 操作用户 + * @return 结果 + */ + @Override + public String importUser(List userList, Boolean isUpdateSupport, String operName) { + if (StringUtils.isNull(userList) || userList.size() == 0) { + throw new ServiceException("导入用户数据不能为空!"); + } + int successNum = 0; + int failureNum = 0; + StringBuilder successMsg = new StringBuilder(); + StringBuilder failureMsg = new StringBuilder(); + String password = configService.selectConfigByKey("sys.user.initPassword"); + for (SysUser user : userList) { + try { + // 验证是否存在这个用户 + SysUser u = userMapper.selectUserByUserName(user.getUserName()); + if (StringUtils.isNull(u)) { + BeanValidators.validateWithException(validator, user); + user.setPassword(SecurityUtils.encryptPassword(password)); + user.setCreateBy(operName); + insertUser(user); + successNum++; + successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 导入成功"); + } else if (isUpdateSupport) { + BeanValidators.validateWithException(validator, user); + user.setUpdateBy(operName); + updateUser(user); + successNum++; + successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 更新成功"); + } else { + failureNum++; + failureMsg.append("
" + failureNum + "、账号 " + user.getUserName() + " 已存在"); + } + } catch (Exception e) { + failureNum++; + String msg = "
" + failureNum + "、账号 " + user.getUserName() + " 导入失败:"; + failureMsg.append(msg + e.getMessage()); + log.error(msg, e); + } + } + if (failureNum > 0) { + failureMsg.insert(0, "很抱歉,导入失败!共 " + failureNum + " 条数据格式不正确,错误如下:"); + throw new ServiceException(failureMsg.toString()); + } else { + successMsg.insert(0, "恭喜您,数据已全部导入成功!共 " + successNum + " 条,数据如下:"); + } + return successMsg.toString(); + } + + @Override + public SysUser getUserInfoById(Long id) { + return sysUserMapper.getUserInfoById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/api/service/SpeciesInfoApiService.java b/ai-bird-system/src/main/java/net/hzvtc/web/api/service/SpeciesInfoApiService.java new file mode 100644 index 0000000..596a59e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/api/service/SpeciesInfoApiService.java @@ -0,0 +1,28 @@ +package net.hzvtc.web.api.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +public interface SpeciesInfoApiService { + public JSONArray getSpeciesCurrentDateStatList(JSONObject var1); + + public JSONObject getSpeciesStatListByParam(JSONObject var1); + + public JSONObject getBirdPeriodStatByParam(JSONObject var1); + + public JSONObject getBirdMonthStatByParam(JSONObject var1); + + public JSONObject getBirdYearStatByParam(JSONObject var1); + + public JSONObject getDeviceInfoListByParam(); + + public JSONObject getAudioDeviceInfoListByParam(); + + public JSONObject getTodayRecordList(); + + public JSONObject getVideoMediaListByParam(JSONObject var1); + + public JSONObject getAudioListByParam(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/api/service/impl/SpeciesInfoApiServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/api/service/impl/SpeciesInfoApiServiceImpl.java new file mode 100644 index 0000000..7219b70 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/api/service/impl/SpeciesInfoApiServiceImpl.java @@ -0,0 +1,371 @@ +package net.hzvtc.web.api.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import net.hzvtc.bird.domain.BirdSpecies; +import net.hzvtc.bird.service.BirdSpeciesService; +import net.hzvtc.common.utils.PageUtils; +import net.hzvtc.common.utils.SecurityUtils; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.domain.ResultRecord; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.echart.service.BirdDataStatService; +import net.hzvtc.web.api.service.SpeciesInfoApiService; +import net.hzvtc.web.stat.service.BirdWebPageStatService; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +@Service +public class SpeciesInfoApiServiceImpl +implements SpeciesInfoApiService { + private static final Logger log = LoggerFactory.getLogger(SpeciesInfoApiServiceImpl.class); + private final BirdDataStatService birdRealTimeService; + private final BirdWebPageStatService birdWebPageStatService; + private final SpeciesDailyStatService speciesDailyStatService; + private final DeviceInfoService deviceInfoService; + private final ResultRecordService resultRecordService; + private final ResultMediaService resultMediaService; + private final BirdSpeciesService birdSpeciesService; + @Value(value="${hzvtc.fileServerUrl}") + private String fileServerUrl; + + @Override + public JSONArray getSpeciesCurrentDateStatList(JSONObject params) { + Long areaId; + if (params == null) { + params = new JSONObject(); + } + if ((areaId = this.getAreaId()) == null) { + return new JSONArray(); + } + params.put("areaId", (Object)areaId); + List list = this.birdRealTimeService.getBirdRealStatByParam(params); + JSONArray array = new JSONArray(); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("id", (Object)item.getId()); + String url = item.getLocation(); + if (url != null) { + if (url.startsWith("/")) { + object.put("img", (Object)(this.fileServerUrl + url)); + } else { + object.put("img", (Object)(this.fileServerUrl + "/" + url)); + } + } + object.put("count", (Object)item.getCount()); + object.put("name", (Object)item.getName()); + array.add((Object)object); + }); + return array; + } + + @Override + public JSONObject getSpeciesStatListByParam(JSONObject params) { + Long areaId; + if (params == null) { + params = new JSONObject(); + } + if ((areaId = this.getAreaId()) == null) { + return new JSONObject(); + } + params.put("areaId", (Object)areaId); + return this.birdWebPageStatService.getBirdDailyStatListByParam(params); + } + + @Override + public JSONObject getBirdPeriodStatByParam(JSONObject params) { + Long areaId; + if (params == null) { + params = new JSONObject(); + } + if ((areaId = this.getAreaId()) == null) { + return new JSONObject(); + } + params.put("areaId", (Object)areaId); + List list = this.speciesDailyStatService.getBirdPeriodStatListByParam(params); + JSONArray array = new JSONArray(); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("shortDate", (Object)item.getShortDate()); + object.put("dateTime", (Object)item.getDateTime()); + object.put("avgCount", (Object)item.getAvgCount()); + object.put("maxCount", (Object)item.getCount()); + array.add((Object)object); + }); + JSONObject object = new JSONObject(); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getBirdMonthStatByParam(JSONObject params) { + Long areaId; + if (params == null) { + params = new JSONObject(); + } + if ((areaId = this.getAreaId()) == null) { + return new JSONObject(); + } + params.put("areaId", (Object)areaId); + List list = this.speciesDailyStatService.getBirdMonthStatListByParam(params); + JSONArray array = new JSONArray(); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("month", (Object)item.getMonth()); + object.put("avgCount", (Object)item.getAvgCount()); + object.put("maxCount", (Object)item.getCount()); + array.add((Object)object); + }); + JSONObject object = new JSONObject(); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getBirdYearStatByParam(JSONObject param) { + Long areaId = this.getAreaId(); + if (areaId == null) { + return new JSONObject(); + } + param.put("areaId", (Object)areaId); + List list = this.birdWebPageStatService.getBirdStatYearInfoByParam(param); + JSONArray array = new JSONArray(); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("year", (Object)item.getYear()); + object.put("avgCount", (Object)item.getAvgCount()); + object.put("maxCount", (Object)item.getCount()); + array.add((Object)object); + }); + JSONObject object = new JSONObject(); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getDeviceInfoListByParam() { + Long areaId = this.getAreaId(); + if (areaId == null) { + return new JSONObject(); + } + JSONArray array = new JSONArray(); + List list = this.deviceInfoService.getDeviceStatInfoByAreaId(areaId); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("id", (Object)item.getId()); + object.put("name", (Object)item.getDeviceName()); + object.put("serialNumber", (Object)item.getSerialNumber()); + array.add((Object)object); + }); + JSONObject object = new JSONObject(); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getAudioDeviceInfoListByParam() { + Long areaId = this.getAreaId(); + if (areaId == null) { + return new JSONObject(); + } + HashMap map = new HashMap(); + map.put("areaId", areaId); + map.put("deviceType", 2); + List list = this.deviceInfoService.getDeviceListInfoByParam(map); + JSONArray array = new JSONArray(); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("id", (Object)item.getId()); + object.put("name", (Object)item.getDeviceName()); + object.put("serialNumber", (Object)item.getSerialNumber()); + object.put("lon", (Object)item.getLongitude()); + object.put("lat", (Object)item.getLatitude()); + array.add((Object)object); + }); + JSONObject object = new JSONObject(); + object.put("list", (Object)array); + return object; + } + + @Override + public JSONObject getTodayRecordList() { + JSONObject param = new JSONObject(); + param.put("areaId", (Object)this.getAreaId()); + List list = this.resultRecordService.getCurrentDateResultRecordList(param); + JSONArray array = new JSONArray(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + list.forEach(item -> { + JSONObject object = new JSONObject(); + object.put("id", (Object)item.getRecordId()); + object.put("recordTime", (Object)df.format(item.getRecordTime())); + object.put("deviceId", (Object)item.getDeviceId()); + JSONArray subArray = new JSONArray(); + item.getList().forEach(subItem -> { + String url; + JSONObject obj = new JSONObject(); + obj.put("id", (Object)subItem.getDetailsId()); + obj.put("count", (Object)subItem.getCount()); + obj.put("speciesId", (Object)subItem.getSpeciesId()); + String string = url = subItem.getResultMedia() != null ? subItem.getResultMedia().getMediaUrl() : null; + if (url != null) { + if (url.startsWith("/")) { + obj.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + obj.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + } + subArray.add((Object)obj); + }); + object.put("records", (Object)subArray); + array.add((Object)object); + }); + JSONObject result = new JSONObject(); + result.put("list", (Object)array); + return result; + } + + @Override + public JSONObject getVideoMediaListByParam(JSONObject object) { + JSONObject param = new JSONObject(); + param.put("areaId", (Object)this.getAreaId()); + String dateFrom = object.getString("dateFrom"); + String dateTo = object.getString("dateTo"); + if (dateFrom == null || dateFrom.isEmpty() || dateTo == null || dateTo.isEmpty()) { + return new JSONObject(); + } + param.put("dateFrom", (Object)dateFrom); + param.put("dateTo", (Object)dateTo); + Long speciesId = object.getLong("speciesId"); + param.put("speciesId", (Object)speciesId); + Long deviceId = object.getLong("deviceId"); + param.put("deviceId", (Object)deviceId); + List list = this.resultMediaService.getVideoMediaListByParam((Map)param); + JSONArray array = new JSONArray(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("speciesName", (Object)item.getSpeciesName()); + obj.put("speciesId", (Object)item.getSpeciesId()); + obj.put("deviceId", (Object)item.getDeviceId()); + obj.put("time", (Object)df.format(item.getTime())); + String url = item.getMediaUrl(); + if (url != null) { + if (url.startsWith("/")) { + obj.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + obj.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + } + if ((url = item.getMetaUrl()) != null) { + if (url.startsWith("/")) { + obj.put("imgPath", (Object)(this.fileServerUrl + url)); + } else { + obj.put("imgPath", (Object)(this.fileServerUrl + "/" + url)); + } + } + array.add((Object)obj); + }); + } + JSONObject result = new JSONObject(); + result.put("list", (Object)array); + return result; + } + + @Override + public JSONObject getAudioListByParam(JSONObject object) { + JSONObject param = new JSONObject(); + param.put("areaId", (Object)this.getAreaId()); + String calcDate = object.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + param.put("calcDate", (Object)calcDate); + Long speciesId = object.getLong("speciesId"); + param.put("speciesId", (Object)speciesId); + String serialNumber = object.getString("serialNumber"); + param.put("serialNumber", (Object)serialNumber); + Long deviceId = object.getLong("deviceId"); + param.put("deviceId", (Object)deviceId); + Integer pageNum = object.getInteger("pageNum"); + Integer pageSize = object.getInteger("pageSize"); + PageUtils.startPage((Integer)pageNum, (Integer)pageSize); + List list = this.resultMediaService.getAudioMediaListByParam((Map)param); + long total = new PageInfo(list).getTotal(); + ArrayList array = new ArrayList(); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + if (!list.isEmpty()) { + list.forEach(item -> { + String url; + JSONObject obj = new JSONObject(); + BirdSpecies birdSpecies = this.birdSpeciesService.getBirdSpeciesInfoById(item.getSpeciesId()); + obj.put("speciesName", (Object)birdSpecies.getName()); + obj.put("scientificName", (Object)birdSpecies.getScientificName()); + if (birdSpecies.getMediaList() != null && !birdSpecies.getMediaList().isEmpty()) { + url = this.fileServerUrl + birdSpecies.getMediaList().get(0).getUrl(); + obj.put("avatar", (Object)url); + } + obj.put("speciesId", (Object)item.getSpeciesId()); + obj.put("deviceId", (Object)item.getDeviceId()); + obj.put("time", (Object)df.format(item.getTime())); + url = item.getMediaUrl(); + if (url != null) { + if (url.startsWith("/")) { + obj.put("mediaUrl", (Object)(this.fileServerUrl + url)); + } else { + obj.put("mediaUrl", (Object)(this.fileServerUrl + "/" + url)); + } + } + if ((url = item.getMetaUrl()) != null) { + if (url.startsWith("/")) { + obj.put("imgPath", (Object)(this.fileServerUrl + url)); + } else { + obj.put("imgPath", (Object)(this.fileServerUrl + "/" + url)); + } + } + array.add(obj); + }); + } + JSONObject result = new JSONObject(); + result.put("total", (Object)total); + result.put("row", array); + return result; + } + + private Long getAreaId() { + Set set = SecurityUtils.getLoginUser().getAreaIds(); + if (set == null || set.isEmpty()) { + return null; + } + ArrayList ids = new ArrayList(set); + return (Long)ids.get(0); + } + + public SpeciesInfoApiServiceImpl(BirdDataStatService birdRealTimeService, BirdWebPageStatService birdWebPageStatService, SpeciesDailyStatService speciesDailyStatService, DeviceInfoService deviceInfoService, ResultRecordService resultRecordService, ResultMediaService resultMediaService, BirdSpeciesService birdSpeciesService) { + this.birdRealTimeService = birdRealTimeService; + this.birdWebPageStatService = birdWebPageStatService; + this.speciesDailyStatService = speciesDailyStatService; + this.deviceInfoService = deviceInfoService; + this.resultRecordService = resultRecordService; + this.resultMediaService = resultMediaService; + this.birdSpeciesService = birdSpeciesService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/BirdWebPageStatController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/BirdWebPageStatController.java new file mode 100644 index 0000000..a63e54c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/BirdWebPageStatController.java @@ -0,0 +1,87 @@ +package net.hzvtc.web.stat.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.web.stat.service.BirdWebPageStatService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/web/page/stat"}) +public class BirdWebPageStatController { + private static final Logger log = LoggerFactory.getLogger(BirdWebPageStatController.class); + @Autowired + private BirdWebPageStatService birdWebPageStatService; + + @PostMapping(value={"/birdDailyAmount"}) + public AjaxResult getBirdDailyStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdDailyAmountListByParam(obj)); + } + + @PostMapping(value={"/birdDailyStat"}) + public AjaxResult getBirdDailyStatList(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdDailyStatListByParam(obj)); + } + + @PostMapping(value={"/birdAudioDailyStat"}) + public AjaxResult getBirdAudioDailyStatList(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdAudioDailyStatListByParam(obj)); + } + + @PostMapping(value={"/birdAudioMonthStat"}) + public AjaxResult getBirdAudioMonthStatList(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdAudioMonthStatListByParam(obj)); + } + + @PostMapping(value={"/birdAudioYearStat"}) + public AjaxResult getBirdAudioYearStatList(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdAudioYearStatListByParam(obj)); + } + + @PostMapping(value={"/familyDailyStat"}) + public AjaxResult getFamilyDailyStat(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdWebPageStatService.getBirdDailyFamilyListByParam(obj)); + } + + @PostMapping(value={"/periodAudioStat"}) + public AjaxResult getBirdPeriodStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdPeriodStatByParam(obj)); + } + + @PostMapping(value={"/audioMonthStat"}) + public AjaxResult getBirdAudioMonthStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdAudioMonthStatByParam(obj)); + } + + @PostMapping(value={"/audioYearStat"}) + public AjaxResult getBirdAudioYearStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdAudioYearStatByParam(obj)); + } + + @PostMapping(value={"/monthStat"}) + public AjaxResult getBirdMonthStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdMonthStatByParam(obj)); + } + + @PostMapping(value={"/yearAmountStat"}) + public AjaxResult getBirdYearAmountStat(@RequestBody JSONObject obj) { + return AjaxResult.success(this.birdWebPageStatService.getBirdStatYearInfoByParam(obj)); + } + + @PostMapping(value={"/winterAudioStat"}) + public AjaxResult getBirdWinterPeriodAudioStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getSpeciesWinterPeriodAudioAmountByParam(obj)); + } + + @PostMapping(value={"/birdResidentStat"}) + public AjaxResult getBirdResidentStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.birdWebPageStatService.getBirdArriveAndLeaveInfoByParam(obj)); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyInhabitController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyInhabitController.java new file mode 100644 index 0000000..09a0f30 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyInhabitController.java @@ -0,0 +1,70 @@ +package net.hzvtc.web.stat.controller; + +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.web.stat.domain.SpeciesDailyInhabit; +import net.hzvtc.web.stat.service.SpeciesDailyInhabitService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 生境数量统计Controller + * + * @author admin + * @date 2023-08-21 + */ +@RestController +@RequestMapping("/stat/inhabit") +public class SpeciesDailyInhabitController extends BaseController { + @Autowired + private SpeciesDailyInhabitService speciesDailyInhabitService; + + /** + * 查询生境数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabit:list')") + @GetMapping("/list") + public TableDataInfo list(SpeciesDailyInhabit speciesDailyInhabit) { + startPage(); + List list = speciesDailyInhabitService.selectSpeciesDailyInhabitList(speciesDailyInhabit); + return getDataTable(list); + } + + /** + * 导出生境数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabit:export')") + @Log(title = "生境数量统计", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SpeciesDailyInhabit speciesDailyInhabit) { + List list = speciesDailyInhabitService.selectSpeciesDailyInhabitList(speciesDailyInhabit); + ExcelUtil util = new ExcelUtil(SpeciesDailyInhabit.class); + util.exportExcel(response, list, "生境数量统计数据"); + } + + + /** + * 新增生境数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabit:add')") + @Log(title = "生境数量统计", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesDailyInhabit speciesDailyInhabit) { + return toAjax(speciesDailyInhabitService.insertSpeciesDailyInhabit(speciesDailyInhabit)); + } + + @PostMapping("/inhabitList") + public AjaxResult getSpeciesListByParam(@RequestBody JSONObject param) { + return AjaxResult.success(speciesDailyInhabitService.getSpeciesListByParam(param)); + } + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyStatController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyStatController.java new file mode 100644 index 0000000..1ecfb90 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesDailyStatController.java @@ -0,0 +1,206 @@ +package net.hzvtc.web.stat.controller; + +import com.alibaba.fastjson.JSONObject; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.file.FileUtils; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.web.stat.domain.SpeciesDailyStat; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(value={"/stat/dailystat"}) +public class SpeciesDailyStatController +extends BaseController { + @Autowired + private SpeciesDailyStatService speciesDailyStatService; + + @PreAuthorize(value="@ss.hasPermi('stat:dailystat:list')") + @GetMapping(value={"/list"}) + public TableDataInfo list(SpeciesDailyStat speciesDailyStat) { + this.startPage(); + List list = this.speciesDailyStatService.selectSpeciesDailyStatList(speciesDailyStat); + return this.getDataTable(list); + } + + @PreAuthorize(value="@ss.hasPermi('stat:dailystat:export')") + @Log(title="\u7269\u79cd\u6bcf\u65e5\u7edf\u8ba1", businessType=BusinessType.EXPORT) + @PostMapping(value={"/export"}) + public void export(HttpServletResponse response, SpeciesDailyStat speciesDailyStat) { + List list = this.speciesDailyStatService.selectSpeciesDailyStatList(speciesDailyStat); + ExcelUtil util = new ExcelUtil(SpeciesDailyStat.class); + util.exportExcel(response, list, "\u7269\u79cd\u6bcf\u65e5\u7edf\u8ba1\u6570\u636e"); + } + + @PreAuthorize(value="@ss.hasPermi('stat:dailystat:add')") + @Log(title="\u7269\u79cd\u6bcf\u65e5\u7edf\u8ba1", businessType=BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesDailyStat speciesDailyStat) { + return this.toAjax(this.speciesDailyStatService.insertSpeciesDailyStat(speciesDailyStat)); + } + + @PostMapping(value={"/periodStat"}) + public AjaxResult getBirdPeriodStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesDailyStatService.getBirdPeriodStatByParam(obj)); + } + + @PostMapping(value={"/monthStat"}) + public AjaxResult getBirdMonthStat(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesDailyStatService.getBirdMonthStatByParam(obj)); + } + + @PostMapping(value={"/weeklyReport"}) + public AjaxResult getBirdWeeklyStatReport(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesDailyStatService.getSpeciesWeeklyReportByParam(obj)); + } + + @PostMapping(value={"/downloadWeeklyReport"}) + public void downloadWeeklyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + String filePath = this.speciesDailyStatService.getBirdDataWeeklyStatFileByParam(params); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @PostMapping(value={"/downloadMonthlyReport"}) + public void downloadMonthlyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + String filePath = this.speciesDailyStatService.getBirdDataMonthlyStatFileByParam(params); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @PostMapping(value={"/downloadYearlyReport"}) + public void downloadYearlyReport(@RequestParam Map params, HttpServletResponse response, HttpServletRequest request) { + String filePath = this.speciesDailyStatService.getBirdDataYearlyStatFileByParam(params); + if (filePath != null) { + try { + String realFileName = System.currentTimeMillis() + ".xlsx"; + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + FileUtils.setAttachmentResponseHeader((HttpServletResponse)response, (String)realFileName); + FileUtils.writeBytes((String)filePath, (OutputStream)response.getOutputStream()); + } + catch (Exception ex) { + ex.printStackTrace(); + } + } + } + + @PostMapping(value={"/monthlyReport"}) + public AjaxResult getBirdMonthlyStatReport(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesDailyStatService.getSpeciesMonthlyStatByParam(obj)); + } + + @PostMapping(value={"/yearlyReport"}) + public AjaxResult getBirdYearlyStatReport(@RequestBody JSONObject obj) { + return AjaxResult.success((Object)this.speciesDailyStatService.getSpeciesYearlyStatByParam(obj)); + } + + @PostMapping(value={"/sendWeeklyEmail"}) + public AjaxResult sendWeeklyEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.speciesDailyStatService.sendBirdDataWeeklyStatEmail(object)); + } + + @PostMapping(value={"/sendMonthlyEmail"}) + public AjaxResult sendMonthlyEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.speciesDailyStatService.sendBirdDataMonthlyStatEmail(object)); + } + + @PostMapping(value={"/sendYearlyEmail"}) + public AjaxResult sendYearlyEmail(@RequestBody JSONObject object) { + return AjaxResult.success((Object)this.speciesDailyStatService.sendBirdDataYearlyStatEmail(object)); + } + + @PostMapping(value={"/areaAmountInfo"}) + public JSONObject getAreaStatInfoByParam(@RequestBody JSONObject object) { + return this.speciesDailyStatService.getAreaStatInfoByParam(object); + } + + @GetMapping(value={"/statAmountInfo/{type}"}) + public JSONObject getStatInfoByParam(@PathVariable int type) { + return this.speciesDailyStatService.getStatInfoByParam(type); + } + + @PostMapping(value={"/yearAmountByMonth"}) + public JSONObject getSpeciesYearTotalStatByParam(@RequestBody JSONObject object) { + return this.speciesDailyStatService.getSpeciesYearTotalStatByParam(object); + } + + @PostMapping(value={"/statInfoByParam"}) + public JSONObject getSpeciesStatInfoByParam(@RequestBody JSONObject object) { + return this.speciesDailyStatService.getSpeciesStatInfoByParam(object); + } + + @PostMapping(value={"/speciesMediaStatList"}) + public JSONObject getSpeciesMediaListByParam(@RequestBody JSONObject object) { + return this.speciesDailyStatService.getSpeciesMediaListByParam(object); + } + + @PostMapping(value={"/speciesStatList"}) + public JSONObject getSpeciesMediaStatInfoByParam(@RequestBody JSONObject object) { + return this.speciesDailyStatService.getSpeciesStatListByParam(object); + } + + @PostMapping(value={"/speciesAmountListByParam"}) + public JSONObject getSpeciesAmountReportByParam(@RequestBody JSONObject param) { + return this.speciesDailyStatService.getSpeciesAmountReportByParam(param); + } + + @PostMapping(value={"/winterPeriodAmountByParam"}) + public JSONObject getSpeciesWinterAmountByParam(@RequestBody JSONObject param) { + return this.speciesDailyStatService.getSpeciesWinterPeriodAmountByParam(param); + } + + @PostMapping(value={"/speciesStatListByParam"}) + public JSONObject getSpeciesDailyStatByParam(@RequestBody JSONObject param) { + return this.speciesDailyStatService.getSpeciesDailyStatByParam(param); + } + + @PostMapping(value={"/speciesGroupStatListByParam"}) + public JSONObject getSpeciesGroupStatByParam(@RequestBody JSONObject param) { + return this.speciesDailyStatService.getSpeciesGroupStatByParam(param); + } + + @PostMapping(value={"/postStatData"}) + public AjaxResult postStatData() { + return AjaxResult.success((Object)this.speciesDailyStatService.postTodaySpeciesData(57L)); + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesInhabitStatController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesInhabitStatController.java new file mode 100644 index 0000000..4a5515c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesInhabitStatController.java @@ -0,0 +1,97 @@ +package net.hzvtc.web.stat.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.web.stat.domain.SpeciesInhabitStat; +import net.hzvtc.web.stat.service.SpeciesInhabitStatService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 物种生境数量统计Controller + * + * @author admin + * @date 2022-11-05 + */ +@RestController +@RequestMapping("/stat/bird/inhabit") +public class SpeciesInhabitStatController extends BaseController { + @Autowired + private SpeciesInhabitStatService speciesInhabitStatService; + + /** + * 查询物种生境数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:list')") + @GetMapping("/list") + public TableDataInfo list(SpeciesInhabitStat speciesInhabitStat) { + startPage(); + List list = speciesInhabitStatService.selectSpeciesInhabitStatList(speciesInhabitStat); + return getDataTable(list); + } + + @GetMapping("/amount") + public AjaxResult getAmount(SpeciesInhabitStat speciesInhabitStat) { + List list = speciesInhabitStatService.selectSpeciesInhabitStatList(speciesInhabitStat); + return AjaxResult.success(list); + } + + /** + * 导出物种生境数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:export')") + @Log(title = "物种生境数量统计", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SpeciesInhabitStat speciesInhabitStat) { + List list = speciesInhabitStatService.selectSpeciesInhabitStatList(speciesInhabitStat); + ExcelUtil util = new ExcelUtil(SpeciesInhabitStat.class); + util.exportExcel(response, list, "物种生境数量统计数据"); + } + + /** + * 获取物种生境数量统计详细信息 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(speciesInhabitStatService.selectSpeciesInhabitStatById(id)); + } + + /** + * 新增物种生境数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:add')") + @Log(title = "物种生境数量统计", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesInhabitStat speciesInhabitStat) { + return toAjax(speciesInhabitStatService.insertSpeciesInhabitStat(speciesInhabitStat)); + } + + /** + * 修改物种生境数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:edit')") + @Log(title = "物种生境数量统计", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody SpeciesInhabitStat speciesInhabitStat) { + return toAjax(speciesInhabitStatService.updateSpeciesInhabitStat(speciesInhabitStat)); + } + + /** + * 删除物种生境数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:inhabitstat:remove')") + @Log(title = "物种生境数量统计", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(speciesInhabitStatService.deleteSpeciesInhabitStatByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesLocationInfoController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesLocationInfoController.java new file mode 100644 index 0000000..c803a5d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesLocationInfoController.java @@ -0,0 +1,96 @@ +package net.hzvtc.web.stat.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.web.stat.domain.SpeciesLocationInfo; +import net.hzvtc.web.stat.service.SpeciesLocationInfoService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 国内鸟类分布点Controller + * + * @author admin + * @date 2022-11-06 + */ +@RestController +@RequestMapping("/stat/bird/location") +public class SpeciesLocationInfoController extends BaseController { + @Autowired + private SpeciesLocationInfoService speciesLocationInfoService; + + /** + * 查询国内鸟类分布点列表 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:list')") + @GetMapping("/list") + public TableDataInfo list(SpeciesLocationInfo speciesLocationInfo) { + startPage(); + List list = speciesLocationInfoService.selectSpeciesLocationInfoList(speciesLocationInfo); + return getDataTable(list); + } + + @GetMapping("/listForWeb") + public AjaxResult listForWeb(SpeciesLocationInfo speciesLocationInfo) { + return AjaxResult.success(speciesLocationInfoService.selectSpeciesLocationInfoList(speciesLocationInfo)); + } + + /** + * 导出国内鸟类分布点列表 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:export')") + @Log(title = "国内鸟类分布点", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SpeciesLocationInfo speciesLocationInfo) { + List list = speciesLocationInfoService.selectSpeciesLocationInfoList(speciesLocationInfo); + ExcelUtil util = new ExcelUtil(SpeciesLocationInfo.class); + util.exportExcel(response, list, "国内鸟类分布点数据"); + } + + /** + * 获取国内鸟类分布点详细信息 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(speciesLocationInfoService.selectSpeciesLocationInfoById(id)); + } + + /** + * 新增国内鸟类分布点 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:add')") + @Log(title = "国内鸟类分布点", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesLocationInfo speciesLocationInfo) { + return toAjax(speciesLocationInfoService.insertSpeciesLocationInfo(speciesLocationInfo)); + } + + /** + * 修改国内鸟类分布点 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:edit')") + @Log(title = "国内鸟类分布点", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody SpeciesLocationInfo speciesLocationInfo) { + return toAjax(speciesLocationInfoService.updateSpeciesLocationInfo(speciesLocationInfo)); + } + + /** + * 删除国内鸟类分布点 + */ + @PreAuthorize("@ss.hasPermi('stat:birdlocation:remove')") + @Log(title = "国内鸟类分布点", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(speciesLocationInfoService.deleteSpeciesLocationInfoByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesWinterPeriodController.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesWinterPeriodController.java new file mode 100644 index 0000000..f42a41a --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/controller/SpeciesWinterPeriodController.java @@ -0,0 +1,96 @@ +package net.hzvtc.web.stat.controller; + +import net.hzvtc.common.annotation.Log; +import net.hzvtc.common.core.controller.BaseController; +import net.hzvtc.common.core.domain.AjaxResult; +import net.hzvtc.common.core.page.TableDataInfo; +import net.hzvtc.common.enums.BusinessType; +import net.hzvtc.common.utils.poi.ExcelUtil; +import net.hzvtc.web.stat.domain.SpeciesWinterPeriod; +import net.hzvtc.web.stat.service.SpeciesWinterPeriodService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 物种越冬期数量统计Controller + * + * @author admin + * @date 2022-11-04 + */ +@RestController +@RequestMapping("/stat/bird/winter/period/count") +public class SpeciesWinterPeriodController extends BaseController { + @Autowired + private SpeciesWinterPeriodService speciesWinterPeriodService; + + /** + * 查询物种越冬期数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:period:list')") + @GetMapping("/list") + public TableDataInfo list(SpeciesWinterPeriod speciesWinterPeriod) { + startPage(); + List list = speciesWinterPeriodService.selectSpeciesWinterPeriodList(speciesWinterPeriod); + return getDataTable(list); + } + + @GetMapping("/amount") + public AjaxResult getAmount(SpeciesWinterPeriod speciesWinterPeriod) { + return AjaxResult.success(speciesWinterPeriodService.selectSpeciesWinterPeriodList(speciesWinterPeriod)); + } + + /** + * 导出物种越冬期数量统计列表 + */ + @PreAuthorize("@ss.hasPermi('stat:period:export')") + @Log(title = "物种越冬期数量统计", businessType = BusinessType.EXPORT) + @PostMapping("/export") + public void export(HttpServletResponse response, SpeciesWinterPeriod speciesWinterPeriod) { + List list = speciesWinterPeriodService.selectSpeciesWinterPeriodList(speciesWinterPeriod); + ExcelUtil util = new ExcelUtil(SpeciesWinterPeriod.class); + util.exportExcel(response, list, "物种越冬期数量统计数据"); + } + + /** + * 获取物种越冬期数量统计详细信息 + */ + @PreAuthorize("@ss.hasPermi('stat:period:query')") + @GetMapping(value = "/{id}") + public AjaxResult getInfo(@PathVariable("id") Long id) { + return AjaxResult.success(speciesWinterPeriodService.selectSpeciesWinterPeriodById(id)); + } + + /** + * 新增物种越冬期数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:period:add')") + @Log(title = "物种越冬期数量统计", businessType = BusinessType.INSERT) + @PostMapping + public AjaxResult add(@RequestBody SpeciesWinterPeriod speciesWinterPeriod) { + return toAjax(speciesWinterPeriodService.insertSpeciesWinterPeriod(speciesWinterPeriod)); + } + + /** + * 修改物种越冬期数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:period:edit')") + @Log(title = "物种越冬期数量统计", businessType = BusinessType.UPDATE) + @PutMapping + public AjaxResult edit(@RequestBody SpeciesWinterPeriod speciesWinterPeriod) { + return toAjax(speciesWinterPeriodService.updateSpeciesWinterPeriod(speciesWinterPeriod)); + } + + /** + * 删除物种越冬期数量统计 + */ + @PreAuthorize("@ss.hasPermi('stat:period:remove')") + @Log(title = "物种越冬期数量统计", businessType = BusinessType.DELETE) + @DeleteMapping("/{ids}") + public AjaxResult remove(@PathVariable Long[] ids) { + return toAjax(speciesWinterPeriodService.deleteSpeciesWinterPeriodByIds(ids)); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyInhabit.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyInhabit.java new file mode 100644 index 0000000..a1a388b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyInhabit.java @@ -0,0 +1,19 @@ +package net.hzvtc.web.stat.domain; + +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesDailyInhabit") +@Data +public class SpeciesDailyInhabit { + private static final long serialVersionUID = 1L; + private Long id; + private Long recordId; + private Long speciesId; + private String habitat; + private Long areaId; + private Long deviceId; + private String statDate; + private int amount; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyStat.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyStat.java new file mode 100644 index 0000000..a996eaa --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesDailyStat.java @@ -0,0 +1,21 @@ +package net.hzvtc.web.stat.domain; + +import com.fasterxml.jackson.annotation.JsonFormat; +import java.util.Date; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesDailyStat") +@Data +public class SpeciesDailyStat { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private Long areaId; + private Long deviceId; + private Long recordId; + private Date statDate; + private int maxValue; + private int avgValue; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesInhabitStat.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesInhabitStat.java new file mode 100644 index 0000000..f33489c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesInhabitStat.java @@ -0,0 +1,22 @@ +package net.hzvtc.web.stat.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesInhabitStat") +@Data +public class SpeciesInhabitStat extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long statYear; + private Long speciesId; + private Long areaId; + private Long data1; + private Long data2; + private Long data3; + private Long data4; + private Long data5; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesLocationInfo.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesLocationInfo.java new file mode 100644 index 0000000..8cac813 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesLocationInfo.java @@ -0,0 +1,19 @@ +package net.hzvtc.web.stat.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesLocationInfo") +@Data +public class SpeciesLocationInfo extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Long speciesId; + private String name; + private String longitude; + private String latitude; + private String memo; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesWinterPeriod.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesWinterPeriod.java new file mode 100644 index 0000000..08ce051 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/domain/SpeciesWinterPeriod.java @@ -0,0 +1,23 @@ +package net.hzvtc.web.stat.domain; + + +import net.hzvtc.common.core.domain.BaseEntity; +import lombok.Data; +import net.hzvtc.common.annotation.Excel; +import org.apache.ibatis.type.Alias; + +@Alias(value="SpeciesWinterPeriod") +@Data +public class SpeciesWinterPeriod extends BaseEntity { + private static final long serialVersionUID = 1L; + private Long id; + private Integer year; + private Long areaId; + private Long speciesId; + private int data1; + private int data2; + private int data3; + private int data4; + private int data5; + private int data6; +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/BirdWebPageStatMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/BirdWebPageStatMapper.java new file mode 100644 index 0000000..0ab6e17 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/BirdWebPageStatMapper.java @@ -0,0 +1,42 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.bird.domain.BirdLeaveArriveInfo; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface BirdWebPageStatMapper { + public List getBirdDailyAmountListByParam(Map var1); + + public List getBirdDailyAmountNormalListByParam(Map var1); + + public List getBirdDailyStatListByParam(Map var1); + + public List getBirdAudioDailyStatListByParam(Map var1); + + public List getBirdAudioMonthStatListByParam(Map var1); + + public List getBirdAudioYearStatListByParam(Map var1); + + public List getBirdDailyAmountAbnormalListByParam(Map var1); + + public List getBirdDailyOtherAmountListByParam(Map var1); + + public List getBirdDailyFamilyListByParam(Map var1); + + public List getBirdPeriodStatByParam(Map var1); + + public List getBirdAudioMonthStatByParam(Map var1); + + public List getBirdAudioYearStatByParam(Map var1); + + public List getSpeciesWinterPeriodAudioAmountByParam(Map var1); + + public List getBirdMonthStatByParam(Map var1); + + public List getBirdStatYearInfoByParam(Map var1); + + public List getBirdArriveAndLeaveInfoByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyInhabitMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyInhabitMapper.java new file mode 100644 index 0000000..0fb1ebb --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyInhabitMapper.java @@ -0,0 +1,29 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.web.stat.domain.SpeciesDailyInhabit; + +public interface SpeciesDailyInhabitMapper { + public List selectSpeciesDailyInhabitList(SpeciesDailyInhabit var1); + + public int insertSpeciesDailyInhabit(SpeciesDailyInhabit var1); + + public List getSpeciesDailyInhabitListByParam(Map var1); + + public List getSpeciesDailyInhabitRealListByParam(Map var1); + + public int batchInsertSpeciesDailyInhabit(List var1); + + public List getSpeciesDailyInhabitYearAmountListByParam(Map var1); + + public List getSpeciesDailyInhabitWeeklyAmountListByParam(Map var1); + + public List getSpeciesDailyInhabitMonthlyAmountListByParam(Map var1); + + public List getSpeciesInhabitStatYearListByParam(Map var1); + + public int deleteSpeciesDailyInhabitByDate(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyStatMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyStatMapper.java new file mode 100644 index 0000000..fc323e0 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesDailyStatMapper.java @@ -0,0 +1,72 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import java.util.Map; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.web.stat.domain.SpeciesDailyStat; + +public interface SpeciesDailyStatMapper { + public List selectSpeciesDailyStatList(SpeciesDailyStat var1); + + public List getSpeciesDailyStatListByParam(Map var1); + + public List getRecordDateListByParam(Map var1); + + public List getBirdPeriodStatByParam(Map var1); + + public List getSpeciesDailyStatByParam(Map var1); + + public List getSpeciesGroupStatByParam(Map var1); + + public List getBirdMonthStatByParam(Map var1); + + public List getSpeciesWinterPeriodData(Map var1); + + public List getSpeciesWeeklyStatByDeviceId(Map var1); + + public List getSpeciesMonthlyStatByDeviceId(Map var1); + + public List getSpeciesYearlyStatByDeviceId(Map var1); + + public List getSpeciesYearlyStatBySpeciesId(Map var1); + + public List getSpeciesWeeklyStatBySpeciesId(Map var1); + + public List getSpeciesYearTotalStatByParam(Map var1); + + public List getSpeciesYearTotalMaxStatByParam(Map var1); + + public List getSpeciesStatInfoByParam(Map var1); + + public List getSpeciesAmountReportByParam(Map var1); + + public List getSpeciesMonthlyStatBySpeciesId(Map var1); + + public List getSpeciesWinterPeriodAmountByParam(Map var1); + + public List getSpeciesDailyAmountByParam(Map var1); + + public Integer getSpeciesDailySpeciesAmountByParam(Map var1); + + public Long getSpeciesTotalAmountByAreaId(Map var1); + + public int getBirdCatalogueAmount(); + + public int getBirdFamilyAmount(); + + public int getBirdGenusAmount(); + + public int insertSpeciesDailyStat(SpeciesDailyStat var1); + + public int batchInsertSpeciesDailyStat(List var1); + + public int deleteSpeciesDailyStatByDate(Map var1); + + public Integer getSpeciesAmountByParam(Map var1); + + public Integer getSpeciesMaxAmountByParam(Map var1); + + public Integer getStatAmountByParam(Map var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesInhabitStatMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesInhabitStatMapper.java new file mode 100644 index 0000000..a786a88 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesInhabitStatMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import net.hzvtc.web.stat.domain.SpeciesInhabitStat; + +/** + * 物种生境数量统计Mapper接口 + * + * @author admin + * @date 2022-11-05 + */ +public interface SpeciesInhabitStatMapper +{ + /** + * 查询物种生境数量统计 + * + * @param id 物种生境数量统计主键 + * @return 物种生境数量统计 + */ + public SpeciesInhabitStat selectSpeciesInhabitStatById(Long id); + + /** + * 查询物种生境数量统计列表 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 物种生境数量统计集合 + */ + public List selectSpeciesInhabitStatList(SpeciesInhabitStat speciesInhabitStat); + + /** + * 新增物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + public int insertSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat); + + /** + * 修改物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + public int updateSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat); + + /** + * 删除物种生境数量统计 + * + * @param id 物种生境数量统计主键 + * @return 结果 + */ + public int deleteSpeciesInhabitStatById(Long id); + + /** + * 批量删除物种生境数量统计 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteSpeciesInhabitStatByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesLocationInfoMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesLocationInfoMapper.java new file mode 100644 index 0000000..65976fe --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesLocationInfoMapper.java @@ -0,0 +1,61 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import net.hzvtc.web.stat.domain.SpeciesLocationInfo; + +/** + * 国内鸟类分布点Mapper接口 + * + * @author admin + * @date 2022-11-06 + */ +public interface SpeciesLocationInfoMapper +{ + /** + * 查询国内鸟类分布点 + * + * @param id 国内鸟类分布点主键 + * @return 国内鸟类分布点 + */ + public SpeciesLocationInfo selectSpeciesLocationInfoById(Long id); + + /** + * 查询国内鸟类分布点列表 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 国内鸟类分布点集合 + */ + public List selectSpeciesLocationInfoList(SpeciesLocationInfo speciesLocationInfo); + + /** + * 新增国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + public int insertSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo); + + /** + * 修改国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + public int updateSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo); + + /** + * 删除国内鸟类分布点 + * + * @param id 国内鸟类分布点主键 + * @return 结果 + */ + public int deleteSpeciesLocationInfoById(Long id); + + /** + * 批量删除国内鸟类分布点 + * + * @param ids 需要删除的数据主键集合 + * @return 结果 + */ + public int deleteSpeciesLocationInfoByIds(Long[] ids); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesWinterPeriodMapper.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesWinterPeriodMapper.java new file mode 100644 index 0000000..0316fa2 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/mapper/SpeciesWinterPeriodMapper.java @@ -0,0 +1,22 @@ +package net.hzvtc.web.stat.mapper; + +import java.util.List; +import net.hzvtc.web.stat.domain.SpeciesWinterPeriod; + +public interface SpeciesWinterPeriodMapper { + public SpeciesWinterPeriod selectSpeciesWinterPeriodById(Long var1); + + public List selectSpeciesWinterPeriodList(SpeciesWinterPeriod var1); + + public int insertSpeciesWinterPeriod(SpeciesWinterPeriod var1); + + public int updateSpeciesWinterPeriod(SpeciesWinterPeriod var1); + + public int batchInsertSpeciesWinterPeriod(List var1); + + public int deleteSpeciesWinterPeriodById(Long var1); + + public int deleteSpeciesWinterPeriodByIds(Long[] var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/BirdWebPageStatService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/BirdWebPageStatService.java new file mode 100644 index 0000000..b2ed332 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/BirdWebPageStatService.java @@ -0,0 +1,35 @@ +package net.hzvtc.web.stat.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; + +public interface BirdWebPageStatService { + public JSONObject getBirdDailyAmountListByParam(JSONObject var1); + + public JSONObject getBirdDailyStatListByParam(JSONObject var1); + + public JSONObject getBirdAudioDailyStatListByParam(JSONObject var1); + + public List getBirdDailyFamilyListByParam(JSONObject var1); + + public JSONObject getBirdPeriodStatByParam(JSONObject var1); + + public JSONObject getBirdMonthStatByParam(JSONObject var1); + + public List getBirdStatYearInfoByParam(JSONObject var1); + + public JSONObject getBirdAudioMonthStatListByParam(JSONObject var1); + + public JSONObject getBirdAudioYearStatListByParam(JSONObject var1); + + public JSONObject getBirdArriveAndLeaveInfoByParam(JSONObject var1); + + public JSONObject getBirdAudioMonthStatByParam(JSONObject var1); + + public JSONObject getBirdAudioYearStatByParam(JSONObject var1); + + public JSONObject getSpeciesWinterPeriodAudioAmountByParam(JSONObject var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyInhabitService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyInhabitService.java new file mode 100644 index 0000000..82092b1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyInhabitService.java @@ -0,0 +1,33 @@ +package net.hzvtc.web.stat.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.web.stat.domain.SpeciesDailyInhabit; + +public interface SpeciesDailyInhabitService { + public List selectSpeciesDailyInhabitList(SpeciesDailyInhabit var1); + + public int insertSpeciesDailyInhabit(SpeciesDailyInhabit var1); + + public List getSpeciesDailyInhabitListByParam(Map var1); + + public List getSpeciesDailyInhabitRealListByParam(Map var1); + + public int batchInsertSpeciesDailyInhabit(List var1); + + public List getSpeciesDailyInhabitYearAmountListByParam(Map var1); + + public List getSpeciesDailyInhabitWeeklyAmountListByParam(Map var1); + + public List getSpeciesDailyInhabitMonthlyAmountListByParam(Map var1); + + public List getSpeciesInhabitStatYearListByParam(Map var1); + + public JSONArray getSpeciesListByParam(JSONObject var1); + + public int deleteSpeciesDailyInhabitByDate(String var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyStatService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyStatService.java new file mode 100644 index 0000000..c387930 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesDailyStatService.java @@ -0,0 +1,91 @@ +package net.hzvtc.web.stat.service; + +import com.alibaba.fastjson.JSONObject; +import java.util.List; +import java.util.Map; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.web.stat.domain.SpeciesDailyStat; + +public interface SpeciesDailyStatService { + public List selectSpeciesDailyStatList(SpeciesDailyStat var1); + + public int insertSpeciesDailyStat(SpeciesDailyStat var1); + + public List getSpeciesDailyStatListByParam(JSONObject var1); + + public List getSpeciesDailyStatListByParam(Map var1); + + public void calculateDailyResultRecord(String var1); + + public void calculateDailyResultRecordByParam(JSONObject var1); + + public void calculateAllResultRecord(); + + public JSONObject getBirdPeriodStatByParam(JSONObject var1); + + public List getBirdPeriodStatListByParam(JSONObject var1); + + public JSONObject getBirdMonthStatByParam(JSONObject var1); + + public List getBirdMonthStatListByParam(JSONObject var1); + + public JSONObject getSpeciesDailyStatByParam(JSONObject var1); + + public JSONObject getSpeciesGroupStatByParam(JSONObject var1); + + public List getSpeciesWinterPeriodData(Map var1); + + public JSONObject getSpeciesWeeklyReportByParam(JSONObject var1); + + public JSONObject getSpeciesMonthlyStatByParam(JSONObject var1); + + public JSONObject getSpeciesYearlyStatByParam(JSONObject var1); + + public String getBirdDataWeeklyStatFileByParam(Map var1); + + public String getBirdDataMonthlyStatFileByParam(Map var1); + + public String getBirdDataYearlyStatFileByParam(Map var1); + + public boolean sendBirdDataWeeklyStatEmail(JSONObject var1); + + public boolean sendBirdDataMonthlyStatEmail(JSONObject var1); + + public boolean sendBirdDataYearlyStatEmail(JSONObject var1); + + public int deleteSpeciesDailyStatByDate(String var1); + + public JSONObject getAreaStatInfoByParam(JSONObject var1); + + public JSONObject getStatInfoByParam(int var1); + + public JSONObject getSpeciesYearTotalStatByParam(JSONObject var1); + + public JSONObject getSpeciesStatInfoByParam(JSONObject var1); + + public JSONObject getSpeciesMediaListByParam(JSONObject var1); + + public JSONObject getSpeciesStatListByParam(JSONObject var1); + + public JSONObject getSpeciesAmountReportByParam(JSONObject var1); + + public JSONObject getSpeciesWinterPeriodAmountByParam(JSONObject var1); + + public int getBirdCatalogueAmount(); + + public int getBirdFamilyAmount(); + + public int getBirdGenusAmount(); + + public SpeciesDailyStat getSpeciesDailyAmountByParam(Map var1); + + public Integer getSpeciesDailySpeciesAmountByParam(Map var1); + + public int getSpeciesDailyStatAmountByParam(Map var1); + + public Long getSpeciesTotalAmountByAreaId(Map var1); + + public JSONObject postTodaySpeciesData(Long var1); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesInhabitStatService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesInhabitStatService.java new file mode 100644 index 0000000..49c1a3d --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesInhabitStatService.java @@ -0,0 +1,61 @@ +package net.hzvtc.web.stat.service; + +import java.util.List; + +import net.hzvtc.web.stat.domain.SpeciesInhabitStat; + +/** + * 物种生境数量统计Service接口 + * + * @author admin + * @date 2022-11-05 + */ +public interface SpeciesInhabitStatService { + /** + * 查询物种生境数量统计 + * + * @param id 物种生境数量统计主键 + * @return 物种生境数量统计 + */ + public SpeciesInhabitStat selectSpeciesInhabitStatById(Long id); + + /** + * 查询物种生境数量统计列表 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 物种生境数量统计集合 + */ + public List selectSpeciesInhabitStatList(SpeciesInhabitStat speciesInhabitStat); + + /** + * 新增物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + public int insertSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat); + + /** + * 修改物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + public int updateSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat); + + /** + * 批量删除物种生境数量统计 + * + * @param ids 需要删除的物种生境数量统计主键集合 + * @return 结果 + */ + public int deleteSpeciesInhabitStatByIds(Long[] ids); + + /** + * 删除物种生境数量统计信息 + * + * @param id 物种生境数量统计主键 + * @return 结果 + */ + public int deleteSpeciesInhabitStatById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesLocationInfoService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesLocationInfoService.java new file mode 100644 index 0000000..7b277da --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesLocationInfoService.java @@ -0,0 +1,61 @@ +package net.hzvtc.web.stat.service; + +import java.util.List; + +import net.hzvtc.web.stat.domain.SpeciesLocationInfo; + +/** + * 国内鸟类分布点Service接口 + * + * @author admin + * @date 2022-11-06 + */ +public interface SpeciesLocationInfoService { + /** + * 查询国内鸟类分布点 + * + * @param id 国内鸟类分布点主键 + * @return 国内鸟类分布点 + */ + public SpeciesLocationInfo selectSpeciesLocationInfoById(Long id); + + /** + * 查询国内鸟类分布点列表 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 国内鸟类分布点集合 + */ + public List selectSpeciesLocationInfoList(SpeciesLocationInfo speciesLocationInfo); + + /** + * 新增国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + public int insertSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo); + + /** + * 修改国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + public int updateSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo); + + /** + * 批量删除国内鸟类分布点 + * + * @param ids 需要删除的国内鸟类分布点主键集合 + * @return 结果 + */ + public int deleteSpeciesLocationInfoByIds(Long[] ids); + + /** + * 删除国内鸟类分布点信息 + * + * @param id 国内鸟类分布点主键 + * @return 结果 + */ + public int deleteSpeciesLocationInfoById(Long id); +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesWinterPeriodService.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesWinterPeriodService.java new file mode 100644 index 0000000..a040c11 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/SpeciesWinterPeriodService.java @@ -0,0 +1,22 @@ +package net.hzvtc.web.stat.service; + +import java.util.List; +import net.hzvtc.web.stat.domain.SpeciesWinterPeriod; + +public interface SpeciesWinterPeriodService { + public SpeciesWinterPeriod selectSpeciesWinterPeriodById(Long var1); + + public List selectSpeciesWinterPeriodList(SpeciesWinterPeriod var1); + + public int insertSpeciesWinterPeriod(SpeciesWinterPeriod var1); + + public int updateSpeciesWinterPeriod(SpeciesWinterPeriod var1); + + public int deleteSpeciesWinterPeriodByIds(Long[] var1); + + public int deleteSpeciesWinterPeriodById(Long var1); + + public void calcSpeciesWinterPeriodByParam(); +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/BirdWebPageStatServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/BirdWebPageStatServiceImpl.java new file mode 100644 index 0000000..71b9463 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/BirdWebPageStatServiceImpl.java @@ -0,0 +1,432 @@ +package net.hzvtc.web.stat.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Calendar; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.web.stat.mapper.BirdWebPageStatMapper; +import net.hzvtc.web.stat.service.BirdWebPageStatService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class BirdWebPageStatServiceImpl +implements BirdWebPageStatService { + private static final Logger log = LoggerFactory.getLogger(BirdWebPageStatServiceImpl.class); + @Resource + private BirdWebPageStatMapper birdWebPageStatMapper; + + @Override + public JSONObject getBirdDailyAmountListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Integer limit = param.getInteger("limit"); + if (limit == null) { + limit = 10; + } + map.put("limit", limit); + map.put("isCommont", 1); + List list = this.birdWebPageStatMapper.getBirdDailyAmountListByParam(map); + if (list != null && list.size() > 0) { + List ids = list.stream().map(item -> item.getId()).collect(Collectors.toList()); + map.put("list", ids); + List otherList = this.birdWebPageStatMapper.getBirdDailyOtherAmountListByParam(map); + if (otherList != null && otherList.size() > 0) { + BirdStatDataVo data2 = otherList.get(0); + data2.setName("\u5176\u4ed6"); + list.add(data2); + } + JSONArray array = new JSONArray(); + Map arealist = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getName, LinkedHashMap::new, Collectors.toList())); + arealist.forEach((key, data) -> { + JSONObject obj = new JSONObject(); + obj.put("name", key); + int[] data1 = new int[]{0}; + int[] data2 = new int[]{0}; + data.stream().forEach(item -> { + if (item.getHour() <= 12) { + if (item.getCount() > data1[0]) { + data1[0] = item.getCount(); + } + } else if (item.getCount() > data2[0]) { + data2[0] = item.getCount(); + } + }); + obj.put("data1", (Object)data1[0]); + obj.put("data2", (Object)data2[0]); + array.add((Object)obj); + }); + result.put("list", (Object)array); + } + return result; + } + + @Override + public JSONObject getBirdDailyStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + List list = this.birdWebPageStatMapper.getBirdDailyStatListByParam(map); + result.put("list", list); + return result; + } + + @Override + public JSONObject getBirdAudioDailyStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + List list = this.birdWebPageStatMapper.getBirdAudioDailyStatListByParam(map); + if (list != null && !list.isEmpty()) { + int[] hourAmount = new int[24]; + JSONArray array = new JSONArray(); + list.forEach(item -> { + int n = item.getHour(); + hourAmount[n] = hourAmount[n] + item.getCount(); + }); + result.put("hourAmount", (Object)hourAmount); + Map subList = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getSpeciesId, LinkedHashMap::new, Collectors.toList())); + subList.forEach((key, data) -> { + JSONObject obj = new JSONObject(); + obj.put("id", key); + String[] name = new String[]{""}; + Long[] familyId = new Long[]{0L}; + String[] familyName = new String[]{""}; + String[] code = new String[]{""}; + String[] codeName = new String[]{""}; + int[] amount = new int[]{0, 0}; + data.forEach(item -> { + name[0] = item.getName(); + familyId[0] = item.getFamilyId(); + familyName[0] = item.getFamilyName(); + code[0] = item.getCode(); + codeName[0] = item.getCodeName(); + if (item.getHour() < 18 && item.getHour() >= 6) { + amount[0] = amount[0] + item.getCount(); + } else { + amount[1] = amount[1] + item.getCount(); + } + }); + obj.put("data1", (Object)amount[0]); + obj.put("data2", (Object)amount[1]); + obj.put("dataAll", (Object)(amount[0] + amount[1])); + obj.put("name", (Object)name[0]); + obj.put("familyId", (Object)familyId[0]); + obj.put("familyName", (Object)familyName[0]); + obj.put("code", (Object)code[0]); + obj.put("codeName", (Object)codeName[0]); + array.add((Object)obj); + }); + array.sort(Comparator.comparing(obj -> ((JSONObject)obj).getInteger("dataAll")).reversed()); + result.put("list", (Object)array); + } + return result; + } + + @Override + public List getBirdDailyFamilyListByParam(JSONObject param) { + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + if (calcDate == null || calcDate.isEmpty()) { + calcDate = df.format(new Date()); + } + map.put("calcDate", calcDate); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + return this.birdWebPageStatMapper.getBirdDailyFamilyListByParam(map); + } + + @Override + public JSONObject getBirdPeriodStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + String dateTo = param.getString("dateTo"); + if (dateTo == null || dateTo.isEmpty()) { + dateTo = df.format(new Date()); + } + map.put("dateTo", dateTo); + String dateFrom = param.getString("dateFrom"); + if (dateFrom == null || dateFrom.isEmpty()) { + Calendar calendar = Calendar.getInstance(); + try { + calendar.setTime(df.parse(dateTo)); + calendar.add(5, -30); + Date minDate = calendar.getTime(); + dateFrom = df.format(minDate); + } + catch (Exception exception) { + // empty catch block + } + } + map.put("dateFrom", dateFrom); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + result.put("list", this.birdWebPageStatMapper.getBirdPeriodStatByParam(map)); + result.put("dateFrom", (Object)dateFrom); + result.put("dateTo", (Object)dateTo); + return result; + } + + @Override + public JSONObject getBirdMonthStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Integer calcYear = param.getInteger("calcYear"); + if (calcYear == null) { + calcYear = Calendar.getInstance().get(1); + } + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + map.put("calcYear", calcYear); + result.put("list", this.birdWebPageStatMapper.getBirdMonthStatByParam(map)); + result.put("calcYear", (Object)calcYear); + return result; + } + + @Override + public List getBirdStatYearInfoByParam(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer startYear = param.getInteger("calcStartYear"); + map.put("startYear", startYear); + Integer endYear = param.getInteger("calcEndYear"); + map.put("endYear", endYear); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + return this.birdWebPageStatMapper.getBirdStatYearInfoByParam(map); + } + + @Override + public JSONObject getBirdAudioMonthStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer calcYear = param.getInteger("calcYear"); + if (calcYear == null) { + calcYear = LocalDate.now().getYear(); + } + map.put("calcYear", calcYear); + List list = this.birdWebPageStatMapper.getBirdAudioMonthStatListByParam(map); + if (list != null && !list.isEmpty()) { + Map subList = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getMonth, LinkedHashMap::new, Collectors.toList())); + JSONArray array = new JSONArray(); + subList.forEach((key, data) -> { + JSONObject obj = new JSONObject(); + obj.put("month", key); + int[] amount = new int[]{0, 0}; + data.forEach(item -> { + if (item.getHour() < 18 && item.getHour() >= 6) { + amount[0] = amount[0] + item.getCount(); + } else { + amount[1] = amount[1] + item.getCount(); + } + }); + obj.put("data1", (Object)amount[0]); + obj.put("data2", (Object)amount[1]); + array.add((Object)obj); + }); + result.put("list", (Object)array); + } + return result; + } + + @Override + public JSONObject getBirdAudioYearStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + Integer startYear = param.getInteger("startYear"); + map.put("startYear", startYear); + Integer endYear = param.getInteger("endYear"); + map.put("endYear", endYear); + List list = this.birdWebPageStatMapper.getBirdAudioYearStatListByParam(map); + if (list != null && !list.isEmpty()) { + Map subList = list.stream().collect(Collectors.groupingBy(BirdStatDataVo::getYear, LinkedHashMap::new, Collectors.toList())); + JSONArray array = new JSONArray(); + subList.forEach((key, data) -> { + JSONObject obj = new JSONObject(); + obj.put("year", key); + int[] amount = new int[]{0, 0, 0, 0}; + data.forEach(item -> { + if (item.getMonth() <= 3 && item.getMonth() >= 1) { + amount[0] = amount[0] + item.getCount(); + } else if (item.getMonth() <= 6 && item.getMonth() >= 4) { + amount[1] = amount[1] + item.getCount(); + } else if (item.getMonth() <= 9 && item.getMonth() >= 7) { + amount[2] = amount[2] + item.getCount(); + } else { + amount[3] = amount[3] + item.getCount(); + } + }); + obj.put("data1", (Object)amount[0]); + obj.put("data2", (Object)amount[1]); + obj.put("data3", (Object)amount[2]); + obj.put("data4", (Object)amount[3]); + array.add((Object)obj); + }); + result.put("list", (Object)array); + } + return result; + } + + @Override + public JSONObject getBirdArriveAndLeaveInfoByParam(JSONObject param) { + HashMap map = new HashMap(); + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + if (speciesId != null) { + map.put("speciesId", speciesId); + Integer startYear = param.getInteger("calcStartYear"); + map.put("startYear", startYear); + Integer endYear = param.getInteger("calcEndYear"); + map.put("endYear", endYear); + } else { + Integer year = param.getInteger("calcYear"); + if (year == null) { + year = Calendar.getInstance().get(1) - 1; + } + map.put("year", year); + result.put("calcYear", (Object)year); + } + result.put("list", this.birdWebPageStatMapper.getBirdArriveAndLeaveInfoByParam(map)); + return result; + } + + @Override + public JSONObject getBirdAudioMonthStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer year = param.getInteger("calcYear"); + if (year == null) { + year = LocalDate.now().getYear(); + } + map.put("calcYear", year); + List list = this.birdWebPageStatMapper.getBirdAudioMonthStatByParam(map); + result.put("list", list); + result.put("calcYear", (Object)year); + return result; + } + + @Override + public JSONObject getBirdAudioYearStatByParam(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer calcStartYear = param.getInteger("calcStartYear"); + map.put("calcStartYear", calcStartYear); + Integer calcEndYear = param.getInteger("calcEndYear"); + map.put("calcEndYear", calcEndYear); + List list = this.birdWebPageStatMapper.getBirdAudioYearStatByParam(map); + JSONObject result = new JSONObject(); + result.put("list", list); + return result; + } + + @Override + public JSONObject getSpeciesWinterPeriodAudioAmountByParam(JSONObject param) { + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer startYear = param.getInteger("startYear"); + Integer endYear = param.getInteger("endYear"); + if (startYear == null && endYear == null) { + Integer curYear = LocalDate.now().getYear(); + array.add((Object)this.getStatListByYear(curYear, map)); + object.put("startYear", (Object)(curYear + "")); + object.put("endYear", (Object)(curYear + "")); + } else if (startYear == null || endYear == null) { + Integer curYear = startYear == null ? endYear : startYear; + array.add((Object)this.getStatListByYear(curYear, map)); + object.put("startYear", (Object)(curYear + "")); + object.put("endYear", (Object)(curYear + "")); + } else { + for (int i = startYear.intValue(); i <= endYear; ++i) { + array.add((Object)this.getStatListByYear(i, map)); + } + object.put("startYear", (Object)(startYear + "")); + object.put("endYear", (Object)(endYear + "")); + } + object.put("list", (Object)array); + return object; + } + + private JSONObject getStatListByYear(Integer curYear, Map map) { + map.put("dateFrom", curYear - 1 + "-10-01"); + map.put("dateTo", curYear + "-03-31"); + List list = this.birdWebPageStatMapper.getSpeciesWinterPeriodAudioAmountByParam(map); + JSONObject obj = new JSONObject(); + obj.put("year", (Object)curYear); + obj.put("list", list); + return obj; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyInhabitServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyInhabitServiceImpl.java new file mode 100644 index 0000000..b5e67b4 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyInhabitServiceImpl.java @@ -0,0 +1,141 @@ +package net.hzvtc.web.stat.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import net.hzvtc.web.stat.domain.SpeciesDailyInhabit; +import net.hzvtc.web.stat.mapper.SpeciesDailyInhabitMapper; +import net.hzvtc.web.stat.service.SpeciesDailyInhabitService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 生境数量统计Service业务层处理 + * + * @author admin + * @date 2023-08-21 + */ +@Service +public class SpeciesDailyInhabitServiceImpl implements SpeciesDailyInhabitService { + @Resource + private SpeciesDailyInhabitMapper speciesDailyInhabitMapper; + + + /** + * 查询生境数量统计列表 + * + * @param speciesDailyInhabit 生境数量统计 + * @return 生境数量统计 + */ + @Override + public List selectSpeciesDailyInhabitList(SpeciesDailyInhabit speciesDailyInhabit) { + return speciesDailyInhabitMapper.selectSpeciesDailyInhabitList(speciesDailyInhabit); + } + + /** + * 新增生境数量统计 + * + * @param speciesDailyInhabit 生境数量统计 + * @return 结果 + */ + @Override + public int insertSpeciesDailyInhabit(SpeciesDailyInhabit speciesDailyInhabit) { + return speciesDailyInhabitMapper.insertSpeciesDailyInhabit(speciesDailyInhabit); + } + + @Override + public List getSpeciesDailyInhabitListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesDailyInhabitListByParam(map); + } + + @Override + public List getSpeciesDailyInhabitRealListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesDailyInhabitRealListByParam(map); + } + + @Override + public int batchInsertSpeciesDailyInhabit(List list) { + return speciesDailyInhabitMapper.batchInsertSpeciesDailyInhabit(list); + } + + @Override + public List getSpeciesDailyInhabitYearAmountListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesDailyInhabitYearAmountListByParam(map); + } + + @Override + public List getSpeciesDailyInhabitWeeklyAmountListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesDailyInhabitWeeklyAmountListByParam(map); + } + + @Override + public List getSpeciesDailyInhabitMonthlyAmountListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesDailyInhabitMonthlyAmountListByParam(map); + } + + @Override + public List getSpeciesInhabitStatYearListByParam(Map map) { + return speciesDailyInhabitMapper.getSpeciesInhabitStatYearListByParam(map); + } + + @Override + public JSONArray getSpeciesListByParam(JSONObject param) { + JSONArray array = new JSONArray(); + Map map = new HashMap<>(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer startYear = param.getInteger("startYear"); + map.put("startYear", startYear); + Integer endYear = param.getInteger("startYear"); + map.put("endYear", endYear); + List yearList = speciesDailyInhabitMapper.getSpeciesInhabitStatYearListByParam(map); + if (yearList != null && !yearList.isEmpty()) { + yearList.forEach(calcYear -> { + map.put("calcYear", calcYear); + List amountList = speciesDailyInhabitMapper.getSpeciesDailyInhabitYearAmountListByParam(map); + JSONObject object = combineObject(amountList); + object.put("statYear", calcYear); + array.add(object); + }); + } + return array; + } + + @Override + public int deleteSpeciesDailyInhabitByDate(String statDate) { + return speciesDailyInhabitMapper.deleteSpeciesDailyInhabitByDate(statDate); + } + + private JSONObject combineObject(List list) { + JSONObject obj = new JSONObject(); + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + switch (item.getHabitat()) { + case "water": + obj.put("water", item.getAmount()); + break; + case "tree": + obj.put("tree", item.getAmount()); + break; + case "shoreside": + obj.put("shoreside", item.getAmount()); + break; + case "ground": + obj.put("ground", item.getAmount()); + break; + default: + obj.put("other", item.getAmount()); + break; + } + }); + } + return obj; + } + + +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyStatServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyStatServiceImpl.java new file mode 100644 index 0000000..be6a4c1 --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesDailyStatServiceImpl.java @@ -0,0 +1,1382 @@ +package net.hzvtc.web.stat.service.impl; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import javax.annotation.Resource; +import net.hzvtc.area.domain.ProtectedArea; +import net.hzvtc.area.service.ProtectedAreaService; +import net.hzvtc.area.service.ProtectedAreaSpeciesService; +import net.hzvtc.common.utils.DateUtils; +import net.hzvtc.data.check.domain.ResultMedia; +import net.hzvtc.data.check.service.ResultMediaService; +import net.hzvtc.data.check.service.ResultRecordService; +import net.hzvtc.device.domain.DeviceInfo; +import net.hzvtc.device.service.DeviceInfoService; +import net.hzvtc.echart.domain.vo.BirdStatDataVo; +import net.hzvtc.echart.service.BirdDataStatService; +import net.hzvtc.email.service.EmailService; +import net.hzvtc.web.stat.domain.SpeciesDailyInhabit; +import net.hzvtc.web.stat.domain.SpeciesDailyStat; +import net.hzvtc.web.stat.mapper.SpeciesDailyStatMapper; +import net.hzvtc.web.stat.service.SpeciesDailyInhabitService; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class SpeciesDailyStatServiceImpl +implements SpeciesDailyStatService { + private static final Logger log = LoggerFactory.getLogger(SpeciesDailyStatServiceImpl.class); + @Resource + private SpeciesDailyStatMapper speciesDailyStatMapper; + private final ResultRecordService resultRecordService; + private final DeviceInfoService deviceInfoService; + private final SpeciesDailyInhabitService speciesDailyInhabitService; + private final BirdDataStatService birdDataStatService; + private final ProtectedAreaService protectedAreaService; + @Value(value="${hzvtc.dailyReportFilePath}") + private String dailyReportFilePath; + @Value(value="${hzvtc.dailyReportFileOutPath}") + private String dailyReportFileOutPath; + private final EmailService emailService; + private final ProtectedAreaSpeciesService protectedAreaSpeciesService; + private final ResultMediaService resultMediaService; + @Value(value="${hzvtc.fileServerUrl}") + private String fileServerUrl; + @Value(value="${VideoPostUrl.yuyuantanDataUrl}") + private String postDataUrl; + + @Override + public List selectSpeciesDailyStatList(SpeciesDailyStat speciesDailyStat) { + return this.speciesDailyStatMapper.selectSpeciesDailyStatList(speciesDailyStat); + } + + @Override + public int insertSpeciesDailyStat(SpeciesDailyStat speciesDailyStat) { + return this.speciesDailyStatMapper.insertSpeciesDailyStat(speciesDailyStat); + } + + @Override + public List getSpeciesDailyStatListByParam(JSONObject object) { + HashMap map = new HashMap(); + Long areaId = object.getLong("areaId"); + map.put("areaId", areaId); + String calcDate = object.getString("calcDate"); + map.put("calcDate", calcDate); + Integer recordType = object.getInteger("recordType"); + map.put("recordType", recordType); + JSONArray array = object.getJSONArray("list"); + if (array != null) { + List list = JSONArray.parseArray((String)array.toJSONString(), Long.class); + map.put("list", list); + } + return this.speciesDailyStatMapper.getSpeciesDailyStatListByParam(map); + } + + @Override + public List getSpeciesDailyStatListByParam(Map map) { + return this.speciesDailyStatMapper.getSpeciesDailyStatListByParam(map); + } + + @Override + @Transactional + public void calculateDailyResultRecord(String calcDate) { + HashMap map = new HashMap(); + if (calcDate == null || calcDate.isEmpty()) { + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + calcDate = fmDate.format(LocalDate.now()); + } + map.put("calcDate", calcDate); + this.speciesDailyStatMapper.deleteSpeciesDailyStatByDate(map); + this.speciesDailyInhabitService.deleteSpeciesDailyInhabitByDate(calcDate); + List areaList = this.resultRecordService.getResultAreaListByParam(map); + String finalCalcDate = calcDate; + areaList.forEach(areaId -> this.saveToSpeciesDailyStat((Long)areaId, finalCalcDate)); + } + + @Override + public void calculateDailyResultRecordByParam(JSONObject param) { + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + return; + } + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return; + } + HashMap map = new HashMap(); + map.put("calcDate", calcDate); + map.put("areaId", areaId); + this.speciesDailyStatMapper.deleteSpeciesDailyStatByDate(map); + this.saveToSpeciesDailyStat(areaId, calcDate); + } + + private void saveToSpeciesDailyStat(Long areaId, String calcDate) { + HashMap map = new HashMap(); + List deviceIds = this.deviceInfoService.getDeviceCameraInfoByAreaId(areaId); + deviceIds.forEach(deviceId -> { + map.put("deviceId", deviceId); + map.put("recordType", 1); + map.put("calcDate", calcDate); + List list = this.speciesDailyStatMapper.getSpeciesDailyStatListByParam(map); + if (list != null && !list.isEmpty()) { + List speciesIds = list.stream().map(SpeciesDailyStat::getSpeciesId).collect(Collectors.toList()); + map.put("list", speciesIds); + map.put("recordType", 2); + List sublist = this.speciesDailyStatMapper.getSpeciesDailyStatListByParam(map); + list.addAll(sublist); + } else { + map.put("recordType", 2); + list = this.speciesDailyStatMapper.getSpeciesDailyStatListByParam(map); + } + if (list != null && !list.isEmpty()) { + list.forEach(item -> { + item.setAreaId(areaId); + item.setDeviceId((Long)deviceId); + }); + this.speciesDailyStatMapper.batchInsertSpeciesDailyStat(list); + HashMap params = new HashMap(); + ArrayList dailyInhabits = new ArrayList(); + list.forEach(item -> { + params.put("speciesId", item.getSpeciesId()); + params.put("recordId", item.getRecordId()); + List inhabits = this.speciesDailyInhabitService.getSpeciesDailyInhabitRealListByParam(params); + if (inhabits != null && !inhabits.isEmpty()) { + dailyInhabits.addAll(inhabits); + } + }); + if (!dailyInhabits.isEmpty()) { + dailyInhabits.forEach(item -> { + item.setAreaId(areaId); + item.setDeviceId((Long)deviceId); + item.setStatDate(calcDate); + }); + this.speciesDailyInhabitService.batchInsertSpeciesDailyInhabit(dailyInhabits); + } + } + }); + } + + @Override + public void calculateAllResultRecord() { + HashMap map = new HashMap(); + List areaList = this.resultRecordService.getResultAreaListByParam(map); + if (areaList != null && !areaList.isEmpty()) { + areaList.stream().forEach(areaId -> { + map.put("areaId", areaId); + List calcDates = this.speciesDailyStatMapper.getRecordDateListByParam(map); + if (calcDates != null && !calcDates.isEmpty()) { + calcDates.stream().forEach(calcDate -> this.saveToSpeciesDailyStat((Long)areaId, (String)calcDate)); + } + }); + } + } + + @Override + public JSONObject getBirdPeriodStatByParam(JSONObject object) { + String dateFrom; + HashMap map = new HashMap(); + Long areaId = object.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = object.getLong("speciesId"); + map.put("speciesId", speciesId); + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String dateTo = object.getString("dateTo"); + if (dateTo == null || dateTo.isEmpty()) { + dateTo = fmDate.format(LocalDate.now()); + } + if ((dateFrom = object.getString("dateFrom")) == null || dateFrom.isEmpty()) { + LocalDate before = LocalDate.parse(dateTo).plusDays(-30L); + dateFrom = fmDate.format(before); + } + map.put("dateFrom", dateFrom); + map.put("dateTo", dateTo); + Long deviceId = object.getLong("deviceId"); + map.put("deviceId", deviceId); + JSONObject result = new JSONObject(); + result.put("list", this.speciesDailyStatMapper.getBirdPeriodStatByParam(map)); + result.put("dateFrom", (Object)dateFrom); + result.put("dateTo", (Object)dateTo); + return result; + } + + @Override + public List getBirdPeriodStatListByParam(JSONObject object) { + String dateFrom; + HashMap map = new HashMap(); + Long areaId = object.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = object.getLong("speciesId"); + map.put("speciesId", speciesId); + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String dateTo = object.getString("dateTo"); + if (dateTo == null || dateTo.isEmpty()) { + dateTo = fmDate.format(LocalDate.now()); + } + if ((dateFrom = object.getString("dateFrom")) == null || dateFrom.isEmpty()) { + LocalDate before = LocalDate.parse(dateTo).plusDays(-30L); + dateFrom = fmDate.format(before); + } + map.put("dateFrom", dateFrom); + map.put("dateTo", dateTo); + Long deviceId = object.getLong("deviceId"); + map.put("deviceId", deviceId); + return this.speciesDailyStatMapper.getBirdPeriodStatByParam(map); + } + + @Override + public JSONObject getBirdMonthStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + Integer calcYear = param.getInteger("calcYear"); + if (calcYear == null) { + calcYear = LocalDate.now().getYear(); + } + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + map.put("calcYear", calcYear); + result.put("list", this.speciesDailyStatMapper.getBirdMonthStatByParam(map)); + result.put("calcYear", (Object)calcYear); + return result; + } + + @Override + public List getBirdMonthStatListByParam(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + Integer calcYear = param.getInteger("calcYear"); + if (calcYear == null) { + calcYear = LocalDate.now().getYear(); + } + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + map.put("calcYear", calcYear); + return this.speciesDailyStatMapper.getBirdMonthStatByParam(map); + } + + private Map createQueryParam(JSONObject param) { + String dateFrom; + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long deviceId = param.getLong("deviceId"); + map.put("deviceId", deviceId); + DateTimeFormatter fmDate = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String dateTo = param.getString("dateTo"); + if (dateTo == null || dateTo.isEmpty()) { + dateTo = fmDate.format(LocalDate.now()); + } + if ((dateFrom = param.getString("dateFrom")) == null || dateFrom.isEmpty()) { + LocalDate before = LocalDate.parse(dateTo).plusDays(-30L); + dateFrom = fmDate.format(before); + } + map.put("dateFrom", dateFrom); + map.put("dateTo", dateTo); + return map; + } + + @Override + public JSONObject getSpeciesDailyStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Map map = this.createQueryParam(param); + result.put("dateFrom", map.get("dateFrom")); + result.put("dateTo", map.get("dateTo")); + List list = this.speciesDailyStatMapper.getSpeciesDailyStatByParam(map); + result.put("list", list); + return result; + } + + @Override + public JSONObject getSpeciesGroupStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Map map = this.createQueryParam(param); + result.put("dateFrom", map.get("dateFrom")); + result.put("dateTo", map.get("dateTo")); + List list = this.speciesDailyStatMapper.getSpeciesGroupStatByParam(map); + result.put("list", list); + return result; + } + + @Override + public List getSpeciesWinterPeriodData(Map map) { + return this.speciesDailyStatMapper.getSpeciesWinterPeriodData(map); + } + + private Map getSpeciesWeeklyParam(JSONObject param) { + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + map.put("dateBegin", DateUtils.getFirstDayOfWeek((String)calcDate)); + map.put("dateEnd", DateUtils.getLastDayOfWeek((String)calcDate)); + map.put("areaId", areaId); + map.put("isCommon", param.getInteger("isCommon")); + return map; + } + + @Override + public JSONObject getSpeciesWeeklyReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + Map map = this.getSpeciesWeeklyParam(param); + result.put("areaData", (Object)this.getSpeciesStatByDeviceId(map, areaId, 0, 1)); + result.put("speciesData", (Object)this.getSpeciesStatBySpeciesId(map, 0, 1)); + result.put("habitatData", (Object)this.getSpeciesStatByInhabit(map, 1)); + return result; + } + + @Override + public JSONObject getSpeciesMonthlyStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String[] arr = calcDate.split("-"); + map.put("areaId", areaId); + map.put("year", Integer.parseInt(arr[0])); + map.put("month", Integer.parseInt(arr[1])); + int days = DateUtils.getDaysOfMonth((String)calcDate); + result.put("days", (Object)days); + result.put("areaData", (Object)this.getSpeciesStatByDeviceId(map, areaId, days, 2)); + result.put("speciesData", (Object)this.getSpeciesStatBySpeciesId(map, days, 2)); + result.put("habitatData", (Object)this.getSpeciesStatByInhabit(map, 2)); + return result; + } + + @Override + public JSONObject getSpeciesYearlyStatByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + HashMap map = new HashMap(); + Integer year = param.getInteger("calcDate"); + if (year == null) { + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + year = Integer.parseInt(df.format(new Date())); + } + map.put("year", year); + map.put("areaId", areaId); + result.put("areaData", (Object)this.getSpeciesStatByDeviceId(map, areaId, 12, 3)); + result.put("speciesData", (Object)this.getSpeciesStatBySpeciesId(map, 12, 3)); + result.put("habitatData", (Object)this.getSpeciesStatByInhabit(map, 3)); + return result; + } + + @Override + public String getBirdDataWeeklyStatFileByParam(Map param) { + try { + List list; + AtomicInteger starRow; + String areaId = (String)param.get("areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "weekly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5"); + String calcDate = (String)param.get("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + dateBegin + "~" + dateEnd); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u5468\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("dateBegin", dateBegin); + param.put("dateEnd", dateEnd); + param.put("limit", 8); + param.put("isCommon", 1); + JSONArray array = this.getSpeciesStatByDeviceId(param, Long.parseLong(areaId), 0, 1); + if (array != null) { + int[] sum = new int[8]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + counts[element.getWeekDay().intValue()] = element.getCount(); + }); + } + int i = 0; + for (int val : counts) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + int n = i; + sum[n] = sum[n] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 8 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = this.getSpeciesStatBySpeciesId(param, 0, 1)) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int[] counts = new int[7]; + if (subarray != null) { + subarray.stream().map(el -> (BirdStatDataVo)el).forEach(element -> { + counts[element.getWeekDay().intValue()] = element.getCount(); + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + Arrays.sort(counts); + int max = counts[counts.length - 1]; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = this.getSpeciesStatByInhabit(param, 1)) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (SpeciesDailyInhabit)el).forEach(element -> { + if ("ground".equals(element.getHabitat())) { + counts[0] = element.getAmount(); + } else if ("shoreside".equals(element.getHabitat())) { + counts[1] = element.getAmount(); + } else if ("water".equals(element.getHabitat())) { + counts[2] = element.getAmount(); + } else if ("tree".equals(element.getHabitat())) { + counts[3] = element.getAmount(); + } else { + counts[4] = element.getAmount(); + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + dateBegin + "-" + dateEnd + ").xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception exception) { + return null; + } + } + + @Override + public String getBirdDataMonthlyStatFileByParam(Map param) { + try { + List list; + AtomicInteger starRow; + String areaId = (String)param.get("areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "monthly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u6708\u62a5"); + String calcDate = (String)param.get("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String[] arr = calcDate.split("-"); + param.put("year", Integer.parseInt(arr[0])); + param.put("month", Integer.parseInt(arr[1])); + int days = DateUtils.getDaysOfMonth((String)calcDate); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708"); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u6708\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("limit", 8); + param.put("isCommon", 1); + JSONArray array = this.getSpeciesStatByDeviceId(param, Long.parseLong(areaId), days, 2); + if (array != null) { + int[] sum = new int[days + 1]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + int i = 0; + while (i < days) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + int n = days; + sum[n] = sum[n] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 8 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = this.getSpeciesStatBySpeciesId(param, days, 2)) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + for (int i = 0; i < days; ++i) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = this.getSpeciesStatByInhabit(param, 2)) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (SpeciesDailyInhabit)el).forEach(element -> { + if ("ground".equals(element.getHabitat())) { + counts[0] = element.getAmount(); + } else if ("shoreside".equals(element.getHabitat())) { + counts[1] = element.getAmount(); + } else if ("water".equals(element.getHabitat())) { + counts[2] = element.getAmount(); + } else if ("tree".equals(element.getHabitat())) { + counts[3] = element.getAmount(); + } else { + counts[4] = element.getAmount(); + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + arr[0] + "\u5e74" + arr[1] + "\u6708).xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + @Override + public String getBirdDataYearlyStatFileByParam(Map param) { + try { + List list; + AtomicInteger starRow; + String areaId = (String)param.get("areaId"); + String areaName = ""; + if (areaId == null || areaId.isEmpty()) { + return "500"; + } + ProtectedArea protectedArea = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + areaName = protectedArea.getName(); + XSSFWorkbook xssfWorkbook = new XSSFWorkbook((InputStream)new FileInputStream(this.dailyReportFilePath + "yearly_report_tmpl.xlsx")); + XSSFSheet sheet = xssfWorkbook.getSheetAt(0); + sheet.getRow(1).getCell(1).setCellValue(areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5e74\u62a5"); + String calcDate = (String)param.get("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + calcDate = df.format(new Date()); + } + param.put("year", Integer.parseInt(calcDate)); + sheet.getRow(2).getCell(1).setCellValue("\u65e5\u671f\uff1a" + calcDate + "\u5e74"); + sheet.getRow(4).getCell(1).setCellValue(areaName + "\u6bcf\u5e74\u9e1f\u7c7b\u667a\u6167\u76d1\u6d4b\u6570\u636e\uff0c\u5305\u542b\u9e1f\u7c7b\u76d1\u6d4b\u603b\u6570\uff0c\u5173\u952e\u9e1f\u7c7b\u751f\u5883\u5206\u5e03\u548c\u5173\u952e\u7269\u79cd\u76d1\u6d4b\u6570\u91cf"); + param.put("limit", 8); + param.put("isCommon", 1); + JSONArray array = this.getSpeciesStatByDeviceId(param, Long.parseLong(areaId), 12, 3); + if (array != null) { + int[] sum = new int[13]; + AtomicInteger starRow2 = new AtomicInteger(8); + array.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + int i = 0; + while (i < 12) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + int n = i++; + sum[n] = sum[n] + val; + } + sum[12] = sum[12] + max; + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)max); + starRow2.getAndIncrement(); + }); + int cell = 2; + starRow2.set(28); + for (int val : sum) { + sheet.getRow(starRow2.get()).getCell(cell++).setCellValue((double)val); + } + int start = 8 + array.size(); + for (int i = 0; i < 20 - array.size(); ++i) { + XSSFRow row = sheet.getRow(start + i); + row.setZeroHeight(true); + } + } + if ((array = this.getSpeciesStatBySpeciesId(param, 12, 3)) != null) { + starRow = new AtomicInteger(43); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + JSONArray subarray = obj.getJSONArray("list"); + int max = 0; + for (int i = 0; i < 12; ++i) { + int val = (Integer)subarray.get(i); + if (val > max) { + max = val; + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)max); + starRow.getAndIncrement(); + }); + } + if ((array = this.getSpeciesStatByInhabit(param, 2)) != null) { + starRow = new AtomicInteger(67); + list = array.size() > 8 ? array.subList(0, 8) : array.subList(0, array.size()); + list.stream().forEach(data -> { + JSONObject obj = (JSONObject)data; + int cell = 1; + sheet.getRow(starRow.get()).getCell(cell++).setCellValue(obj.getString("name")); + int[] counts = new int[5]; + JSONArray subarray = obj.getJSONArray("list"); + if (subarray != null) { + subarray.stream().map(el -> (SpeciesDailyInhabit)el).forEach(element -> { + if ("ground".equals(element.getHabitat())) { + counts[0] = element.getAmount(); + } else if ("shoreside".equals(element.getHabitat())) { + counts[1] = element.getAmount(); + } else if ("water".equals(element.getHabitat())) { + counts[2] = element.getAmount(); + } else if ("tree".equals(element.getHabitat())) { + counts[3] = element.getAmount(); + } else { + counts[4] = element.getAmount(); + } + }); + } + for (int val : counts) { + sheet.getRow(starRow.get()).getCell(cell++).setCellValue((double)val); + } + starRow.getAndIncrement(); + }); + } + String outfile = this.dailyReportFileOutPath + areaName + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5(\u65e5\u671f" + calcDate + "\u5e74).xlsx"; + FileOutputStream fileOut = new FileOutputStream(outfile); + xssfWorkbook.write((OutputStream)fileOut); + xssfWorkbook.close(); + fileOut.close(); + return outfile; + } + catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + + @Override + public boolean sendBirdDataWeeklyStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + String dateBegin = DateUtils.getFirstDayOfWeek((String)calcDate); + String dateEnd = DateUtils.getLastDayOfWeek((String)calcDate); + HashMap map = new HashMap(); + map.put("calcDate", calcDate); + map.put("areaId", areaId); + map.put("dateBegin", dateBegin); + map.put("dateEnd", dateEnd); + String filePath = this.getBirdDataWeeklyStatFileByParam(map); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + dateBegin + "~" + dateEnd, "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + dateBegin + "~" + dateEnd + ",\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataMonthlyStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + if (areaId == null || areaId.isEmpty()) { + return false; + } + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); + calcDate = df.format(new Date()); + } + String[] arr = calcDate.split("-"); + map.put("areaId", areaId); + map.put("calcDate", calcDate); + String filePath = this.getBirdDataMonthlyStatFileByParam(map); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u6708\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708", "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + arr[0] + "\u5e74" + arr[1] + "\u6708,\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public boolean sendBirdDataYearlyStatEmail(JSONObject param) { + String areaId = param.getString("areaId"); + if (areaId == null || areaId.isEmpty()) { + return false; + } + ProtectedArea data = null; + if (areaId == null || areaId.isEmpty()) { + return false; + } + data = this.protectedAreaService.selectProtectedAreaById(Long.parseLong(areaId)); + HashMap map = new HashMap(); + String calcDate = param.getString("calcDate"); + if (calcDate == null || calcDate.isEmpty()) { + SimpleDateFormat df = new SimpleDateFormat("yyyy"); + calcDate = df.format(new Date()); + } + map.put("areaId", areaId); + map.put("calcDate", calcDate); + String filePath = this.getBirdDataYearlyStatFileByParam(map); + if (filePath != null && !filePath.isEmpty()) { + this.emailService.sendEmailWithAttachment(data.getName() + "\u9e1f\u7c7b\u76d1\u6d4b\u5e74\u62a5\uff0c\u68c0\u6d4b\u65f6\u95f4\uff1a" + calcDate + "\u5e74", "\u9644\u4ef6\u4e3a\u9e1f\u7c7b\u76d1\u6d4b\u5468\u62a5,\u68c0\u6d4b\u65f6\u95f4\u4e3a\uff1a" + calcDate + "\u5e74,\u8bf7\u67e5\u6536\uff01", filePath, data.getEmail()); + return true; + } + return false; + } + + @Override + public int deleteSpeciesDailyStatByDate(String statDate) { + HashMap map = new HashMap(); + map.put("calcDate", statDate); + return this.speciesDailyStatMapper.deleteSpeciesDailyStatByDate(map); + } + + @Override + public JSONObject getAreaStatInfoByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Integer total = this.speciesDailyStatMapper.getSpeciesMaxAmountByParam(map); + result.put("total", (Object)(total == null ? 0 : total)); + LocalDate localDate = LocalDate.now(); + map.put("statDate", localDate.toString()); + Integer today = this.speciesDailyStatMapper.getSpeciesMaxAmountByParam(map); + result.put("today", (Object)(today == null ? 0 : today)); + LocalDate yesterday = localDate.plusDays(-1L); + map.put("statDate", yesterday.toString()); + Integer amount = this.speciesDailyStatMapper.getSpeciesMaxAmountByParam(map); + result.put("yesterday", (Object)(amount == null ? 0 : amount)); + return result; + } + + @Override + public JSONObject getStatInfoByParam(int type) { + HashMap map = new HashMap(); + DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDateTime endDate = LocalDateTime.now(); + LocalDateTime startDate = null; + if (type == 1) { + startDate = endDate.minusMonths(6L); + map.put("dateFrom", startDate.format(df)); + map.put("dateTo", endDate.format(df)); + } else if (type == 2) { + startDate = endDate.minusDays(30L); + map.put("dateFrom", startDate.format(df)); + map.put("dateTo", endDate.format(df)); + } else if (type == 3) { + startDate = endDate.minusDays(7L); + map.put("dateFrom", startDate.format(df)); + map.put("dateTo", endDate.format(df)); + } else if (type == 4) { + startDate = endDate.minusDays(1L); + map.put("statDate", startDate.format(df)); + } else if (type == 5) { + map.put("statDate", endDate.format(df)); + } + Integer total = this.speciesDailyStatMapper.getStatAmountByParam(map); + JSONObject result = new JSONObject(); + result.put("total", (Object)(total == null ? 0 : total)); + return result; + } + + @Override + public JSONObject getSpeciesYearTotalStatByParam(JSONObject param) { + List subList; + JSONObject result = new JSONObject(); + LocalDate localDate = LocalDate.now(); + int month = localDate.getMonth().getValue(); + int year = localDate.getYear(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + if (areaId == null) { + return result; + } + ArrayList list = new ArrayList(); + if (month < 12) { + map.put("year", year - 1); + map.put("monthFrom", month + 1); + subList = this.speciesDailyStatMapper.getSpeciesYearTotalMaxStatByParam(map); + subList.forEach(item -> item.setYear(year - 1)); + list.addAll(subList); + } + map.clear(); + map.put("areaId", areaId); + map.put("year", year); + subList = this.speciesDailyStatMapper.getSpeciesYearTotalMaxStatByParam(map); + subList.forEach(item -> item.setYear(year)); + list.addAll(subList); + result.put("list", list); + return result; + } + + @Override + public JSONObject getSpeciesStatInfoByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return null; + } + int type = param.getInteger("type"); + switch (type) { + case 2: { + LocalDate today = LocalDate.now(); + map.put("dateTo", today.toString()); + result.put("dateTo", (Object)today.toString()); + today = today.plusDays(-6L); + map.put("dateFrom", today.toString()); + result.put("dateFrom", (Object)today.toString()); + break; + } + case 3: { + LocalDate today = LocalDate.now(); + map.put("dateTo", today.toString()); + result.put("dateTo", (Object)today.toString()); + today = today.plusDays(-29L); + map.put("dateFrom", today.toString()); + result.put("dateFrom", (Object)today.toString()); + break; + } + case 4: { + String dateFrom = param.getString("dateFrom"); + map.put("dateFrom", dateFrom); + result.put("dateFrom", (Object)dateFrom); + String dateTo = param.getString("dateTo"); + map.put("dateTo", dateTo); + result.put("dateTo", (Object)dateTo); + break; + } + default: { + LocalDate now = LocalDate.now(); + map.put("curDate", now.toString()); + result.put("dateFrom", (Object)now.toString()); + break; + } + } + map.put("areaId", areaId); + List list = this.speciesDailyStatMapper.getSpeciesStatInfoByParam(map); + result.put("list", list); + return result; + } + + @Override + public JSONObject getSpeciesMediaListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + map.put("areaId", areaId); + Integer limit = param.getInteger("limit"); + map.put("limit", limit); + List list = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByAreaId(map); + if (list == null) { + return result; + } + ArrayList dataList = new ArrayList(); + HashMap itemMap = new HashMap(); + itemMap.put("areaId", areaId); + list.forEach(item -> { + itemMap.clear(); + itemMap.put("areaId", areaId); + itemMap.put("speciesId", item.getSpeciesId()); + ResultMedia data = this.resultMediaService.getResultInfoForStatByParam(itemMap); + if (data != null) { + item.setMediaId(data.getMediaId()); + item.setMediaUrl(data.getMediaUrl()); + item.setMetaUrl(data.getMetaUrl()); + List sublist = this.speciesDailyStatMapper.getSpeciesStatInfoByParam(itemMap); + item.setTotal(sublist == null || sublist.isEmpty() ? 0 : sublist.get(0).getCount()); + LocalDate now = LocalDate.now(); + itemMap.put("curDate", (Long)((Object)now.toString())); + sublist = this.speciesDailyStatMapper.getSpeciesStatInfoByParam(itemMap); + item.setToday(sublist == null || sublist.isEmpty() ? 0 : sublist.get(0).getCount()); + itemMap.put("curDate", (Long)((Object)now.plusDays(-1L).toString())); + sublist = this.speciesDailyStatMapper.getSpeciesStatInfoByParam(itemMap); + item.setYesterday(sublist == null || sublist.isEmpty() ? 0 : sublist.get(0).getCount()); + dataList.add(item); + } + }); + result.put("list", dataList); + return result; + } + + @Override + public JSONObject getSpeciesStatListByParam(JSONObject param) { + JSONObject result = new JSONObject(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + if (areaId == null) { + return result; + } + map.put("areaId", areaId); + Integer limit = param.getInteger("limit"); + map.put("limit", limit); + List list = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByAreaId(map); + if (list == null) { + return result; + } + HashMap itemMap = new HashMap(); + list.forEach(item -> { + itemMap.clear(); + itemMap.put("speciesId", item.getSpeciesId()); + itemMap.put("mediaType", 3); + int count = this.resultMediaService.getResultMediaAmountByParam(itemMap); + item.setVideoCount(count); + itemMap.put("mediaType", 2); + count = this.resultMediaService.getResultMediaAmountByParam(itemMap); + item.setImageCount(count); + List devList = this.resultMediaService.getResultMediaDeviceListByParam(itemMap); + item.setDeviceIds(devList); + }); + result.put("list", list); + return result; + } + + @Override + public JSONObject getSpeciesAmountReportByParam(JSONObject param) { + JSONObject result = new JSONObject(); + Long areaId = param.getLong("areaId"); + Long deviceId = param.getLong("deviceId"); + if (areaId == null && deviceId == null) { + return result; + } + HashMap map = new HashMap(); + map.put("areaId", areaId); + map.put("deviceId", deviceId); + Integer calcYear = param.getInteger("calcYear"); + map.put("calcYear", calcYear); + Integer calcMonth = param.getInteger("calcMonth"); + map.put("calcMonth", calcMonth); + Integer monthFrom = param.getInteger("monthFrom"); + map.put("monthFrom", monthFrom); + Integer monthTo = param.getInteger("monthTo"); + map.put("monthTo", monthTo); + List list = this.speciesDailyStatMapper.getSpeciesAmountReportByParam(map); + result.put("list", list); + result.put("catalogueAmount", (Object)this.speciesDailyStatMapper.getBirdCatalogueAmount()); + result.put("familyAmount", (Object)this.speciesDailyStatMapper.getBirdFamilyAmount()); + result.put("genusAmount", (Object)this.speciesDailyStatMapper.getBirdGenusAmount()); + return result; + } + + @Override + public JSONObject getSpeciesWinterPeriodAmountByParam(JSONObject param) { + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + HashMap map = new HashMap(); + Long areaId = param.getLong("areaId"); + map.put("areaId", areaId); + Long speciesId = param.getLong("speciesId"); + map.put("speciesId", speciesId); + Integer startYear = param.getInteger("startYear"); + Integer endYear = param.getInteger("endYear"); + if (startYear == null && endYear == null) { + Integer curYear = LocalDate.now().getYear(); + array.add((Object)this.getStatListByYear(curYear, map)); + object.put("startYear", (Object)(curYear + "")); + object.put("endYear", (Object)(curYear + "")); + } else if (startYear == null || endYear == null) { + Integer curYear = startYear == null ? endYear : startYear; + array.add((Object)this.getStatListByYear(curYear, map)); + object.put("startYear", (Object)(curYear + "")); + object.put("endYear", (Object)(curYear + "")); + } else { + for (int i = startYear.intValue(); i <= endYear; ++i) { + array.add((Object)this.getStatListByYear(i, map)); + } + object.put("startYear", (Object)(startYear + "")); + object.put("endYear", (Object)(endYear + "")); + } + object.put("list", (Object)array); + return object; + } + + @Override + public int getBirdCatalogueAmount() { + return this.speciesDailyStatMapper.getBirdCatalogueAmount(); + } + + @Override + public int getBirdFamilyAmount() { + return this.speciesDailyStatMapper.getBirdFamilyAmount(); + } + + @Override + public int getBirdGenusAmount() { + return this.speciesDailyStatMapper.getBirdGenusAmount(); + } + + @Override + public SpeciesDailyStat getSpeciesDailyAmountByParam(Map map) { + List list = this.speciesDailyStatMapper.getSpeciesDailyAmountByParam(map); + if (list != null && !list.isEmpty()) { + return list.get(0); + } + return null; + } + + @Override + public Integer getSpeciesDailySpeciesAmountByParam(Map map) { + return this.speciesDailyStatMapper.getSpeciesDailySpeciesAmountByParam(map); + } + + @Override + public int getSpeciesDailyStatAmountByParam(Map map) { + List sublist = this.speciesDailyStatMapper.getSpeciesStatInfoByParam(map); + return sublist == null || sublist.isEmpty() ? 0 : sublist.get(0).getCount(); + } + + @Override + public Long getSpeciesTotalAmountByAreaId(Map param) { + return this.speciesDailyStatMapper.getSpeciesTotalAmountByAreaId(param); + } + + @Override + public JSONObject postTodaySpeciesData(Long areaId) { + HashMap param = new HashMap(); + param.put("areaId", areaId); + List list = this.protectedAreaSpeciesService.getProtectedAreaSpeciesListByAreaId(param); + if (list == null) { + return null; + } + JSONObject object = new JSONObject(); + long total = this.getSpeciesTotalAmountByAreaId(param); + object.put("total", (Object)total); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + LocalDate toady = LocalDate.now(); + param.put("calcDate", toady.format(formatter)); + long amount = this.getSpeciesTotalAmountByAreaId(param); + object.put("today", (Object)amount); + object.put("date", (Object)toady.format(formatter)); + JSONArray array = new JSONArray(); + for (BirdStatDataVo item : list) { + ResultMedia resultMedia; + param.put("speciesId", item.getSpeciesId()); + Long count = this.getSpeciesTotalAmountByAreaId(param); + if (count == null || count <= 0L || (resultMedia = this.resultMediaService.getMediaVideoUrlListByParam(param)) == null) continue; + JSONObject obj = new JSONObject(); + obj.put("id", (Object)item.getSpeciesId()); + obj.put("name", (Object)item.getName()); + obj.put("count", (Object)count); + String url = resultMedia.getMediaUrl(); + if (url != null) { + if (url.startsWith("/")) { + obj.put("video", (Object)(this.fileServerUrl + url)); + } else { + obj.put("video", (Object)(this.fileServerUrl + "/" + url)); + } + } + if ((url = resultMedia.getMetaUrl()) != null) { + if (url.startsWith("/")) { + obj.put("img", (Object)(this.fileServerUrl + url)); + } else { + obj.put("img", (Object)(this.fileServerUrl + "/" + url)); + } + } + array.add((Object)obj); + } + object.put("species", (Object)array); + JSONObject result = new JSONObject(); + result.put("data", (Object)object); + this.postStatData(result); + return result; + } + + /* + * WARNING - Removed try catching itself - possible behaviour change. + */ + private void postStatData(JSONObject data) { + CloseableHttpClient client = HttpClientBuilder.create().build(); + HttpPost post = new HttpPost(this.postDataUrl); + try { + StringEntity s = new StringEntity(data.toString(), StandardCharsets.UTF_8); + s.setContentEncoding("UTF-8"); + s.setContentType("application/json"); + post.setEntity((HttpEntity)s); + CloseableHttpResponse res = client.execute((HttpUriRequest)post); + if (res.getStatusLine().getStatusCode() == 200) { + String result = EntityUtils.toString((HttpEntity)res.getEntity()); + System.out.println(result); + } + } + catch (Exception e) { + log.error("error", (Throwable)e); + } + finally { + try { + client.close(); + } + catch (Exception exception) {} + } + } + + private JSONObject getStatListByYear(Integer curYear, Map map) { + map.put("dateFrom", curYear - 1 + "-10-01"); + map.put("dateTo", curYear + "-03-31"); + List list = this.speciesDailyStatMapper.getSpeciesWinterPeriodAmountByParam(map); + JSONObject obj = new JSONObject(); + obj.put("year", (Object)curYear); + obj.put("list", list); + return obj; + } + + private JSONArray getSpeciesStatByDeviceId(Map map, Long areaId, int arrayCount, int type) { + JSONArray areaDataList = new JSONArray(); + List deviceInfoList = this.deviceInfoService.getDeviceStatInfoByAreaId(areaId); + deviceInfoList.forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("id", (Object)item.getId()); + obj.put("name", (Object)item.getDeviceName()); + map.put("deviceId", item.getId()); + if (type == 3) { + List list = this.speciesDailyStatMapper.getSpeciesYearlyStatByDeviceId(map); + int[] counts = new int[arrayCount]; + list.forEach(subItem -> { + counts[subItem.getWeekDay().intValue() - 1] = subItem.getCount(); + }); + obj.put("list", (Object)counts); + } else if (type == 2) { + List list = this.speciesDailyStatMapper.getSpeciesMonthlyStatByDeviceId(map); + int[] counts = new int[arrayCount]; + list.forEach(subItem -> { + counts[subItem.getWeekDay().intValue() - 1] = subItem.getCount(); + }); + obj.put("list", (Object)counts); + } else if (type == 1) { + List list = this.speciesDailyStatMapper.getSpeciesWeeklyStatByDeviceId(map); + obj.put("list", list); + } + areaDataList.add((Object)obj); + }); + return areaDataList; + } + + private JSONArray getSpeciesStatBySpeciesId(Map map, int days, int type) { + JSONArray array = new JSONArray(); + List list = this.birdDataStatService.getAreaBirdSpeciesByParam(map); + list.stream().forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + if (type == 2) { + List subList = this.speciesDailyStatMapper.getSpeciesMonthlyStatBySpeciesId(map); + int[] dataList = new int[days]; + subList.forEach(subItem -> { + dataList[subItem.getWeekDay().intValue() - 1] = subItem.getCount(); + }); + obj.put("list", (Object)dataList); + } else if (type == 3) { + List subList = this.speciesDailyStatMapper.getSpeciesYearlyStatBySpeciesId(map); + int[] dataList = new int[days]; + subList.forEach(subItem -> { + dataList[subItem.getWeekDay().intValue() - 1] = subItem.getCount(); + }); + obj.put("list", (Object)dataList); + } else if (type == 1) { + List subList = this.speciesDailyStatMapper.getSpeciesWeeklyStatBySpeciesId(map); + obj.put("list", subList); + } + array.add((Object)obj); + }); + return array; + } + + private JSONArray getSpeciesStatByInhabit(Map map, int type) { + JSONArray array = new JSONArray(); + List list = this.birdDataStatService.getAreaBirdSpeciesByParam(map); + list.stream().forEach(item -> { + JSONObject obj = new JSONObject(); + obj.put("name", (Object)item.getName()); + obj.put("id", (Object)item.getId()); + map.put("speciesId", item.getId()); + if (type == 1) { + List subList = this.speciesDailyInhabitService.getSpeciesDailyInhabitWeeklyAmountListByParam(map); + obj.put("list", subList); + } else if (type == 2) { + List subList = this.speciesDailyInhabitService.getSpeciesDailyInhabitMonthlyAmountListByParam(map); + obj.put("list", subList); + } else if (type == 3) { + List subList = this.speciesDailyInhabitService.getSpeciesDailyInhabitMonthlyAmountListByParam(map); + obj.put("list", subList); + } + array.add((Object)obj); + }); + return array; + } + + public SpeciesDailyStatServiceImpl(ResultRecordService resultRecordService, DeviceInfoService deviceInfoService, SpeciesDailyInhabitService speciesDailyInhabitService, BirdDataStatService birdDataStatService, ProtectedAreaService protectedAreaService, EmailService emailService, ProtectedAreaSpeciesService protectedAreaSpeciesService, ResultMediaService resultMediaService) { + this.resultRecordService = resultRecordService; + this.deviceInfoService = deviceInfoService; + this.speciesDailyInhabitService = speciesDailyInhabitService; + this.birdDataStatService = birdDataStatService; + this.protectedAreaService = protectedAreaService; + this.emailService = emailService; + this.protectedAreaSpeciesService = protectedAreaSpeciesService; + this.resultMediaService = resultMediaService; + } +} + + diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesInhabitStatServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesInhabitStatServiceImpl.java new file mode 100644 index 0000000..f7e501e --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesInhabitStatServiceImpl.java @@ -0,0 +1,87 @@ +package net.hzvtc.web.stat.service.impl; + +import java.util.List; +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import net.hzvtc.web.stat.mapper.SpeciesInhabitStatMapper; +import net.hzvtc.web.stat.domain.SpeciesInhabitStat; +import net.hzvtc.web.stat.service.SpeciesInhabitStatService; + +/** + * 物种生境数量统计Service业务层处理 + * + * @author admin + * @date 2022-11-05 + */ +@Service +public class SpeciesInhabitStatServiceImpl implements SpeciesInhabitStatService { + @Resource + private SpeciesInhabitStatMapper speciesInhabitStatMapper; + + /** + * 查询物种生境数量统计 + * + * @param id 物种生境数量统计主键 + * @return 物种生境数量统计 + */ + @Override + public SpeciesInhabitStat selectSpeciesInhabitStatById(Long id) { + return speciesInhabitStatMapper.selectSpeciesInhabitStatById(id); + } + + /** + * 查询物种生境数量统计列表 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 物种生境数量统计 + */ + @Override + public List selectSpeciesInhabitStatList(SpeciesInhabitStat speciesInhabitStat) { + return speciesInhabitStatMapper.selectSpeciesInhabitStatList(speciesInhabitStat); + } + + /** + * 新增物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + @Override + public int insertSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat) { + return speciesInhabitStatMapper.insertSpeciesInhabitStat(speciesInhabitStat); + } + + /** + * 修改物种生境数量统计 + * + * @param speciesInhabitStat 物种生境数量统计 + * @return 结果 + */ + @Override + public int updateSpeciesInhabitStat(SpeciesInhabitStat speciesInhabitStat) { + return speciesInhabitStatMapper.updateSpeciesInhabitStat(speciesInhabitStat); + } + + /** + * 批量删除物种生境数量统计 + * + * @param ids 需要删除的物种生境数量统计主键 + * @return 结果 + */ + @Override + public int deleteSpeciesInhabitStatByIds(Long[] ids) { + return speciesInhabitStatMapper.deleteSpeciesInhabitStatByIds(ids); + } + + /** + * 删除物种生境数量统计信息 + * + * @param id 物种生境数量统计主键 + * @return 结果 + */ + @Override + public int deleteSpeciesInhabitStatById(Long id) { + return speciesInhabitStatMapper.deleteSpeciesInhabitStatById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesLocationInfoServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesLocationInfoServiceImpl.java new file mode 100644 index 0000000..dc3217c --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesLocationInfoServiceImpl.java @@ -0,0 +1,87 @@ +package net.hzvtc.web.stat.service.impl; + +import java.util.List; +import javax.annotation.Resource; + +import org.springframework.stereotype.Service; +import net.hzvtc.web.stat.mapper.SpeciesLocationInfoMapper; +import net.hzvtc.web.stat.domain.SpeciesLocationInfo; +import net.hzvtc.web.stat.service.SpeciesLocationInfoService; + +/** + * 国内鸟类分布点Service业务层处理 + * + * @author admin + * @date 2022-11-06 + */ +@Service +public class SpeciesLocationInfoServiceImpl implements SpeciesLocationInfoService { + @Resource + private SpeciesLocationInfoMapper speciesLocationInfoMapper; + + /** + * 查询国内鸟类分布点 + * + * @param id 国内鸟类分布点主键 + * @return 国内鸟类分布点 + */ + @Override + public SpeciesLocationInfo selectSpeciesLocationInfoById(Long id) { + return speciesLocationInfoMapper.selectSpeciesLocationInfoById(id); + } + + /** + * 查询国内鸟类分布点列表 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 国内鸟类分布点 + */ + @Override + public List selectSpeciesLocationInfoList(SpeciesLocationInfo speciesLocationInfo) { + return speciesLocationInfoMapper.selectSpeciesLocationInfoList(speciesLocationInfo); + } + + /** + * 新增国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + @Override + public int insertSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo) { + return speciesLocationInfoMapper.insertSpeciesLocationInfo(speciesLocationInfo); + } + + /** + * 修改国内鸟类分布点 + * + * @param speciesLocationInfo 国内鸟类分布点 + * @return 结果 + */ + @Override + public int updateSpeciesLocationInfo(SpeciesLocationInfo speciesLocationInfo) { + return speciesLocationInfoMapper.updateSpeciesLocationInfo(speciesLocationInfo); + } + + /** + * 批量删除国内鸟类分布点 + * + * @param ids 需要删除的国内鸟类分布点主键 + * @return 结果 + */ + @Override + public int deleteSpeciesLocationInfoByIds(Long[] ids) { + return speciesLocationInfoMapper.deleteSpeciesLocationInfoByIds(ids); + } + + /** + * 删除国内鸟类分布点信息 + * + * @param id 国内鸟类分布点主键 + * @return 结果 + */ + @Override + public int deleteSpeciesLocationInfoById(Long id) { + return speciesLocationInfoMapper.deleteSpeciesLocationInfoById(id); + } +} diff --git a/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesWinterPeriodServiceImpl.java b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesWinterPeriodServiceImpl.java new file mode 100644 index 0000000..adca12b --- /dev/null +++ b/ai-bird-system/src/main/java/net/hzvtc/web/stat/service/impl/SpeciesWinterPeriodServiceImpl.java @@ -0,0 +1,149 @@ +package net.hzvtc.web.stat.service.impl; + +import net.hzvtc.web.stat.domain.SpeciesDailyStat; +import net.hzvtc.web.stat.domain.SpeciesWinterPeriod; +import net.hzvtc.web.stat.mapper.SpeciesWinterPeriodMapper; +import net.hzvtc.web.stat.service.SpeciesDailyStatService; +import net.hzvtc.web.stat.service.SpeciesWinterPeriodService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.time.LocalDate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 物种越冬期数量统计Service业务层处理 + * + * @author admin + * @date 2022-11-04 + */ +@Service +public class SpeciesWinterPeriodServiceImpl implements SpeciesWinterPeriodService { + @Resource + private SpeciesWinterPeriodMapper speciesWinterPeriodMapper; + @Autowired + private SpeciesDailyStatService speciesDailyStatService; + + /** + * 查询物种越冬期数量统计 + * + * @param id 物种越冬期数量统计主键 + * @return 物种越冬期数量统计 + */ + @Override + public SpeciesWinterPeriod selectSpeciesWinterPeriodById(Long id) { + return speciesWinterPeriodMapper.selectSpeciesWinterPeriodById(id); + } + + /** + * 查询物种越冬期数量统计列表 + * + * @param speciesWinterPeriod 物种越冬期数量统计 + * @return 物种越冬期数量统计 + */ + @Override + public List selectSpeciesWinterPeriodList(SpeciesWinterPeriod speciesWinterPeriod) { + return speciesWinterPeriodMapper.selectSpeciesWinterPeriodList(speciesWinterPeriod); + } + + /** + * 新增物种越冬期数量统计 + * + * @param speciesWinterPeriod 物种越冬期数量统计 + * @return 结果 + */ + @Override + public int insertSpeciesWinterPeriod(SpeciesWinterPeriod speciesWinterPeriod) { + return speciesWinterPeriodMapper.insertSpeciesWinterPeriod(speciesWinterPeriod); + } + + /** + * 修改物种越冬期数量统计 + * + * @param speciesWinterPeriod 物种越冬期数量统计 + * @return 结果 + */ + @Override + public int updateSpeciesWinterPeriod(SpeciesWinterPeriod speciesWinterPeriod) { + return speciesWinterPeriodMapper.updateSpeciesWinterPeriod(speciesWinterPeriod); + } + + /** + * 批量删除物种越冬期数量统计 + * + * @param ids 需要删除的物种越冬期数量统计主键 + * @return 结果 + */ + @Override + public int deleteSpeciesWinterPeriodByIds(Long[] ids) { + return speciesWinterPeriodMapper.deleteSpeciesWinterPeriodByIds(ids); + } + + /** + * 删除物种越冬期数量统计信息 + * + * @param id 物种越冬期数量统计主键 + * @return 结果 + */ + @Override + public int deleteSpeciesWinterPeriodById(Long id) { + return speciesWinterPeriodMapper.deleteSpeciesWinterPeriodById(id); + } + + @Override + public void calcSpeciesWinterPeriodByParam() { + Map map = new HashMap<>(); + int year = LocalDate.now().getYear(); + String dateFrom = String.format("%d-10-01", year - 1); + map.put("dateFrom", dateFrom); + String dateTo = String.format("%d-04-01", year); + map.put("dateTo", dateTo); + List list = speciesDailyStatService.getSpeciesWinterPeriodData(map); + List dataList = new ArrayList<>(); + list.stream().forEach(item -> { + List filterData = dataList.stream().filter(subItem -> (subItem.getSpeciesId() == item.getSpeciesId()) && (subItem.getAreaId() == item.getAreaId())).collect(Collectors.toList()); + if (filterData == null || filterData.isEmpty()) { + SpeciesWinterPeriod data = new SpeciesWinterPeriod(); + data = combineData(data, item.getMaxValue(), item.getAvgValue()); + data.setSpeciesId(item.getSpeciesId()); + data.setAreaId(item.getAreaId()); + data.setYear(year); + dataList.add(data); + } else { + combineData(filterData.get(0), item.getMaxValue(), item.getAvgValue()); + } + }); + if (dataList.size() > 0) { + speciesWinterPeriodMapper.batchInsertSpeciesWinterPeriod(dataList); + } + } + + private SpeciesWinterPeriod combineData(SpeciesWinterPeriod data, int value, int month) { + switch (month) { + case 10: + data.setData1(value); + break; + case 11: + data.setData2(value); + break; + case 12: + data.setData3(value); + break; + case 1: + data.setData4(value); + break; + case 2: + data.setData5(value); + break; + case 3: + data.setData6(value); + break; + } + return data; + } +} diff --git a/ai-bird-system/src/main/resources/mapper/app/AppUpgradeMapper.xml b/ai-bird-system/src/main/resources/mapper/app/AppUpgradeMapper.xml new file mode 100644 index 0000000..32d6611 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/app/AppUpgradeMapper.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaMapper.xml b/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaMapper.xml new file mode 100644 index 0000000..9d01937 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaMapper.xml @@ -0,0 +1,299 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into protected_area + (code, + name, + short_name, + url, + province, + area_level, + introduction, + lon, + lat, + manager, + telephone, + sendEmail, + email, + is_deleted, + create_by, + create_time, + pic_width, + pic_height, + pic_num, + banner_file, + zoom, + gis_file, + logo_path, + title, + en_title) + values (#{code}, + #{name}, + #{shortName}, + #{url}, + #{province}, + #{areaLevel}, + #{introduction}, + #{lon}, + #{lat}, + #{manager}, + #{telephone}, + #{sendEmail}, + #{email}, + #{isDeleted}, + #{createBy}, + #{createTime}, + #{picWidth}, + #{picHeight}, + #{picNum}, + #{bannerFile}, + #{zoom}, + #{gisFile}, + #{logoPath}, + #{title}, + #{enTitle}) + + + + update protected_area + set code = #{code}, + name = #{name}, + short_name = #{shortName}, + url = #{url}, + province = #{province}, + area_level = #{areaLevel}, + introduction = #{introduction}, + lon = #{lon}, + lat = #{lat}, + manager = #{manager}, + telephone = #{telephone}, + sendEmail = #{sendEmail}, + email = #{email}, + pic_width = #{picWidth}, + pic_height = #{picHeight}, + pic_num = #{picNum}, + banner_file = #{bannerFile}, + zoom = #{zoom}, + gis_file = #{gisFile}, + logo_path = #{logoPath}, + title = #{title}, + en_title = #{enTitle} + where id = #{id} + + + + update protected_area + set is_deleted = 1 + where id = #{id} + + + + update protected_area set is_deleted = 1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaSpeciesMapper.xml b/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaSpeciesMapper.xml new file mode 100644 index 0000000..1a2e06d --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/area/ProtectedAreaSpeciesMapper.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into protected_area_species + (species_id, + area_id, + position, + is_common, + is_special, + create_time, + is_deleted) + values (#{speciesId}, + #{areaId}, + #{position}, + #{isCommon}, + #{isSpecial}, + #{createTime}, + #{isDeleted}) + + + insert into protected_area_species + (species_id, + area_id, + is_common, + is_special, + create_time, + is_deleted) + values + + (#{item.speciesId}, + #{item.areaId}, + #{item.isCommon}, + #{item.isSpecial}, + #{item.createTime}, + #{item.isDeleted}) + + + + + update protected_area_species + set is_common = #{isCommon} + where + area_id = #{areaId} + and + species_id in + + #{id} + + + + + update protected_area_species + set is_common = #{isCommon}, + position = #{position}, + is_special = #{isSpecial} + where id = #{id} + + + + update protected_area_species + set is_deleted = 1 + where id = #{id} + + + + update protected_area_species set is_deleted = 1 where id in + + #{id} + + + + + delete + from protected_area_species + where species_id = #{speciesId} + and area_id = #{areaId} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/area/ProtectedCareSpeciesMapper.xml b/ai-bird-system/src/main/resources/mapper/area/ProtectedCareSpeciesMapper.xml new file mode 100644 index 0000000..e9bb7d1 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/area/ProtectedCareSpeciesMapper.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + insert into protected_care_species + (species_id, + area_id, + create_time) + values (#{speciesId}, + #{areaId}, + #{createTime}) + + + + delete + from protected_care_species + where id = #{id} + and area_id = #{areaId} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/area/SpeciesAbnormalInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/area/SpeciesAbnormalInfoMapper.xml new file mode 100644 index 0000000..1286d77 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/area/SpeciesAbnormalInfoMapper.xml @@ -0,0 +1,159 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into species_abnormal_info + (device_id, + happen_time, + species_id, + media_id, + is_deleted) + values (#{deviceId}, + #{happenTime}, + #{speciesId}, + #{mediaId}, + #{isDeleted}) + + + insert into species_abnormal_info + (device_id, + happen_time, + species_id, + media_id, + count, + type, + record_id, + is_deleted) + values + + (#{item.deviceId}, + #{item.happenTime}, + #{item.speciesId}, + #{item.mediaId}, + #{item.count}, + #{item.type}, + #{item.recordId}, + 0) + + + + update species_abnormal_info + set is_deleted=1 + where id = #{id} + + + update species_abnormal_info + set is_deleted=1 + where media_id = #{id} + + + update species_abnormal_info set is_deleted=1 + where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/area/WinteringPeriodMapper.xml b/ai-bird-system/src/main/resources/mapper/area/WinteringPeriodMapper.xml new file mode 100644 index 0000000..a676135 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/area/WinteringPeriodMapper.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into wintering_period + (protected_area_id, + year, + start_time, + end_time, + amount) + values (#{protectedAreaId}, + #{year}, + #{startTime}, + #{endTime}, + #{amount}) + + + + update wintering_period + set protected_area_id = #{protectedAreaId}, + year = #{year}, + start_time = #{startTime}, + end_time = #{endTime}, + amount = #{amount} + where id = #{id} + + + + delete + from wintering_period + where id = #{id} + + + + delete from wintering_period where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdCatalogueMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdCatalogueMapper.xml new file mode 100644 index 0000000..7b7da21 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdCatalogueMapper.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_catalogue + (name, + scientific_name, + english_name, + description) + values (#{name}, + #{scientificName}, + #{englishName}, + #{description}) + + + + update bird_catalogue + set name = #{name}, + scientific_name = #{scientificName}, + english_name = #{englishName}, + description = #{description} + where id = #{id} + + + + update bird_catalogue + set is_deleted=1 + where id = #{id} + + + + update bird_catalogue set is_deleted=1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFamilyMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFamilyMapper.xml new file mode 100644 index 0000000..17621ab --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFamilyMapper.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_family + (family_name, + scientific_name, + english_name, + description, + catalogue_id) + values (#{familyName}, + #{scientificName}, + #{englishName}, + #{description}, + #{catalogueId}) + + + + update bird_family + set family_name = #{familyName}, + scientific_name = #{scientificName}, + english_name = #{englishName}, + description = #{description}, + catalogue_id = #{catalogueId} + where id = #{id} + + + + update bird_family + set is_deleted = 1 + where id = #{id} + + + + update bird_family + set is_deleted = 1 + where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFlyingInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFlyingInfoMapper.xml new file mode 100644 index 0000000..0114ed9 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdFlyingInfoMapper.xml @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + insert into bird_flying_info + (species_id, + source, + source_longitude, + source_latitude, + target, + target_longitude, + target_latitude, + is_deleted) + values (#{speciesId}, + #{source}, + #{sourceLongitude}, + #{sourceLatitude}, + #{target}, + #{targetLongitude}, + #{targetLatitude}, + #{isDeleted}) + + + + update bird_flying_info + set species_id = #{speciesId}, + source = #{source}, + source_longitude = #{sourceLongitude}, + source_latitude = #{sourceLatitude}, + target = #{target}, + target_longitude = #{targetLongitude}, + target_latitude = #{targetLatitude} + where id = #{id} + + + + update bird_flying_info + set is_deleted = 1 + where id = #{id} + + + + update bird_flying_info set is_deleted = 1 + where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdGenusMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdGenusMapper.xml new file mode 100644 index 0000000..1cd6f00 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdGenusMapper.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_genus + (name, + scientific_name, + english_name, + family_id, + description) + values (#{name}, + #{scientificName}, + #{englishName}, + #{familyId}, + #{description}) + + + + update bird_genus + set name = #{name}, + scientific_name = #{scientificName}, + english_name = #{englishName}, + family_id = #{familyId}, + description = #{description} + where id = #{id} + + + + update bird_genus + set is_deleted =1 + where id = #{id} + + + + update bird_genus set is_deleted =1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdLeaveArriveInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdLeaveArriveInfoMapper.xml new file mode 100644 index 0000000..d11cc62 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdLeaveArriveInfoMapper.xml @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_leave_arrive_info + (area_id, + species_id, + stat_year, + leave_date, + arrive_date, + is_deleted) + values (#{areaId}, + #{speciesId}, + #{statYear}, + #{leaveDate}, + #{arriveDate}, + #{isDeleted}) + + + insert into bird_leave_arrive_info + (area_id, + species_id, + stat_year, + leave_date, + arrive_date, + is_deleted) + values + + ( + #{item.areaId}, + #{item.speciesId}, + #{item.statYear}, + #{item.leaveDate}, + #{item.arriveDate}, + #{item.isDeleted} + ) + + + + + update bird_leave_arrive_info + set area_id = #{areaId}, + species_id = #{speciesId}, + stat_year = #{statYear}, + leave_date = #{leaveDate}, + arrive_date = #{arriveDate} + where id = #{id} + + + + delete + from bird_leave_arrive_info + where id = #{id} + + + + delete from bird_leave_arrive_info where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdMediaMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdMediaMapper.xml new file mode 100644 index 0000000..a556554 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdMediaMapper.xml @@ -0,0 +1,128 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_media + (species_id, + name, + media_type, + url, + pc_show, + description, + is_deleted, + create_time) + values (#{speciesId}, + #{name}, + #{mediaType}, + #{url}, + #{pcShow}, + #{description}, + #{isDeleted}, + #{createTime}) + + + + update bird_media + set species_id = #{speciesId}, + name = #{name}, + media_type = #{mediaType}, + url = #{url}, + pc_show = #{pcShow}, + description = #{description} + where id = #{id} + + + + update bird_media + set is_deleted = 1 + where id = #{id} + + + + update bird_media set is_deleted = 1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/BirdSpeciesMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdSpeciesMapper.xml new file mode 100644 index 0000000..57e502b --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/BirdSpeciesMapper.xml @@ -0,0 +1,306 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into bird_species + (name, + scientific_name, + english_name, + morphology, + habitat, + voice, + distribution, + overseas_distribution, + domestic_distribution, + avatar, + protect_level, + iucn, + residence_type, + species_type, + is_deleted, + create_by, + create_time, + catalogue_id, + family_id, + genus_id) + values (#{name}, + #{scientificName}, + #{englishName}, + #{morphology}, + #{habitat}, + #{voice}, + #{distribution}, + #{overseasDistribution}, + #{domesticDistribution}, + #{avatar}, + #{protectLevel}, + #{iucn}, + #{residenceType}, + #{speciesType}, + #{isDeleted}, + #{createBy}, + #{createTime}, + #{catalogueId}, + #{familyId}, + #{genusId}) + + + + update bird_species + set name = #{name}, + scientific_name = #{scientificName}, + english_name = #{englishName}, + morphology = #{morphology}, + habitat = #{habitat}, + voice = #{voice}, + distribution = #{distribution}, + overseas_distribution = #{overseasDistribution}, + domestic_distribution = #{domesticDistribution}, + avatar = #{avatar}, + protect_level = #{protectLevel}, + iucn = #{iucn}, + residence_type = #{residenceType}, + species_type = #{speciesType}, + update_by = #{updateBy}, + update_time = #{updateTime}, + catalogue_id = #{catalogueId}, + family_id = #{familyId}, + genus_id = #{genusId} + where id = #{id} + + + + update bird_species + set is_deleted = 1 + where id = #{id} + + + + update bird_species set is_deleted = 1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesAnswerMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesAnswerMapper.xml new file mode 100644 index 0000000..d96feaa --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesAnswerMapper.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + insert into species_answer(species_id) + values (#{speciesId}); + + + insert into species_answer_item(cn, en, pid) + values + + (#{item.cn}, + #{item.en}, + #{item.pid}) + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesIntroMapper.xml b/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesIntroMapper.xml new file mode 100644 index 0000000..b6e1446 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/birdInfo/SpeciesIntroMapper.xml @@ -0,0 +1,81 @@ + + + + + + insert into species_intro(species_id, + audio, + frame, + image, + spectrogram, + txt, + video, + video_img) + values (#{speciesId}, + #{audio}, + #{frame}, + #{image}, + #{spectrogram}, + #{txt}, + #{video}, + #{videoImg}) + + + insert into species_intro(species_id, + audio, + frame, + image, + spectrogram, + txt, + video, + video_img) + values + + (#{item.speciesId}, + #{item.audio}, + #{item.frame}, + #{item.image}, + #{item.spectrogram}, + #{item.txt}, + #{item.video}, + #{item.videoImg}) + + + + update species_intro + set video_img= null + where id = #{id} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/dataCheck/FavoriteMediaMapper.xml b/ai-bird-system/src/main/resources/mapper/dataCheck/FavoriteMediaMapper.xml new file mode 100644 index 0000000..11482b0 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/dataCheck/FavoriteMediaMapper.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + delete + from favorite_media + where media_id = #{mediaId} + + + + + + + + + insert into favorite_media + (media_id, + user_id, + create_date, + is_deleted) + values (#{mediaId}, + #{userId}, + #{createDate}, + #{isDeleted}) + + + + update favorite_media + set media_id = #{mediaId}, + user_id = #{userId}, + is_deleted = #{isDeleted} + where id = #{id} + + + + delete + from favorite_media + where id = #{id} + + + + delete from favorite_media where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/dataCheck/MediaItemMapper.xml b/ai-bird-system/src/main/resources/mapper/dataCheck/MediaItemMapper.xml new file mode 100644 index 0000000..869df2d --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/dataCheck/MediaItemMapper.xml @@ -0,0 +1,90 @@ + + + + + + + + + + + + + + + + + + + + + + + insert into media_item + (device_id, + camera_volt, + solar_volt, + extra_volt, + temperature, + humidity, + atmosphere, + lat, + lon, + parent_id) + values (#{deviceId}, + #{cameraVolt}, + #{solarVolt}, + #{extraVolt}, + #{temperature}, + #{humidity}, + #{atmosphere}, + #{lat}, + #{lon}, + #{parentId}) + + + + update media_item + set device_id = #{deviceId}, + camera_volt = #{cameraVolt}, + solar_volt = #{solarVolt}, + extra_volt = #{extraVolt}, + temperature = #{temperature}, + humidity = #{humidity}, + atmosphere = #{atmosphere}, + lat = #{lat}, + lon = #{lon}, + parent_id = #{parentId} + where id = #{id} + + + + delete + from media_item + where id = #{id} + + + + delete from media_item where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/dataCheck/ResultMediaMapper.xml b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultMediaMapper.xml new file mode 100644 index 0000000..4c340b9 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultMediaMapper.xml @@ -0,0 +1,628 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + delete + from result_media + where device_id = #{deviceId} + and media_type = 4 + + + insert into result_media + (device_id, + media_type, + media_url, + meta_url, + time, + description) + values (#{deviceId}, + #{mediaType}, + #{mediaUrl}, + #{metaUrl}, + #{time}, + #{description}) + + + insert into result_media + ( + device_id, + media_type, + sub_type, + media_url, + meta_url, + file_url, + time, + description + ) + values + + ( + #{item.deviceId}, + #{item.mediaType}, + #{item.subType}, + #{item.mediaUrl}, + #{item.metaUrl}, + #{item.fileUrl}, + #{item.time}, + #{item.description} + ) + + + + + + + + + + + + + + + + + + + + + + + update result_media + set is_deleted=1 + where media_id = #{mediaId} + + + update result_media set is_deleted=1 where media_id in + + #{mediaId} + + + + update result_media + set is_deleted = #{isDeleted} + where media_id = #{mediaId} + + + update result_media + set is_deleted = 0 + where is_deleted = 1 + + and device_id in (select id from device_info where is_deleted = 0 and protected_area_id = #{areaId}) + + + and device_id = #{deviceId} + + + and DATE_FORMAT(time, '%Y-%m-%d') >= DATE_FORMAT(#{dateFrom}, '%Y-%m-%d') + + + and DATE_FORMAT(time, '%Y-%m-%d') <= DATE_FORMAT(#{dateTo}, '%Y-%m-%d') + + + and media_type = #{mediaType} + + + + update result_media + set file_url = #{fileUrl} + where media_id = #{mediaId} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordDetailsMapper.xml b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordDetailsMapper.xml new file mode 100644 index 0000000..0636e79 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordDetailsMapper.xml @@ -0,0 +1,675 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into result_record_details + (record_id, + species_id, + habitat, + count, + location, + confidence, + media_id, + location_site_x, + location_site_y, + old_record_id, + old_media_id) + values (#{recordId}, + #{speciesId}, + #{habitat}, + #{count}, + #{location}, + #{confidence}, + #{mediaId}, + #{locationSiteX}, + #{locationSiteY}, + #{oldRecordId}, + #{oldMediaId}) + + + insert into result_record_details + (details_id, + record_id, + species_id, + habitat, + count, + location, + confidence, + media_id, + location_site_x, + location_site_y + ) + values + + (#{item.detailsId}, + #{item.recordId}, + #{item.speciesId}, + #{item.habitat}, + #{item.count}, + #{item.location}, + #{item.confidence}, + #{item.mediaId}, + #{item.locationSiteX}, + #{item.locationSiteY} + ) + + + + + UPDATE result_record_details a + INNER JOIN result_record b ON b.old_record_id = a.old_record_id + SET a.record_id=b.record_id + where a.old_record_id > #{recordId} + + + UPDATE result_record_details a + INNER JOIN result_media b ON b.old_media_id = a.old_media_id + SET a.media_id=b.media_id + where a.old_record_id > #{recordId} + + + update result_record_details + set species_id = #{speciesId}, + checked = #{checked} + where details_id = #{detailsId} + + + + update result_record_details + set species_id = #{speciesId}, + checked = #{checked} + where details_id in + + #{detailsId} + + + + + update result_record_details + set checked = 1 + where details_id = #{id} + + + update result_record_details + set checked = 1 + where details_id in + + #{detailsId} + + + + + + + + + update result_record_details + set is_deleted = 1 + where details_id = #{detailsId} + + + + update result_record_details + set is_deleted = #{isDeleted} + where details_id = #{id} + + + + + + + + + + + update result_record_details + set is_deleted = 1 + where details_id in + + #{detailsId} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordMapper.xml b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordMapper.xml new file mode 100644 index 0000000..55f37df --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/dataCheck/ResultRecordMapper.xml @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into result_record + (device_id, + record_time, + record_type, + old_record_id) + values (#{deviceId}, + #{recordTime}, + #{recordType}, + #{oldRecordId}) + + + insert into result_record + ( + record_id, + device_id, + record_time, + record_type) + values + + (#{item.recordId}, + #{item.deviceId}, + #{item.strRecordTime}, + #{item.recordType} + ) + + + + update result_record + set device_id = #{deviceId}, + record_time = #{recordTime}, + record_type = #{recordType} + where record_id = #{recordId} + + + + delete + from result_record + where record_id = #{recordId} + + + + delete from result_record where record_id in + + #{recordId} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/device/DeviceInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/device/DeviceInfoMapper.xml new file mode 100644 index 0000000..7e57c31 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/device/DeviceInfoMapper.xml @@ -0,0 +1,323 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + update device_info + set status = #{status} + where id = #{id} + + + + + + + + + + + + + + + + + + + insert into device_info + (device_name, + protected_area_id, + manufacturer, + model, + serial_number, + description, + longitude, + latitude, + grid_info, + status, + device_ip, + device_user, + device_password, + rtsp, + rtsp_inner, + rtsp_out, + device_type, + is_deleted, + create_time, + location_x, + location_y, + dept_id) + values (#{deviceName}, + #{protectedAreaId}, + #{manufacturer}, + #{model}, + #{serialNumber}, + #{description}, + #{longitude}, + #{latitude}, + #{gridInfo}, + #{status}, + #{deviceIp}, + #{deviceUser}, + #{devicePassword}, + #{rtsp}, + #{rtspInner}, + #{rtspOut}, + #{deviceType}, + #{isDeleted}, + #{createTime}, + #{locationX}, + #{locationY}, + #{deptId}) + + + + update device_info + set device_name = #{deviceName}, + protected_area_id = #{protectedAreaId}, + manufacturer = #{manufacturer}, + model = #{model}, + serial_number = #{serialNumber}, + description = #{description}, + longitude = #{longitude}, + latitude = #{latitude}, + grid_info = #{gridInfo}, + status = #{status}, + device_ip = #{deviceIp}, + device_user = #{deviceUser}, + device_password = #{devicePassword}, + rtsp = #{rtsp}, + rtsp_inner = #{rtspInner}, + rtsp_out = #{rtspOut}, + device_type = #{deviceType}, + location_x = #{locationX}, + location_y = #{locationY}, + dept_id = #{deptId} + where id = #{id} + + + + update device_info + set is_deleted = #{isDeleted} + where id = #{id} + + + + update device_info + set is_deleted = 1 + where id = #{id} + + + + update device_info set is_deleted = 1 + where id in + + #{id} + + + diff --git a/ai-bird-system/src/main/resources/mapper/device/HeatmapInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/device/HeatmapInfoMapper.xml new file mode 100644 index 0000000..11b268f --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/device/HeatmapInfoMapper.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + insert into heatmap_info + (id, + name, + center_x, + center_y, + start_x, + end_x, + start_y, + end_y, + device_id, + is_deleted, + create_time) + values (#{id}, + #{name}, + #{centerX}, + #{centerY}, + #{startX}, + #{endX}, + #{startY}, + #{endY}, + #{deviceId}, + #{isDeleted}, + #{createTime}) + + + + update heatmap_info + set name = #{name}, + center_x = #{centerX}, + center_y = #{centerY}, + start_x = #{startX}, + end_x = #{endX}, + start_y = #{startY}, + end_y = #{endY}, + device_id = #{deviceId} + where id = #{id} + + + + update heatmap_info + set is_deleted =1 + where id = #{id} + + + + update heatmap_info set is_deleted =1 + where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/echart/BirdDataStatMapper.xml b/ai-bird-system/src/main/resources/mapper/echart/BirdDataStatMapper.xml new file mode 100644 index 0000000..729415d --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/echart/BirdDataStatMapper.xml @@ -0,0 +1,616 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/file/MediaFileInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/file/MediaFileInfoMapper.xml new file mode 100644 index 0000000..b82ed07 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/file/MediaFileInfoMapper.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + select * + from media_file_info + + + + + + + + insert into media_file_info + (upload_type, + device_id, + user_id, + version, + create_date, + is_deleted) + values (#{uploadType}, + #{deviceId}, + #{userId}, + #{version}, + #{createDate}, + #{isDeleted}) + + + + update media_file_info + set upload_type = #{uploadType}, + device_id = #{deviceId}, + user_id = #{userId}, + version = #{version}, + is_deleted = #{isDeleted} + where id = #{id} + + + + update media_file_info + set is_deleted = 1 + where id = #{id} + + + + update media_file_info set is_deleted = 1 where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/file/MediaFileItemMapper.xml b/ai-bird-system/src/main/resources/mapper/file/MediaFileItemMapper.xml new file mode 100644 index 0000000..30cb609 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/file/MediaFileItemMapper.xml @@ -0,0 +1,102 @@ + + + + + + + + + + + + + + + + select * + from media_file_item + + + + + + + + insert into media_file_item + (file_name, + file_type, + url_path, + meta_path, + time, + parent_id) + values (#{fileName}, + #{fileType}, + #{urlPath}, + #{metaPath}, + #{time}, + #{parentId}) + + + + insert into media_file_item + (file_name, + file_type, + url_path, + meta_path, + time, + parent_id) + values + + (#{item.fileName}, + #{item.fileType}, + #{item.urlPath}, + #{item.metaPath}, + #{item.time}, + #{item.parentId}) + + + + + update media_file_item + set file_name = #{fileName}, + file_type = #{fileType}, + url_path = #{urlPath}, + meta_path = #{metaPath}, + time = #{time}, + parent_id = #{parentId} + where id = #{id} + + + + delete + from media_file_item + where id = #{id} + + + + delete from media_file_item where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/job/TableStatInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/job/TableStatInfoMapper.xml new file mode 100644 index 0000000..13cbb93 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/job/TableStatInfoMapper.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + insert into table_stat_info + (table_id, type) + values (#{tableId}, #{type}) + + + + update table_stat_info + set table_id = #{tableId}, + type = #{type} + where id = #{id} + + + + delete + from table_stat_info + where id = #{id} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/naturalist/ObservationFilesMapper.xml b/ai-bird-system/src/main/resources/mapper/naturalist/ObservationFilesMapper.xml new file mode 100644 index 0000000..8383945 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/naturalist/ObservationFilesMapper.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + insert into observation_files + (location, + file_type, + file_ext, + file_name, + observation_id, + create_date) + values (#{location}, + #{fileType}, + #{fileExt}, + #{fileName}, + #{observationId}, + #{createDate}) + + + + update observation_files + set location = #{location}, + file_type = #{fileType}, + file_ext = #{fileExt}, + file_name = #{fileName}, + observation_id = #{observationId}, + create_date = #{createDate} + where id = #{id} + + + + delete + from observation_files + where id = #{id} + + + + delete from observation_files where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/naturalist/ObservationsMapper.xml b/ai-bird-system/src/main/resources/mapper/naturalist/ObservationsMapper.xml new file mode 100644 index 0000000..8959169 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/naturalist/ObservationsMapper.xml @@ -0,0 +1,94 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into observations + (observed_on, + lat, + lon, + description, + species_guess, + user_id, + taxon_id, + is_deleted, + create_date) + values (#{observedOn}, + #{lat}, + #{lon}, + #{description}, + #{speciesGuess}, + #{userId}, + #{taxonId}, + #{isDeleted}, + #{createDate}) + + + + update observations + set observed_on = #{observedOn}, + lat = #{lat}, + lon = #{lon}, + description = #{description}, + species_guess = #{speciesGuess}, + user_id = #{userId}, + taxon_id = #{taxonId}, + update_date = #{updateDate} + where id = #{id} + + + + delete + from observations + where id = #{id} + + + + delete from observations where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/BirdWebPageStatMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/BirdWebPageStatMapper.xml new file mode 100644 index 0000000..762795d --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/BirdWebPageStatMapper.xml @@ -0,0 +1,514 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyInhabitMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyInhabitMapper.xml new file mode 100644 index 0000000..21d2ca1 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyInhabitMapper.xml @@ -0,0 +1,198 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into species_daily_inhabit + (record_id, + habitat, + area_id, + device_id, + stat_date, + species_id, + amount) + values (#{recordId}, + #{habitat}, + #{areaId}, + #{deviceId}, + #{statDate}, + #{speciesId}, + #{amount}) + + + + insert into species_daily_inhabit + (record_id, + habitat, + area_id, + device_id, + stat_date, + species_id, + amount) + values + + (#{item.recordId}, + #{item.habitat}, + #{item.areaId}, + #{item.deviceId}, + #{item.statDate}, + #{item.speciesId}, + #{item.amount}) + + + + + + + + + + + + + delete + from species_daily_inhabit + where DATE_FORMAT(stat_date, '%Y-%m-%d') = DATE_FORMAT(#{statDate}, '%Y-%m-%d') + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyStatMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyStatMapper.xml new file mode 100644 index 0000000..28e214f --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/SpeciesDailyStatMapper.xml @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into species_daily_stat + (species_id, + area_id, + stat_date, + max_value, + avg_value, + record_id) + values (#{speciesId}, + #{areaId}, + #{statDate}, + #{maxValue}, + #{avgValue}, + #{recordId}) + + + delete + from species_daily_stat + where DATE_FORMAT(stat_date, '%Y-%m-%d') = DATE_FORMAT(#{calcDate}, '%Y-%m-%d') + + and area_id = #{areaId} + + + + insert into species_daily_stat + (species_id, + area_id, + device_id, + stat_date, + max_value, + avg_value, + record_id) + values + + (#{item.speciesId}, + #{item.areaId}, + #{item.deviceId}, + #{item.statDate}, + #{item.maxValue}, + #{item.avgValue}, + #{item.recordId}) + + + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/SpeciesInhabitStatMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/SpeciesInhabitStatMapper.xml new file mode 100644 index 0000000..b89a0e8 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/SpeciesInhabitStatMapper.xml @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + insert into species_inhabit_stat + (id, + stat_year, + species_id, + area_id, + data1, + data2, + data3, + data4, + data5) + values (#{id}, + #{statYear}, + #{speciesId}, + #{areaId}, + #{data1}, + #{data2}, + #{data3}, + #{data4}, + #{data5}) + + + + update species_inhabit_stat + set stat_year = #{statYear}, + species_id = #{speciesId}, + area_id = #{areaId}, + data1 = #{data1}, + data2 = #{data2}, + data3 = #{data3}, + data4 = #{data4}, + data5 = #{data5} + where id = #{id} + + + + delete + from species_inhabit_stat + where id = #{id} + + + + delete from species_inhabit_stat where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/SpeciesLocationInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/SpeciesLocationInfoMapper.xml new file mode 100644 index 0000000..6c2ca22 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/SpeciesLocationInfoMapper.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + insert into species_location_info + (species_id, + name, + longitude, + latitude, + memo, + is_deleted) + values (#{speciesId}, + #{name}, + #{longitude}, + #{latitude}, + #{memo}, + #{isDeleted}) + + + + update species_location_info + set species_id = #{speciesId}, + name = #{name}, + longitude = #{longitude}, + latitude = #{latitude}, + memo = #{memo}, + is_deleted = #{isDeleted} + where id = #{id} + + + + delete + from species_location_info + where id = #{id} + + + + delete from species_location_info where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/stat/SpeciesWinterPeriodMapper.xml b/ai-bird-system/src/main/resources/mapper/stat/SpeciesWinterPeriodMapper.xml new file mode 100644 index 0000000..3f36cdb --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/stat/SpeciesWinterPeriodMapper.xml @@ -0,0 +1,125 @@ + + + + + + + + + + + + + + + + + + + + + + + + insert into species_winter_period + (id, + year, + area_id, + species_id, + data1, + data2, + data3, + data4, + data5, + data6) + values (#{id}, + #{year}, + #{areaId}, + #{speciesId}, + #{data1}, + #{data2}, + #{data3}, + #{data4}, + #{data5}, + #{data6}) + + + insert into species_winter_period + ( + year, + area_id, + species_id, + data1, + data2, + data3, + data4, + data5, + data6) + values + + ( + #{item.year}, + #{item.areaId}, + #{item.speciesId}, + #{item.data1}, + #{item.data2}, + #{item.data3}, + #{item.data4}, + #{item.data5}, + #{item.data6}) + + + + update species_winter_period + set year = #{year}, + area_id = #{areaId}, + species_id = #{speciesId}, + data1 = #{data1}, + data2 = #{data2}, + data3 = #{data3}, + data4 = #{data4}, + data5 = #{data5}, + data6 = #{data6} + where id = #{id} + + + + delete + from species_winter_period + where id = #{id} + + + + delete from species_winter_period where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/MenuInSysMapper.xml b/ai-bird-system/src/main/resources/mapper/system/MenuInSysMapper.xml new file mode 100644 index 0000000..fbf53ea --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/MenuInSysMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + select * + from menu_in_sys + + + + + + + + insert into menu_in_sys + (menu_id, + parent_id, + order_num, + sys_id, + is_deleted) + values (#{menuId}, + #{parentId}, + #{orderNum}, + #{sysId}, + #{isDeleted}) + + + + update menu_in_sys + set menu_id = #{menuId}, + parent_id = #{parentId}, + order_num = #{orderNum}, + sys_id = #{sysId}, + is_deleted = #{isDeleted} + where id = #{id} + + + + delete + from menu_in_sys + where id = #{id} + + + + delete from menu_in_sys where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/MessageReadInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/system/MessageReadInfoMapper.xml new file mode 100644 index 0000000..ae91ef0 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/MessageReadInfoMapper.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + insert into message_read_info + (id, + user_id, + message_id, + read_date, + message_type) + values (#{id}, + #{userId}, + #{messageId}, + now(), + #{messageType}) + + + + + update message_read_info + set user_id = #{userId}, + message_id = #{messageId}, + read_date = #{readDate}, + message_type = #{messageType} + where id = #{id} + + + + delete + from message_read_info + where id = #{id} + + + + delete from message_read_info where id in + + #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/NoticeFileInfoMapper.xml b/ai-bird-system/src/main/resources/mapper/system/NoticeFileInfoMapper.xml new file mode 100644 index 0000000..e6f7ce4 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/NoticeFileInfoMapper.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + insert into notice_file_info + (file_path, + file_type, + name, + notice_id) + values (#{filePath}, + #{fileType}, + #{name}, + #{noticeId}) + + + insert into notice_file_info + (file_path, + file_type, + name, + notice_id) + values + + (#{item.filePath}, + #{item.fileType}, + #{item.name}, + #{item.noticeId}) + + + + delete + from notice_file_info + where id = #{id} + + + + delete from notice_file_info where id not in + + #{id} + + and notice_id = #{noticeId} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/NoticeReadDeptMapper.xml b/ai-bird-system/src/main/resources/mapper/system/NoticeReadDeptMapper.xml new file mode 100644 index 0000000..d3dda85 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/NoticeReadDeptMapper.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + insert into notice_read_dept + (dept_id, + notice_id) + values (#{deptId}, + #{noticeId}) + + + + insert into notice_read_dept + (dept_id, + notice_id) + values + + (#{item.deptId}, + #{item.noticeId}) + + + + + delete + from notice_read_dept + where notice_id = #{id} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/NoticeReaderMapper.xml b/ai-bird-system/src/main/resources/mapper/system/NoticeReaderMapper.xml new file mode 100644 index 0000000..b7b11aa --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/NoticeReaderMapper.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + insert into notice_reader + (person_id, + dept_id, + read_time, + notice_id) + values (#{personId}, + #{deptId}, + #{readTime}, + #{noticeId}) + + + + delete + from notice_reader + where id = #{id} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysConfigMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysConfigMapper.xml new file mode 100644 index 0000000..79da4e2 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysConfigMapper.xml @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + select config_id, + config_name, + config_key, + config_value, + config_type, + create_by, + create_time, + update_by, + update_time, + remark + from sys_config + + + + + + + and config_id = #{configId} + + + and config_key = #{configKey} + + + + + + + + + + + + insert into sys_config ( + config_name, + config_key, + config_value, + config_type, + create_by, + remark, + create_time + )values( + #{configName}, + #{configKey}, + #{configValue}, + #{configType}, + #{createBy}, + #{remark}, + sysdate() + ) + + + + update sys_config + + config_name = #{configName}, + config_key = #{configKey}, + config_value = #{configValue}, + config_type = #{configType}, + update_by = #{updateBy}, + remark = #{remark}, + update_time = sysdate() + + where config_id = #{configId} + + + + delete + from sys_config + where config_id = #{configId} + + + + delete from sys_config where config_id in + + #{configId} + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysDeptMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysDeptMapper.xml new file mode 100644 index 0000000..878c867 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysDeptMapper.xml @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select d.* + from sys_dept d + + + + + + + + + + + + + update sys_dept + set ancestor_path=#{ancestorPath} + where dept_id = #{deptId} + + + + + + + + + + + + + + + + + + + + + + insert into sys_dept(parent_id, + dept_name, + full_name, + dept_code, + ancestors, + order_num, + leader, + phone, + email, + full_pinyin, + simple_pinyin, + status, + create_by, + create_time, + dept_level, + ancestor_path) + values (#{parentId}, + #{deptName}, + #{fullName}, + #{deptCode}, + #{ancestors}, + #{orderNum}, + #{leader}, + #{phone}, + #{email}, + #{fullPinyin}, + #{simplePinyin}, + #{status}, + #{createBy}, + sysdate(), + #{deptLevel}, + #{ancestorPath}) + + + update sys_dept + set dept_name = #{deptName}, + dept_code = #{deptCode}, + full_name = #{fullName}, + order_num = #{orderNum}, + leader = #{leader}, + phone = #{phone}, + full_pinyin = #{fullPinyin}, + simple_pinyin = #{simplePinyin}, + update_by = #{updateBy}, + update_time = sysdate(), + ancestor_path=#{ancestorPath} + where dept_id = #{deptId} + + + + update sys_dept set ancestors = + + when #{item.deptId} then #{item.ancestors} + + ,dept_level= + + when #{item.deptId} then #{item.deptLevel} + + where dept_id in + + #{item.deptId} + + + + + update sys_dept set status = '0' where dept_id in + + #{deptId} + + + + + update sys_dept + set del_flag = '2' + where dept_id = #{deptId} + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysDictDataMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysDictDataMapper.xml new file mode 100644 index 0000000..0712deb --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysDictDataMapper.xml @@ -0,0 +1,124 @@ + + + + + + + + + + + + + + + + + + + + + + select dict_code, dict_sort, dict_label, dict_value, dict_type, css_class, list_class, is_default, status, create_by, create_time, remark + from sys_dict_data + + + + + + + + + + + + + + delete from sys_dict_data where dict_code = #{dictCode} + + + + delete from sys_dict_data where dict_code in + + #{dictCode} + + + + + update sys_dict_data + + dict_sort = #{dictSort}, + dict_label = #{dictLabel}, + dict_value = #{dictValue}, + dict_type = #{dictType}, + css_class = #{cssClass}, + list_class = #{listClass}, + is_default = #{isDefault}, + status = #{status}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where dict_code = #{dictCode} + + + + update sys_dict_data set dict_type = #{newDictType} where dict_type = #{oldDictType} + + + + insert into sys_dict_data( + dict_sort, + dict_label, + dict_value, + dict_type, + css_class, + list_class, + is_default, + status, + remark, + create_by, + create_time + )values( + #{dictSort}, + #{dictLabel}, + #{dictValue}, + #{dictType}, + #{cssClass}, + #{listClass}, + #{isDefault}, + #{status}, + #{remark}, + #{createBy}, + sysdate() + ) + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysDictTypeMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysDictTypeMapper.xml new file mode 100644 index 0000000..5e23f6c --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysDictTypeMapper.xml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + select dict_id, dict_name, dict_type, status, create_by, create_time, remark + from sys_dict_type + + + + + + + + + + + + + + delete + from sys_dict_type + where dict_id = #{dictId} + + + + delete from sys_dict_type where dict_id in + + #{dictId} + + + + + update sys_dict_type + + dict_name = #{dictName}, + dict_type = #{dictType}, + status = #{status}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where dict_id = #{dictId} + + + + insert into sys_dict_type( + dict_name, + dict_type, + status, + remark, + create_by, + create_time + )values( + #{dictName}, + #{dictType}, + #{status}, + #{remark}, + #{createBy}, + sysdate() + ) + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysLogininforMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysLogininforMapper.xml new file mode 100644 index 0000000..5c8d6dd --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysLogininforMapper.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + insert into sys_logininfor (user_name, status, ipaddr, login_location, browser, os, msg, login_time) + values (#{userName}, #{status}, #{ipaddr}, #{loginLocation}, #{browser}, #{os}, #{msg}, sysdate()) + + + + + + delete from sys_logininfor where info_id in + + #{infoId} + + + + + truncate table sys_logininfor + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysMenuMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysMenuMapper.xml new file mode 100644 index 0000000..df4df07 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysMenuMapper.xml @@ -0,0 +1,272 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select menu_id, + menu_name, + parent_id, + order_num, + path, + component, + query, + is_frame, + is_cache, + menu_type, + visible, + status, + ifnull(perms, '') as perms, + icon, + create_time + from sys_menu + + + + + + + + + + + + + + + + + + + + + + + + update sys_menu + + menu_name = #{menuName}, + parent_id = #{parentId}, + order_num = #{orderNum}, + path = #{path}, + component = #{component}, + query = #{query}, + is_frame = #{isFrame}, + is_cache = #{isCache}, + menu_type = #{menuType}, + visible = #{visible}, + status = #{status}, + perms = #{perms}, + icon = #{icon}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where menu_id = #{menuId} + + + + insert into sys_menu( + menu_id, + parent_id, + menu_name, + order_num, + path, + component, + query, + is_frame, + is_cache, + menu_type, + visible, + status, + perms, + icon, + remark, + create_by, + create_time + )values( + #{menuId}, + #{parentId}, + #{menuName}, + #{orderNum}, + #{path}, + #{component}, + #{query}, + #{isFrame}, + #{isCache}, + #{menuType}, + #{visible}, + #{status}, + #{perms}, + #{icon}, + #{remark}, + #{createBy}, + sysdate() + ) + + + + delete + from sys_menu + where menu_id = #{menuId} + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysNoticeMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysNoticeMapper.xml new file mode 100644 index 0000000..58ddcaa --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysNoticeMapper.xml @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into sys_notice (notice_title, + notice_type, + notice_content, + status, + remark, + create_by, + create_time, + is_deleted, + create_dept) + values (#{noticeTitle}, + #{noticeType}, + #{noticeContent}, + #{status}, + #{remark}, + #{createBy}, + #{createTime}, + #{isDeleted}, + #{createDept}) + + + + update sys_notice + set notice_title = #{noticeTitle}, + notice_type = #{noticeType}, + notice_content = #{noticeContent}, + status = #{status}, + update_by = #{updateBy}, + update_time = #{updateTime} + where notice_id = #{noticeId} + + + + update sys_notice + set is_deleted = 1 + where notice_id = #{noticeId} + + + + update sys_notice set is_deleted = 1 + where notice_id in + + #{noticeId} + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysOperLogMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysOperLogMapper.xml new file mode 100644 index 0000000..9591367 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysOperLogMapper.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + select oper_id, + title, + business_type, + method, + request_method, + operator_type, + oper_name, + dept_name, + oper_url, + oper_ip, + oper_location, + oper_param, + json_result, + status, + error_msg, + oper_time + from sys_oper_log + + + + insert into sys_oper_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time) + values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, sysdate()) + + + + + + delete from sys_oper_log where oper_id in + + #{operId} + + + + + + + truncate table sys_oper_log + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysPostMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysPostMapper.xml new file mode 100644 index 0000000..d7ddf4f --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysPostMapper.xml @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + select post_id, post_code, post_name, post_sort, status, create_by, create_time, remark + from sys_post + + + + + + + + + + + + + + + + + + update sys_post + + post_code = #{postCode}, + post_name = #{postName}, + post_sort = #{postSort}, + status = #{status}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where post_id = #{postId} + + + + insert into sys_post( + post_id, + post_code, + post_name, + post_sort, + status, + remark, + create_by, + create_time + )values( + #{postId}, + #{postCode}, + #{postName}, + #{postSort}, + #{status}, + #{remark}, + #{createBy}, + sysdate() + ) + + + + delete from sys_post where post_id = #{postId} + + + + delete from sys_post where post_id in + + #{postId} + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml new file mode 100644 index 0000000..7f5e724 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysRoleDeptMapper.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + delete from sys_role_dept where role_id=#{roleId} + + + + + + delete from sys_role_dept where role_id in + + #{roleId} + + + + + insert into sys_role_dept(role_id, dept_id) values + + (#{item.roleId},#{item.deptId}) + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysRoleMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysRoleMapper.xml new file mode 100644 index 0000000..0a7bd58 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysRoleMapper.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + select distinct r.role_id, + r.role_name, + r.role_key, + r.role_sort, + r.data_scope, + r.menu_check_strictly, + r.dept_check_strictly, + r.status, + r.del_flag, + r.create_time, + r.remark + from sys_role r + left join sys_user_role ur on ur.role_id = r.role_id + left join sys_user u on u.user_id = ur.user_id + left join sys_dept d on u.dept_id = d.dept_id + + + + + + + + + + + + + + + + + + + + insert into sys_role( + role_id, + role_name, + role_key, + role_sort, + data_scope, + menu_check_strictly, + dept_check_strictly, + status, + remark, + create_by, + sys_id, + create_time + )values( + #{roleId}, + #{roleName}, + #{roleKey}, + #{roleSort}, + #{dataScope}, + #{menuCheckStrictly}, + #{deptCheckStrictly}, + #{status}, + #{remark}, + #{createBy}, + #{sysId}, + sysdate() + ) + + + + update sys_role + + role_name = #{roleName}, + role_key = #{roleKey}, + role_sort = #{roleSort}, + data_scope = #{dataScope}, + menu_check_strictly = #{menuCheckStrictly}, + dept_check_strictly = #{deptCheckStrictly}, + status = #{status}, + remark = #{remark}, + update_by = #{updateBy}, + update_time = sysdate() + + where role_id = #{roleId} + + + + update sys_role + set del_flag = '2' + where role_id = #{roleId} + + + + update sys_role set del_flag = '2' where role_id in + + #{roleId} + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml new file mode 100644 index 0000000..f7ce28d --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysRoleMenuMapper.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + delete + from sys_role_menu + where role_id = #{roleId} + + + + delete + from role_in_area + where role_id = #{roleId} + + + + delete from sys_role_menu where role_id in + + #{roleId} + + + + insert into role_in_area(role_id, area_id) values + + (#{item.roleId},#{item.areaId}) + + + + insert into sys_role_menu(role_id, menu_id) values + + (#{item.roleId},#{item.menuId}) + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysUserMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysUserMapper.xml new file mode 100644 index 0000000..2b464cc --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysUserMapper.xml @@ -0,0 +1,332 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + select u.user_id, + u.dept_id, + u.user_name, + u.nick_name, + u.email, + u.avatar, + u.phonenumber, + u.password, + u.sex, + u.status, + u.del_flag, + u.login_ip, + u.login_date, + u.create_by, + u.create_time, + u.remark, + u.web_login, + u.portal_login, + d.dept_id, + d.parent_id, + d.dept_name, + d.order_num, + d.leader, + d.status as dept_status, + r.role_id, + r.role_name, + r.role_key, + r.role_sort, + r.data_scope, + r.status as role_status + from sys_user u + left join sys_dept d on u.dept_id = d.dept_id + left join sys_user_role ur on u.user_id = ur.user_id + left join sys_role r on r.role_id = ur.role_id + + + + + + + + + + + + + + + + + + + + insert into sys_user(user_id, dept_id, user_name, nick_name, + email, + avatar, + phonenumber, + password, + status, + create_by, + remark, + create_time, + web_login, + portal_login) + values (#{userId}, + #{deptId}, + #{userName}, + #{nickName}, + #{email}, + #{avatar}, + #{phonenumber}, + #{password}, + #{status}, + #{createBy}, + #{remark}, + sysdate(), + #{webLogin}, + #{portalLogin}) + + + + update sys_user + set password = #{password}, + update_by = #{updateBy} + where user_id = #{userId} + + + + update sys_user + set dept_id = #{deptId}, + nick_name = #{nickName}, + email = #{email}, + phonenumber = #{phonenumber}, + status = #{status}, + update_by = #{updateBy}, + remark = #{remark}, + update_time = sysdate(), + web_login = #{webLogin}, + portal_login = #{portalLogin} + where user_id = #{userId} + + + + update sys_user + set login_ip = #{loginIp}, + login_date = #{loginDate}, + update_time = sysdate() + where user_id = #{userId} + + + + update sys_user + set status = #{status} + where user_id = #{userId} + + + + update sys_user + set avatar = #{avatar} + where user_name = #{userName} + + + + update sys_user + set password = #{password} + where user_name = #{userName} + + + + update sys_user + set del_flag = '2' + where user_id = #{userId} + + + + update sys_user set del_flag = '2' where user_id in + + #{userId} + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysUserPostMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysUserPostMapper.xml new file mode 100644 index 0000000..47cc546 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysUserPostMapper.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + delete from sys_user_post where user_id=#{userId} + + + + + + delete from sys_user_post where user_id in + + #{userId} + + + + + insert into sys_user_post(user_id, post_id) values + + (#{item.userId},#{item.postId}) + + + + \ No newline at end of file diff --git a/ai-bird-system/src/main/resources/mapper/system/SysUserRoleMapper.xml b/ai-bird-system/src/main/resources/mapper/system/SysUserRoleMapper.xml new file mode 100644 index 0000000..ceb3c06 --- /dev/null +++ b/ai-bird-system/src/main/resources/mapper/system/SysUserRoleMapper.xml @@ -0,0 +1,52 @@ + + + + + + + + + + + delete from sys_user_role where user_id=#{userId} + + and role_id in (select role_id from sys_role where sys_id=#{sysId}) + + + + + + + delete from sys_user_role where user_id in + + #{userId} + + + + + insert into sys_user_role(user_id, role_id) values + + (#{item.userId},#{item.roleId}) + + + + + delete + from sys_user_role + where user_id = #{userId} + and role_id = #{roleId} + + + + delete from sys_user_role where role_id=#{roleId} and user_id in + + #{userId} + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..ec7d3a7 --- /dev/null +++ b/pom.xml @@ -0,0 +1,297 @@ + + + 4.0.0 + + net.hzvtc + aibird + 1.2.0 + + ai-bird-es-sys + http://www.hzvtc.net + 湿地公园鸟类智慧检测 + + + 1.2.0 + UTF-8 + UTF-8 + UTF-8 + 1.8 + 3.1.1 + 1.2.8 + 1.21 + 3.0.0 + 2.3.2 + 2.2.0 + 1.4.7 + 1.2.83 + 5.8.6 + 5.10.0 + 2.11.0 + 1.4 + 3.2.2 + 5.2.3 + 2.3 + 0.12.5 + 2.1.2 + + + + + + + + org.springframework.boot + spring-boot-dependencies + 2.7.18 + pom + import + + + + org.springframework.boot + spring-boot-starter-mail + 2.3.5.RELEASE + + + + + com.alibaba + druid-spring-boot-starter + ${druid.version} + + + + + eu.bitwalker + UserAgentUtils + ${bitwalker.version} + + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + ${mybatis-spring-boot.version} + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + ${pagehelper.boot.version} + + + + co.elastic.clients + elasticsearch-java + 8.14.3 + + + org.elasticsearch.client + elasticsearch-rest-client + 8.14.3 + + + + + + + + + + + com.github.oshi + oshi-core + ${oshi.version} + + + + net.java.dev.jna + jna + ${jna.version} + + + + net.java.dev.jna + jna-platform + ${jna.version} + + + + + io.springfox + springfox-boot-starter + ${swagger.version} + + + io.swagger + swagger-models + + + + + + + commons-io + commons-io + ${commons.io.version} + + + + + commons-fileupload + commons-fileupload + ${commons.fileupload.version} + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + + jakarta.json + jakarta.json-api + ${jakarta-json.version} + + + + + org.apache.velocity + velocity-engine-core + ${velocity.version} + + + + + commons-collections + commons-collections + ${commons.collections.version} + + + + + com.alibaba + fastjson + ${fastjson.version} + + + + + io.jsonwebtoken + jjwt + ${jwt.version} + + + + + com.github.penggle + kaptcha + ${kaptcha.version} + + + + + net.hzvtc + ai-bird-quartz + ${aibird.version} + + + + + net.hzvtc + ai-bird-generator + ${aibird.version} + + + + + net.hzvtc + ai-bird-framework + ${aibird.version} + + + + + net.hzvtc + ai-bird-system + ${aibird.version} + + + + + net.hzvtc + ai-bird-common + ${aibird.version} + + + + net.hzvtc + ai-bird-es + ${aibird.version} + + + + + + + ai-bird-admin + ai-bird-system + ai-bird-framework + ai-bird-quartz + ai-bird-generator + ai-bird-common + ai-bird-es + + pom + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + ${project.build.sourceEncoding} + + + + + + + + public + aliyun nexus + https://maven.aliyun.com/repository/public + + true + + + + + + + public + aliyun nexus + https://maven.aliyun.com/repository/public + + true + + + false + + + + + \ No newline at end of file